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
fbdaee3d865cf9cc7fc2a998ff22f96354b49c2b
1fbca480c1574e809ae95a3eda58188ff42a5e41
/src/util/data/finite.lean
e55e88d76d67bea9ce0c2a69453ab93f5132b5ff
[]
no_license
unitb/lean-lib
560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e
439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9
refs/heads/master
1,610,706,025,400
1,570,144,245,000
1,570,144,245,000
99,579,229
5
0
null
null
null
null
UTF-8
Lean
false
false
767
lean
import util.data.nat open nat (hiding zero_le) open list def fin_interleave (n : ℕ) (i : ℕ) : fin (succ n) := ⟨i % succ n,mod_lt _ (succ_le_succ $ nat.zero_le _)⟩ theorem inf_repeat_fin_inter {n : ℕ} : ∀ x i, ∃ j, fin_interleave n (i+j) = x := begin intro x, cases x with x H, intro i, existsi x + succ n - (i % succ n), tactic.swap, unfold fin_interleave, have h : i % succ n ≤ succ n, { apply nat.le_of_lt (mod_lt _ _), apply succ_le_succ, apply nat.zero_le }, apply fin.eq_of_veq, unfold fin.val , rw [nat.add_sub_assoc h,add_comm x,← add_assoc,mod_add,@mod_add i], rw [← @mod_add' (i % succ n),← nat.add_sub_assoc h], rw [nat.add_sub_cancel_left, nat.mod_self',nat.zero_add,mod_mod,mod_of_lt], apply H, end
a8d5ca2cc763d9988d33f1a27742101857f063cb
da3a76c514d38801bae19e8a9e496dc31f8e5866
/library/init/meta/smt/interactive.lean
647cd424fcf60828ca7effa7789a006816ccf54b
[ "Apache-2.0" ]
permissive
cipher1024/lean
270c1ac5781e6aee12f5c8d720d267563a164beb
f5cbdff8932dd30c6dd8eec68f3059393b4f8b3a
refs/heads/master
1,611,223,459,029
1,487,566,573,000
1,487,566,573,000
83,356,543
0
0
null
1,488,229,336,000
1,488,229,336,000
null
UTF-8
Lean
false
false
10,213
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.smt.smt_tactic init.meta.interactive import init.meta.smt.rsimp namespace smt_tactic meta def save_info (line : nat) (col : nat) : smt_tactic unit := do (ss, ts) ← smt_tactic.read, tactic.save_info_thunk line col (λ _, smt_state.to_format ss ts) meta def skip : smt_tactic unit := return () meta def solve_goals : smt_tactic unit := repeat close meta def step {α : Type} (tac : smt_tactic α) : smt_tactic unit := tac >> solve_goals meta def istep {α : Type} (line : nat) (col : nat) (tac : smt_tactic α) : smt_tactic unit := λ ss ts, @scope_trace _ line col ((tac >> solve_goals) ss ts) meta def rstep {α : Type} (line : nat) (col : nat) (tac : smt_tactic α) : smt_tactic unit := λ ss ts, result.cases_on (istep line col tac ss ts) (λ ⟨a, new_ss⟩ new_ts, result.success ((), new_ss) new_ts) (λ msg_thunk e, tactic.report_exception line col msg_thunk) meta def execute (tac : smt_tactic unit) : tactic unit := using_smt tac meta def execute_with (cfg : smt_config) (tac : smt_tactic unit) : tactic unit := using_smt tac cfg namespace interactive open lean.parser open interactive open interactive.types local postfix ?:9001 := optional local postfix *:9001 := many meta def itactic : Type := smt_tactic unit meta def irtactic : Type := smt_tactic unit meta def intros : parse ident* → smt_tactic unit | [] := smt_tactic.intros | hs := smt_tactic.intro_lst hs /-- Try to close main goal by using equalities implied by the congruence closure module. -/ meta def close : smt_tactic unit := smt_tactic.close /-- Produce new facts using heuristic lemma instantiation based on E-matching. This tactic tries to match patterns from lemmas in the main goal with terms in the main goal. The set of lemmas is populated with theorems tagged with the attribute specified at smt_config.em_attr, and lemmas added using tactics such as `smt_tactic.add_lemmas`. The current set of lemmas can be retrieved using the tactic `smt_tactic.get_lemmas`. -/ meta def ematch : smt_tactic unit := smt_tactic.ematch meta def apply (q : parse texpr) : smt_tactic unit := tactic.interactive.apply q meta def fapply (q : parse texpr) : smt_tactic unit := tactic.interactive.fapply q meta def apply_instance : smt_tactic unit := tactic.apply_instance meta def change (q : parse texpr) : smt_tactic unit := tactic.interactive.change q meta def exact (q : parse texpr) : smt_tactic unit := tactic.interactive.exact q meta def assert (h : parse ident) (q : parse $ tk ":" *> texpr) : smt_tactic unit := do e ← tactic.to_expr_strict q, smt_tactic.assert h e meta def define (h : parse ident) (q : parse $ tk ":" *> texpr) : smt_tactic unit := do e ← tactic.to_expr_strict q, smt_tactic.define h e meta def assertv (h : parse ident) (q₁ : parse $ tk ":" *> texpr) (q₂ : parse $ tk ":=" *> texpr) : smt_tactic unit := do t ← tactic.to_expr_strict q₁, v ← tactic.to_expr_strict ``(%%q₂ : %%t), smt_tactic.assertv h t v meta def definev (h : parse ident) (q₁ : parse $ tk ":" *> texpr) (q₂ : parse $ tk ":=" *> texpr) : smt_tactic unit := do t ← tactic.to_expr_strict q₁, v ← tactic.to_expr_strict ``(%%q₂ : %%t), smt_tactic.definev h t v meta def note (h : parse ident) (q : parse $ tk ":=" *> texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.note h p meta def pose (h : parse ident) (q : parse $ tk ":=" *> texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.pose h p meta def add_fact (q : parse texpr) : smt_tactic unit := do h ← tactic.get_unused_name `h none, p ← tactic.to_expr_strict q, smt_tactic.note h p meta def trace_state : smt_tactic unit := smt_tactic.trace_state meta def trace {α : Type} [has_to_tactic_format α] (a : α) : smt_tactic unit := tactic.trace a meta def destruct (q : parse texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.destruct p meta def by_cases (q : parse texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.by_cases p meta def by_contradiction : smt_tactic unit := smt_tactic.by_contradiction meta def by_contra : smt_tactic unit := smt_tactic.by_contradiction open tactic (resolve_name transparency to_expr) private meta def report_invalid_em_lemma {α : Type} (n : name) : tactic α := fail ("invalid ematch lemma '" ++ to_string n ++ "'") private meta def add_lemma_name (md : transparency) (lhs_lemma : bool) (n : name) (ref : expr) : smt_tactic unit := do e ← resolve_name n, match e with | expr.const n _ := (add_ematch_lemma_from_decl_core md lhs_lemma n >> tactic.save_const_type_info n ref) <|> report_invalid_em_lemma n | _ := (add_ematch_lemma_core md lhs_lemma e >> try (tactic.save_type_info e ref)) <|> report_invalid_em_lemma n end private meta def add_lemma_pexpr (md : transparency) (lhs_lemma : bool) (p : pexpr) : smt_tactic unit := let e := pexpr.to_raw_expr p in match e with | (expr.const c []) := add_lemma_name md lhs_lemma c e | (expr.local_const c _ _ _) := add_lemma_name md lhs_lemma c e | _ := do new_e ← to_expr p, add_ematch_lemma_core md lhs_lemma new_e end private meta def add_lemma_pexprs (md : transparency) (lhs_lemma : bool) : list pexpr → smt_tactic unit | [] := return () | (p::ps) := add_lemma_pexpr md lhs_lemma p >> add_lemma_pexprs ps meta def add_lemma (l : parse qexpr_list_or_texpr) : smt_tactic unit := add_lemma_pexprs reducible ff l meta def add_lhs_lemma (l : parse qexpr_list_or_texpr) : smt_tactic unit := add_lemma_pexprs reducible tt l private meta def add_eqn_lemmas_for_core (md : transparency) : list name → smt_tactic unit | [] := return () | (c::cs) := do e ← resolve_name c, match e with | expr.const n _ := add_ematch_eqn_lemmas_for_core md n >> add_eqn_lemmas_for_core cs | _ := fail $ "'" ++ to_string c ++ "' is not a constant" end meta def add_eqn_lemmas_for (ids : parse ident*) : smt_tactic unit := add_eqn_lemmas_for_core reducible ids meta def add_eqn_lemmas (ids : parse ident*) : smt_tactic unit := add_eqn_lemmas_for ids private meta def add_hinst_lemma_from_name (md : transparency) (lhs_lemma : bool) (n : name) (hs : hinst_lemmas) (ref : expr) : smt_tactic hinst_lemmas := do e ← resolve_name n, match e with | expr.const n _ := (do h ← hinst_lemma.mk_from_decl_core md n lhs_lemma, tactic.save_const_type_info n ref, return $ hs^.add h) <|> (do hs₁ ← mk_ematch_eqn_lemmas_for_core md n, tactic.save_const_type_info n ref, return $ hs^.merge hs₁) <|> report_invalid_em_lemma n | _ := (do h ← hinst_lemma.mk_core md e lhs_lemma, try (tactic.save_type_info e ref), return $ hs^.add h) <|> report_invalid_em_lemma n end private meta def add_hinst_lemma_from_pexpr (md : transparency) (lhs_lemma : bool) (p : pexpr) (hs : hinst_lemmas) : smt_tactic hinst_lemmas := let e := pexpr.to_raw_expr p in match e with | (expr.const c []) := add_hinst_lemma_from_name md lhs_lemma c hs e | (expr.local_const c _ _ _) := add_hinst_lemma_from_name md lhs_lemma c hs e | _ := do new_e ← to_expr p, h ← hinst_lemma.mk_core md new_e lhs_lemma, return $ hs^.add h end private meta def add_hinst_lemmas_from_pexprs (md : transparency) (lhs_lemma : bool) : list pexpr → hinst_lemmas → smt_tactic hinst_lemmas | [] hs := return hs | (p::ps) hs := do hs₁ ← add_hinst_lemma_from_pexpr md lhs_lemma p hs, add_hinst_lemmas_from_pexprs ps hs₁ meta def ematch_using (l : parse qexpr_list_or_texpr) : smt_tactic unit := do hs ← add_hinst_lemmas_from_pexprs reducible ff l hinst_lemmas.mk, smt_tactic.ematch_using hs /-- Try the given tactic, and do nothing if it fails. -/ meta def try (t : itactic) : smt_tactic unit := smt_tactic.try t /-- Keep applying the given tactic until it fails. -/ meta def repeat (t : itactic) : smt_tactic unit := smt_tactic.repeat t /-- Apply the given tactic to all remaining goals. -/ meta def all_goals (t : itactic) : smt_tactic unit := smt_tactic.all_goals t meta def induction (p : parse texpr) (rec_name : parse using_ident) (ids : parse with_ident_list) : smt_tactic unit := slift (tactic.interactive.induction p rec_name ids) open tactic /-- Simplify the target type of the main goal. -/ meta def simp (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (cfg : simp_config := {}) : smt_tactic unit := tactic.interactive.simp hs attr_names ids [] cfg /-- Simplify the target type of the main goal using simplification lemmas and the current set of hypotheses. -/ meta def simp_using_hs (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (cfg : simp_config := {}) : smt_tactic unit := tactic.interactive.simp_using_hs hs attr_names ids cfg meta def simph (hs : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) (cfg : simp_config := {}) : smt_tactic unit := simp_using_hs hs attr_names ids cfg meta def dsimp (es : parse opt_qexpr_list) (attr_names : parse with_ident_list) (ids : parse without_ident_list) : smt_tactic unit := tactic.interactive.dsimp es attr_names ids [] meta def rsimp : smt_tactic unit := do ccs ← to_cc_state, rsimp.rsimplify_goal ccs meta def add_simp_lemmas : smt_tactic unit := get_hinst_lemmas_for_attr `rsimp_attr >>= add_lemmas /-- Keep applying heuristic instantiation until the current goal is solved, or it fails. -/ meta def eblast : smt_tactic unit := smt_tactic.eblast /-- Keep applying heuristic instantiation using the given lemmas until the current goal is solved, or it fails. -/ meta def eblast_using (l : parse qexpr_list_or_texpr) : smt_tactic unit := do hs ← add_hinst_lemmas_from_pexprs reducible ff l hinst_lemmas.mk, smt_tactic.repeat (smt_tactic.ematch_using hs >> smt_tactic.try smt_tactic.close) end interactive end smt_tactic
37b3ebcf1ddb93e3f734b92df980707a29c592da
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/bad_set_option.lean
b65e023626b5874dadc0702d3baace04c65167b2
[ "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
45
lean
set_option boo true set_option pp.unicode a
a7d18e7e8eda1ebe2206758d2028bdf53212ed6b
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/topology/instances/ennreal.lean
31a9297318a5bf2f26855cb8f862e11a70effb68
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
55,670
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import topology.instances.nnreal import topology.algebra.ordered.liminf_limsup /-! # Extended non-negative reals -/ noncomputable theory open classical set filter metric open_locale classical topological_space ennreal nnreal big_operators filter variables {α : Type*} {β : Type*} {γ : Type*} namespace ennreal variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0} variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞} section topological_space open topological_space /-- Topology on `ℝ≥0∞`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊤}`, while this topology doesn't have singleton elements. -/ instance : topological_space ℝ≥0∞ := preorder.topology ℝ≥0∞ instance : order_topology ℝ≥0∞ := ⟨rfl⟩ instance : t2_space ℝ≥0∞ := by apply_instance -- short-circuit type class inference instance : second_countable_topology ℝ≥0∞ := ⟨⟨⋃q ≥ (0:ℚ), {{a : ℝ≥0∞ | a < real.to_nnreal q}, {a : ℝ≥0∞ | ↑(real.to_nnreal q) < a}}, (countable_encodable _).bUnion $ assume a ha, (countable_singleton _).insert _, le_antisymm (le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt}) (le_generate_from $ λ s h, begin rcases h with ⟨a, hs | hs⟩; [ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < real.to_nnreal q}, {b | ↑(real.to_nnreal q) < b}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]), rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(real.to_nnreal q) < a}, {b | b < ↑(real.to_nnreal q)}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])]; { apply is_open_Union, intro q, apply is_open_Union, intro hq, exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) } end)⟩⟩ lemma embedding_coe : embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0∞ _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : ℝ≥0 | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : ℝ≥0 | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0 _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, coe_eq_coe.1⟩ lemma is_open_ne_top : is_open {a : ℝ≥0∞ | a ≠ ⊤} := is_open_ne lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio} lemma open_embedding_coe : open_embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨embedding_coe, by { convert is_open_ne_top, ext (x|_); simp [none_eq_top, some_eq_coe] }⟩ lemma coe_range_mem_nhds : range (coe : ℝ≥0 → ℝ≥0∞) ∈ 𝓝 (r : ℝ≥0∞) := is_open.mem_nhds open_embedding_coe.open_range $ mem_range_self _ @[norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {a : ℝ≥0} : tendsto (λa, (m a : ℝ≥0∞)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ≥0∞) := embedding_coe.continuous lemma continuous_coe_iff {α} [topological_space α] {f : α → ℝ≥0} : continuous (λa, (f a : ℝ≥0∞)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : ℝ≥0} : 𝓝 (r : ℝ≥0∞) = (𝓝 r).map coe := (open_embedding_coe.map_nhds_eq r).symm lemma tendsto_nhds_coe_iff {α : Type*} {l : filter α} {x : ℝ≥0} {f : ℝ≥0∞ → α} : tendsto f (𝓝 ↑x) l ↔ tendsto (f ∘ coe : ℝ≥0 → α) (𝓝 x) l := show _ ≤ _ ↔ _ ≤ _, by rw [nhds_coe, filter.map_map] lemma continuous_at_coe_iff {α : Type*} [topological_space α] {x : ℝ≥0} {f : ℝ≥0∞ → α} : continuous_at f (↑x) ↔ continuous_at (f ∘ coe : ℝ≥0 → α) x := tendsto_nhds_coe_iff lemma nhds_coe_coe {r p : ℝ≥0} : 𝓝 ((r : ℝ≥0∞), (p : ℝ≥0∞)) = (𝓝 (r, p)).map (λp:ℝ≥0×ℝ≥0, (p.1, p.2)) := ((open_embedding_coe.prod open_embedding_coe).map_nhds_eq (r, p)).symm lemma continuous_of_real : continuous ennreal.of_real := (continuous_coe_iff.2 continuous_id).comp nnreal.continuous_of_real lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) : tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) := tendsto.comp (continuous.tendsto continuous_of_real _) h lemma tendsto_to_nnreal {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_nnreal (𝓝 a) (𝓝 a.to_nnreal) := begin lift a to ℝ≥0 using ha, rw [nhds_coe, tendsto_map'_iff], exact tendsto_id end lemma eventually_eq_of_to_real_eventually_eq {l : filter α} {f g : α → ℝ≥0∞} (hfi : ∀ᶠ x in l, f x ≠ ∞) (hgi : ∀ᶠ x in l, g x ≠ ∞) (hfg : (λ x, (f x).to_real) =ᶠ[l] (λ x, (g x).to_real)) : f =ᶠ[l] g := begin filter_upwards [hfi, hgi, hfg], intros x hfx hgx hfgx, rwa ← ennreal.to_real_eq_to_real hfx hgx, end lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} := λ a ha, continuous_at.continuous_within_at (tendsto_to_nnreal ha) lemma tendsto_to_real {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_real (𝓝 a) (𝓝 a.to_real) := nnreal.tendsto_coe.2 $ tendsto_to_nnreal ha /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ ℝ≥0 := { continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal, continuous_inv_fun := continuous_subtype_mk _ continuous_coe, .. ne_top_equiv_nnreal } /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ ℝ≥0 := by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal; simp only [mem_set_of_eq, lt_top_iff_ne_top] lemma nhds_top : 𝓝 ∞ = ⨅ a ≠ ∞, 𝓟 (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_top' : 𝓝 ∞ = ⨅ r : ℝ≥0, 𝓟 (Ioi r) := nhds_top.trans $ infi_ne_top _ lemma nhds_top_basis : (𝓝 ∞).has_basis (λ a, a < ∞) (λ a, Ioi a) := nhds_top_basis lemma tendsto_nhds_top_iff_nnreal {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ≥0, ∀ᶠ a in f, ↑x < m a := by simp only [nhds_top', tendsto_infi, tendsto_principal, mem_Ioi] lemma tendsto_nhds_top_iff_nat {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a := tendsto_nhds_top_iff_nnreal.trans ⟨λ h n, by simpa only [ennreal.coe_nat] using h n, λ h x, let ⟨n, hn⟩ := exists_nat_gt x in (h n).mono (λ y, lt_trans $ by rwa [← ennreal.coe_nat, coe_lt_coe])⟩ lemma tendsto_nhds_top {m : α → ℝ≥0∞} {f : filter α} (h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) := tendsto_nhds_top_iff_nat.2 h lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) := tendsto_nhds_top $ λ n, mem_at_top_sets.2 ⟨n+1, λ m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩ @[simp, norm_cast] lemma tendsto_coe_nhds_top {f : α → ℝ≥0} {l : filter α} : tendsto (λ x, (f x : ℝ≥0∞)) l (𝓝 ∞) ↔ tendsto f l at_top := by rw [tendsto_nhds_top_iff_nnreal, at_top_basis_Ioi.tendsto_right_iff]; [simp, apply_instance, apply_instance] lemma nhds_zero : 𝓝 (0 : ℝ≥0∞) = ⨅a ≠ 0, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] lemma nhds_zero_basis : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) (λ a, Iio a) := nhds_bot_basis lemma nhds_zero_basis_Iic : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) Iic := nhds_bot_basis_Iic @[instance] lemma nhds_within_Ioi_coe_ne_bot {r : ℝ≥0} : (𝓝[Ioi r] (r : ℝ≥0∞)).ne_bot := nhds_within_Ioi_self_ne_bot' ennreal.coe_lt_top @[instance] lemma nhds_within_Ioi_zero_ne_bot : (𝓝[Ioi 0] (0 : ℝ≥0∞)).ne_bot := nhds_within_Ioi_coe_ne_bot -- using Icc because -- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0 -- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not lemma Icc_mem_nhds (xt : x ≠ ⊤) (ε0 : ε ≠ 0) : Icc (x - ε) (x + ε) ∈ 𝓝 x := begin rw _root_.mem_nhds_iff, by_cases x0 : x = 0, { use Iio (x + ε), have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt, use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ }, { use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self, exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ } end lemma nhds_of_ne_top (xt : x ≠ ⊤) : 𝓝 x = ⨅ ε > 0, 𝓟 (Icc (x - ε) (x + ε)) := begin refine le_antisymm _ _, -- first direction simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0.lt.ne', -- second direction rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _), rcases hs with ⟨xs, ⟨a, (rfl : s = Ioi a)|(rfl : s = Iio a)⟩⟩, { rcases exists_between xs with ⟨b, ab, bx⟩, have xb_pos : 0 < x - b := ennreal.sub_pos.2 bx, have xxb : x - (x - b) = b := sub_sub_cancel xt bx.le, refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ }, { rcases exists_between xs with ⟨b, xb, ba⟩, have bx_pos : 0 < b - x := ennreal.sub_pos.2 xb, have xbx : x + (b - x) = b := add_sub_cancel_of_le xb.le, refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba }, end /-- Characterization of neighborhoods for `ℝ≥0∞` numbers. See also `tendsto_order` for a version with strict inequalities. -/ protected theorem tendsto_nhds {f : filter α} {u : α → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) := by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc] protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) := by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually] instance : has_continuous_add ℝ≥0∞ := begin refine ⟨continuous_iff_continuous_at.2 _⟩, rintro ⟨(_|a), b⟩, { exact tendsto_nhds_top_mono' continuous_at_fst (λ p, le_add_right le_rfl) }, rcases b with (_|b), { exact tendsto_nhds_top_mono' continuous_at_snd (λ p, le_add_left le_rfl) }, simp only [continuous_at, some_eq_coe, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘), tendsto_coe, tendsto_add] end protected lemma tendsto_at_top_zero [hβ : nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} : filter.at_top.tendsto f (𝓝 0) ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, f n ≤ ε := begin rw ennreal.tendsto_at_top zero_ne_top, { simp_rw [set.mem_Icc, zero_add, zero_sub, zero_le _, true_and], }, { exact hβ, }, end protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) := have ht : ∀b:ℝ≥0∞, b ≠ 0 → tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 ((⊤:ℝ≥0∞), b)) (𝓝 ⊤), begin refine assume b hb, tendsto_nhds_top_iff_nnreal.2 $ assume n, _, rcases lt_iff_exists_nnreal_btwn.1 (pos_iff_ne_zero.2 hb) with ⟨ε, hε, hεb⟩, replace hε : 0 < ε, from coe_pos.1 hε, filter_upwards [prod_is_open.mem_nhds (lt_mem_nhds $ @coe_lt_top (n / ε)) (lt_mem_nhds hεb)], rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, dsimp at h₁ h₂ ⊢, rw [← div_mul_cancel n hε.ne', coe_mul], exact mul_lt_mul h₁ h₂ end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, simp [*, nhds_swap (a : ℝ≥0∞) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul] end protected lemma tendsto.mul {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λa, ma a * mb a) f (𝓝 (a * b)) := show tendsto ((λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb) protected lemma tendsto.const_mul {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb) protected lemma tendsto.mul_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) := by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha lemma tendsto_finset_prod_of_ne_top {ι : Type*} {f : ι → α → ℝ≥0∞} {x : filter α} {a : ι → ℝ≥0∞} (s : finset ι) (h : ∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) (h' : ∀ i ∈ s, a i ≠ ∞): tendsto (λ b, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := begin induction s using finset.induction with a s has IH, { simp [tendsto_const_nhds] }, simp only [finset.prod_insert has], apply tendsto.mul (h _ (finset.mem_insert_self _ _)), { right, exact (prod_lt_top (λ i hi, h' _ (finset.mem_insert_of_mem hi))).ne }, { exact IH (λ i hi, h _ (finset.mem_insert_of_mem hi)) (λ i hi, h' _ (finset.mem_insert_of_mem hi)) }, { exact or.inr (h' _ (finset.mem_insert_self _ _)) } end protected lemma continuous_at_const_mul {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at ((*) a) b := tendsto.const_mul tendsto_id h.symm protected lemma continuous_at_mul_const {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at (λ x, x * a) b := tendsto.mul_const tendsto_id h.symm protected lemma continuous_const_mul {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous ((*) a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_const_mul (or.inl ha) protected lemma continuous_mul_const {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous (λ x, x * a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_mul_const (or.inl ha) lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0∞} (h : ∀ a < 1, a * x ≤ y) : x ≤ y := begin have : tendsto (* x) (𝓝[Iio 1] 1) (𝓝 (1 * x)) := (ennreal.continuous_at_mul_const (or.inr one_ne_zero)).mono_left inf_le_left, rw one_mul at this, haveI : (𝓝[Iio 1] (1 : ℝ≥0∞)).ne_bot := nhds_within_Iio_self_ne_bot' ennreal.zero_lt_one, exact le_of_tendsto this (eventually_nhds_within_iff.2 $ eventually_of_forall h) end lemma infi_mul_left' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, a * f i) = a * ⨅ i, f i := begin by_cases H : a = ⊤ ∧ (⨅ i, f i) = 0, { rcases h H.1 H.2 with ⟨i, hi⟩, rw [H.2, mul_zero, ← bot_eq_zero, infi_eq_bot], exact λ b hb, ⟨i, by rwa [hi, mul_zero, ← bot_eq_zero]⟩ }, { rw not_and_distrib at H, casesI is_empty_or_nonempty ι, { rw [infi_of_empty, infi_of_empty, mul_top, if_neg], exact mt h0 (not_nonempty_iff.2 ‹_›) }, { exact (map_infi_of_continuous_at_of_monotone' (ennreal.continuous_at_const_mul H) ennreal.mul_left_mono).symm } } end lemma infi_mul_left {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, a * f i) = a * ⨅ i, f i := infi_mul_left' h (λ _, ‹nonempty ι›) lemma infi_mul_right' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, f i * a) = (⨅ i, f i) * a := by simpa only [mul_comm a] using infi_mul_left' h h0 lemma infi_mul_right {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, f i * a) = (⨅ i, f i) * a := infi_mul_right' h (λ _, ‹nonempty ι›) protected lemma continuous_inv : continuous (has_inv.inv : ℝ≥0∞ → ℝ≥0∞) := continuous_iff_continuous_at.2 $ λ a, tendsto_order.2 ⟨begin assume b hb, simp only [@ennreal.lt_inv_iff_lt_inv b], exact gt_mem_nhds (ennreal.lt_inv_iff_lt_inv.1 hb), end, begin assume b hb, simp only [gt_iff_lt, @ennreal.inv_lt_iff_inv_lt _ b], exact lt_mem_nhds (ennreal.inv_lt_iff_inv_lt.1 hb) end⟩ @[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} : tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) := ⟨λ h, by simpa only [function.comp, ennreal.inv_inv] using (ennreal.continuous_inv.tendsto a⁻¹).comp h, (ennreal.continuous_inv.tendsto a).comp⟩ protected lemma tendsto.div {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λa, ma a / mb a) f (𝓝 (a / b)) := by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] } protected lemma tendsto.const_div {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) := by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] } protected lemma tendsto.div_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) := by { apply tendsto.mul_const hm, simp [ha] } protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ℝ≥0∞)⁻¹) at_top (𝓝 0) := ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top lemma bsupr_add {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} : (⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a := begin simp only [← Sup_image], symmetry, rw [image_comp (+ a)], refine is_lub.Sup_eq ((is_lub_Sup $ f '' s).is_lub_of_tendsto _ (hs.image _) _), exacts [λ x _ y _ hxy, add_le_add hxy le_rfl, tendsto.add (tendsto_id' inf_le_left) tendsto_const_nhds] end lemma Sup_add {s : set ℝ≥0∞} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a := by rw [Sup_eq_supr, bsupr_add hs] lemma supr_add {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : supr s + a = ⨆b, s b + a := let ⟨x⟩ := h in calc supr s + a = Sup (range s) + a : by rw Sup_range ... = (⨆b∈range s, b + a) : Sup_add ⟨s x, x, rfl⟩ ... = _ : supr_range lemma add_supr {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp [add_comm] lemma supr_add_supr {ι : Sort*} {f g : ι → ℝ≥0∞} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin by_cases hι : nonempty ι, { letI := hι, refine le_antisymm _ (supr_le $ λ a, add_le_add (le_supr _ _) (le_supr _ _)), simpa [add_supr, supr_add] using λ i j:ι, show f i + g j ≤ ⨆ a, f a + g a, from let ⟨k, hk⟩ := h i j in le_supr_of_le k hk }, { have : ∀f:ι → ℝ≥0∞, (⨆i, f i) = 0 := λ f, supr_eq_zero.mpr (λ i, (hι ⟨i⟩).elim), rw [this, this, this, zero_add] } end lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι] {f g : ι → ℝ≥0∞} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ℝ≥0∞} (hf : ∀a, monotone (f a)) : ∑ a in s, supr (f a) = (⨆ n, ∑ a in s, f a n) := begin refine finset.induction_on s _ _, { simp, }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum $ assume a ha, hf a h) } end lemma mul_Sup {s : set ℝ≥0∞} {a : ℝ≥0∞} : a * Sup s = ⨆i∈s, a * i := begin by_cases hs : ∀x∈s, x = (0:ℝ≥0∞), { have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm ▸ le_refl 0), have h₂ : (⨆i ∈ s, a * i) = 0 := (bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]), rw [h₁, h₂, mul_zero] }, { simp only [not_forall] at hs, rcases hs with ⟨x, hx, hx0⟩, have s₁ : Sup s ≠ 0 := pos_iff_ne_zero.1 (lt_of_lt_of_le (pos_iff_ne_zero.2 hx0) (le_Sup hx)), have : Sup ((λb, a * b) '' s) = a * Sup s := is_lub.Sup_eq ((is_lub_Sup s).is_lub_of_tendsto (assume x _ y _ h, mul_le_mul_left' h _) ⟨x, hx⟩ (ennreal.tendsto.const_mul (tendsto_id' inf_le_left) (or.inl s₁))), rw [this.symm, Sup_image] } end lemma mul_supr {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : a * supr f = ⨆i, a * f i := by rw [← Sup_range, mul_Sup, supr_range] lemma supr_mul {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] lemma supr_div {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f / a = ⨆i, f i / a := supr_mul protected lemma tendsto_coe_sub : ∀{b:ℝ≥0∞}, tendsto (λb:ℝ≥0∞, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) := begin refine (forall_ennreal.2 $ and.intro (assume a, _) _), { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm], exact tendsto_const_nhds.sub tendsto_id }, simp, exact (tendsto.congr' (mem_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ι : Sort*} [nonempty ι] {b : ι → ℝ≥0∞} (hr : a < ⊤) : a - (⨆i, b i) = (⨅i, a - b i) := let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb.Inf_eq $ is_lub_supr.is_glb_of_tendsto (assume x _ y _, sub_le_sub (le_refl _)) (range_nonempty _) (ennreal.tendsto_coe_sub.comp (tendsto_id' inf_le_left)), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _ end topological_space section tsum variables {f g : α → ℝ≥0∞} @[norm_cast] protected lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} : has_sum (λa, (f a : ℝ≥0∞)) ↑r ↔ has_sum f r := have (λs:finset α, ∑ a in s, ↑(f a)) = (coe : ℝ≥0 → ℝ≥0∞) ∘ (λs:finset α, ∑ a in s, f a), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold has_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : α → ℝ≥0} (h : has_sum f r) : ∑'a, (f a : ℝ≥0∞) = r := (ennreal.has_sum_coe.2 h).tsum_eq protected lemma coe_tsum {f : α → ℝ≥0} : summable f → ↑(tsum f) = ∑'a, (f a : ℝ≥0∞) | ⟨r, hr⟩ := by rw [hr.tsum_eq, ennreal.tsum_coe_eq hr] protected lemma has_sum : has_sum f (⨆s:finset α, ∑ a in s, f a) := tendsto_at_top_supr $ λ s t, finset.sum_le_sum_of_subset @[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩ lemma tsum_coe_ne_top_iff_summable {f : β → ℝ≥0} : ∑' b, (f b:ℝ≥0∞) ≠ ∞ ↔ summable f := begin refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩, lift (∑' b, (f b:ℝ≥0∞)) to ℝ≥0 using h with a ha, refine ⟨a, ennreal.has_sum_coe.1 _⟩, rw ha, exact ennreal.summable.has_sum end protected lemma tsum_eq_supr_sum : ∑'a, f a = (⨆s:finset α, ∑ a in s, f a) := ennreal.has_sum.tsum_eq protected lemma tsum_eq_supr_sum' {ι : Type*} (s : ι → finset α) (hs : ∀ t, ∃ i, t ⊆ s i) : ∑' a, f a = ⨆ i, ∑ a in s i, f a := begin rw [ennreal.tsum_eq_supr_sum], symmetry, change (⨆i:ι, (λ t : finset α, ∑ a in t, f a) (s i)) = ⨆s:finset α, ∑ a in s, f a, exact (finset.sum_mono_set f).supr_comp_eq hs end protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ℝ≥0∞) : ∑'p:Σa, β a, f p.1 p.2 = ∑'a b, f a b := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ℝ≥0∞) : ∑'p:(Σa, β a), f p = ∑'a b, f ⟨a, b⟩ := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_prod {f : α → β → ℝ≥0∞} : ∑'p:α×β, f p.1 p.2 = ∑'a, ∑'b, f a b := tsum_prod' ennreal.summable $ λ _, ennreal.summable protected lemma tsum_comm {f : α → β → ℝ≥0∞} : ∑'a, ∑'b, f a b = ∑'b, ∑'a, f a b := tsum_comm' ennreal.summable (λ _, ennreal.summable) (λ _, ennreal.summable) protected lemma tsum_add : ∑'a, (f a + g a) = (∑'a, f a) + (∑'a, g a) := tsum_add ennreal.summable ennreal.summable protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : ∑'a, f a ≤ ∑'a, g a := tsum_le_tsum h ennreal.summable ennreal.summable protected lemma sum_le_tsum {f : α → ℝ≥0∞} (s : finset α) : ∑ x in s, f x ≤ ∑' x, f x := sum_le_tsum s (λ x hx, zero_le _) ennreal.summable protected lemma tsum_eq_supr_nat' {f : ℕ → ℝ≥0∞} {N : ℕ → ℕ} (hN : tendsto N at_top at_top) : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range (N i), f a) := ennreal.tsum_eq_supr_sum' _ $ λ t, let ⟨n, hn⟩ := t.exists_nat_subset_range, ⟨k, _, hk⟩ := exists_le_of_tendsto_at_top hN 0 n in ⟨k, finset.subset.trans hn (finset.range_mono hk)⟩ protected lemma tsum_eq_supr_nat {f : ℕ → ℝ≥0∞} : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range i, f a) := ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range protected lemma tsum_eq_liminf_sum_nat {f : ℕ → ℝ≥0∞} : ∑' i, f i = filter.at_top.liminf (λ n, ∑ i in finset.range n, f i) := begin rw [ennreal.tsum_eq_supr_nat, filter.liminf_eq_supr_infi_of_nat], congr, refine funext (λ n, le_antisymm _ _), { refine le_binfi (λ i hi, finset.sum_le_sum_of_subset_of_nonneg _ (λ _ _ _, zero_le _)), simpa only [finset.range_subset, add_le_add_iff_right] using hi, }, { refine le_trans (infi_le _ n) _, simp [le_refl n, le_refl ((finset.range n).sum f)], }, end protected lemma le_tsum (a : α) : f a ≤ ∑'a, f a := le_tsum' ennreal.summable a protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → ∑' a, f a = ∞ | ⟨a, ha⟩ := top_unique $ ha ▸ ennreal.le_tsum a @[simp] protected lemma tsum_top [nonempty α] : ∑' a : α, ∞ = ∞ := let ⟨a⟩ := ‹nonempty α› in ennreal.tsum_eq_top_of_eq_top ⟨a, rfl⟩ lemma tsum_const_eq_top_of_ne_zero {α : Type*} [infinite α] {c : ℝ≥0∞} (hc : c ≠ 0) : (∑' (a : α), c) = ∞ := begin have A : tendsto (λ (n : ℕ), (n : ℝ≥0∞) * c) at_top (𝓝 (∞ * c)), { apply ennreal.tendsto.mul_const tendsto_nat_nhds_top, simp only [true_or, top_ne_zero, ne.def, not_false_iff] }, have B : ∀ (n : ℕ), (n : ℝ≥0∞) * c ≤ (∑' (a : α), c), { assume n, rcases infinite.exists_subset_card_eq α n with ⟨s, hs⟩, simpa [hs] using @ennreal.sum_le_tsum α (λ i, c) s }, simpa [hc] using le_of_tendsto' A B, end protected lemma ne_top_of_tsum_ne_top (h : ∑' a, f a ≠ ∞) (a : α) : f a ≠ ∞ := λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩ protected lemma tsum_mul_left : ∑'i, a * f i = a * ∑'i, f i := if h : ∀i, f i = 0 then by simp [h] else let ⟨i, (hi : f i ≠ 0)⟩ := not_forall.mp h in have sum_ne_0 : ∑'i, f i ≠ 0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≤ ∑'i, f i : ennreal.le_tsum _, have tendsto (λs:finset α, ∑ j in s, a * f j) at_top (𝓝 (a * ∑'i, f i)), by rw [← show (*) a ∘ (λs:finset α, ∑ j in s, f j) = λs, ∑ j in s, a * f j, from funext $ λ s, finset.mul_sum]; exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0), has_sum.tsum_eq this protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a := by simp [mul_comm, ennreal.tsum_mul_left] @[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ℝ≥0∞} : ∑'b:α, (⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc (∑ b in s, ⨆ (h : a = b), f b) ≤ ∑ b in {a}, ⨆ (h : a = b), f b : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl ... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0∞} (r : ℝ≥0∞) : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact ennreal.summable.has_sum }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end lemma tendsto_nat_tsum (f : ℕ → ℝ≥0∞) : tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 (∑' n, f n)) := by { rw ← has_sum_iff_tendsto_nat, exact ennreal.summable.has_sum } lemma to_nnreal_apply_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) (x : α) : (((ennreal.to_nnreal ∘ f) x : ℝ≥0) : ℝ≥0∞) = f x := coe_to_nnreal $ ennreal.ne_top_of_tsum_ne_top hf _ lemma summable_to_nnreal_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) : summable (ennreal.to_nnreal ∘ f) := by simpa only [←tsum_coe_ne_top_iff_summable, to_nnreal_apply_of_tsum_ne_top hf] using hf lemma tendsto_cofinite_zero_of_tsum_ne_top {α} {f : α → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto f cofinite (𝓝 0) := begin have f_ne_top : ∀ n, f n ≠ ∞, from ennreal.ne_top_of_tsum_ne_top hf, have h_f_coe : f = λ n, ((f n).to_nnreal : ennreal), from funext (λ n, (coe_to_nnreal (f_ne_top n)).symm), rw [h_f_coe, ←@coe_zero, tendsto_coe], exact nnreal.tendsto_cofinite_zero_of_summable (summable_to_nnreal_of_tsum_ne_top hf), end lemma tendsto_at_top_zero_of_tsum_ne_top {f : ℕ → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_tsum_ne_top hf } protected lemma tsum_apply {ι α : Type*} {f : ι → α → ℝ≥0∞} {x : α} : (∑' i, f i) x = ∑' i, f i x := tsum_apply $ pi.summable.mpr $ λ _, ennreal.summable lemma tsum_sub {f : ℕ → ℝ≥0∞} {g : ℕ → ℝ≥0∞} (h₁ : ∑' i, g i ≠ ∞) (h₂ : g ≤ f) : ∑' i, (f i - g i) = (∑' i, f i) - (∑' i, g i) := begin have h₃: ∑' i, (f i - g i) = ∑' i, (f i - g i + g i) - ∑' i, g i, { rw [ennreal.tsum_add, add_sub_self h₁]}, have h₄:(λ i, (f i - g i) + (g i)) = f, { ext n, rw ennreal.sub_add_cancel_of_le (h₂ n)}, rw h₄ at h₃, apply h₃, end end tsum lemma tendsto_to_real_iff {ι} {fi : filter ι} {f : ι → ℝ≥0∞} (hf : ∀ i, f i ≠ ∞) {x : ℝ≥0∞} (hx : x ≠ ∞) : fi.tendsto (λ n, (f n).to_real) (𝓝 x.to_real) ↔ fi.tendsto f (𝓝 x) := begin refine ⟨λ h, _, λ h, tendsto.comp (ennreal.tendsto_to_real hx) h⟩, have h_eq : f = (λ n, ennreal.of_real (f n).to_real), by { ext1 n, rw ennreal.of_real_to_real (hf n), }, rw [h_eq, ← ennreal.of_real_to_real hx], exact ennreal.tendsto_of_real h, end lemma tsum_coe_ne_top_iff_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) ≠ ∞ ↔ summable (λ a, (f a : ℝ)) := begin rw nnreal.summable_coe, exact tsum_coe_ne_top_iff_summable, end lemma tsum_coe_eq_top_iff_not_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) = ∞ ↔ ¬ summable (λ a, (f a : ℝ)) := begin rw [← @not_not (∑' a, ↑(f a) = ⊤)], exact not_congr tsum_coe_ne_top_iff_summable_coe end lemma summable_to_real {f : α → ℝ≥0∞} (hsum : ∑' x, f x ≠ ∞) : summable (λ x, (f x).to_real) := begin lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hsum, rwa ennreal.tsum_coe_ne_top_iff_summable_coe at hsum, end end ennreal namespace nnreal open_locale nnreal lemma tsum_eq_to_nnreal_tsum {f : β → ℝ≥0} : (∑' b, f b) = (∑' b, (f b : ℝ≥0∞)).to_nnreal := begin by_cases h : summable f, { rw [← ennreal.coe_tsum h, ennreal.to_nnreal_coe] }, { have A := tsum_eq_zero_of_not_summable h, simp only [← ennreal.tsum_coe_ne_top_iff_summable, not_not] at h, simp only [h, ennreal.top_to_nnreal, A] } end /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma exists_le_has_sum_of_le {f g : β → ℝ≥0} {r : ℝ≥0} (hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p := have ∑'b, (g b : ℝ≥0∞) ≤ r, begin refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩ /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma summable_of_le {f g : β → ℝ≥0} (hgf : ∀b, g b ≤ f b) : summable f → summable g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0} {r : ℝ≥0} : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end lemma not_summable_iff_tendsto_nat_at_top {f : ℕ → ℝ≥0} : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin split, { intros h, refine ((tendsto_of_monotone _).resolve_right h).comp _, exacts [finset.sum_mono_set _, tendsto_finset_range] }, { rintros hnat ⟨r, hr⟩, exact not_tendsto_nhds_of_tendsto_at_top hnat _ (has_sum_iff_tendsto_nat.1 hr) } end lemma summable_iff_not_tendsto_nat_at_top {f : ℕ → ℝ≥0} : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top] lemma summable_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply summable_iff_not_tendsto_nat_at_top.2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := le_of_tendsto' (has_sum_iff_tendsto_nat.1 (summable_of_sum_range_le h).has_sum) h lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ≥0} (hf : summable f) {i : β → α} (hi : function.injective i) : ∑' x, f (i x) ≤ ∑' x, f x := tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_refl _) (summable_comp_injective hf hi) hf lemma summable_sigma {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ≥0} : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := begin split, { simp only [← nnreal.summable_coe, nnreal.coe_tsum], exact λ h, ⟨h.sigma_factor, h.sigma⟩ }, { rintro ⟨h₁, h₂⟩, simpa only [← ennreal.tsum_coe_ne_top_iff_summable, ennreal.tsum_sigma', ennreal.coe_tsum, h₁] using h₂ } end lemma indicator_summable {f : α → ℝ≥0} (hf : summable f) (s : set α) : summable (s.indicator f) := begin refine nnreal.summable_of_le (λ a, le_trans (le_of_eq (s.indicator_apply f a)) _) hf, split_ifs, exact le_refl (f a), exact zero_le_coe, end lemma tsum_indicator_ne_zero {f : α → ℝ≥0} (hf : summable f) {s : set α} (h : ∃ a ∈ s, f a ≠ 0) : ∑' x, (s.indicator f) x ≠ 0 := λ h', let ⟨a, ha, hap⟩ := h in hap (trans (set.indicator_apply_eq_self.mpr (absurd ha)).symm (((tsum_eq_zero_iff (indicator_summable hf s)).1 h') a)) open finset /-- For `f : ℕ → ℝ≥0`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin rw ← tendsto_coe, convert tendsto_sum_nat_add (λ i, (f i : ℝ)), norm_cast, end lemma has_sum_lt {f g : α → ℝ≥0} {sf sg : ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hf : has_sum f sf) (hg : has_sum g sg) : sf < sg := begin have A : ∀ (a : α), (f a : ℝ) ≤ g a := λ a, nnreal.coe_le_coe.2 (h a), have : (sf : ℝ) < sg := has_sum_lt A (nnreal.coe_lt_coe.2 hi) (has_sum_coe.2 hf) (has_sum_coe.2 hg), exact nnreal.coe_lt_coe.1 this end @[mono] lemma has_sum_strict_mono {f g : α → ℝ≥0} {sf sg : ℝ≥0} (hf : has_sum f sf) (hg : has_sum g sg) (h : f < g) : sf < sg := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum {f g : α → ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi (summable_of_le h hg).has_sum hg.has_sum @[mono] lemma tsum_strict_mono {f g : α → ℝ≥0} (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hg lemma tsum_pos {g : α → ℝ≥0} (hg : summable g) (i : α) (hi : 0 < g i) : 0 < ∑' b, g b := by { rw ← tsum_zero, exact tsum_lt_tsum (λ a, zero_le _) hi hg } end nnreal namespace ennreal lemma tsum_to_real_eq {f : α → ℝ≥0∞} (hf : ∀ a, f a ≠ ∞) : (∑' a, f a).to_real = ∑' a, (f a).to_real := begin lift f to α → ℝ≥0 using hf, have : (∑' (a : α), (f a : ℝ≥0∞)).to_real = ((∑' (a : α), (f a : ℝ≥0∞)).to_nnreal : ℝ≥0∞).to_real, { rw [ennreal.coe_to_real], refl }, rw [this, ← nnreal.tsum_eq_to_nnreal_tsum, ennreal.coe_to_real], exact nnreal.coe_tsum end lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0∞) (hf : ∑' i, f i ≠ ∞) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin lift f to ℕ → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf, replace hf : summable f := tsum_coe_ne_top_iff_summable.1 hf, simp only [← ennreal.coe_tsum, nnreal.summable_nat_add _ hf, ← ennreal.coe_zero], exact_mod_cast nnreal.tendsto_sum_nat_add f end end ennreal lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := begin lift f to α → ℝ≥0 using hn, rw nnreal.summable_coe at hf, simpa only [(∘), ← nnreal.coe_tsum] using nnreal.tsum_comp_le_tsum_of_inj hf hi end /-- Comparison test of convergence of series of non-negative real numbers. -/ lemma summable_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g := begin lift f to β → ℝ≥0 using λ b, (hg b).trans (hgf b), lift g to β → ℝ≥0 using hg, rw nnreal.summable_coe at hf ⊢, exact nnreal.summable_of_le (λ b, nnreal.coe_le_coe.1 (hgf b)) hf end /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) : has_sum f r ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin lift f to ℕ → ℝ≥0 using hf, simp only [has_sum, ← nnreal.coe_sum, nnreal.tendsto_coe'], exact exists_congr (λ hr, nnreal.has_sum_iff_tendsto_nat) end lemma ennreal.of_real_tsum_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) : ennreal.of_real (∑' n, f n) = ∑' n, ennreal.of_real (f n) := by simp_rw [ennreal.of_real, ennreal.tsum_coe_eq (nnreal.has_sum_of_real_of_nonneg hf_nonneg hf)] lemma not_summable_iff_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin lift f to ℕ → ℝ≥0 using hf, exact_mod_cast nnreal.not_summable_iff_tendsto_nat_at_top end lemma summable_iff_not_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top_of_nonneg hf] lemma summable_sigma_of_nonneg {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ} (hf : ∀ x, 0 ≤ f x) : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := by { lift f to (Σ x, β x) → ℝ≥0 using hf, exact_mod_cast nnreal.summable_sigma } lemma summable_of_sum_le {ι : Type*} {f : ι → ℝ} {c : ℝ} (hf : 0 ≤ f) (h : ∀ u : finset ι, ∑ x in u, f x ≤ c) : summable f := ⟨ ⨆ u : finset ι, ∑ x in u, f x, tendsto_at_top_csupr (finset.sum_mono_set_of_nonneg hf) ⟨c, λ y ⟨u, hu⟩, hu ▸ h u⟩ ⟩ lemma summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply (summable_iff_not_tendsto_nat_at_top_of_nonneg hf).2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := le_of_tendsto' ((has_sum_iff_tendsto_nat_of_nonneg hf _).1 (summable_of_sum_range_le hf h).has_sum) h /-- If a sequence `f` with non-negative terms is dominated by a sequence `g` with summable series and at least one term of `f` is strictly smaller than the corresponding term in `g`, then the series of `f` is strictly smaller than the series of `g`. -/ lemma tsum_lt_tsum_of_nonneg {i : ℕ} {f g : ℕ → ℝ} (h0 : ∀ (b : ℕ), 0 ≤ f b) (h : ∀ (b : ℕ), f b ≤ g b) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := tsum_lt_tsum h hi (summable_of_nonneg_of_le h0 h hg) hg section variables [emetric_space β] open ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : β} {r : ℝ≥0∞} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ := lt_top_iff_ne_top.1 $ calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≤ ⊤ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : β) (r : ℝ≥0∞) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ℝ≥0∞) (h : x ∈ ball a r) : 𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) := (map_nhds_subtype_coe_eq _ $ is_open.mem_nhds emetric.is_open_ball h).symm end section variable [pseudo_emetric_space α] open emetric lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} : tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) := by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball, @tendsto_order ℝ≥0∞ β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and] /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔ (∃ (b: β → ℝ≥0∞), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ (tendsto b at_top (𝓝 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/ let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, { refine λm n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (𝓝 0), { refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩, rcases exists_between εpos with ⟨δ, δpos, δlt⟩, rcases hs δ δpos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩, have : b n ≤ δ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN p q (le_trans hn hp) (le_trans hn hq)) end, simpa using lt_of_le_of_lt this δlt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, b_lim : tendsto b at_top (𝓝 0)-/ refine emetric.cauchy_seq_iff.2 (λε εpos, _), have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, λm n hm hn, calc edist (s m) (s n) ≤ b N : b_bound m n N hm hn ... < ε : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : α → ℝ≥0∞} (C : ℝ≥0∞) (hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f := begin refine continuous_iff_continuous_at.2 (λx, tendsto_order.2 ⟨_, _⟩), show ∀e, e < f x → ∀ᶠ y in 𝓝 x, e < f y, { assume e he, let ε := min (f x - e) 1, have : ε ≠ ⊤ := ne_top_of_le_ne_top ennreal.coe_ne_top (min_le_right _ _), have : 0 < ε := by simp [ε, hC, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, { simp [C_zero, ‹0 < ε›] }, { calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (‹0 < ε›.ne') (‹ε ≠ ⊤›) }}, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | e < f y}, { rintros y hy, by_cases htop : f y = ⊤, { simp [htop, lt_top_iff_ne_top, ne_top_of_lt he] }, { rw [emetric.mem_ball] at hy, have : e + ε < f y + ε := calc e + ε ≤ e + (f x - e) : add_le_add_left (min_le_left _ _) _ ... = f x : ennreal.add_sub_cancel_of_le he.le ... ≤ f y + C * edist x y : h x y ... = f y + C * edist y x : by simp [edist_comm] ... ≤ f y + C * (C⁻¹ * (ε/2)) : add_le_add_left (mul_le_mul_left' (le_of_lt hy) _) _ ... < f y + ε : ennreal.add_lt_add_left htop I, show e < f y, from lt_of_add_lt_add_right this } }, apply filter.mem_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, show ∀e, f x < e → ∀ᶠ y in 𝓝 x, f y < e, { assume e he, let ε := min (e - f x) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, simp [C_zero, ‹0 < ε›], calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (‹0 < ε›.ne') (‹ε < ⊤›.ne) }, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | f y < e}, { rintros y hy, have htop : f x ≠ ⊤ := ne_top_of_lt he, show f y < e, from calc f y ≤ f x + C * edist y x : h y x ... ≤ f x + C * (C⁻¹ * (ε/2)) : add_le_add_left (mul_le_mul_left' (le_of_lt hy) _) _ ... < f x + ε : ennreal.add_lt_add_left htop I ... ≤ f x + (e - f x) : add_le_add_left (min_le_left _ _) _ ... = e : by simp [le_of_lt he] }, apply filter.mem_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, end theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by norm_num), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc ... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end theorem continuous.edist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) := continuous_edist.comp (hf.prod_mk hg : _) theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) := (continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) : cauchy_seq f := begin lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i), rw ennreal.tsum_coe_ne_top_iff_summable at hd, exact cauchy_seq_of_edist_le_of_summable d hf hd end lemma emetric.is_closed_ball {a : α} {r : ℝ≥0∞} : is_closed (closed_ball a r) := is_closed_le (continuous_id.edist continuous_const) continuous_const @[simp] lemma emetric.diam_closure (s : set α) : diam (closure s) = diam s := begin refine le_antisymm (diam_le $ λ x hx y hy, _) (diam_mono subset_closure), have : edist x y ∈ closure (Iic (diam s)), from map_mem_closure2 (@continuous_edist α _) hx hy (λ _ _, edist_le_diam_of_mem), rwa closure_Iic at this end @[simp] lemma metric.diam_closure {α : Type*} [pseudo_metric_space α] (s : set α) : metric.diam (closure s) = diam s := by simp only [metric.diam, emetric.diam_closure] namespace real /-- For a bounded set `s : set ℝ`, its `emetric.diam` is equal to `Sup s - Inf s` reinterpreted as `ℝ≥0∞`. -/ lemma ediam_eq {s : set ℝ} (h : bounded s) : emetric.diam s = ennreal.of_real (Sup s - Inf s) := begin rcases eq_empty_or_nonempty s with rfl|hne, { simp }, refine le_antisymm (metric.ediam_le_of_forall_dist_le $ λ x hx y hy, _) _, { have := real.subset_Icc_Inf_Sup_of_bounded h, exact real.dist_le_of_mem_Icc (this hx) (this hy) }, { apply ennreal.of_real_le_of_le_to_real, rw [← metric.diam, ← metric.diam_closure], have h' := real.bounded_iff_bdd_below_bdd_above.1 h, calc Sup s - Inf s ≤ dist (Sup s) (Inf s) : le_abs_self _ ... ≤ diam (closure s) : dist_le_diam_of_mem h.closure (cSup_mem_closure hne h'.2) (cInf_mem_closure hne h'.1) } end /-- For a bounded set `s : set ℝ`, its `metric.diam` is equal to `Sup s - Inf s`. -/ lemma diam_eq {s : set ℝ} (h : bounded s) : metric.diam s = Sup s - Inf s := begin rw [metric.diam, real.ediam_eq h, ennreal.to_real_of_real], rw real.bounded_iff_bdd_below_bdd_above at h, exact sub_nonneg.2 (real.Inf_le_Sup s h.1 h.2) end @[simp] lemma ediam_Ioo (a b : ℝ) : emetric.diam (Ioo a b) = ennreal.of_real (b - a) := begin rcases le_or_lt b a with h|h, { simp [h] }, { rw [real.ediam_eq (bounded_Ioo _ _), cSup_Ioo h, cInf_Ioo h] }, end @[simp] lemma ediam_Icc (a b : ℝ) : emetric.diam (Icc a b) = ennreal.of_real (b - a) := begin rcases le_or_lt a b with h|h, { rw [real.ediam_eq (bounded_Icc _ _), cSup_Icc h, cInf_Icc h] }, { simp [h, h.le] } end @[simp] lemma ediam_Ico (a b : ℝ) : emetric.diam (Ico a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ico_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ico_self) @[simp] lemma ediam_Ioc (a b : ℝ) : emetric.diam (Ioc a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ioc_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ioc_self) end real /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.edist ha) (mem_at_top_sets.2 ⟨n, λ m hnm, _⟩), refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _, rw [finset.sum_Ico_eq_sum_range], exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ ∑' m, d m := by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0 end --section
f05c4bd9cd304dc989aa956cac40409107a9cb17
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/polynomial/iterated_deriv.lean
03afd32d12e1a4a6c66240b835b9897897474e5e
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,101
lean
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import data.polynomial.derivative import logic.function.iterate import data.finset.intervals import tactic.ring import tactic.linarith /-! # Theory of iterated derivative We define and prove some lemmas about iterated (formal) derivative for polynomials over a semiring. -/ noncomputable theory open finset nat polynomial open_locale big_operators namespace polynomial universes u variable {R : Type u} section semiring variables [semiring R] (r : R) (f p q : polynomial R) (n k : ℕ) /-- `iterated_deriv f n` is the `n`-th formal derivative of the polynomial `f` -/ def iterated_deriv : polynomial R := derivative ^[n] f @[simp] lemma iterated_deriv_zero_right : iterated_deriv f 0 = f := rfl lemma iterated_deriv_succ : iterated_deriv f (n + 1) = (iterated_deriv f n).derivative := by rw [iterated_deriv, iterated_deriv, function.iterate_succ'] @[simp] lemma iterated_deriv_zero_left : iterated_deriv (0 : polynomial R) n = 0 := begin induction n with n hn, { exact iterated_deriv_zero_right _ }, { rw [iterated_deriv_succ, hn, derivative_zero] }, end @[simp] lemma iterated_deriv_add : iterated_deriv (p + q) n = iterated_deriv p n + iterated_deriv q n := begin induction n with n ih, { simp only [iterated_deriv_zero_right], }, { simp only [iterated_deriv_succ, ih, derivative_add] } end @[simp] lemma iterated_deriv_smul : iterated_deriv (r • p) n = r • iterated_deriv p n := begin induction n with n ih, { simp only [iterated_deriv_zero_right] }, { simp only [iterated_deriv_succ, ih, derivative_smul] } end @[simp] lemma iterated_deriv_X_zero : iterated_deriv (X : polynomial R) 0 = X := by simp only [iterated_deriv_zero_right] @[simp] lemma iterated_deriv_X_one : iterated_deriv (X : polynomial R) 1 = 1 := by simp only [iterated_deriv, derivative_X, function.iterate_one] @[simp] lemma iterated_deriv_X (h : 1 < n) : iterated_deriv (X : polynomial R) n = 0 := begin induction n with n ih, { exfalso, exact not_lt_zero 1 h}, { simp only [iterated_deriv_succ], by_cases H : n = 1, { rw H, simp only [iterated_deriv_X_one, derivative_one] }, { replace h : 1 < n := array.push_back_idx h (ne.symm H), rw ih h, simp only [derivative_zero] } } end @[simp] lemma iterated_deriv_C_zero : iterated_deriv (C r) 0 = C r := by simp only [iterated_deriv_zero_right] @[simp] lemma iterated_deriv_C (h : 0 < n) : iterated_deriv (C r) n = 0 := begin induction n with n ih, { exfalso, exact nat.lt_asymm h h }, { by_cases H : n = 0, { rw [iterated_deriv_succ, H], simp only [iterated_deriv_C_zero, derivative_C]}, { replace h : 0 < n := nat.pos_of_ne_zero H, rw [iterated_deriv_succ, ih h], simp only [derivative_zero] } } end @[simp] lemma iterated_deriv_one_zero : iterated_deriv (1 : polynomial R) 0 = 1 := by simp only [iterated_deriv_zero_right] @[simp] lemma iterated_deriv_one : 0 < n → iterated_deriv (1 : polynomial R) n = 0 := λ h, begin have eq1 : (1 : polynomial R) = C 1 := by simp only [ring_hom.map_one], rw eq1, exact iterated_deriv_C _ _ h, end end semiring section ring variables [ring R] (p q : polynomial R) (n : ℕ) @[simp] lemma iterated_deriv_neg : iterated_deriv (-p) n = - iterated_deriv p n := begin induction n with n ih, { simp only [iterated_deriv_zero_right] }, { simp only [iterated_deriv_succ, ih, derivative_neg] } end @[simp] lemma iterated_deriv_sub : iterated_deriv (p - q) n = iterated_deriv p n - iterated_deriv q n := by rw [sub_eq_add_neg, iterated_deriv_add, iterated_deriv_neg, ←sub_eq_add_neg] end ring section comm_semiring variable [comm_semiring R] variables (f p q : polynomial R) (n k : ℕ) lemma coeff_iterated_deriv_as_prod_Ico : ∀ m : ℕ, (iterated_deriv f k).coeff m = (∏ i in Ico m.succ (m + k.succ), i) * (f.coeff (m+k)) := begin induction k with k ih, { simp only [add_zero, forall_const, one_mul, Ico.self_eq_empty, eq_self_iff_true, iterated_deriv_zero_right, prod_empty] }, { intro m, rw [iterated_deriv_succ, coeff_derivative, ih (m+1), mul_right_comm], apply congr_arg2, { have set_eq : (Ico m.succ (m + k.succ.succ)) = (Ico (m + 1).succ (m + 1 + k.succ)) ∪ {m+1}, { rw [union_comm, ←insert_eq, Ico.insert_succ_bot, add_succ, add_succ, add_succ _ k, ←succ_eq_add_one, succ_add], rw succ_eq_add_one, linarith }, rw [set_eq, prod_union], apply congr_arg2, { refl }, { simp only [prod_singleton], norm_cast }, { simp only [succ_pos', disjoint_singleton, and_true, lt_add_iff_pos_right, not_le, Ico.mem], exact lt_add_one (m + 1) } }, { exact congr_arg _ (succ_add m k) } }, end lemma coeff_iterated_deriv_as_prod_range : ∀ m : ℕ, (iterated_deriv f k).coeff m = f.coeff (m + k) * (∏ i in finset.range k, ↑(m + k - i)) := begin induction k with k ih, { simp }, intro m, calc (f.iterated_deriv k.succ).coeff m = f.coeff (m + k.succ) * (∏ i in finset.range k, ↑(m + k.succ - i)) * (m + 1) : by rw [iterated_deriv_succ, coeff_derivative, ih m.succ, succ_add, add_succ] ... = f.coeff (m + k.succ) * (↑(m + 1) * (∏ (i : ℕ) in range k, ↑(m + k.succ - i))) : by { push_cast, ring } ... = f.coeff (m + k.succ) * (∏ (i : ℕ) in range k.succ, ↑(m + k.succ - i)) : by { rw [prod_range_succ, nat.add_sub_assoc (le_succ k), nat.succ_sub le_rfl, nat.sub_self] } end lemma iterated_deriv_eq_zero_of_nat_degree_lt (h : f.nat_degree < n) : iterated_deriv f n = 0 := begin ext m, rw [coeff_iterated_deriv_as_prod_range, coeff_zero, coeff_eq_zero_of_nat_degree_lt, zero_mul], linarith end lemma iterated_deriv_mul : iterated_deriv (p * q) n = ∑ k in range n.succ, (C (n.choose k : R)) * iterated_deriv p (n - k) * iterated_deriv q k := begin induction n with n IH, { simp }, calc (p * q).iterated_deriv n.succ = (∑ (k : ℕ) in range n.succ, C ↑(n.choose k) * p.iterated_deriv (n - k) * q.iterated_deriv k).derivative : by rw [iterated_deriv_succ, IH] ... = ∑ (k : ℕ) in range n.succ, C ↑(n.choose k) * p.iterated_deriv (n - k + 1) * q.iterated_deriv k + ∑ (k : ℕ) in range n.succ, C ↑(n.choose k) * p.iterated_deriv (n - k) * q.iterated_deriv (k + 1) : by simp_rw [derivative_sum, derivative_mul, derivative_C, zero_mul, zero_add, iterated_deriv_succ, sum_add_distrib] ... = (∑ (k : ℕ) in range n.succ, C ↑(n.choose k.succ) * p.iterated_deriv (n - k) * q.iterated_deriv (k + 1) + C ↑1 * p.iterated_deriv n.succ * q.iterated_deriv 0) + ∑ (k : ℕ) in range n.succ, C ↑(n.choose k) * p.iterated_deriv (n - k) * q.iterated_deriv (k + 1) : _ ... = ∑ (k : ℕ) in range n.succ, C ↑(n.choose k) * p.iterated_deriv (n - k) * q.iterated_deriv (k + 1) + ∑ (k : ℕ) in range n.succ, C ↑(n.choose k.succ) * p.iterated_deriv (n - k) * q.iterated_deriv (k + 1) + C ↑1 * p.iterated_deriv n.succ * q.iterated_deriv 0 : by ring ... = ∑ (i : ℕ) in range n.succ, C ↑((n+1).choose (i+1)) * p.iterated_deriv (n + 1 - (i+1)) * q.iterated_deriv (i+1) + C ↑1 * p.iterated_deriv n.succ * q.iterated_deriv 0 : by simp_rw [choose_succ_succ, succ_sub_succ, cast_add, C.map_add, add_mul, sum_add_distrib] ... = ∑ (k : ℕ) in range n.succ.succ, C ↑(n.succ.choose k) * p.iterated_deriv (n.succ - k) * q.iterated_deriv k : by rw [sum_range_succ' _ n.succ, choose_zero_right, nat.sub_zero], congr, refine (sum_range_succ' _ _).trans (congr_arg2 (+) _ _), { rw [sum_range_succ, nat.choose_succ_self, cast_zero, C.map_zero, zero_mul, zero_mul, zero_add], refine sum_congr rfl (λ k hk, _), rw mem_range at hk, congr, rw [← nat.sub_add_comm (nat.succ_le_of_lt hk), nat.succ_sub_succ] }, { rw [choose_zero_right, nat.sub_zero] }, end end comm_semiring end polynomial
09ed852d9414b01e4c5700b6c193d0559a420ad8
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/set/filter.lean
b763bb08ad6225afbf188602c21abebfacb3178a
[ "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
11,875
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Filters, following Hölzl, Immler, and Huffman, "Type classes and filters for mathematical analysis in Isabelle/HOL". -/ import data.set.function logic.identities algebra.complete_lattice namespace set open classical structure filter (A : Type) := (sets : set (set A)) (univ_mem_sets : univ ∈ sets) (inter_closed : ∀ {a b}, a ∈ sets → b ∈ sets → a ∩ b ∈ sets) (is_mono : ∀ {a b}, a ⊆ b → a ∈ sets → b ∈ sets) attribute filter.sets [coercion] namespace filter -- i.e. set.filter variable {A : Type} variables {P Q : A → Prop} variables {F₁ : filter A} {F₂ : filter A} {F : filter A} definition eventually (P : A → Prop) (F : filter A) : Prop := P ∈ F -- TODO: notation for eventually? -- notation `forallf` binders `∈` F `,` r:(scoped:1 P, P) := eventually r F -- notation `'∀f` binders `∈` F `,` r:(scoped:1 P, P) := eventually r F theorem eventually_true (F : filter A) : eventually (λx, true) F := !filter.univ_mem_sets theorem eventually_of_forall {P : A → Prop} (F : filter A) (H : ∀ x, P x) : eventually P F := by rewrite [eq_univ_of_forall H]; apply eventually_true theorem eventually_mono (H₁ : eventually P F) (H₂ : ∀x, P x → Q x) : eventually Q F := !filter.is_mono H₂ H₁ theorem eventually_and (H₁ : eventually P F) (H₂ : eventually Q F) : eventually (λ x, P x ∧ Q x) F := !filter.inter_closed H₁ H₂ theorem eventually_mp (H₁ : eventually (λx, P x → Q x) F) (H₂ : eventually P F) : eventually Q F := have ∀ x, (P x → Q x) ∧ P x → Q x, from take x, assume H, and.left H (and.right H), eventually_mono (eventually_and H₁ H₂) this theorem eventually_mpr (H₁ : eventually P F) (H₂ : eventually (λx, P x → Q x) F) : eventually Q F := eventually_mp H₂ H₁ variables (P Q F) theorem eventually_and_iff : eventually (λ x, P x ∧ Q x) F ↔ eventually P F ∧ eventually Q F := iff.intro (assume H, and.intro (eventually_mpr H (eventually_of_forall F (take x, and.left))) (eventually_mpr H (eventually_of_forall F (take x, and.right)))) (assume H, eventually_and (and.left H) (and.right H)) variables {P Q F} -- TODO: port eventually_ball_finite_distrib, etc. theorem eventually_choice {B : Type} [nonemptyB : nonempty B] {R : A → B → Prop} {F : filter A} (H : eventually (λ x, ∃ y, R x y) F) : ∃ f, eventually (λ x, R x (f x)) F := let f := λ x, epsilon (λ y, R x y) in exists.intro f (eventually_mono H (take x, suppose ∃ y, R x y, show R x (f x), from epsilon_spec this)) theorem exists_not_of_not_eventually (H : ¬ eventually P F) : ∃ x, ¬ P x := exists_not_of_not_forall (assume H', H (eventually_of_forall F H')) theorem eventually_iff_mp (H₁ : eventually (λ x, P x ↔ Q x) F) (H₂ : eventually P F) : eventually Q F := eventually_mono (eventually_and H₁ H₂) (λ x H, iff.mp (and.left H) (and.right H)) theorem eventually_iff_mpr (H₁ : eventually (λ x, P x ↔ Q x) F) (H₂ : eventually Q F) : eventually P F := eventually_mono (eventually_and H₁ H₂) (λ x H, iff.mpr (and.left H) (and.right H)) theorem eventually_iff_iff (H : eventually (λ x, P x ↔ Q x) F) : eventually P F ↔ eventually Q F := iff.intro (eventually_iff_mp H) (eventually_iff_mpr H) -- TODO: port frequently and properties? /- filters form a lattice under ⊇ -/ protected theorem eq : sets F₁ = sets F₂ → F₁ = F₂ := begin cases F₁ with s₁ u₁ i₁ m₁, cases F₂ with s₂ u₂ i₂ m₂, esimp, intro eqs₁s₂, revert [u₁, i₁, m₁, u₂, i₂, m₂], subst s₁, intros, exact rfl end definition weakens [reducible] (F₁ F₂ : filter A) := F₁ ⊇ F₂ infix `≼`:50 := weakens definition refines [reducible] (F₁ F₂ : filter A) := F₁ ⊆ F₂ infix `≽`:50 := refines theorem weakens.refl (F : filter A) : F ≼ F := subset.refl _ theorem weakens.trans {F₁ F₂ F₃ : filter A} (H₁ : F₁ ≼ F₂) (H₂ : F₂ ≼ F₃) : F₁ ≼ F₃ := subset.trans H₂ H₁ theorem weakens.antisymm (H₁ : F₁ ≼ F₂) (H₂ : F₂ ≼ F₁) : F₁ = F₂ := filter.eq (eq_of_subset_of_subset H₂ H₁) definition bot : filter A := ⦃ filter, sets := univ, univ_mem_sets := trivial, inter_closed := λ a b Ha Hb, trivial, is_mono := λ a b Ha Hsub, trivial ⦄ notation `⊥` := bot definition top : filter A := ⦃ filter, sets := '{univ}, univ_mem_sets := !or.inl rfl, inter_closed := abstract λ a b Ha Hb, by rewrite [*!mem_singleton_iff at *]; substvars; exact !inter_univ end, is_mono := abstract λ a b Hsub Ha, begin rewrite [mem_singleton_iff at Ha], subst [Ha], exact or.inl (eq_univ_of_univ_subset Hsub) end end ⦄ notation `⊤` := top definition sup (F₁ F₂ : filter A) : filter A := ⦃ filter, sets := F₁ ∩ F₂, univ_mem_sets := and.intro (filter.univ_mem_sets F₁) (filter.univ_mem_sets F₂), inter_closed := abstract λ a b Ha Hb, and.intro (filter.inter_closed F₁ (and.left Ha) (and.left Hb)) (filter.inter_closed F₂ (and.right Ha) (and.right Hb)) end, is_mono := abstract λ a b Hsub Ha, and.intro (filter.is_mono F₁ Hsub (and.left Ha)) (filter.is_mono F₂ Hsub (and.right Ha)) end ⦄ infix `⊔`:65 := sup definition inf (F₁ F₂ : filter A) : filter A := ⦃ filter, sets := {r | ∃₀ s ∈ F₁, ∃₀ t ∈ F₂, r ⊇ s ∩ t}, univ_mem_sets := abstract bounded_exists.intro (univ_mem_sets F₁) (bounded_exists.intro (univ_mem_sets F₂) (by rewrite univ_inter; apply subset.refl)) end, inter_closed := abstract λ a b Ha Hb, obtain a₁ [a₁F₁ [a₂ [a₂F₂ (Ha' : a ⊇ a₁ ∩ a₂)]]], from Ha, obtain b₁ [b₁F₁ [b₂ [b₂F₂ (Hb' : b ⊇ b₁ ∩ b₂)]]], from Hb, assert a₁ ∩ b₁ ∩ (a₂ ∩ b₂) = a₁ ∩ a₂ ∩ (b₁ ∩ b₂), by rewrite [*inter_assoc, inter_left_comm b₁], have a ∩ b ⊇ a₁ ∩ b₁ ∩ (a₂ ∩ b₂), begin rewrite this, apply subset_inter, {apply subset.trans, apply inter_subset_left, exact Ha'}, apply subset.trans, apply inter_subset_right, exact Hb' end, bounded_exists.intro (inter_closed F₁ a₁F₁ b₁F₁) (bounded_exists.intro (inter_closed F₂ a₂F₂ b₂F₂) this) end, is_mono := abstract λ a b Hsub Ha, obtain a₁ [a₁F₁ [a₂ [a₂F₂ (Ha' : a ⊇ a₁ ∩ a₂)]]], from Ha, bounded_exists.intro a₁F₁ (bounded_exists.intro a₂F₂ (subset.trans Ha' Hsub)) end ⦄ infix `⊓`:70 := inf definition Sup (S : set (filter A)) : filter A := ⦃ filter, sets := {s | ∀₀ F ∈ S, s ∈ F}, univ_mem_sets := λ F FS, univ_mem_sets F, inter_closed := abstract λ a b Ha Hb F FS, inter_closed F (Ha F FS) (Hb F FS) end, is_mono := abstract λ a b asubb Ha F FS, is_mono F asubb (Ha F FS) end ⦄ prefix `⨆`:65 := Sup definition Inf (S : set (filter A)) : filter A := Sup {F | ∀ G, G ∈ S → G ≽ F} prefix `⨅`:70 := Inf theorem eventually_of_refines (H₁ : eventually P F₁) (H₂ : F₁ ≽ F₂) : eventually P F₂ := H₂ H₁ theorem refines_of_forall (H : ∀ P, eventually P F₁ → eventually P F₂) : F₁ ≽ F₂ := H theorem eventually_bot (P : A → Prop) : eventually P ⊥ := trivial theorem refines_bot (F : filter A) : F ≽ ⊥ := take P, suppose eventually P F, eventually_bot P theorem eventually_top_of_forall (H : ∀ x, P x) : eventually P ⊤ := by rewrite [↑eventually, ↑top, mem_singleton_iff]; exact eq_univ_of_forall H theorem forall_of_eventually_top : eventually P ⊤ → ∀ x, P x := by rewrite [↑eventually, ↑top, mem_singleton_iff]; intro H x; rewrite H; exact trivial theorem eventually_top (P : A → Prop) : eventually P top ↔ ∀ x, P x := iff.intro forall_of_eventually_top eventually_top_of_forall theorem top_refines (F : filter A) : ⊤ ≽ F := take P, suppose eventually P top, eventually_of_forall F (forall_of_eventually_top this) theorem eventually_sup (P : A → Prop) (F₁ F₂ : filter A) : eventually P (sup F₁ F₂) ↔ eventually P F₁ ∧ eventually P F₂ := !iff.refl theorem sup_refines_left (F₁ F₂ : filter A) : F₁ ⊔ F₂ ≽ F₁ := inter_subset_left _ _ theorem sup_refines_right (F₁ F₂ : filter A) : F₁ ⊔ F₂ ≽ F₂ := inter_subset_right _ _ theorem refines_sup (H₁ : F ≽ F₁) (H₂ : F ≽ F₂) : F ≽ F₁ ⊔ F₂ := subset_inter H₁ H₂ theorem refines_inf_left (F₁ F₂ : filter A) : F₁ ≽ F₁ ⊓ F₂ := take s, suppose s ∈ F₁, bounded_exists.intro `s ∈ F₁` (bounded_exists.intro (univ_mem_sets F₂) (by rewrite inter_univ; apply subset.refl)) theorem refines_inf_right (F₁ F₂ : filter A) : F₂ ≽ F₁ ⊓ F₂ := take s, suppose s ∈ F₂, bounded_exists.intro (univ_mem_sets F₁) (bounded_exists.intro `s ∈ F₂` (by rewrite univ_inter; apply subset.refl)) theorem inf_refines (H₁ : F₁ ≽ F) (H₂ : F₂ ≽ F) : F₁ ⊓ F₂ ≽ F := take s : set A, suppose (#set.filter s ∈ F₁ ⊓ F₂), obtain a₁ [a₁F₁ [a₂ [a₂F₂ (Hsub : s ⊇ a₁ ∩ a₂)]]], from this, have a₁ ∈ F, from H₁ a₁F₁, have a₂ ∈ F, from H₂ a₂F₂, show s ∈ F, from is_mono F Hsub (inter_closed F `a₁ ∈ F` `a₂ ∈ F`) theorem refines_Sup {F : filter A} {S : set (filter A)} (H : ∀₀ G ∈ S, F ≽ G) : F ≽ ⨆ S := λ s Fs G GS, H GS Fs theorem Sup_refines {F : filter A} {S : set (filter A)} (FS : F ∈ S) : ⨆ S ≽ F := λ s sInfS, sInfS F FS theorem Inf_refines {F : filter A} {S : set (filter A)} (H : ∀₀ G ∈ S, G ≽ F) : ⨅ S ≽ F := Sup_refines H theorem refines_Inf {F : filter A} {S : set (filter A)} (FS : F ∈ S) : F ≽ ⨅ S := refines_Sup (λ G GS, GS F FS) protected definition complete_lattice_Inf [reducible] [instance] : complete_lattice_Inf (filter A) := ⦃ complete_lattice_Inf, le := weakens, le_refl := weakens.refl, le_trans := @weakens.trans A, le_antisymm := @weakens.antisymm A, -- inf := inf, -- le_inf := @inf_refines A, -- inf_le_left := refines_inf_left, -- inf_le_right := refines_inf_right, -- sup := sup, -- sup_le := @refines_sup A, -- le_sup_left := sup_refines_left, -- le_sup_right := sup_refines_right, Inf := Inf, Inf_le := @refines_Inf A, le_Inf := @Inf_refines A ⦄ -- The previous instance is enough for showing that (filter A) is a complete_lattice example {A : Type} : complete_lattice (filter A) := _ end filter end set
304a79973d4b555591d959a3a6e36ffd825c4cf9
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/unique_factorization_domain.lean
2c17a35d0f8ee68483446d6e7de72e5e5519cf8f
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
48,059
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker, Aaron Anderson -/ import algebra.gcd_monoid import ring_theory.integral_domain import ring_theory.noetherian /-- # Unique factorization ## Main Definitions * `wf_dvd_monoid` holds for `monoid`s for which a strict divisibility relation is well-founded. * `unique_factorization_monoid` holds for `wf_dvd_monoid`s where `irreducible` is equivalent to `prime` ## To do * set up the complete lattice structure on `factor_set`. -/ variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Well-foundedness of the strict version of |, which is equivalent to the descending chain condition on divisibility and to the ascending chain condition on principal ideals in an integral domain. -/ class wf_dvd_monoid (α : Type*) [comm_monoid_with_zero α] : Prop := (well_founded_dvd_not_unit : well_founded (@dvd_not_unit α _)) export wf_dvd_monoid (well_founded_dvd_not_unit) @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring.wf_dvd_monoid [integral_domain α] [is_noetherian_ring α] : wf_dvd_monoid α := ⟨by { convert inv_image.wf (λ a, ideal.span ({a} : set α)) (well_founded_submodule_gt _ _), ext, exact ideal.span_singleton_lt_span_singleton.symm }⟩ namespace wf_dvd_monoid variables [comm_monoid_with_zero α] open associates nat theorem of_wf_dvd_monoid_associates (h : wf_dvd_monoid (associates α)): wf_dvd_monoid α := ⟨begin haveI := h, refine (surjective.well_founded_iff mk_surjective _).2 wf_dvd_monoid.well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ variables [wf_dvd_monoid α] instance wf_dvd_monoid_associates : wf_dvd_monoid (associates α) := ⟨begin refine (surjective.well_founded_iff mk_surjective _).1 wf_dvd_monoid.well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ theorem well_founded_associates : well_founded ((<) : associates α → associates α → Prop) := subrelation.wf (λ x y, dvd_not_unit_of_lt) wf_dvd_monoid.well_founded_dvd_not_unit local attribute [elab_as_eliminator] well_founded.fix lemma exists_irreducible_factor {a : α} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩) (well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma induction_on_irreducible {P : α → Prop} (a : α) (h0 : P 0) (hu : ∀ u : α, is_unit u → P u) (hi : ∀ a i : α, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : α) : a ≠ 0 → ∃f : multiset α, (∀b ∈ f, irreducible b) ∧ associated f.prod a := wf_dvd_monoid.induction_on_irreducible a (λ h, (h rfl).elim) (λ u hu _, ⟨0, ⟨by simp [hu], associated.symm (by simp [hu, associated_one_iff_is_unit])⟩⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i ::ₘ s, ⟨by clear _let_match; finish, by { rw multiset.prod_cons, exact associated_mul_mul (by refl) hs.2 }⟩⟩) end wf_dvd_monoid theorem wf_dvd_monoid.of_well_founded_associates [comm_cancel_monoid_with_zero α] (h : well_founded ((<) : associates α → associates α → Prop)) : wf_dvd_monoid α := wf_dvd_monoid.of_wf_dvd_monoid_associates ⟨by { convert h, ext, exact associates.dvd_not_unit_iff_lt }⟩ theorem wf_dvd_monoid.iff_well_founded_associates [comm_cancel_monoid_with_zero α] : wf_dvd_monoid α ↔ well_founded ((<) : associates α → associates α → Prop) := ⟨by apply wf_dvd_monoid.well_founded_associates, wf_dvd_monoid.of_well_founded_associates⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- unique factorization monoids. These are defined as `comm_cancel_monoid_with_zero`s with well-founded strict divisibility relations, but this is equivalent to more familiar definitions: Each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. Each element (except zero) is non-uniquely represented as a multiset of prime factors. To define a UFD using the definition in terms of multisets of irreducible factors, use the definition `of_exists_unique_irreducible_factors` To define a UFD using the definition in terms of multisets of prime factors, use the definition `of_exists_prime_factors` -/ class unique_factorization_monoid (α : Type*) [comm_cancel_monoid_with_zero α] extends wf_dvd_monoid α : Prop := (irreducible_iff_prime : ∀ {a : α}, irreducible a ↔ prime a) instance ufm_of_gcd_of_wf_dvd_monoid [nontrivial α] [comm_cancel_monoid_with_zero α] [wf_dvd_monoid α] [gcd_monoid α] : unique_factorization_monoid α := { irreducible_iff_prime := λ _, gcd_monoid.irreducible_iff_prime .. ‹wf_dvd_monoid α› } instance associates.ufm [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] : unique_factorization_monoid (associates α) := { irreducible_iff_prime := by { rw ← associates.irreducible_iff_prime_iff, apply unique_factorization_monoid.irreducible_iff_prime, } .. (wf_dvd_monoid.wf_dvd_monoid_associates : wf_dvd_monoid (associates α)) } end prio namespace unique_factorization_monoid variables [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] theorem exists_prime_factors (a : α) : a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a := by { simp_rw ← unique_factorization_monoid.irreducible_iff_prime, apply wf_dvd_monoid.exists_factors a } @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := begin simp_rw ← unique_factorization_monoid.irreducible_iff_prime at h₃, exact wf_dvd_monoid.induction_on_irreducible a h₁ h₂ h₃, end lemma factors_unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).1 (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ (dvd_iff_dvd_of_rel_right hfg).1 (show p ∣ (p ::ₘ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated_mul_left_cancel (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) end unique_factorization_monoid lemma prime_factors_unique [comm_cancel_monoid_with_zero α] : ∀ {f g : multiset α}, (∀ x ∈ f, prime x) → (∀ x ∈ g, prime x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (irreducible_of_prime $ hg x hx).1 (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (hf p (by simp)) (λ q hq, hg _ hq) $ (dvd_iff_dvd_of_rel_right hfg).1 (show p ∣ (p ::ₘ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated_mul_left_cancel (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) /-- If an irreducible has a prime factorization, then it is an associate of one of its prime factors. -/ lemma prime_factors_irreducible [comm_cancel_monoid_with_zero α] {a : α} {f : multiset α} (ha : irreducible a) (pfa : (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) : ∃ p, a ~ᵤ p ∧ f = p ::ₘ 0 := begin haveI := classical.dec_eq α, refine multiset.induction_on f (λ h, (ha.1 (associated_one_iff_is_unit.1 (associated.symm h))).elim) _ pfa.2 pfa.1, rintros p s _ ⟨u, hu⟩ hs, use p, have hs0 : s = 0, { by_contra hs0, obtain ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0, apply (hs q (by simp [hq])).2.1, refine (ha.2 ((p * ↑u) * (s.erase q).prod) _ _).resolve_left _, { rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq, ← hu, mul_comm, mul_comm p _, mul_assoc], simp, }, apply mt is_unit_of_mul_is_unit_left (mt is_unit_of_mul_is_unit_left _), apply (hs p (multiset.mem_cons_self _ _)).2.1 }, simp only [mul_one, multiset.prod_cons, multiset.prod_zero, hs0] at *, exact ⟨associated.symm ⟨u, hu⟩, rfl⟩, end section exists_prime_factors variables [comm_cancel_monoid_with_zero α] variables (pf : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) include pf lemma wf_dvd_monoid.of_exists_prime_factors : wf_dvd_monoid α := ⟨begin classical, apply rel_hom.well_founded (rel_hom.mk _ _) (with_top.well_founded_lt nat.lt_wf), { intro a, by_cases h : a = 0, { exact ⊤ }, exact (classical.some (pf a h)).card }, rintros a b ⟨ane0, ⟨c, hc, b_eq⟩⟩, rw dif_neg ane0, by_cases h : b = 0, { simp [h, lt_top_iff_ne_top] }, rw [dif_neg h, with_top.coe_lt_coe], have cne0 : c ≠ 0, { refine mt (λ con, _) h, rw [b_eq, con, mul_zero] }, calc multiset.card (classical.some (pf a ane0)) < _ + multiset.card (classical.some (pf c cne0)) : lt_add_of_pos_right _ (multiset.card_pos.mpr (λ con, hc (associated_one_iff_is_unit.mp _))) ... = multiset.card (classical.some (pf a ane0) + classical.some (pf c cne0)) : (multiset.card_add _ _).symm ... = multiset.card (classical.some (pf b h)) : multiset.card_eq_card_of_rel (prime_factors_unique _ (classical.some_spec (pf _ h)).1 _), { convert (classical.some_spec (pf c cne0)).2.symm, rw [con, multiset.prod_zero] }, { intros x hadd, rw multiset.mem_add at hadd, cases hadd; apply (classical.some_spec (pf _ _)).1 _ hadd }, { rw multiset.prod_add, transitivity a * c, { apply associated_mul_mul; apply (classical.some_spec (pf _ _)).2 }, { rw ← b_eq, apply (classical.some_spec (pf _ _)).2.symm, } } end⟩ lemma irreducible_iff_prime_of_exists_prime_factors {p : α} : irreducible p ↔ prime p := begin by_cases hp0 : p = 0, { simp [hp0] }, refine ⟨λ h, _, irreducible_of_prime⟩, obtain ⟨f, hf⟩ := pf p hp0, obtain ⟨q, hq, rfl⟩ := prime_factors_irreducible h hf, rw prime_iff_of_associated hq, exact hf.1 q (multiset.mem_cons_self _ _) end theorem unique_factorization_monoid.of_exists_prime_factors : unique_factorization_monoid α := { irreducible_iff_prime := λ _, irreducible_iff_prime_of_exists_prime_factors pf, .. wf_dvd_monoid.of_exists_prime_factors pf } end exists_prime_factors theorem unique_factorization_monoid.iff_exists_prime_factors [comm_cancel_monoid_with_zero α] : unique_factorization_monoid α ↔ (∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) := ⟨λ h, @unique_factorization_monoid.exists_prime_factors _ _ h, unique_factorization_monoid.of_exists_prime_factors⟩ theorem irreducible_iff_prime_of_exists_unique_irreducible_factors [comm_cancel_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a) (uif : ∀ (f g : multiset α), (∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) (p : α) : irreducible p ↔ prime p := ⟨by letI := classical.dec_eq α; exact λ hpi, ⟨hpi.ne_zero, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from left_ne_zero_of_mul hab0, have hb0 : b ≠ 0, from right_ne_zero_of_mul hab0, begin cases eif x hx0 with fx hfx, cases eif a ha0 with fa hfa, cases eif b hb0 with fb hfb, have h : multiset.rel associated (p ::ₘ fx) (fa + fb), { apply uif, { exact λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (hfx.1 _), }, { exact λ i hi, (multiset.mem_add.1 hi).elim (hfa.1 _) (hfb.1 _), }, calc multiset.prod (p ::ₘ fx) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact associated_mul_mul (by refl) hfx.2 ... ~ᵤ (fa).prod * (fb).prod : associated_mul_mul hfa.2.symm hfb.2.symm ... = _ : by rw multiset.prod_add, }, exact let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem h (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right hfa.2).1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right hfb.2).1 (multiset.dvd_prod hqb)) end⟩, irreducible_of_prime⟩ theorem unique_factorization_monoid.of_exists_unique_irreducible_factors [comm_cancel_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a) (uif : ∀ (f g : multiset α), (∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) : unique_factorization_monoid α := unique_factorization_monoid.of_exists_prime_factors (by { convert eif, simp_rw irreducible_iff_prime_of_exists_unique_irreducible_factors eif uif }) namespace unique_factorization_monoid variables [comm_cancel_monoid_with_zero α] [decidable_eq α] [nontrivial α] [normalization_monoid α] variables [unique_factorization_monoid α] /-- Noncomputably determines the multiset of prime factors. -/ noncomputable def factors (a : α) : multiset α := if h : a = 0 then 0 else multiset.map normalize $ classical.some (unique_factorization_monoid.exists_prime_factors a h) theorem factors_prod {a : α} (ane0 : a ≠ 0) : associated (factors a).prod a := begin rw [factors, dif_neg ane0], refine associated.trans _ (classical.some_spec (exists_prime_factors a ane0)).2, rw [← associates.mk_eq_mk_iff_associated, ← associates.prod_mk, ← associates.prod_mk, multiset.map_map], congr' 2, ext, rw [function.comp_apply, associates.mk_normalize], end theorem prime_of_factor {a : α} : ∀ (x : α), x ∈ factors a → prime x := begin rw [factors], split_ifs with ane0, { simp }, intros x hx, rcases multiset.mem_map.1 hx with ⟨y, ⟨hy, rfl⟩⟩, rw prime_iff_of_associated (normalize_associated), exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 y hy, end theorem irreducible_of_factor {a : α} : ∀ (x : α), x ∈ factors a → irreducible x := λ x h, irreducible_of_prime (prime_of_factor x h) theorem normalize_factor {a : α} : ∀ (x : α), x ∈ factors a → normalize x = x := begin rw factors, split_ifs with h, { simp }, intros x hx, obtain ⟨y, hy, rfl⟩ := multiset.mem_map.1 hx, apply normalize_idem end lemma factors_irreducible {a : α} (ha : irreducible a) : factors a = normalize a ::ₘ 0 := begin obtain ⟨p, a_assoc, hp⟩ := prime_factors_irreducible ha ⟨prime_of_factor, factors_prod ha.ne_zero⟩, have p_mem : p ∈ factors a, { rw hp, apply multiset.mem_cons_self }, convert hp, rwa [← normalize_factor p p_mem, normalize_eq_normalize_iff, dvd_dvd_iff_associated] end lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p ::ₘ factors b) (factors a), from factors_unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_of_factor _)) irreducible_of_factor (associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p ::ₘ factors b) : by rw multiset.prod_cons; exact associated_mul_mul (associated.refl _) (associated.symm (factors_prod hb0))), multiset.exists_mem_of_rel_of_mem this (by simp) @[simp] lemma factors_one : factors (1 : α) = 0 := begin rw ← multiset.rel_zero_right, apply factors_unique irreducible_of_factor, { intros x hx, exfalso, apply multiset.not_mem_zero x hx }, { simp [factors_prod one_ne_zero] }, apply_instance end @[simp] lemma factors_mul {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) : factors (x * y) = factors x + factors y := begin have h : (normalize : α → α) = associates.out ∘ associates.mk, { ext, rw [function.comp_apply, associates.out_mk], }, rw [← multiset.map_id' (factors (x * y)), ← multiset.map_id' (factors x), ← multiset.map_id' (factors y), ← multiset.map_congr normalize_factor, ← multiset.map_congr normalize_factor, ← multiset.map_congr normalize_factor, ← multiset.map_add, h, ← multiset.map_map associates.out, eq_comm, ← multiset.map_map associates.out], refine congr rfl _, apply multiset.map_mk_eq_map_mk_of_rel, apply factors_unique, { intros x hx, rcases multiset.mem_add.1 hx with hx | hx; exact irreducible_of_factor x hx }, { exact irreducible_of_factor }, { rw multiset.prod_add, exact associated.trans (associated_mul_mul (factors_prod hx) (factors_prod hy)) (factors_prod (mul_ne_zero hx hy)).symm, } end end unique_factorization_monoid namespace unique_factorization_monoid open_locale classical open multiset associates noncomputable theory variables [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] /-- Noncomputably defines a `normalization_monoid` structure on a `unique_factorization_monoid`. -/ protected def normalization_monoid : normalization_monoid α := normalization_monoid_of_monoid_hom_right_inverse { to_fun := λ a : associates α, if a = 0 then 0 else ((factors a).map (classical.some mk_surjective.has_right_inverse : associates α → α)).prod, map_one' := by simp, map_mul' := λ x y, by { by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, simp [hx, hy] } } begin intro x, dsimp, by_cases hx : x = 0, { simp [hx] }, have h : associates.mk_monoid_hom ∘ (classical.some mk_surjective.has_right_inverse) = (id : associates α → associates α), { ext x, rw [function.comp_apply, mk_monoid_hom_apply, classical.some_spec mk_surjective.has_right_inverse x], refl }, rw [if_neg hx, ← mk_monoid_hom_apply, monoid_hom.map_multiset_prod, map_map, h, map_id, ← associated_iff_eq], apply factors_prod hx end instance : inhabited (normalization_monoid α) := ⟨unique_factorization_monoid.normalization_monoid⟩ end unique_factorization_monoid namespace unique_factorization_monoid variables {R : Type*} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R] lemma no_factors_of_no_prime_factors {a b : R} (ha : a ≠ 0) (h : (∀ {d}, d ∣ a → d ∣ b → ¬ prime d)) : ∀ {d}, d ∣ a → d ∣ b → is_unit d := λ d, induction_on_prime d (by { simp only [zero_dvd_iff], intros, contradiction }) (λ x hx _ _, hx) (λ d q hp hq ih dvd_a dvd_b, absurd hq (h (dvd_of_mul_right_dvd dvd_a) (dvd_of_mul_right_dvd dvd_b))) /-- Euclid's lemma: if `a ∣ b * c` and `a` and `c` have no common prime factors, `a ∣ b`. Compare `is_coprime.dvd_of_dvd_mul_left`. -/ lemma dvd_of_dvd_mul_left_of_no_prime_factors {a b c : R} (ha : a ≠ 0) : (∀ {d}, d ∣ a → d ∣ c → ¬ prime d) → a ∣ b * c → a ∣ b := begin refine induction_on_prime c _ _ _, { intro no_factors, simp only [dvd_zero, mul_zero, forall_prop_of_true], haveI := classical.prop_decidable, exact is_unit_iff_forall_dvd.mp (no_factors_of_no_prime_factors ha @no_factors (dvd_refl a) (dvd_zero a)) _ }, { rintros _ ⟨x, rfl⟩ _ a_dvd_bx, apply units.dvd_mul_right.mp a_dvd_bx }, { intros c p hc hp ih no_factors a_dvd_bpc, apply ih (λ q dvd_a dvd_c hq, no_factors dvd_a (dvd_mul_of_dvd_right dvd_c _) hq), rw mul_left_comm at a_dvd_bpc, refine or.resolve_left (left_dvd_or_dvd_right_of_dvd_prime_mul hp a_dvd_bpc) (λ h, _), exact no_factors h (dvd_mul_right p c) hp } end /-- Euclid's lemma: if `a ∣ b * c` and `a` and `b` have no common prime factors, `a ∣ c`. Compare `is_coprime.dvd_of_dvd_mul_right`. -/ lemma dvd_of_dvd_mul_right_of_no_prime_factors {a b c : R} (ha : a ≠ 0) (no_factors : ∀ {d}, d ∣ a → d ∣ b → ¬ prime d) : a ∣ b * c → a ∣ c := by simpa [mul_comm b c] using dvd_of_dvd_mul_left_of_no_prime_factors ha @no_factors /-- If `a ≠ 0, b` are elements of a unique factorization domain, then dividing out their common factor `c'` gives `a'` and `b'` with no factors in common. -/ lemma exists_reduced_factors : ∀ (a ≠ (0 : R)) b, ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := begin haveI := classical.prop_decidable, intros a, refine induction_on_prime a _ _ _, { intros, contradiction }, { intros a a_unit a_ne_zero b, use [a, b, 1], split, { intros p p_dvd_a _, exact is_unit_of_dvd_unit p_dvd_a a_unit }, { simp } }, { intros a p a_ne_zero p_prime ih_a pa_ne_zero b, by_cases p ∣ b, { rcases h with ⟨b, rfl⟩, obtain ⟨a', b', c', no_factor, ha', hb'⟩ := ih_a a_ne_zero b, refine ⟨a', b', p * c', @no_factor, _, _⟩, { rw [mul_assoc, ha'] }, { rw [mul_assoc, hb'] } }, { obtain ⟨a', b', c', coprime, rfl, rfl⟩ := ih_a a_ne_zero b, refine ⟨p * a', b', c', _, mul_left_comm _ _ _, rfl⟩, intros q q_dvd_pa' q_dvd_b', cases left_dvd_or_dvd_right_of_dvd_prime_mul p_prime q_dvd_pa' with p_dvd_q q_dvd_a', { have : p ∣ c' * b' := dvd_mul_of_dvd_right (dvd_trans p_dvd_q q_dvd_b') _, contradiction }, exact coprime q_dvd_a' q_dvd_b' } } end lemma exists_reduced_factors' (a b : R) (hb : b ≠ 0) : ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := let ⟨b', a', c', no_factor, hb, ha⟩ := exists_reduced_factors b hb a in ⟨a', b', c', λ _ hpb hpa, no_factor hpa hpb, ha, hb⟩ end unique_factorization_monoid namespace associates open unique_factorization_monoid associated multiset variables [comm_cancel_monoid_with_zero α] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `factors` are only unique up to associated elements, while the multisets in `factor_set α` are unqiue by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [comm_cancel_monoid_with_zero α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑(a + b) : factor_set α) = a + b := by norm_cast lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates α)] : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end /-- Evaluates the product of a `factor_set` to be the product of the corresponding multiset, or `0` if there is none. -/ def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map coe).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map coe).prod := rfl @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [← factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _ | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h /-- `bcount p s` is the multiplicity of `p` in the factor_set `s` (with bundled `p`)-/ def bcount [decidable_eq (associates α)] (p : {a : associates α // irreducible a}) : factor_set α → ℕ | none := 0 | (some s) := s.count p variables [dec_irr : Π (p : associates α), decidable (irreducible p)] include dec_irr /-- `count p s` is the multiplicity of the irreducible `p` in the factor_set `s`. If `p` is not irreducible, `count p s` is defined to be `0`. -/ def count [decidable_eq (associates α)] (p : associates α) : factor_set α → ℕ := if hp : irreducible p then bcount ⟨p, hp⟩ else 0 @[simp] lemma count_some [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) (s : multiset _) : count p (some s) = s.count ⟨p, hp⟩:= by { dunfold count, split_ifs, refl } @[simp] lemma count_zero [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) : count p (0 : factor_set α) = 0 := by { dunfold count, split_ifs, refl } lemma count_reducible [decidable_eq (associates α)] {p : associates α} (hp : ¬ irreducible p) : count p = 0 := dif_neg hp omit dec_irr /-- membership in a factor_set (bundled version) -/ def bfactor_set_mem : {a : associates α // irreducible a} → (factor_set α) → Prop | _ ⊤ := true | p (some l) := p ∈ l include dec_irr /-- `factor_set_mem p s` is the predicate that the irreducible `p` is a member of `s : factor_set α`. If `p` is not irreducible, `p` is not a member of any `factor_set`. -/ def factor_set_mem (p : associates α) (s : factor_set α) : Prop := if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false instance : has_mem (associates α) (factor_set α) := ⟨factor_set_mem⟩ @[simp] lemma factor_set_mem_eq_mem (p : associates α) (s : factor_set α) : factor_set_mem p s = (p ∈ s) := rfl lemma mem_factor_set_top {p : associates α} {hp : irreducible p} : p ∈ (⊤ : factor_set α) := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, exact trivial end lemma mem_factor_set_some {p : associates α} {hp : irreducible p} {l : multiset {a : associates α // irreducible a }} : p ∈ (l : factor_set α) ↔ subtype.mk p hp ∈ l := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, refl end lemma reducible_not_mem_factor_set {p : associates α} (hp : ¬ irreducible p) (s : factor_set α) : ¬ p ∈ s := λ (h : if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false), by rwa [dif_neg hp] at h omit dec_irr variable [unique_factorization_monoid α] theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_monoid.factors_unique _ _ _), { exact assume a ha, ((irreducible_mk _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end variables [nontrivial α] [normalization_monoid α] private theorem forall_map_mk_factors_irreducible [decidable_eq α] (x : α) (hx : x ≠ 0) : ∀(a : associates α), a ∈ multiset.map associates.mk (factors x) → irreducible a := begin assume a ha, rcases multiset.mem_map.1 ha with ⟨c, hc, rfl⟩, exact (irreducible_mk c).2 (irreducible_of_factor _ hc) end theorem prod_le_prod_iff_le {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin classical, rintros ⟨⟨c⟩, eqc⟩, have : c ≠ 0, from (mt mk_eq_zero.2 $ assume (hc : quot.mk setoid.r c = 0), have (0 : associates α) ∈ q, from prod_eq_zero_iff.1 $ eqc.symm ▸ hc.symm ▸ mul_zero _, not_irreducible_zero ((irreducible_mk 0).1 $ hq _ this)), have : associates.mk (factors c).prod = quot.mk setoid.r c, from mk_eq_mk_iff_associated.2 (factors_prod this), refine multiset.le_iff_exists_add.2 ⟨(factors c).map associates.mk, unique' hq _ _⟩, { assume x hx, rcases multiset.mem_add.1 hx with h | h, exact hp x h, exact forall_map_mk_factors_irreducible c ‹c ≠ 0› _ h }, { simp [multiset.prod_add, prod_mk, *] at * } end prod_le_prod variables [dec : decidable_eq α] [dec' : decidable_eq (associates α)] include dec /-- This returns the multiset of irreducible factors as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors' (a : α) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk _).2 ha⟩) (irreducible_of_factor) @[simp] theorem map_subtype_coe_factors' {a : α} : (factors' a).map coe = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : a ~ᵤ b) : factors' a = factors' b := have multiset.rel associated (factors a) (factors b), from factors_unique irreducible_of_factor irreducible_of_factor ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), by simpa [(multiset.map_eq_map subtype.coe_injective).symm, rel_associated_iff_map_eq_map.symm] include dec' /-- This returns the multiset of irreducible factors of an associate as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp only [associated_zero_iff_eq_zero] at this, simp only [quotient_mk_eq_mk, this, mk_eq_zero] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong (λ c, ha (mk_eq_zero.2 c)) (λ c, hb (mk_eq_zero.2 c)) hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a := by { classical, apply dif_neg, apply (mt mk_eq_zero.1 h) } theorem prod_factors : ∀(s : factor_set α), s.prod.factors = s | none := by simp [factor_set.prod]; refl | (some s) := begin unfold factor_set.prod, generalize eq_a : (s.map coe).prod = a, rcases a with ⟨a⟩, rw quot_mk_eq_mk at *, have : (s.map (coe : _ → associates α)).prod ≠ 0, from assume ha, let ⟨⟨a, ha⟩, h, eq⟩ := multiset.mem_map.1 (prod_eq_zero_iff.1 ha) in have irreducible (0 : associates α), from eq ▸ ha, not_irreducible_zero ((irreducible_mk _).1 this), have ha : a ≠ 0, by simp [*] at *, suffices : (unique_factorization_monoid.factors a).map associates.mk = s.map coe, { rw [factors_mk a ha], apply congr_arg some _, simpa [(multiset.map_eq_map subtype.coe_injective).symm] }, refine unique' (forall_map_mk_factors_irreducible _ ha) (assume a ha, let ⟨⟨x, hx⟩, ha, eq⟩ := multiset.mem_map.1 ha in eq ▸ hx) _, rw [prod_mk, eq_a, mk_eq_mk_iff_associated], exact factors_prod ha end @[simp] theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this omit dec dec' theorem eq_of_prod_eq_prod {a b : factor_set α} (h : a.prod = b.prod) : a = b := begin classical, have : a.prod.factors = b.prod.factors, by rw h, rwa [prod_factors, prod_factors] at this end include dec dec' @[simp] theorem factors_mul (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right bot_le theorem factors_le {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono omit dec dec' theorem prod_le {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := begin classical, exact iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono end include dec dec' noncomputable instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ noncomputable instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ noncomputable instance : bounded_lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order, .. associates.order_top, .. associates.order_bot } lemma sup_mul_inf (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end include dec_irr lemma dvd_of_mem_factors {a p : associates α} {hp : irreducible p} (hm : p ∈ factors a) : p ∣ a := begin by_cases ha0 : a = 0, { rw ha0, exact dvd_zero p }, obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha0, rw [← associates.factors_prod a], rw [← ha', factors_mk a0 nza] at hm ⊢, erw prod_coe, apply multiset.dvd_prod, apply multiset.mem_map.mpr, exact ⟨⟨p, hp⟩, mem_factor_set_some.mp hm, rfl⟩ end omit dec' lemma dvd_of_mem_factors' {a : α} {p : associates α} {hp : irreducible p} {hz : a ≠ 0} (h_mem : subtype.mk p hp ∈ factors' a) : p ∣ associates.mk a := by { haveI := classical.dec_eq (associates α), apply @dvd_of_mem_factors _ _ _ _ _ _ _ _ _ _ hp, rw factors_mk _ hz, apply mem_factor_set_some.2 h_mem } omit dec_irr lemma mem_factors'_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a := begin obtain ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd ha0 hp hd, apply multiset.mem_pmap.mpr, use q, use hq, exact subtype.eq (eq.symm (mk_eq_mk_iff_associated.mpr hpq)) end include dec_irr lemma mem_factors'_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors', apply ha0 }, { apply mem_factors'_of_dvd ha0 } end include dec' lemma mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : (associates.mk p) ∈ factors (associates.mk a) := begin rw factors_mk _ ha0, exact mem_factor_set_some.mpr (mem_factors'_of_dvd ha0 hp hd) end lemma mem_factors_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : (associates.mk p) ∈ factors (associates.mk a) ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors, exact (irreducible_mk p).mpr hp }, { apply mem_factors_of_dvd ha0 hp } end lemma exists_prime_dvd_of_not_inf_one {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : (associates.mk a) ⊓ (associates.mk b) ≠ 1) : ∃ (p : α), prime p ∧ p ∣ a ∧ p ∣ b := begin have hz : (factors (associates.mk a)) ⊓ (factors (associates.mk b)) ≠ 0, { contrapose! h with hf, change ((factors (associates.mk a)) ⊓ (factors (associates.mk b))).prod = 1, rw hf, exact multiset.prod_zero }, rw [factors_mk a ha, factors_mk b hb, ← with_top.coe_inf] at hz, obtain ⟨⟨p0, p0_irr⟩, p0_mem⟩ := multiset.exists_mem_of_ne_zero ((mt with_top.coe_eq_coe.mpr) hz), rw multiset.inf_eq_inter at p0_mem, obtain ⟨p, rfl⟩ : ∃ p, associates.mk p = p0 := quot.exists_rep p0, refine ⟨p, _, _, _⟩, { rw [← irreducible_iff_prime, ← irreducible_mk], exact p0_irr }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).left, apply ha, }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).right, apply hb } end theorem coprime_iff_inf_one {a b : α} (ha0 : a ≠ 0) (hb0 : b ≠ 0) : (associates.mk a) ⊓ (associates.mk b) = 1 ↔ ∀ {d : α}, d ∣ a → d ∣ b → ¬ prime d := begin split, { intros hg p ha hb hp, refine ((associates.prime_mk _).mpr hp).not_unit (is_unit_of_dvd_one _ _), rw ← hg, exact le_inf (mk_le_mk_of_dvd ha) (mk_le_mk_of_dvd hb) }, { contrapose, intros hg hc, obtain ⟨p, hp, hpa, hpb⟩ := exists_prime_dvd_of_not_inf_one ha0 hb0 hg, exact hc hpa hpb hp } end omit dec_irr theorem factors_prime_pow {p : associates α} (hp : irreducible p) (k : ℕ) : factors (p ^ k) = some (multiset.repeat ⟨p, hp⟩ k) := eq_of_prod_eq_prod (by rw [associates.factors_prod, factor_set.prod, multiset.map_repeat, multiset.prod_repeat, subtype.coe_mk]) include dec_irr theorem prime_pow_dvd_iff_le {m p : associates α} (h₁ : m ≠ 0) (h₂ : irreducible p) {k : ℕ} : p ^ k ≤ m ↔ k ≤ count p m.factors := begin obtain ⟨a, nz, rfl⟩ := associates.exists_non_zero_rep h₁, rw [factors_mk _ nz, ← with_top.some_eq_coe, count_some, multiset.le_count_iff_repeat_le, ← factors_le, factors_prime_pow h₂, factors_mk _ nz], exact with_top.coe_le_coe end theorem le_of_count_ne_zero {m p : associates α} (h0 : m ≠ 0) (hp : irreducible p) : count p m.factors ≠ 0 → p ≤ m := begin rw [← nat.pos_iff_ne_zero], intro h, rw [← pow_one p], apply (prime_pow_dvd_iff_le h0 hp).2, simpa only end theorem count_mul {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) : count p (factors (a * b)) = count p a.factors + count p b.factors := begin obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha, obtain ⟨b0, nzb, hb'⟩ := exists_non_zero_rep hb, rw [factors_mul, ← ha', ← hb', factors_mk a0 nza, factors_mk b0 nzb, ← factor_set.coe_add, ← with_top.some_eq_coe, ← with_top.some_eq_coe, ← with_top.some_eq_coe, count_some hp, multiset.count_add, count_some hp, count_some hp] end theorem count_of_coprime {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {p : associates α} (hp : irreducible p) : count p a.factors = 0 ∨ count p b.factors = 0 := begin rw [or_iff_not_imp_left, ← ne.def], intro hca, contrapose! hab with hcb, exact ⟨p, le_of_count_ne_zero ha hp hca, le_of_count_ne_zero hb hp hcb, (irreducible_iff_prime.mp hp)⟩, end theorem count_mul_of_coprime {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) : count p a.factors = 0 ∨ count p a.factors = count p (a * b).factors := begin cases count_of_coprime ha hb hab hp with hz hb0, { tauto }, apply or.intro_right, rw [count_mul ha hb hp, hb0, add_zero] end theorem count_mul_of_coprime' {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) : count p (a * b).factors = count p a.factors ∨ count p (a * b).factors = count p b.factors := begin rw [count_mul ha hb hp], cases count_of_coprime ha hb hab hp with ha0 hb0, { apply or.intro_right, rw [ha0, zero_add] }, { apply or.intro_left, rw [hb0, add_zero] } end theorem dvd_count_of_dvd_count_mul {a b : associates α} (ha : a ≠ 0) (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (habk : k ∣ count p (a * b).factors) : k ∣ count p a.factors := begin cases count_of_coprime ha hb hab hp with hz h, { rw hz, exact dvd_zero k }, { rw [count_mul ha hb hp, h] at habk, exact habk } end omit dec_irr @[simp] lemma factors_one : factors (1 : associates α) = 0 := begin apply eq_of_prod_eq_prod, rw associates.factors_prod, exact multiset.prod_zero, end @[simp] theorem pow_factors {a : associates α} {k : ℕ} : (a ^ k).factors = k •ℕ a.factors := begin induction k with n h, { rw [zero_nsmul, pow_zero], exact factors_one }, { rw [pow_succ, succ_nsmul, factors_mul, h] } end include dec_irr lemma count_pow {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : count p (a ^ k).factors = k * count p a.factors := begin induction k with n h, { rw [pow_zero, factors_one, zero_mul, count_zero hp] }, { rw [pow_succ, count_mul ha (pow_ne_zero' _ ha) hp, h, nat.succ_eq_add_one], ring } end theorem dvd_count_pow {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : k ∣ count p (a ^ k).factors := by { rw count_pow ha hp, apply dvd_mul_right } theorem is_pow_of_dvd_count {a : associates α} (ha : a ≠ 0) {k : ℕ} (hk : ∀ (p : associates α) (hp : irreducible p), k ∣ count p a.factors) : ∃ (b : associates α), a = b ^ k := begin obtain ⟨a0, hz, rfl⟩ := exists_non_zero_rep ha, rw [factors_mk a0 hz] at hk, have hk' : ∀ (p : {a : associates α // irreducible a}), k ∣ (factors' a0).count p, { intro p, have pp : p = ⟨p.val, p.2⟩, { simp only [subtype.coe_eta, subtype.val_eq_coe] }, rw [pp, ← count_some p.2], exact hk p.val p.2 }, obtain ⟨u, hu⟩ := multiset.exists_smul_of_dvd_count _ hk', use (u : factor_set α).prod, apply eq_of_factors_eq_factors, rw [pow_factors, prod_factors, factors_mk a0 hz, ← with_top.some_eq_coe, hu], exact with_bot.coe_nsmul u k end omit dec omit dec_irr omit dec' theorem eq_pow_of_mul_eq_pow {a b c : associates α} (ha : a ≠ 0) (hb : b ≠ 0) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (h : a * b = c ^ k) : ∃ (d : associates α), a = d ^ k := begin classical, by_cases hk0 : k = 0, { use 1, rw [hk0, pow_zero] at h ⊢, apply (mul_eq_one_iff.1 h).1 }, { refine is_pow_of_dvd_count ha _, intros p hp, apply dvd_count_of_dvd_count_mul ha hb hp hab, rw h, apply dvd_count_pow _ hp, rintros rfl, rw zero_pow' _ hk0 at h, cases mul_eq_zero.mp h; contradiction } end end associates section open associates unique_factorization_monoid /-- `to_gcd_monoid` constructs a GCD monoid out of a normalization on a unique factorization domain. -/ noncomputable def unique_factorization_monoid.to_gcd_monoid (α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] [normalization_monoid α] [decidable_eq (associates α)] [decidable_eq α] : gcd_monoid α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, show (associates.mk a ⊓ associates.mk b).out * (associates.mk a ⊔ associates.mk b).out = normalize (a * b), by rw [← out_mk, ← out_mul, mul_comm, sup_mul_inf]; refl, normalize_gcd := assume a b, by convert normalize_out _, .. ‹normalization_monoid α› } end
f4024761320acab8210b01a020c1e2913d43372b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/liouville/liouville_constant.lean
09f200e7d362daddb2cc83b83ade97907b2fca20
[ "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
8,799
lean
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa, Jujian Zhang -/ import number_theory.liouville.basic /-! # Liouville constants This file contains a construction of a family of Liouville numbers, indexed by a natural number $m$. The most important property is that they are examples of transcendental real numbers. This fact is recorded in `liouville.is_transcendental`. More precisely, for a real number $m$, Liouville's constant is $$ \sum_{i=0}^\infty\frac{1}{m^{i!}}. $$ The series converges only for $1 < m$. However, there is no restriction on $m$, since, if the series does not converge, then the sum of the series is defined to be zero. We prove that, for $m \in \mathbb{N}$ satisfying $2 \le m$, Liouville's constant associated to $m$ is a transcendental number. Classically, the Liouville number for $m = 2$ is the one called ``Liouville's constant''. ## Implementation notes The indexing $m$ is eventually a natural number satisfying $2 ≤ m$. However, we prove the first few lemmas for $m \in \mathbb{R}$. -/ noncomputable theory open_locale nat big_operators open real finset namespace liouville /-- For a real number `m`, Liouville's constant is $$ \sum_{i=0}^\infty\frac{1}{m^{i!}}. $$ The series converges only for `1 < m`. However, there is no restriction on `m`, since, if the series does not converge, then the sum of the series is defined to be zero. -/ def liouville_number (m : ℝ) : ℝ := ∑' (i : ℕ), 1 / m ^ i! /-- `liouville_number_initial_terms` is the sum of the first `k + 1` terms of Liouville's constant, i.e. $$ \sum_{i=0}^k\frac{1}{m^{i!}}. $$ -/ def liouville_number_initial_terms (m : ℝ) (k : ℕ) : ℝ := ∑ i in range (k+1), 1 / m ^ i! /-- `liouville_number_tail` is the sum of the series of the terms in `liouville_number m` starting from `k+1`, i.e $$ \sum_{i=k+1}^\infty\frac{1}{m^{i!}}. $$ -/ def liouville_number_tail (m : ℝ) (k : ℕ) : ℝ := ∑' i, 1 / m ^ (i + (k+1))! lemma liouville_number_tail_pos {m : ℝ} (hm : 1 < m) (k : ℕ) : 0 < liouville_number_tail m k := -- replace `0` with the constantly zero series `∑ i : ℕ, 0` calc (0 : ℝ) = ∑' i : ℕ, 0 : tsum_zero.symm ... < liouville_number_tail m k : -- to show that a series with non-negative terms has strictly positive sum it suffices -- to prove that tsum_lt_tsum_of_nonneg -- 1. the terms of the zero series are indeed non-negative (λ _, rfl.le) -- 2. the terms of our series are non-negative (λ i, one_div_nonneg.mpr (pow_nonneg (zero_le_one.trans hm.le) _)) -- 3. one term of our series is strictly positive -- they all are, we use the first term (one_div_pos.mpr (pow_pos (zero_lt_one.trans hm) (0 + (k + 1))!)) $ -- 4. our series converges -- it does since it is the tail of a converging series, though -- this is not the argument here. summable_one_div_pow_of_le hm (λ i, trans le_self_add (nat.self_le_factorial _)) /-- Split the sum definining a Liouville number into the first `k` term and the rest. -/ lemma liouville_number_eq_initial_terms_add_tail {m : ℝ} (hm : 1 < m) (k : ℕ) : liouville_number m = liouville_number_initial_terms m k + liouville_number_tail m k := (sum_add_tsum_nat_add _ (summable_one_div_pow_of_le hm (λ i, i.self_le_factorial))).symm /-! We now prove two useful inequalities, before collecting everything together. -/ /-- Partial inequality, works with `m ∈ ℝ` satisfying `1 < m`. -/ lemma tsum_one_div_pow_factorial_lt (n : ℕ) {m : ℝ} (m1 : 1 < m) : ∑' (i : ℕ), 1 / m ^ (i + (n + 1))! < (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) := -- two useful inequalities have m0 : 0 < m := (zero_lt_one.trans m1), have mi : |1 / m| < 1 := (le_of_eq (abs_of_pos (one_div_pos.mpr m0))).trans_lt ((div_lt_one m0).mpr m1), calc (∑' i, 1 / m ^ (i + (n + 1))!) < ∑' i, 1 / m ^ (i + (n + 1)!) : -- to show the strict inequality between these series, we prove that: tsum_lt_tsum_of_nonneg -- 1. the first series has non-negative terms (λ b, one_div_nonneg.mpr (pow_nonneg m0.le _)) -- 2. the second series dominates the first (λ b, one_div_pow_le_one_div_pow_of_le m1.le (b.add_factorial_succ_le_factorial_add_succ n)) -- 3. the term with index `i = 2` of the first series is strictly smaller than -- the corresponding term of the second series (one_div_pow_strict_anti m1 (n.add_factorial_succ_lt_factorial_add_succ rfl.le)) -- 4. the second series is summable, since its terms grow quickly (summable_one_div_pow_of_le m1 (λ j, nat.le.intro rfl)) ... = ∑' i, (1 / m) ^ i * (1 / m ^ (n + 1)!) : -- split the sum in the exponent and massage by { congr, ext i, rw [pow_add, ← div_div, div_eq_mul_one_div, one_div_pow] } -- factor the constant `(1 / m ^ (n + 1)!)` out of the series ... = (∑' i, (1 / m) ^ i) * (1 / m ^ (n + 1)!) : tsum_mul_right ... = (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) : -- the series if the geometric series mul_eq_mul_right_iff.mpr (or.inl (tsum_geometric_of_abs_lt_1 mi)) lemma aux_calc (n : ℕ) {m : ℝ} (hm : 2 ≤ m) : (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) ≤ 1 / (m ^ n!) ^ n := calc (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) ≤ 2 * (1 / m ^ (n + 1)!) : -- the second factors coincide (and are non-negative), -- the first factors, satisfy the inequality `sub_one_div_inv_le_two` mul_mono_nonneg (one_div_nonneg.mpr (pow_nonneg (zero_le_two.trans hm) _)) (sub_one_div_inv_le_two hm) ... = 2 / m ^ (n + 1)! : mul_one_div 2 _ ... = 2 / m ^ (n! * (n + 1)) : congr_arg ((/) 2) (congr_arg (pow m) (mul_comm _ _)) ... ≤ 1 / m ^ (n! * n) : begin -- [ NB: in this block, I do not follow the brace convention for subgoals -- I wait until -- I solve all extraneous goals at once with `exact pow_pos (zero_lt_two.trans_le hm) _`. ] -- Clear denominators and massage* apply (div_le_div_iff _ _).mpr, conv_rhs { rw [one_mul, mul_add, pow_add, mul_one, pow_mul, mul_comm, ← pow_mul] }, -- the second factors coincide, so we prove the inequality of the first factors* refine (mul_le_mul_right _).mpr _, -- solve all the inequalities `0 < m ^ ??` any_goals { exact pow_pos (zero_lt_two.trans_le hm) _ }, -- `2 ≤ m ^ n!` is a consequence of monotonicity of exponentiation at `2 ≤ m`. exact trans (trans hm (pow_one _).symm.le) (pow_mono (one_le_two.trans hm) n.factorial_pos) end ... = 1 / (m ^ n!) ^ n : congr_arg ((/) 1) (pow_mul m n! n) /-! Starting from here, we specialize to the case in which `m` is a natural number. -/ /-- The sum of the `k` initial terms of the Liouville number to base `m` is a ratio of natural numbers where the denominator is `m ^ k!`. -/ lemma liouville_number_rat_initial_terms {m : ℕ} (hm : 0 < m) (k : ℕ) : ∃ p : ℕ, liouville_number_initial_terms m k = p / m ^ k! := begin induction k with k h, { exact ⟨1, by rw [liouville_number_initial_terms, range_one, sum_singleton, nat.cast_one]⟩ }, { rcases h with ⟨p_k, h_k⟩, use p_k * (m ^ ((k + 1)! - k!)) + 1, unfold liouville_number_initial_terms at h_k ⊢, rw [sum_range_succ, h_k, div_add_div, div_eq_div_iff, add_mul], { norm_cast, rw [add_mul, one_mul, nat.factorial_succ, show k.succ * k! - k! = (k.succ - 1) * k!, by rw [tsub_mul, one_mul], nat.succ_sub_one, add_mul, one_mul, pow_add], simp [mul_assoc] }, refine mul_ne_zero_iff.mpr ⟨_, _⟩, all_goals { exact pow_ne_zero _ (nat.cast_ne_zero.mpr hm.ne.symm) } } end theorem is_liouville {m : ℕ} (hm : 2 ≤ m) : liouville (liouville_number m) := begin -- two useful inequalities have mZ1 : 1 < (m : ℤ), { norm_cast, exact one_lt_two.trans_le hm }, have m1 : 1 < (m : ℝ), { norm_cast, exact one_lt_two.trans_le hm }, intro n, -- the first `n` terms sum to `p / m ^ k!` rcases liouville_number_rat_initial_terms (zero_lt_two.trans_le hm) n with ⟨p, hp⟩, refine ⟨p, m ^ n!, one_lt_pow mZ1 n.factorial_ne_zero, _⟩, push_cast, -- separate out the sum of the first `n` terms and the rest rw [liouville_number_eq_initial_terms_add_tail m1 n, ← hp, add_sub_cancel', abs_of_nonneg (liouville_number_tail_pos m1 _).le], exact ⟨((lt_add_iff_pos_right _).mpr (liouville_number_tail_pos m1 n)).ne.symm, (tsum_one_div_pow_factorial_lt n m1).trans_le (aux_calc _ (nat.cast_two.symm.le.trans (nat.cast_le.mpr hm)))⟩ end /- Placing this lemma outside of the `open/closed liouville`-namespace would allow to remove `_root_.`, at the cost of some other small weirdness. -/ lemma is_transcendental {m : ℕ} (hm : 2 ≤ m) : _root_.transcendental ℤ (liouville_number m) := transcendental (is_liouville hm) end liouville
bc518ff1a51e7a523d440ff62a9061555ffebea6
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebraic_geometry/projective_spectrum/scheme.lean
2137c7ae90ad3b03b284cfff3e8b6fa967ba5cce
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
14,901
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import algebraic_geometry.projective_spectrum.structure_sheaf import algebraic_geometry.Spec /-! # Proj as a scheme This file is to prove that `Proj` is a scheme. ## Notation * `Proj` : `Proj` as a locally ringed space * `Proj.T` : the underlying topological space of `Proj` * `Proj| U` : `Proj` restricted to some open set `U` * `Proj.T| U` : the underlying topological space of `Proj` restricted to open set `U` * `pbo f` : basic open set at `f` in `Proj` * `Spec` : `Spec` as a locally ringed space * `Spec.T` : the underlying topological space of `Spec` * `sbo g` : basic open set at `g` in `Spec` * `A⁰_x` : the degree zero part of localized ring `Aₓ` ## Implementation In `src/algebraic_geometry/projective_spectrum/structure_sheaf.lean`, we have given `Proj` a structure sheaf so that `Proj` is a locally ringed space. In this file we will prove that `Proj` equipped with this structure sheaf is a scheme. We achieve this by using an affine cover by basic open sets in `Proj`, more specifically: 1. We prove that `Proj` can be covered by basic open sets at homogeneous element of positive degree. 2. We prove that for any `f : A`, `Proj.T | (pbo f)` is homeomorphic to `Spec.T A⁰_f`: - forward direction : for any `x : pbo f`, i.e. a relevant homogeneous prime ideal `x`, send it to `x ∩ span {g / 1 | g ∈ A}` (see `Top_component.forward.carrier`). This ideal is prime, the proof is in `Top_component.forward.to_fun`. The fact that this function is continuous is found in `Top_component.forward` - backward direction : TBC ## Main Definitions and Statements * `degree_zero_part`: the degree zero part of the localized ring `Aₓ` where `x` is a homogeneous element of degree `n` is the subring of elements of the form `a/f^m` where `a` has degree `mn`. For a homogeneous element `f` of degree `n` * `Top_component.forward`: `forward f` is the continuous map between `Proj.T| pbo f` and `Spec.T A⁰_f` * `Top_component.forward.preimage_eq`: for any `a: A`, if `a/f^m` has degree zero, then the preimage of `sbo a/f^m` under `forward f` is `pbo f ∩ pbo a`. * [Robin Hartshorne, *Algebraic Geometry*][Har77]: Chapter II.2 Proposition 2.5 -/ noncomputable theory namespace algebraic_geometry open_locale direct_sum big_operators pointwise big_operators open direct_sum set_like.graded_monoid localization finset (hiding mk_zero) variables {R A : Type*} variables [comm_ring R] [comm_ring A] [algebra R A] variables (𝒜 : ℕ → submodule R A) variables [graded_algebra 𝒜] open Top topological_space open category_theory opposite open projective_spectrum.structure_sheaf local notation `Proj` := Proj.to_LocallyRingedSpace 𝒜 -- `Proj` as a locally ringed space local notation `Proj.T` := Proj .1.1.1 -- the underlying topological space of `Proj` local notation `Proj| ` U := Proj .restrict (opens.open_embedding (U : opens Proj.T)) -- `Proj` restrict to some open set local notation `Proj.T| ` U := (Proj .restrict (opens.open_embedding (U : opens Proj.T))).to_SheafedSpace.to_PresheafedSpace.1 -- the underlying topological space of `Proj` restricted to some open set local notation `pbo` x := projective_spectrum.basic_open 𝒜 x -- basic open sets in `Proj` local notation `sbo` f := prime_spectrum.basic_open f -- basic open sets in `Spec` local notation `Spec` ring := Spec.LocallyRingedSpace_obj (CommRing.of ring) -- `Spec` as a locally ringed space local notation `Spec.T` ring := (Spec.LocallyRingedSpace_obj (CommRing.of ring)).to_SheafedSpace.to_PresheafedSpace.1 -- the underlying topological space of `Spec` section variable {𝒜} /-- The degree zero part of the localized ring `Aₓ` is the subring of elements of the form `a/x^n` such that `a` and `x^n` have the same degree. -/ def degree_zero_part {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) : subring (away f) := { carrier := { y | ∃ (n : ℕ) (a : 𝒜 (m * n)), y = mk a.1 ⟨f^n, ⟨n, rfl⟩⟩ }, mul_mem' := λ _ _ ⟨n, ⟨a, h⟩⟩ ⟨n', ⟨b, h'⟩⟩, h.symm ▸ h'.symm ▸ ⟨n+n', ⟨⟨a.1 * b.1, (mul_add m n n').symm ▸ mul_mem a.2 b.2⟩, by {rw mk_mul, congr' 1, simp only [pow_add], refl }⟩⟩, one_mem' := ⟨0, ⟨1, (mul_zero m).symm ▸ one_mem⟩, by { symmetry, convert ← mk_self 1, simp only [pow_zero], refl, }⟩, add_mem' := λ _ _ ⟨n, ⟨a, h⟩⟩ ⟨n', ⟨b, h'⟩⟩, h.symm ▸ h'.symm ▸ ⟨n+n', ⟨⟨f ^ n * b.1 + f ^ n' * a.1, (mul_add m n n').symm ▸ add_mem (mul_mem (by { rw mul_comm, exact set_like.graded_monoid.pow_mem n f_deg }) b.2) begin rw add_comm, refine mul_mem _ a.2, rw mul_comm, exact set_like.graded_monoid.pow_mem _ f_deg end⟩, begin rw add_mk, congr' 1, simp only [pow_add], refl, end⟩⟩, zero_mem' := ⟨0, ⟨0, (mk_zero _).symm⟩⟩, neg_mem' := λ x ⟨n, ⟨a, h⟩⟩, h.symm ▸ ⟨n, ⟨-a, neg_mk _ _⟩⟩ } end local notation `A⁰_` f_deg := degree_zero_part f_deg section variable {𝒜} instance (f : A) {m : ℕ} (f_deg : f ∈ 𝒜 m) : comm_ring (A⁰_ f_deg) := (degree_zero_part f_deg).to_comm_ring /-- Every element in the degree zero part of `Aₓ` can be written as `a/x^n` for some `a` and `n : ℕ`, `degree_zero_part.deg` picks this natural number `n` -/ def degree_zero_part.deg {f : A} {m : ℕ} {f_deg : f ∈ 𝒜 m} (x : A⁰_ f_deg) : ℕ := x.2.some /-- Every element in the degree zero part of `Aₓ` can be written as `a/x^n` for some `a` and `n : ℕ`, `degree_zero_part.deg` picks the numerator `a` -/ def degree_zero_part.num {f : A} {m : ℕ} {f_deg : f ∈ 𝒜 m} (x : A⁰_ f_deg) : A := x.2.some_spec.some.1 lemma degree_zero_part.num_mem {f : A} {m : ℕ} {f_deg : f ∈ 𝒜 m} (x : A⁰_ f_deg) : degree_zero_part.num x ∈ 𝒜 (m * degree_zero_part.deg x) := x.2.some_spec.some.2 lemma degree_zero_part.eq {f : A} {m : ℕ} {f_deg : f ∈ 𝒜 m} (x : A⁰_ f_deg) : (x : away f) = mk (degree_zero_part.num x) ⟨f^(degree_zero_part.deg x), ⟨_, rfl⟩⟩ := x.2.some_spec.some_spec lemma degree_zero_part.coe_mul {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (x y : A⁰_ f_deg) : (↑(x * y) : away f) = x * y := rfl end namespace Proj_iso_Spec_Top_component /- This section is to construct the homeomorphism between `Proj` restricted at basic open set at a homogeneous element `x` and `Spec A⁰ₓ` where `A⁰ₓ` is the degree zero part of the localized ring `Aₓ`. -/ namespace to_Spec open ideal -- This section is to construct the forward direction : -- So for any `x` in `Proj| (pbo f)`, we need some point in `Spec A⁰_f`, i.e. a prime ideal, -- and we need this correspondence to be continuous in their Zariski topology. variables {𝒜} {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (x : Proj| (pbo f)) /--For any `x` in `Proj| (pbo f)`, the corresponding ideal in `Spec A⁰_f`. This fact that this ideal is prime is proven in `Top_component.forward.to_fun`-/ def carrier : ideal (A⁰_ f_deg) := ideal.comap (algebra_map (A⁰_ f_deg) (away f)) (ideal.span $ algebra_map A (away f) '' x.1.as_homogeneous_ideal) lemma mem_carrier_iff (z : A⁰_ f_deg) : z ∈ carrier f_deg x ↔ ↑z ∈ ideal.span (algebra_map A (away f) '' x.1.as_homogeneous_ideal) := iff.rfl lemma mem_carrier.clear_denominator [decidable_eq (away f)] {z : A⁰_ f_deg} (hz : z ∈ carrier f_deg x) : ∃ (c : algebra_map A (away f) '' x.1.as_homogeneous_ideal →₀ away f) (N : ℕ) (acd : Π y ∈ c.support.image c, A), f ^ N • ↑z = algebra_map A (away f) (∑ i in c.support.attach, acd (c i) (finset.mem_image.mpr ⟨i, ⟨i.2, rfl⟩⟩) * classical.some i.1.2) := begin rw [mem_carrier_iff, ←submodule_span_eq, finsupp.span_eq_range_total, linear_map.mem_range] at hz, rcases hz with ⟨c, eq1⟩, rw [finsupp.total_apply, finsupp.sum] at eq1, obtain ⟨⟨_, N, rfl⟩, hN⟩ := is_localization.exist_integer_multiples_of_finset (submonoid.powers f) (c.support.image c), choose acd hacd using hN, have prop1 : ∀ i, i ∈ c.support → c i ∈ finset.image c c.support, { intros i hi, rw finset.mem_image, refine ⟨_, hi, rfl⟩, }, refine ⟨c, N, acd, _⟩, rw [← eq1, smul_sum, map_sum, ← sum_attach], congr' 1, ext i, rw [_root_.map_mul, hacd, (classical.some_spec i.1.2).2, smul_eq_mul, smul_mul_assoc], refl end lemma disjoint : (disjoint (x.1.as_homogeneous_ideal.to_ideal : set A) (submonoid.powers f : set A)) := begin by_contra rid, rw [set.not_disjoint_iff] at rid, choose g hg using rid, obtain ⟨hg1, ⟨k, rfl⟩⟩ := hg, by_cases k_ineq : 0 < k, { erw x.1.is_prime.pow_mem_iff_mem _ k_ineq at hg1, exact x.2 hg1 }, { erw [show k = 0, by linarith, pow_zero, ←ideal.eq_top_iff_one] at hg1, apply x.1.is_prime.1, exact hg1 }, end lemma carrier_ne_top : carrier f_deg x ≠ ⊤ := begin have eq_top := disjoint x, classical, contrapose! eq_top, obtain ⟨c, N, acd, eq1⟩ := mem_carrier.clear_denominator _ x ((ideal.eq_top_iff_one _).mp eq_top), rw [algebra.smul_def, subring.coe_one, mul_one] at eq1, change localization.mk (f ^ N) 1 = mk (∑ _, _) 1 at eq1, simp only [mk_eq_mk', is_localization.eq] at eq1, rcases eq1 with ⟨⟨_, ⟨M, rfl⟩⟩, eq1⟩, erw [mul_one, mul_one] at eq1, change f^_ * f^_ = _ * f^_ at eq1, rw set.not_disjoint_iff_nonempty_inter, refine ⟨f^N * f^M, eq1.symm ▸ mul_mem_right _ _ (sum_mem _ (λ i hi, mul_mem_left _ _ _)), ⟨N+M, by rw pow_add⟩⟩, generalize_proofs h, exact (classical.some_spec h).1, end /--The function between the basic open set `D(f)` in `Proj` to the corresponding basic open set in `Spec A⁰_f`. This is bundled into a continuous map in `Top_component.forward`. -/ def to_fun (x : Proj.T| (pbo f)) : (Spec.T (A⁰_ f_deg)) := ⟨carrier f_deg x, carrier_ne_top f_deg x, λ x1 x2 hx12, begin classical, rcases ⟨x1, x2⟩ with ⟨⟨x1, hx1⟩, ⟨x2, hx2⟩⟩, induction x1 using localization.induction_on with data_x1, induction x2 using localization.induction_on with data_x2, rcases ⟨data_x1, data_x2⟩ with ⟨⟨a1, _, ⟨n1, rfl⟩⟩, ⟨a2, _, ⟨n2, rfl⟩⟩⟩, rcases mem_carrier.clear_denominator f_deg x hx12 with ⟨c, N, acd, eq1⟩, simp only [degree_zero_part.coe_mul, algebra.smul_def] at eq1, change localization.mk (f ^ N) 1 * (mk _ _ * mk _ _) = mk (∑ _, _) _ at eq1, simp only [localization.mk_mul, one_mul] at eq1, simp only [mk_eq_mk', is_localization.eq] at eq1, rcases eq1 with ⟨⟨_, ⟨M, rfl⟩⟩, eq1⟩, rw [submonoid.coe_one, mul_one] at eq1, change _ * _ * f^_ = _ * (f^_ * f^_) * f^_ at eq1, rcases x.1.is_prime.mem_or_mem (show a1 * a2 * f ^ N * f ^ M ∈ _, from _) with h1|rid2, rcases x.1.is_prime.mem_or_mem h1 with h1|rid1, rcases x.1.is_prime.mem_or_mem h1 with h1|h2, { left, rw mem_carrier_iff, simp only [show (mk a1 ⟨f ^ n1, _⟩ : away f) = mk a1 1 * mk 1 ⟨f^n1, ⟨n1, rfl⟩⟩, by rw [localization.mk_mul, mul_one, one_mul]], exact ideal.mul_mem_right _ _ (ideal.subset_span ⟨_, h1, rfl⟩), }, { right, rw mem_carrier_iff, simp only [show (mk a2 ⟨f ^ n2, _⟩ : away f) = mk a2 1 * mk 1 ⟨f^n2, ⟨n2, rfl⟩⟩, by rw [localization.mk_mul, mul_one, one_mul]], exact ideal.mul_mem_right _ _ (ideal.subset_span ⟨_, h2, rfl⟩), }, { exact false.elim (x.2 (x.1.is_prime.mem_of_pow_mem N rid1)), }, { exact false.elim (x.2 (x.1.is_prime.mem_of_pow_mem M rid2)), }, { rw [mul_comm _ (f^N), eq1], refine mul_mem_right _ _ (mul_mem_right _ _ (sum_mem _ (λ i hi, mul_mem_left _ _ _))), generalize_proofs h, exact (classical.some_spec h).1 }, end⟩ /- The preimage of basic open set `D(a/f^n)` in `Spec A⁰_f` under the forward map from `Proj A` to `Spec A⁰_f` is the basic open set `D(a) ∩ D(f)` in `Proj A`. This lemma is used to prove that the forward map is continuous. -/ lemma preimage_eq (a : A) (n : ℕ) (a_mem_degree_zero : (mk a ⟨f ^ n, ⟨n, rfl⟩⟩ : away f) ∈ A⁰_ f_deg) : to_fun 𝒜 f_deg ⁻¹' ((sbo (⟨mk a ⟨f ^ n, ⟨_, rfl⟩⟩, a_mem_degree_zero⟩ : A⁰_ f_deg)) : set (prime_spectrum {x // x ∈ A⁰_ f_deg})) = {x | x.1 ∈ (pbo f) ⊓ (pbo a)} := begin classical, ext1 y, split; intros hy, { refine ⟨y.2, _⟩, rw [set.mem_preimage, opens.mem_coe, prime_spectrum.mem_basic_open] at hy, rw projective_spectrum.mem_coe_basic_open, intro a_mem_y, apply hy, rw [to_fun, mem_carrier_iff], simp only [show (mk a ⟨f^n, ⟨_, rfl⟩⟩ : away f) = mk 1 ⟨f^n, ⟨_, rfl⟩⟩ * mk a 1, by rw [mk_mul, one_mul, mul_one]], exact ideal.mul_mem_left _ _ (ideal.subset_span ⟨_, a_mem_y, rfl⟩), }, { change y.1 ∈ _ at hy, rcases hy with ⟨hy1, hy2⟩, rw projective_spectrum.mem_coe_basic_open at hy1 hy2, rw [set.mem_preimage, to_fun, opens.mem_coe, prime_spectrum.mem_basic_open], intro rid, rcases mem_carrier.clear_denominator f_deg _ rid with ⟨c, N, acd, eq1⟩, rw [algebra.smul_def] at eq1, change localization.mk (f^N) 1 * mk _ _ = mk (∑ _, _) _ at eq1, rw [mk_mul, one_mul, mk_eq_mk', is_localization.eq] at eq1, rcases eq1 with ⟨⟨_, ⟨M, rfl⟩⟩, eq1⟩, rw [submonoid.coe_one, mul_one] at eq1, simp only [subtype.coe_mk] at eq1, rcases y.1.is_prime.mem_or_mem (show a * f ^ N * f ^ M ∈ _, from _) with H1 | H3, rcases y.1.is_prime.mem_or_mem H1 with H1 | H2, { exact hy2 H1, }, { exact y.2 (y.1.is_prime.mem_of_pow_mem N H2), }, { exact y.2 (y.1.is_prime.mem_of_pow_mem M H3), }, { rw [mul_comm _ (f^N), eq1], refine mul_mem_right _ _ (mul_mem_right _ _ (sum_mem _ (λ i hi, mul_mem_left _ _ _))), generalize_proofs h, exact (classical.some_spec h).1, }, }, end end to_Spec section variable {𝒜} /--The continuous function between the basic open set `D(f)` in `Proj` to the corresponding basic open set in `Spec A⁰_f`. -/ def to_Spec {f : A} (m : ℕ) (f_deg : f ∈ 𝒜 m) : (Proj.T| (pbo f)) ⟶ (Spec.T (A⁰_ f_deg)) := { to_fun := to_Spec.to_fun 𝒜 f_deg, continuous_to_fun := begin apply is_topological_basis.continuous (prime_spectrum.is_topological_basis_basic_opens), rintros _ ⟨⟨g, hg⟩, rfl⟩, induction g using localization.induction_on with data, obtain ⟨a, ⟨_, ⟨n, rfl⟩⟩⟩ := data, erw to_Spec.preimage_eq, refine is_open_induced_iff.mpr ⟨(pbo f).1 ⊓ (pbo a).1, is_open.inter (pbo f).2 (pbo a).2, _⟩, ext z, split; intros hz; simpa [set.mem_preimage], end } end end Proj_iso_Spec_Top_component end algebraic_geometry
7798aa21d46c8ef3b65aea7439dc2c264fe191c2
4727251e0cd73359b15b664c3170e5d754078599
/archive/imo/imo2005_q3.lean
9f7559da9f278b29a2ed6c62f1f0cd4337dcb844
[ "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,032
lean
/- Copyright (c) 2021 Manuel Candales. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Manuel Candales -/ import data.real.basic /-! # IMO 2005 Q3 Let `x`, `y` and `z` be positive real numbers such that `xyz ≥ 1`. Prove that: `(x^5 - x^2)/(x^5 + y^2 + z^2) + (y^5 - y^2)/(y^5 + z^2 + x^2) + (z^5 - z^2)/(z^5 + x^2 + y^2) ≥ 0` # Solution The solution by Iurie Boreico from Moldova is presented, which won a special prize during the exam. The key insight is that `(x^5-x^2)/(x^5+y^2+z^2) ≥ (x^2-y*z)/(x^2+y^2+z^2)`, which is proven by factoring `(x^5-x^2)/(x^5+y^2+z^2) - (x^5-x^2)/(x^3*(x^2+y^2+z^2))` into a non-negative expression and then making use of `xyz ≥ 1` to show `(x^5-x^2)/(x^3*(x^2+y^2+z^2)) ≥ (x^2-y*z)/(x^2+y^2+z^2)`. -/ lemma key_insight (x y z : ℝ) (hx : x > 0) (hy : y > 0) (hz : z > 0) (h : x*y*z ≥ 1) : (x^5-x^2)/(x^5+y^2+z^2) ≥ (x^2-y*z)/(x^2+y^2+z^2) := begin have h₁ : 0 < x^5+y^2+z^2, linarith [pow_pos hx 5, pow_pos hy 2, pow_pos hz 2], have h₂ : 0 < x^3, exact pow_pos hx 3, have h₃ : 0 < x^2+y^2+z^2, linarith [pow_pos hx 2, pow_pos hy 2, pow_pos hz 2], have h₄ : 0 < x^3*(x^2+y^2+z^2), exact mul_pos h₂ h₃, have key : (x^5-x^2)/(x^5+y^2+z^2) - (x^5-x^2)/(x^3*(x^2+y^2+z^2)) = ((x^3 - 1)^2*x^2*(y^2 + z^2))/((x^5+y^2+z^2)*(x^3*(x^2+y^2+z^2))), { field_simp [h₁.ne', h₄.ne'], ring }, have h₅ : ((x^3 - 1)^2*x^2*(y^2 + z^2))/((x^5+y^2+z^2)*(x^3*(x^2+y^2+z^2))) ≥ 0, { refine div_nonneg _ _, refine mul_nonneg (mul_nonneg (sq_nonneg _) (sq_nonneg _)) _, exact add_nonneg (sq_nonneg _) (sq_nonneg _), exact le_of_lt (mul_pos h₁ h₄) }, calc (x^5-x^2)/(x^5+y^2+z^2) ≥ (x^5-x^2)/(x^3*(x^2+y^2+z^2)) : by linarith [key, h₅] ... ≥ (x^5-x^2*(x*y*z))/(x^3*(x^2+y^2+z^2)) : by { refine (div_le_div_right h₄).mpr _, simp, exact (le_mul_iff_one_le_right (pow_pos hx 2)).mpr h } ... = (x^2-y*z)/(x^2+y^2+z^2) : by { field_simp [h₂.ne', h₃.ne'], ring }, end theorem imo2005_q3 (x y z : ℝ) (hx : x > 0) (hy : y > 0) (hz : z > 0) (h : x*y*z ≥ 1) : (x^5-x^2)/(x^5+y^2+z^2) + (y^5-y^2)/(y^5+z^2+x^2) + (z^5-z^2)/(z^5+x^2+y^2) ≥ 0 := begin calc (x^5-x^2)/(x^5+y^2+z^2) + (y^5-y^2)/(y^5+z^2+x^2) + (z^5-z^2)/(z^5+x^2+y^2) ≥ (x^2-y*z)/(x^2+y^2+z^2) + (y^2-z*x)/(y^2+z^2+x^2) + (z^2-x*y)/(z^2+x^2+y^2) : by { linarith [key_insight x y z hx hy hz h, key_insight y z x hy hz hx (by linarith [h]), key_insight z x y hz hx hy (by linarith [h])] } ... = 1/2*( (x-y)^2 + (y-z)^2 + (z-x)^2 ) / (x^2+y^2+z^2) : by { have h₁ : y^2+z^2+x^2 = x^2+y^2+z^2, ring, have h₂ : z^2+x^2+y^2 = x^2+y^2+z^2, ring, rw [h₁, h₂], ring } ... ≥ 0 : by { exact div_nonneg (by linarith [sq_nonneg (x-y), sq_nonneg (y-z), sq_nonneg (z-x)]) (by linarith [sq_nonneg x, sq_nonneg y, sq_nonneg z]) }, end
f38c48b19842b1a810d93e26a742d90f62a9d9d5
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/injective.lean
cf04c92697effdd04443dedc7d40f255e637a6f4
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
812
lean
universe u v structure InjectiveFunction (α : Type u) (β : Type v) where fn : α → β inj : ∀ a b, fn a = fn b → a = b def add1 : InjectiveFunction Nat Nat where fn a := a + 1 inj a b h := by injection h; assumption instance : CoeFun (InjectiveFunction α β) (fun _ => α → β) where coe s := s.fn #eval add1 10 def mapAdd1 (xs : List Nat) : List Nat := xs.map add1 #eval mapAdd1 [1, 2] def foo : InjectiveFunction Bool (Nat → Nat) where fn | true, a => a + 1 | false, a => a inj a b h := by cases a cases b; rfl; injection (congrFun h 0) cases b; injection (congrFun h 0); rfl theorem ex1 (x : Nat) : foo true x = x + 1 := rfl theorem ex2 (x : Nat) : foo false x = x := rfl #eval foo true 10 #eval foo false 20 #eval [1, 2, 3].map (foo true)
8d543c1aa2034139e08aaf48a2396c0ba275d5ff
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0104/Q0104.lean
cee6aed72c2e954947fd25d900e7c6aecf3b63ac
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,182
lean
/- M1F 2017-18 Sheet 1 Question 1 Author : Kevin Buzzard This file should work with any version of lean -- whether you installed it yourself or are running the version on https://leanprover.github.io/live/latest/ -/ -- We probably need the "law of the excluded middle" for this question -- every -- proposition is either true or false! Don't even ask me to explain what the -- other options are, but Lean does not come with this axiom by default (blame -- the computer scientists) and mathematicians have to add it themselves. -- It's easy to add though. "em" for excluded middle. axiom em (X : Prop) : X ∨ ¬ X variables P Q R S : Prop -- A "Prop" is a proposition, that is, a true/false statement. -- Sheet 1 Q4. **Edit the question** until it corresponds to what you think the -- answer is, and then prove it. -- For example if you think that the answer is that either P and Q are both true -- or P,Q,R are all false, then change the end of the question (after the iff) to -- ((P ∧ Q) ∨ (¬ P ∧ ¬ Q ∧ ¬ R)) theorem m1f_sheet01_q04 : (P → (Q ∨ R)) ∧ (¬ Q → (R ∨ ¬ P)) ∧ ((Q ∧ R) → ¬ P) ↔ ((P ∧ Q ∧ R) ∨ (P ∧ ¬ Q ∧ ¬ R)) := sorry
e4e3e85e29a42a2026c86b0a1d0d982170d084e3
1dd482be3f611941db7801003235dc84147ec60a
/src/group_theory/quotient_group.lean
7b6b3523e2972343601de31cb3b0477fd5e65464
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
8,771
lean
/- Copyright (c) 2018 Kevin Buzzard and Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Patrick Massot. This file is to a certain extent based on `quotient_module.lean` by Johannes Hölzl. -/ import group_theory.coset universes u v namespace quotient_group variables {G : Type u} [group G] (N : set G) [normal_subgroup N] {H : Type v} [group H] instance : group (quotient N) := { one := (1 : G), mul := λ a b, quotient.lift_on₂' a b (λ a b, ((a * b : G) : quotient N)) (λ a₁ a₂ b₁ b₂ hab₁ hab₂, quot.sound ((is_subgroup.mul_mem_cancel_left N (is_subgroup.inv_mem hab₂)).1 (by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹), mul_assoc _ b₂, ← mul_assoc b₂, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)]; exact normal_subgroup.normal _ hab₁ _))), mul_assoc := λ a b c, quotient.induction_on₃' a b c (λ a b c, congr_arg mk (mul_assoc a b c)), one_mul := λ a, quotient.induction_on' a (λ a, congr_arg mk (one_mul a)), mul_one := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_one a)), inv := λ a, quotient.lift_on' a (λ a, ((a⁻¹ : G) : quotient N)) (λ a b hab, quotient.sound' begin show a⁻¹⁻¹ * b⁻¹ ∈ N, rw ← mul_inv_rev, exact is_subgroup.inv_mem (is_subgroup.mem_norm_comm hab) end), mul_left_inv := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_left_inv a)) } attribute [to_additive quotient_add_group.add_group._proof_6] quotient_group.group._proof_6 attribute [to_additive quotient_add_group.add_group._proof_5] quotient_group.group._proof_5 attribute [to_additive quotient_add_group.add_group._proof_4] quotient_group.group._proof_4 attribute [to_additive quotient_add_group.add_group._proof_3] quotient_group.group._proof_3 attribute [to_additive quotient_add_group.add_group._proof_2] quotient_group.group._proof_2 attribute [to_additive quotient_add_group.add_group._proof_1] quotient_group.group._proof_1 attribute [to_additive quotient_add_group.add_group] quotient_group.group attribute [to_additive quotient_add_group.quotient.equations._eqn_1] quotient_group.quotient.equations._eqn_1 attribute [to_additive quotient_add_group.add_group.equations._eqn_1] quotient_group.group.equations._eqn_1 instance : is_group_hom (mk : G → quotient N) := ⟨λ _ _, rfl⟩ attribute [to_additive quotient_add_group.is_add_group_hom] quotient_group.is_group_hom attribute [to_additive quotient_add_group.is_add_group_hom.equations._eqn_1] quotient_group.is_group_hom.equations._eqn_1 instance {G : Type*} [comm_group G] (s : set G) [is_subgroup s] : comm_group (quotient s) := { mul_comm := λ a b, quotient.induction_on₂' a b (λ a b, congr_arg mk (mul_comm a b)), ..@quotient_group.group _ _ s (normal_subgroup_of_comm_group s) } attribute [to_additive quotient_add_group.add_comm_group._proof_6] quotient_group.comm_group._proof_6 attribute [to_additive quotient_add_group.add_comm_group._proof_5] quotient_group.comm_group._proof_5 attribute [to_additive quotient_add_group.add_comm_group._proof_4] quotient_group.comm_group._proof_4 attribute [to_additive quotient_add_group.add_comm_group._proof_3] quotient_group.comm_group._proof_3 attribute [to_additive quotient_add_group.add_comm_group._proof_2] quotient_group.comm_group._proof_2 attribute [to_additive quotient_add_group.add_comm_group._proof_1] quotient_group.comm_group._proof_1 attribute [to_additive quotient_add_group.add_comm_group] quotient_group.comm_group attribute [to_additive quotient_add_group.add_comm_group.equations._eqn_1] quotient_group.comm_group.equations._eqn_1 @[simp] lemma coe_one : ((1 : G) : quotient N) = 1 := rfl @[simp] lemma coe_mul (a b : G) : ((a * b : G) : quotient N) = a * b := rfl @[simp] lemma coe_inv (a : G) : ((a⁻¹ : G) : quotient N) = a⁻¹ := rfl @[simp] lemma coe_pow (a : G) (n : ℕ) : ((a ^ n : G) : quotient N) = a ^ n := @is_group_hom.pow _ _ _ _ mk _ a n attribute [to_additive quotient_add_group.coe_zero] coe_one attribute [to_additive quotient_add_group.coe_add] coe_mul attribute [to_additive quotient_add_group.coe_neg] coe_inv @[simp] lemma coe_gpow (a : G) (n : ℤ) : ((a ^ n : G) : quotient N) = a ^ n := @is_group_hom.gpow _ _ _ _ mk _ a n local notation ` Q ` := quotient N instance is_group_hom_quotient_group_mk : is_group_hom (mk : G → Q) := by refine {..}; intros; refl attribute [to_additive quotient_add_group.is_add_group_hom_quotient_add_group_mk] quotient_group.is_group_hom_quotient_group_mk attribute [to_additive quotient_add_group.is_add_group_hom_quotient_add_group_mk.equations._eqn_1] quotient_group.is_group_hom_quotient_group_mk.equations._eqn_1 def lift (φ : G → H) [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (q : Q) : H := q.lift_on' φ $ assume a b (hab : a⁻¹ * b ∈ N), (calc φ a = φ a * 1 : by simp ... = φ a * φ (a⁻¹ * b) : by rw HN (a⁻¹ * b) hab ... = φ (a * (a⁻¹ * b)) : by rw is_group_hom.mul φ a (a⁻¹ * b) ... = φ b : by simp) attribute [to_additive quotient_add_group.lift._proof_1] lift._proof_1 attribute [to_additive quotient_add_group.lift] lift attribute [to_additive quotient_add_group.lift.equations._eqn_1] lift.equations._eqn_1 @[simp] lemma lift_mk {φ : G → H} [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (g : Q) = φ g := rfl attribute [to_additive quotient_add_group.lift_mk] lift_mk @[simp] lemma lift_mk' {φ : G → H} [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (mk g : Q) = φ g := rfl attribute [to_additive quotient_add_group.lift_mk'] lift_mk' def map (M : set H) [normal_subgroup M] (f : G → H) [is_group_hom f] (h : N ⊆ f ⁻¹' M) : quotient N → quotient M := begin haveI : is_group_hom ((mk : H → quotient M) ∘ f) := is_group_hom.comp _ _, refine quotient_group.lift N (mk ∘ f) _, assume x hx, refine quotient_group.eq.2 _, rw [mul_one, is_subgroup.inv_mem_iff], exact h hx, end attribute [to_additive quotient_add_group.map._proof_1] map._proof_1 attribute [to_additive quotient_add_group.map._proof_2] map._proof_2 attribute [to_additive quotient_add_group.map] map variables (φ : G → H) [is_group_hom φ] (HN : ∀x∈N, φ x = 1) instance is_group_hom_quotient_lift : is_group_hom (lift N φ HN) := ⟨λ q r, quotient.induction_on₂' q r $ λ a b, show φ (a * b) = φ a * φ b, from is_group_hom.mul φ a b⟩ attribute [to_additive quotient_add_group.is_add_group_hom_quotient_lift] quotient_group.is_group_hom_quotient_lift attribute [to_additive quotient_add_group.is_add_group_hom_quotient_lift.equations._eqn_1] quotient_group.is_group_hom_quotient_lift.equations._eqn_1 open function is_group_hom @[to_additive quotient_add_group.injective_ker_lift] lemma injective_ker_lift : injective (lift (ker φ) φ $ λ x h, (mem_ker φ).1 h) := assume a b, quotient.induction_on₂' a b $ assume a b (h : φ a = φ b), quotient.sound' $ show a⁻¹ * b ∈ ker φ, by rw [mem_ker φ, is_group_hom.mul φ, ← h, is_group_hom.inv φ, inv_mul_self] --@[to_additive quotient_add_group.quotient_ker_equiv_range] noncomputable def quotient_ker_equiv_range : (quotient (ker φ)) ≃ set.range φ := @equiv.of_bijective _ (set.range φ) (λ x, ⟨lift (ker φ) φ (by simp [mem_ker]) x, by exact quotient.induction_on' x (λ x, ⟨x, rfl⟩)⟩) ⟨λ a b h, injective_ker_lift _ (subtype.mk.inj h), λ ⟨x, y, hy⟩, ⟨mk y, subtype.eq hy⟩⟩ noncomputable def quotient_ker_equiv_of_surjective (hφ : function.surjective φ) : (quotient (ker φ)) ≃ H := calc (quotient_group.quotient (is_group_hom.ker φ)) ≃ set.range φ : quotient_ker_equiv_range _ ... ≃ H : ⟨λ a, a.1, λ b, ⟨b, hφ b⟩, λ ⟨_, _⟩, rfl, λ _, rfl⟩ end quotient_group namespace quotient_add_group open is_add_group_hom variables {G : Type u} [_root_.add_group G] (N : set G) [normal_add_subgroup N] {H : Type v} [_root_.add_group H] variables (φ : G → H) [_root_.is_add_group_hom φ] noncomputable def quotient_ker_equiv_range : (quotient (ker φ)) ≃ set.range φ := @quotient_group.quotient_ker_equiv_range (multiplicative G) _ (multiplicative H) _ φ _ noncomputable def quotient_ker_equiv_of_surjective (hφ : function.surjective φ) : (quotient (ker φ)) ≃ H := @quotient_group.quotient_ker_equiv_of_surjective (multiplicative G) _ (multiplicative H) _ φ _ hφ attribute [to_additive quotient_add_group.quotient_ker_equiv_range] quotient_group.quotient_ker_equiv_range attribute [to_additive quotient_add_group.quotient_ker_equiv_of_surjective] quotient_group.quotient_ker_equiv_of_surjective end quotient_add_group
ac8a9d360d7be6b9a99166fe62e274c8e69c1297
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/omega/int/preterm.lean
d538758f6e545df404104aec2c12a6a9b1e07004
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,672
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.omega.term import Mathlib.PostPort universes l namespace Mathlib /- Linear integer arithmetic terms in pre-normalized form. -/ namespace omega namespace int /-- The shadow syntax for arithmetic terms. All constants are reified to `cst` (e.g., `-5` is reified to `cst -5`) and all other atomic terms are reified to `exp` (e.g., `-5 * (gcd 14 -7)` is reified to `exp -5 \`(gcd 14 -7)`). `exp` accepts a coefficient of type `int` as its first argument because multiplication by constant is allowed by the omega test. -/ /-- Similar to `exprterm`, except that all exprs are now replaced with de Brujin indices of type `nat`. This is akin to generalizing over the terms represented by the said exprs. -/ inductive preterm where | cst : ℤ → preterm | var : ℤ → ℕ → preterm | add : preterm → preterm → preterm namespace preterm /-- Preterm evaluation -/ @[simp] def val (v : ℕ → ℤ) : preterm → ℤ := sorry /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preterm → ℕ := sorry @[simp] def add_one (t : preterm) : preterm := add t (cst 1) def repr : preterm → string := sorry end preterm /-- Return a term (which is in canonical form by definition) that is equivalent to the input preterm -/ @[simp] def canonize : preterm → term := sorry @[simp] theorem val_canonize {v : ℕ → ℤ} {t : preterm} : term.val v (canonize t) = preterm.val v t := sorry
5b0d8682293fed68b9cd5ff64db3acacc8e4f21f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/localization/away/adjoin_root.lean
2d5ed60a9769cdf18cab83f55aea527415868f6a
[ "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
1,751
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import ring_theory.adjoin_root import ring_theory.localization.away.basic /-! > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The `R`-`alg_equiv` between the localization of `R` away from `r` and `R` with an inverse of `r` adjoined. -/ open polynomial adjoin_root localization variables {R : Type*} [comm_ring R] local attribute [instance] is_localization.alg_hom_subsingleton adjoin_root.alg_hom_subsingleton /-- The `R`-`alg_equiv` between the localization of `R` away from `r` and `R` with an inverse of `r` adjoined. -/ noncomputable def localization.away_equiv_adjoin (r : R) : away r ≃ₐ[R] adjoin_root (C r * X - 1) := alg_equiv.of_alg_hom { commutes' := is_localization.away.away_map.lift_eq r (is_unit_of_mul_eq_one _ _ $ root_is_inv r), .. away_lift _ r _ } (lift_hom _ (is_localization.away.inv_self r) $ by simp only [map_sub, map_mul, aeval_C, aeval_X, is_localization.away.mul_inv_self, aeval_one, sub_self]) (subsingleton.elim _ _) (subsingleton.elim _ _) lemma is_localization.adjoin_inv (r : R) : is_localization.away r (adjoin_root $ C r * X - 1) := is_localization.is_localization_of_alg_equiv _ (localization.away_equiv_adjoin r) lemma is_localization.away.finite_presentation (r : R) {S} [comm_ring S] [algebra R S] [is_localization.away r S] : algebra.finite_presentation R S := (adjoin_root.finite_presentation _).equiv $ (localization.away_equiv_adjoin r).symm.trans $ is_localization.alg_equiv (submonoid.powers r) _ _
22186d36924d1405bdf613616d59dc8b5aaf4f63
675b8263050a5d74b89ceab381ac81ce70535688
/src/topology/algebra/group.lean
5fd3ffc03bd3d78f2dcfb6c6eb12e7fdbf75c722
[ "Apache-2.0" ]
permissive
vozor/mathlib
5921f55235ff60c05f4a48a90d616ea167068adf
f7e728ad8a6ebf90291df2a4d2f9255a6576b529
refs/heads/master
1,675,607,702,231
1,609,023,279,000
1,609,023,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,115
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 order.filter.pointwise import group_theory.quotient_group import topology.algebra.monoid import topology.homeomorph /-! # Theory of topological groups This file defines the following typeclasses: * `topological_group`, `topological_add_group`: multiplicative and additive topological groups, i.e., groups with continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`; * `has_continuous_sub G` means that `G` has a continuous subtraction operation. There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate typeclass because, e.g., `ℕ` and `ℝ≥0` have continuous subtraction but are not additive groups. We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`, `homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in groups. ## Tags topological space, group, topological group -/ open classical set filter topological_space function open_locale classical topological_space filter universes u v w x variables {α : Type u} {β : Type v} {G : Type w} {H : Type x} section continuous_mul_group /-! ### Groups with continuous multiplication In this section we prove a few statements about groups with continuous `(*)`. -/ variables [topological_space G] [group G] [has_continuous_mul G] /-- Multiplication from the left in a topological group as a homeomorphism. -/ @[to_additive "Addition from the left in a topological additive group as a homeomorphism."] protected def homeomorph.mul_left (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[to_additive] lemma is_open_map_mul_left (a : G) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive] lemma is_closed_map_mul_left (a : G) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map /-- Multiplication from the right in a topological group as a homeomorphism. -/ @[to_additive "Addition from the right in a topological additive group as a homeomorphism."] protected def homeomorph.mul_right (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[to_additive] lemma is_open_map_mul_right (a : G) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive] lemma is_closed_map_mul_right (a : G) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map @[to_additive] lemma is_open_map_div_right (a : G) : is_open_map (λ x, x / a) := by simpa only [div_eq_mul_inv] using is_open_map_mul_right (a⁻¹) @[to_additive] lemma is_closed_map_div_right (a : G) : is_closed_map (λ x, x / a) := by simpa only [div_eq_mul_inv] using is_closed_map_mul_right (a⁻¹) end continuous_mul_group section topological_group /-! ### Topological groups A topological group is a group in which the multiplication and inversion operations are continuous. Topological additive groups are defined in the same way. Equivalently, we can require that the division operation `λ x y, x * y⁻¹` (resp., subtraction) is continuous. -/ /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (G : Type u) [topological_space G] [add_group G] extends has_continuous_add G : Prop := (continuous_neg : continuous (λa:G, -a)) /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ @[to_additive] class topological_group (G : Type*) [topological_space G] [group G] extends has_continuous_mul G : Prop := (continuous_inv : continuous (has_inv.inv : G → G)) variables [topological_space G] [group G] [topological_group G] export topological_group (continuous_inv) export topological_add_group (continuous_neg) @[to_additive] lemma continuous_on_inv {s : set G} : continuous_on has_inv.inv s := continuous_inv.continuous_on @[to_additive] lemma continuous_within_at_inv {s : set G} {x : G} : continuous_within_at has_inv.inv s x := continuous_inv.continuous_within_at @[to_additive] lemma continuous_at_inv {x : G} : continuous_at has_inv.inv x := continuous_inv.continuous_at @[to_additive] lemma tendsto_inv (a : G) : tendsto has_inv.inv (𝓝 a) (𝓝 (a⁻¹)) := continuous_at_inv /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive] lemma filter.tendsto.inv {f : α → G} {l : filter α} {y : G} (h : tendsto f l (𝓝 y)) : tendsto (λ x, (f x)⁻¹) l (𝓝 y⁻¹) := (continuous_inv.tendsto y).comp h variables [topological_space α] {f : α → G} {s : set α} {x : α} @[continuity, to_additive] lemma continuous.inv (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf attribute [continuity] continuous.neg -- TODO @[to_additive] lemma continuous_on.inv (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf @[to_additive] lemma continuous_within_at.inv (hf : continuous_within_at f s x) : continuous_within_at (λ x, (f x)⁻¹) s x := hf.inv @[instance, to_additive] instance [topological_space H] [group H] [topological_group H] : topological_group (G × H) := { continuous_inv := continuous_inv.prod_map continuous_inv } variable (G) /-- Inversion in a topological group as a homeomorphism. -/ @[to_additive "Negation in a topological group as a homeomorphism."] protected def homeomorph.inv : G ≃ₜ G := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv G } @[to_additive] lemma nhds_one_symm : comap has_inv.inv (𝓝 (1 : G)) = 𝓝 (1 : G) := begin have lim : tendsto has_inv.inv (𝓝 (1 : G)) (𝓝 1), { simpa only [one_inv] using tendsto_inv (1 : G) }, exact comap_eq_of_inverse _ inv_involutive.comp_self lim lim, end variable {G} @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv {s : set G} (hs : s ∈ 𝓝 (1 : G)) : ∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v / w ∈ s := have ((λp : G × G, p.1 * p.2⁻¹) ⁻¹' s) ∈ 𝓝 ((1, 1) : G × G), from continuous_at_fst.mul continuous_at_snd.inv (by simpa), by simpa only [div_eq_mul_inv, nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage] using this @[to_additive] lemma nhds_translation_mul_inv (x : G) : comap (λ y : G, y * x⁻¹) (𝓝 1) = 𝓝 x := begin refine comap_eq_of_inverse (λ y : G, y * x) _ _ _, { funext x, simp }, { rw ← mul_right_inv x, exact tendsto_id.mul tendsto_const_nhds }, { suffices : tendsto (λ y : G, y * x) (𝓝 1) (𝓝 (1 * x)), { simpa }, exact tendsto_id.mul tendsto_const_nhds } end @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] @[to_additive] lemma topological_group.of_nhds_aux {G : Type*} [group G] [topological_space G] (hinv : tendsto (λ (x : G), x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ (x₀ : G), 𝓝 x₀ = map (λ (x : G), x₀ * x) (𝓝 1)) (hconj : ∀ (x₀ : G), map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) ≤ 𝓝 1) : continuous (λ x : G, x⁻¹) := begin rw continuous_iff_continuous_at, rintros x₀, have key : (λ x, (x₀*x)⁻¹) = (λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹) ∘ (λ x, x⁻¹), by {ext ; simp[mul_assoc] }, calc map (λ x, x⁻¹) (𝓝 x₀) = map (λ x, x⁻¹) (map (λ x, x₀*x) $ 𝓝 1) : by rw hleft ... = map (λ x, (x₀*x)⁻¹) (𝓝 1) : by rw filter.map_map ... = map (((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) ∘ (λ x, x⁻¹)) (𝓝 1) : by rw key ... = map ((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) _ : by rw ← filter.map_map ... ≤ map ((λ x, x₀⁻¹ * x) ∘ λ x, x₀ * x * x₀⁻¹) (𝓝 1) : map_mono hinv ... = map (λ x, x₀⁻¹ * x) (map (λ x, x₀ * x * x₀⁻¹) (𝓝 1)) : filter.map_map ... ≤ map (λ x, x₀⁻¹ * x) (𝓝 1) : map_mono (hconj x₀) ... = 𝓝 x₀⁻¹ : (hleft _).symm end @[to_additive] lemma topological_group.of_nhds_one' {G : Type*} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : topological_group G := begin refine { continuous_mul := (has_continuous_mul.of_nhds_one hmul hleft hright).continuous_mul, continuous_inv := topological_group.of_nhds_aux hinv hleft _ }, intros x₀, suffices : map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) = 𝓝 1, by simp [this, le_refl], rw [show (λ x, x₀ * x * x₀⁻¹) = (λ x, x₀ * x) ∘ λ x, x*x₀⁻¹, by {ext, simp [mul_assoc] }, ← filter.map_map, ← hright, hleft x₀⁻¹, filter.map_map], convert map_id, ext, simp end @[to_additive] lemma topological_group.of_nhds_one {G : Type*} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hconj : ∀ x₀ : G, tendsto (λ x, x₀*x*x₀⁻¹) (𝓝 1) (𝓝 1)) : topological_group G := { continuous_mul := begin rw continuous_iff_continuous_at, rintros ⟨x₀, y₀⟩, have key : (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) = ((λ x, x₀*y₀*x) ∘ (uncurry (*)) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id)), by { ext, simp [uncurry, prod.map, mul_assoc] }, specialize hconj y₀⁻¹, rw inv_inv at hconj, calc map (λ (p : G × G), p.1 * p.2) (𝓝 (x₀, y₀)) = map (λ (p : G × G), p.1 * p.2) ((𝓝 x₀) ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [hleft x₀, hleft y₀, prod_map_map_eq, filter.map_map] ... = map (((λ x, x₀*y₀*x) ∘ (uncurry (*))) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id))((𝓝 1) ×ᶠ (𝓝 1)) : by rw key ... = map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((map (λ x, y₀⁻¹*x*y₀) $ 𝓝 1) ×ᶠ (𝓝 1)) : by rw [← filter.map_map, ← prod_map_map_eq', map_id] ... ≤ map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((𝓝 1) ×ᶠ (𝓝 1)) : map_mono (filter.prod_mono hconj $ le_refl _) ... = map (λ x, x₀*y₀*x) (map (uncurry (*)) ((𝓝 1) ×ᶠ (𝓝 1))) : by rw filter.map_map ... ≤ map (λ x, x₀*y₀*x) (𝓝 1) : map_mono hmul ... = 𝓝 (x₀*y₀) : (hleft _).symm end, continuous_inv := topological_group.of_nhds_aux hinv hleft hconj} @[to_additive] lemma topological_group.of_comm_of_nhds_one {G : Type*} [comm_group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : topological_group G := topological_group.of_nhds_one hmul hinv hleft (by simpa using tendsto_id) end topological_group section quotient_topological_group variables [topological_space G] [group G] [topological_group G] (N : subgroup G) (n : N.normal) @[to_additive] instance {G : Type*} [group G] [topological_space G] (N : subgroup G) : topological_space (quotient_group.quotient N) := quotient.topological_space open quotient_group @[to_additive] lemma quotient_group.is_open_map_coe : is_open_map (coe : G → quotient N) := begin intros s s_op, change is_open ((coe : G → quotient N) ⁻¹' (coe '' s)), rw quotient_group.preimage_image_coe N s, exact is_open_Union (λ n, is_open_map_mul_right n s s_op) end @[to_additive] instance topological_group_quotient [N.normal] : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : G → quotient N) ∘ (λ (p : G × G), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : G × G, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact (quotient_group.is_open_map_coe N).prod (quotient_group.is_open_map_coe N) }, { exact continuous_quot_mk.prod_map continuous_quot_mk }, { exact (surjective_quot_mk _).prod_map (surjective_quot_mk _) } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin have : continuous ((coe : G → quotient N) ∘ (λ (a : G), a⁻¹)) := continuous_quot_mk.comp continuous_inv, convert continuous_quotient_lift _ this, end } attribute [instance] topological_add_group_quotient end quotient_topological_group /-- A typeclass saying that `λ p : G × G, p.1 - p.2` is a continuous function. This property automatically holds for topological additive groups but it also holds, e.g., for `ℝ≥0`. -/ class has_continuous_sub (G : Type*) [topological_space G] [has_sub G] : Prop := (continuous_sub : continuous (λ p : G × G, p.1 - p.2)) @[priority 100] -- see Note [lower instance priority] instance topological_add_group.to_has_continuous_sub [topological_space G] [add_group G] [topological_add_group G] : has_continuous_sub G := ⟨by { simp only [sub_eq_add_neg], exact continuous_fst.add continuous_snd.neg }⟩ export has_continuous_sub (continuous_sub) section has_continuous_sub variables [topological_space G] [has_sub G] [has_continuous_sub G] lemma filter.tendsto.sub {f g : α → G} {l : filter α} {a b : G} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) : tendsto (λx, f x - g x) l (𝓝 (a - b)) := (continuous_sub.tendsto (a, b)).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → G} {s : set α} {x : α} @[continuity] lemma continuous.sub (hf : continuous f) (hg : continuous g) : continuous (λ x, f x - g x) := continuous_sub.comp (hf.prod_mk hg : _) lemma continuous_within_at.sub (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ x, f x - g x) s x := hf.sub hg lemma continuous_on.sub (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s := λ x hx, (hf x hx).sub (hg x hx) end has_continuous_sub lemma nhds_translation [topological_space G] [add_group G] [topological_add_group G] (x : G) : comap (λy:G, y - x) (𝓝 0) = 𝓝 x := by simpa only [sub_eq_add_neg] using nhds_translation_add_neg x /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (G : Type u) extends add_comm_group G := (Z [] : filter G) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:G×G, p.1 - p.2) (Z ×ᶠ Z) Z) namespace add_group_with_zero_nhd variables (G) [add_group_with_zero_nhd G] local notation `Z` := add_group_with_zero_nhd.Z @[priority 100] -- see Note [lower instance priority] instance : topological_space G := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z G) variables {G} lemma neg_Z : tendsto (λa:G, - a) (Z G) (Z G) := have tendsto (λa, (0:G)) (Z G) (Z G), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:G, 0 - a) (Z G) (Z G), from sub_Z.comp (tendsto.prod_mk this tendsto_id), by simpa lemma add_Z : tendsto (λp:G×G, p.1 + p.2) (Z G ×ᶠ Z G) (Z G) := suffices tendsto (λp:G×G, p.1 - -p.2) (Z G ×ᶠ Z G) (Z G), by simpa [sub_eq_add_neg], sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd)) lemma exists_Z_half {s : set G} (hs : s ∈ Z G) : ∃ V ∈ Z G, ∀ (v ∈ V) (w ∈ V), v + w ∈ s := begin have : ((λa:G×G, a.1 + a.2) ⁻¹' s) ∈ Z G ×ᶠ Z G := add_Z (by simpa using hs), rcases mem_prod_self_iff.1 this with ⟨V, H, H'⟩, exact ⟨V, H, prod_subset_iff.1 H'⟩ end lemma nhds_eq (a : G) : 𝓝 a = map (λx, x + a) (Z G) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:G) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:G, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 t0 b hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z G).sets_of_superset ht (assume x hxt, _), simpa [add_assoc] using eqt _ hxt _ hb } end) lemma nhds_zero_eq_Z : 𝓝 0 = Z G := by simp [nhds_eq]; exact filter.map_id @[priority 100] -- see Note [lower instance priority] instance : has_continuous_add G := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, (a + b) + x) ∘ (λp:G×G,p.1 + p.2)) (Z G ×ᶠ Z G) (map (λx:G, (a + b) + x) (Z G)), { simpa [(∘), add_comm, add_left_comm] }, exact tendsto_map.comp add_Z end ⟩ @[priority 100] -- see Note [lower instance priority] instance : topological_add_group G := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, x - a) ∘ (λx:G, -x)) (Z G) (map (λx:G, x - a) (Z G)), { simpa [(∘), add_comm, sub_eq_add_neg] using this }, exact tendsto_map.comp neg_Z end⟩ end add_group_with_zero_nhd section filter_mul section variables [topological_space G] [group G] [topological_group G] @[to_additive] lemma is_open.mul_left {s t : set G} : is_open t → is_open (s * t) := λ ht, begin have : ∀a, is_open ((λ (x : G), a * x) '' t) := assume a, is_open_map_mul_left a t ht, rw ← Union_mul_left_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end @[to_additive] lemma is_open.mul_right {s t : set G} : is_open s → is_open (s * t) := λ hs, begin have : ∀a, is_open ((λ (x : G), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw ← Union_mul_right_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end variables (G) lemma topological_group.t1_space (h : @is_closed G _ {1}) : t1_space G := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space G] : regular_space G := ⟨assume s a hs ha, let f := λ p : G × G, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_fst.mul continuous_snd.inv, -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s) let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ := is_open_prod_iff.1 ((is_open_compl_iff.2 hs).preimage hf) a (1:G) (by simpa [f]) in begin use [s * t₂, ht₂.mul_left, λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩], apply inf_principal_eq_bot, rw mem_nhds_sets_iff, refine ⟨t₁, _, ht₁, a_mem_t₁⟩, rintros x hx ⟨y, z, hy, hz, yz⟩, have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw ← yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space G] : t2_space G := regular_space.t2_space G end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space G] [group G] [topological_group G] /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `KV ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul {K U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V : set G, is_open V ∧ (1 : G) ∈ V ∧ K * V ⊆ U := begin let W : G → set G := λ x, (λ y, x * y) ⁻¹' U, have h1W : ∀ x, is_open (W x) := λ x, hU.preimage (continuous_mul_left x), have h2W : ∀ x ∈ K, (1 : G) ∈ W x := λ x hx, by simp only [mem_preimage, mul_one, hKU hx], choose V hV using λ x : K, exists_open_nhds_one_mul_subset (mem_nhds_sets (h1W x) (h2W x.1 x.2)), let X : K → set G := λ x, (λ y, (x : G)⁻¹ * y) ⁻¹' (V x), cases hK.elim_finite_subcover X (λ x, (hV x).1.preimage (continuous_mul_left x⁻¹)) _ with t ht, swap, { intros x hx, rw [mem_Union], use ⟨x, hx⟩, rw [mem_preimage], convert (hV _).2.1, simp only [mul_left_inv, subtype.coe_mk] }, refine ⟨⋂ x ∈ t, V x, is_open_bInter (finite_mem_finset _) (λ x hx, (hV x).1), _, _⟩, { simp only [mem_Inter], intros x hx, exact (hV x).2.1 }, rintro _ ⟨x, y, hx, hy, rfl⟩, simp only [mem_Inter] at hy, have := ht hx, simp only [mem_Union, mem_preimage] at this, rcases this with ⟨z, h1z, h2z⟩, have : (z : G)⁻¹ * x * y ∈ W z := (hV z).2.2 (mul_mem_mul h2z (hy z h1z)), rw [mem_preimage] at this, convert this using 1, simp only [mul_assoc, mul_inv_cancel_left] end /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset G, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin cases hV with g₀ hg₀, rcases is_compact.elim_finite_subcover hK (λ x : G, interior $ (λ h, x * h) ⁻¹' V) _ _ with ⟨t, ht⟩, { refine ⟨t, subset.trans ht _⟩, apply Union_subset_Union, intro g, apply Union_subset_Union, intro hg, apply interior_subset }, { intro g, apply is_open_interior }, { intros g hg, rw [mem_Union], use g₀ * g⁻¹, apply preimage_interior_subset_interior_preimage, exact continuous_const.mul continuous_id, rwa [mem_preimage, inv_mul_cancel_right] } end end section variables [topological_space G] [comm_group G] [topological_group G] @[to_additive] lemma nhds_mul (x y : G) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_one_split ht with ⟨V, V1, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V1, subset.refl _⟩, ⟨V, V1, subset.refl _⟩, _⟩, rintros a ⟨v, w, v_mem, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) v_mem (w * y⁻¹) w_mem }, { rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, y, _, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_nhds hd }, { simp only [inv_mul_cancel_right] } } end @[to_additive] lemma nhds_is_mul_hom : is_mul_hom (λx:G, 𝓝 x) := ⟨λ_ _, nhds_mul _ _⟩ end end filter_mul
df137c8e2a480e69a5c5e35b63e5b787780a6b4a
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/category/default.lean
1356d79eb30ecf8fde3b7a5b49244a1aa3be9247
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
7,580
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton -/ import tactic.basic import tactic.tidy /-! # Categories Defines a category, as a type class parametrised by the type of objects. ## Notations Introduces notations * `X ⟶ Y` for the morphism spaces, * `f ≫ g` for composition in the 'arrows' convention. Users may like to add `f ⊚ g` for composition in the standard convention, using ```lean local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo ``` -/ -- The order in this declaration matters: v often needs to be explicitly specified while u often -- can be omitted universes v u namespace category_theory /- The propositional fields of `category` are annotated with the auto_param `obviously`, which is defined here as a [`replacer` tactic](https://leanprover-community.github.io/mathlib_docs/commands.html#def_replacer). We then immediately set up `obviously` to call `tidy`. Later, this can be replaced with more powerful tactics. -/ def_replacer obviously @[obviously] meta def obviously' := tactic.tidy class has_hom (obj : Type u) : Type (max u (v+1)) := (hom : obj → obj → Type v) infixr ` ⟶ `:10 := has_hom.hom -- type as \h section prio set_option default_priority 100 -- see Note [default priority] class category_struct (obj : Type u) extends has_hom.{v} obj : Type (max u (v+1)) := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg /-- The typeclass `category C` describes morphisms associated to objects of type `C`. The universe levels of the objects and morphisms are unconstrained, and will often need to be specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.) -/ class category (obj : Type u) extends category_struct.{v} obj : Type (max u (v+1)) := (id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously) (comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously) (assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z), (f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously) end prio -- `restate_axiom` is a command that creates a lemma from a structure field, -- discarding any auto_param wrappers from the type. -- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".) restate_axiom category.id_comp' restate_axiom category.comp_id' restate_axiom category.assoc' attribute [simp] category.id_comp category.comp_id category.assoc attribute [trans] category_struct.comp /-- A `large_category` has objects in one universe level higher than the universe level of the morphisms. It is useful for examples such as the category of types, or the category of groups, etc. -/ abbreviation large_category (C : Type (u+1)) : Type (u+1) := category.{u} C /-- A `small_category` has objects and morphisms in the same universe level. -/ abbreviation small_category (C : Type u) : Type (u+1) := category.{u} C section variables {C : Type u} [category.{v} C] {X Y Z : C} /-- postcompose an equation between morphisms by another morphism -/ lemma eq_whisker {f g : X ⟶ Y} (w : f = g) (h : Y ⟶ Z) : f ≫ h = g ≫ h := by rw w /-- precompose an equation between morphisms by another morphism -/ lemma whisker_eq (f : X ⟶ Y) {g h : Y ⟶ Z} (w : g = h) : f ≫ g = f ≫ h := by rw w infixr ` =≫ `:80 := eq_whisker infixr ` ≫= `:80 := whisker_eq lemma eq_of_comp_left_eq {f g : X ⟶ Y} (w : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_right_eq {f g : Y ⟶ Z} (w : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_left_eq' (f g : X ⟶ Y) (w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g := eq_of_comp_left_eq (λ Z h, by convert congr_fun (congr_fun w Z) h) lemma eq_of_comp_right_eq' (f g : Y ⟶ Z) (w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g := eq_of_comp_right_eq (λ X h, by convert congr_fun (congr_fun w X) h) lemma id_of_comp_left_id (f : X ⟶ X) (w : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma id_of_comp_right_id (f : X ⟶ X) (w : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } class epi (f : X ⟶ Y) : Prop := (left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h) class mono (f : X ⟶ Y) : Prop := (right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h) instance (X : C) : epi.{v} (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ instance (X : C) : mono.{v} (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ lemma cancel_epi (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h := ⟨ λ p, epi.left_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_mono (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} : (g ≫ f = h ≫ f) ↔ g = h := ⟨ λ p, mono.right_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_epi_id (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y := by { convert cancel_epi f, simp, } lemma cancel_mono_id (f : X ⟶ Y) [mono f] {g : X ⟶ X} : (g ≫ f = f) ↔ g = 𝟙 X := by { convert cancel_mono f, simp, } lemma epi_comp {X Y Z : C} (f : X ⟶ Y) [epi f] (g : Y ⟶ Z) [epi g] : epi (f ≫ g) := begin split, intros Z a b w, apply (cancel_epi g).1, apply (cancel_epi f).1, simpa using w, end lemma mono_comp {X Y Z : C} (f : X ⟶ Y) [mono f] (g : Y ⟶ Z) [mono g] : mono (f ≫ g) := begin split, intros Z a b w, apply (cancel_mono f).1, apply (cancel_mono g).1, simpa using w, end lemma mono_of_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [mono (f ≫ g)] : mono f := begin split, intros Z a b w, replace w := congr_arg (λ k, k ≫ g) w, dsimp at w, rw [category.assoc, category.assoc] at w, exact (cancel_mono _).1 w, end lemma mono_of_mono_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [mono h] (w : f ≫ g = h) : mono f := by { resetI, subst h, exact mono_of_mono f g, } lemma epi_of_epi {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi (f ≫ g)] : epi g := begin split, intros Z a b w, replace w := congr_arg (λ k, f ≫ k) w, dsimp at w, rw [←category.assoc, ←category.assoc] at w, exact (cancel_epi _).1 w, end lemma epi_of_epi_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [epi h] (w : f ≫ g = h) : epi g := by { resetI, subst h, exact epi_of_epi f g, } end section variable (C : Type u) variable [category.{v} C] universe u' instance ulift_category : category.{v} (ulift.{u'} C) := { hom := λ X Y, (X.down ⟶ Y.down), id := λ X, 𝟙 X.down, comp := λ _ _ _ f g, f ≫ g } -- We verify that this previous instance can lift small categories to large categories. example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance end end category_theory open category_theory namespace preorder variables (α : Type u) @[priority 100] -- see Note [lower instance priority] instance small_category [preorder α] : small_category α := { hom := λ U V, ulift (plift (U ≤ V)), id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩, comp := λ X Y Z f g, ⟨ ⟨ le_trans _ _ _ f.down.down g.down.down ⟩ ⟩ } end preorder
7d3033832f9847ad9097c3b66c629695db8ec7f1
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/polynomial/div.lean
fcda31c899e9591e74de8f91213930f0aa34a536
[ "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
25,584
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.monic import ring_theory.euclidean_domain import ring_theory.multiplicity /-! # Division of univariate polynomials The main defs are `div_by_monic` and `mod_by_monic`. The compatibility between these is given by `mod_by_monic_add_div`. We also define `root_multiplicity`. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset add_monoid_algebra open_locale big_operators 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 : polynomial R} section /-- The coercion turning a `polynomial` into the function which reports the coefficient of a given monomial `X^n` -/ -- TODO we would like to completely remove this, but this requires fixing some proofs def coeff_coe_to_fun : has_coe_to_fun (polynomial R) := finsupp.has_coe_to_fun local attribute [instance] coeff_coe_to_fun lemma apply_eq_coeff : p n = coeff p n := rfl end /-- `div_X p` return 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 : polynomial R) : polynomial R := { to_fun := λ n, p.coeff (n + 1), support := ⟨(p.support.filter (> 0)).1.map (λ n, n - 1), multiset.nodup_map_on begin simp only [finset.mem_def.symm, finset.mem_erase, finset.mem_filter], assume x hx y hy hxy, rwa [← @add_right_cancel_iff _ _ 1, nat.sub_add_cancel hx.2, nat.sub_add_cancel hy.2] at hxy end (p.support.filter (> 0)).2⟩, mem_support_to_fun := λ n, suffices (∃ (a : ℕ), (¬coeff p a = 0 ∧ a > 0) ∧ a - 1 = n) ↔ ¬coeff p (n + 1) = 0, by simpa [finset.mem_def.symm], ⟨λ ⟨a, ha⟩, by rw [← ha.2, nat.sub_add_cancel ha.1.2]; exact ha.1.1, λ h, ⟨n + 1, ⟨h, nat.succ_pos _⟩, nat.succ_sub_one _⟩⟩ } lemma div_X_mul_X_add (p : polynomial R) : div_X p * X + C (p.coeff 0) = p := ext $ λ n, nat.cases_on n (by simp) (by simp [coeff_C, nat.succ_ne_zero, coeff_mul_X, div_X]) @[simp] lemma div_X_C (a : R) : div_X (C a) = 0 := ext $ λ n, by cases n; simp [div_X, coeff_C]; simp [coeff] 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 [div_X] lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree := by haveI := nonzero.of_polynomial_ne hp0; exact 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 : polynomial R) : 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_refl _), by rw [add_comm, degree_add_eq_of_degree_lt this]; exact degree_lt_degree_mul_X hXp0 ... = p.degree : by rw 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 : polynomial R → Sort*} : Π (p : polynomial R), 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} @[elab_as_eliminator] lemma degree_pos_induction_on {P : polynomial R → Prop} (p : polynomial R) (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 end semiring section comm_semiring variables [comm_semiring R] theorem X_dvd_iff {α : Type u} [comm_semiring α] {f : polynomial α} : X ∣ f ↔ f.coeff 0 = 0 := ⟨λ ⟨g, hfg⟩, by rw [hfg, mul_comm, coeff_mul_X_zero], λ hf, ⟨f.div_X, by rw [mul_comm, ← add_zero (f.div_X * X), ← C_0, ← hf, div_X_mul_X_add]⟩⟩ end comm_semiring section comm_semiring variables [comm_semiring R] {p q : polynomial R} lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p) (hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q := have zn0 : (0 : R) ≠ 1, from λ h, by haveI := subsingleton_of_zero_eq_one h; exact hq (subsingleton.elim _ _), ⟨nat_degree q, λ ⟨r, hr⟩, have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction, have hr0 : r ≠ 0, from λ hr0, by simp * at *, have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1, by simp [show _ = _, from hmp], have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0, from hpn1.symm ▸ zn0.symm, have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0, by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1, one_pow, one_mul, ne.def, hr0]; simp, have hpn0 : p ^ (nat_degree q + 1) ≠ 0, from mt leading_coeff_eq_zero.2 $ by rw [leading_coeff_pow' hpn0', show _ = _, from hmp, one_pow]; exact zn0.symm, have hnp : 0 < nat_degree p, by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0]; exact hp, begin have := congr_arg nat_degree hr, rw [nat_degree_mul' hpnr0, nat_degree_pow' hpn0', add_mul, add_assoc] at this, exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_one_le_right' (nat.zero_le _) hnp) (add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this end⟩ end comm_semiring section ring variables [ring R] {p q : polynomial R} lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) * leading_coeff q ≠ 0, by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one], if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0 then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2)) else have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [degree_mul' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt]) h.2 (by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one]) /-- See `div_by_monic`. -/ noncomputable def div_mod_by_monic_aux : Π (p : polynomial R) {q : polynomial R}, monic q → polynomial R × polynomial R | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial R) : polynomial R := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : polynomial R) : polynomial R := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q) (hq0 : q ≠ 0), degree (p %ₘ q) < degree q | p := λ q hq hq0, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq hq0, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq0)), end using_well_founded {dec_tac := tactic.assumption} @[simp] lemma zero_mod_by_monic (p : polynomial R) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma zero_div_by_monic (p : polynomial R) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma mod_by_monic_zero (p : polynomial R) : p %ₘ 0 = p := if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h @[simp] lemma div_by_monic_zero (p : polynomial R) : p /ₘ 0 = 0 := if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h lemma div_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ theorem degree_mod_by_monic_le (p : polynomial R) {q : polynomial R} (hq : monic q) : degree (p %ₘ q) ≤ degree q := decidable.by_cases (assume H : q = 0, by rw [monic, H, leading_coeff_zero] at hq; have : (0:polynomial R) = 1 := (by rw [← C_0, ← C_1, hq]); exact le_of_eq (congr_arg _ $ eq_of_zero_eq_one this (p %ₘ q) q)) (assume H : q ≠ 0, le_of_lt $ degree_mod_by_monic_lt _ hq H) end ring section comm_ring variables [comm_ring R] {p q : polynomial R} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, unfold div_by_monic, rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero] end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_add_div (p : polynomial R) {q : polynomial R} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := if hq0 : q = 0 then have ∀ (p : polynomial R), p = 0, from λ p, (@subsingleton_of_monic_zero R _ (hq0 ▸ hq)).1 _ _, by rw [this (p /ₘ q), this p, this q]; refl else have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0 ... ≤ _ : by rw [degree_mul' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) lemma degree_div_by_monic_le (p q : polynomial R) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl] else if hq : monic q then have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if h : degree q ≤ degree p then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : polynomial R) {q : polynomial R} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if hpq : degree p < degree q then begin rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_some _ end else begin rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q)) end theorem nat_degree_div_by_monic {R : Type u} [comm_ring R] (f : polynomial R) {g : polynomial R} (hg : g.monic) : nat_degree (f /ₘ g) = nat_degree f - nat_degree g := begin by_cases h01 : (0 : R) = 1, { haveI := subsingleton_of_zero_eq_one h01, rw [subsingleton.elim (f /ₘ g) 0, subsingleton.elim f 0, subsingleton.elim g 0, nat_degree_zero] }, haveI : nontrivial R := ⟨⟨0, 1, h01⟩⟩, by_cases hfg : f /ₘ g = 0, { rw [hfg, nat_degree_zero], rw div_by_monic_eq_zero_iff hg hg.ne_zero at hfg, rw nat.sub_eq_zero_of_le (nat_degree_le_nat_degree $ le_of_lt hfg) }, have hgf := hfg, rw div_by_monic_eq_zero_iff hg hg.ne_zero at hgf, push_neg at hgf, have := degree_add_div_by_monic hg hgf, have hf : f ≠ 0, { intro hf, apply hfg, rw [hf, zero_div_by_monic] }, rw [degree_eq_nat_degree hf, degree_eq_nat_degree hg.ne_zero, degree_eq_nat_degree hfg, ← with_bot.coe_add, with_bot.coe_eq_coe] at this, rw [← this, nat.add_sub_cancel_left] end lemma div_mod_by_monic_unique {f g} (q r : polynomial R) (hg : monic g) (h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r := if hg0 : g = 0 then by split; exact (subsingleton_of_monic_zero (hg0 ▸ hg : monic (0 : polynomial R))).1 _ _ else have h₁ : r - f %ₘ g = -g * (q - f /ₘ g), from eq_of_sub_eq_zero (by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)]; simp [mul_add, mul_comm, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]), have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)), by simp [h₁], have h₄ : degree (r - f %ₘ g) < degree g, from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (-(f %ₘ g))) : degree_add_le _ _ ... < degree g : max_lt_iff.2 ⟨h.2, by rw degree_neg; exact degree_mod_by_monic_lt _ hg hg0⟩, have h₅ : q - (f /ₘ g) = 0, from by_contradiction (λ hqf, not_le_of_gt h₄ $ calc degree g ≤ degree g + degree (q - f /ₘ g) : by erw [degree_eq_nat_degree hg0, degree_eq_nat_degree hqf, with_bot.coe_le_coe]; exact nat.le_add_right _ _ ... = degree (r - f %ₘ g) : by rw [h₂, degree_mul']; simpa [monic.def.1 hg]), ⟨eq.symm $ eq_of_sub_eq_zero h₅, eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩ lemma map_mod_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f := if h01 : (0 : S) = 1 then by haveI := subsingleton_of_zero_eq_one h01; exact ⟨subsingleton.elim _ _, subsingleton.elim _ _⟩ else have h01R : (0 : R) ≠ 1, from mt (congr_arg f) (by rwa [is_semiring_hom.map_one f, is_semiring_hom.map_zero f]), have map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q), from (div_mod_by_monic_unique ((p /ₘ q).map f) _ (monic_map f hq) ⟨eq.symm $ by rw [← map_mul, ← map_add, mod_by_monic_add_div _ hq], calc _ ≤ degree (p %ₘ q) : degree_map_le _ ... < degree q : degree_mod_by_monic_lt _ hq $ (ne_zero_of_monic_of_zero_ne_one hq h01R) ... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _ (by rw [monic.def.1 hq, is_semiring_hom.map_one f]; exact ne.symm h01)⟩), ⟨this.1.symm, this.2.symm⟩ lemma map_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f := (map_mod_div_by_monic f hq).1 lemma map_mod_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p %ₘ q).map f = p.map f %ₘ q.map f := (map_mod_div_by_monic f hq).2 lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, if hq0 : q = 0 then by rw hq0 at hq; exact (subsingleton_of_monic_zero hq).1 _ _ else let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in by_contradiction (λ hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q) := by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr], have degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq hq0, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], by rw [degree_mul' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this; exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩ @[simp] lemma mod_by_monic_one (p : polynomial R) : p %ₘ 1 = 0 := (dvd_iff_mod_by_monic_eq_zero (by convert monic_one)).2 (one_dvd _) @[simp] lemma div_by_monic_one (p : polynomial R) : p /ₘ 1 = p := by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p %ₘ (X - C a) = C (p.eval a) := if h0 : (0 : R) = 1 then by letI := subsingleton_of_zero_eq_one h0; exact subsingleton.elim _ _ else by haveI : nontrivial R := nontrivial_of_ne 0 1 h0; exact have h : (p %ₘ (X - C a)).eval a = p.eval a := by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero], have degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸ ne_zero_of_monic (monic_X_sub_C _)), have degree (p %ₘ (X - C a)) ≤ 0 := begin cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } end, begin rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ lemma mod_by_monic_X (p : polynomial R) : p %ₘ X = C (p.eval 0) := by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero] section multiplicity /-- An algorithm for deciding polynomial divisibility. The algorithm is "compute `p %ₘ q` and compare to `0`". ` See `polynomial.mod_by_monic` for the algorithm that computes `%ₘ`. -/ def decidable_dvd_monic (p : polynomial R) (hq : monic q) : decidable (q ∣ p) := decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq) open_locale classical lemma multiplicity_X_sub_C_finite (a : R) (h0 : p ≠ 0) : multiplicity.finite (X - C a) p := multiplicity_finite_of_degree_pos_of_monic (have (0 : R) ≠ 1, from (λ h, by haveI := subsingleton_of_zero_eq_one h; exact h0 (subsingleton.elim _ _)), by haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩; rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) h0 /-- The largest power of `X - C a` which divides `p`. This is computable via the divisibility algorithm `decidable_dvd_monic`. -/ def root_multiplicity (a : R) (p : polynomial R) : ℕ := if h0 : p = 0 then 0 else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) := λ n, @not.decidable _ (decidable_dvd_monic p (monic_pow (monic_X_sub_C a) (n + 1))) in by exactI nat.find (multiplicity_X_sub_C_finite a h0) lemma root_multiplicity_eq_multiplicity (p : polynomial R) (a : R) : root_multiplicity a p = if h0 : p = 0 then 0 else (multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) := by simp [multiplicity, root_multiplicity, roption.dom]; congr; funext; congr lemma pow_root_multiplicity_dvd (p : polynomial R) (a : R) : (X - C a) ^ root_multiplicity a p ∣ p := if h : p = 0 then by simp [h] else by rw [root_multiplicity_eq_multiplicity, dif_neg h]; exact multiplicity.pow_multiplicity_dvd _ lemma div_by_monic_mul_pow_root_multiplicity_eq (p : polynomial R) (a : R) : p /ₘ ((X - C a) ^ root_multiplicity a p) * (X - C a) ^ root_multiplicity a p = p := have monic ((X - C a) ^ root_multiplicity a p), from monic_pow (monic_X_sub_C _) _, by conv_rhs { rw [← mod_by_monic_add_div p this, (dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] }; simp [mul_comm] lemma eval_div_by_monic_pow_root_multiplicity_ne_zero {p : polynomial R} (a : R) (hp : p ≠ 0) : (p /ₘ ((X - C a) ^ root_multiplicity a p)).eval a ≠ 0 := begin haveI : nontrivial R := nonzero.of_polynomial_ne hp, rw [ne.def, ← is_root.def, ← dvd_iff_is_root], rintros ⟨q, hq⟩, have := div_by_monic_mul_pow_root_multiplicity_eq p a, rw [mul_comm, hq, ← mul_assoc, ← pow_succ', root_multiplicity_eq_multiplicity, dif_neg hp] at this, exact multiplicity.is_greatest' (multiplicity_finite_of_degree_pos_of_monic (show (0 : with_bot ℕ) < degree (X - C a), by rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) hp) (nat.lt_succ_self _) (dvd_of_mul_right_eq _ this) end end multiplicity end comm_ring end polynomial
79485dd57e27fb10659cfb92e9d738ffc16846d3
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/monoidal_categories/internal_objects/free_modules.lean
8e44a4fac98ed9f4c583ae0c19c9f05551298a51
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
3,166
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import .monoids open tqft.categories open tqft.categories.functor open tqft.categories.monoidal_category namespace tqft.categories.internal_objects -- set_option pp.max_steps 50000 -- set_option pp.implicit true -- set_option pp.universes true -- set_option pp.coercions true -- set_option pp.all true -- set_option pp.implicit false -- local attribute [elab_simple] prod.mk -- definition CategoryOfFreeModules { C : Category } { m : MonoidalStructure C } ( A : MonoidObject m ) : Category := -- { -- Obj := C.Obj, -- Hom := λ X Y, C.Hom X (m.tensorObjects A.object Y), -- identity := λ X, C.compose (m.left_unitor.inverse.components X) (m.tensorMorphisms A.unit (C.identity X)), -- compose := λ _ _ Z f g, C.compose (C.compose (C.compose f (m.tensorMorphisms (C.identity A.object) g)) (m.inverse_associator A.object A.object Z)) (m.tensorMorphisms A.multiplication (C.identity Z)), -- left_identity := begin -- -- PROJECT dealing with associativity here is quite tedious. -- -- PROJECT this is a great example problem for clever automation. -- -- A human quickly sees that we need to combine A.unit and A.multiplication to make them cancel, -- -- and then performs the necessary rewrites to get there. -- intros, -- dsimp, -- rewrite C.associativity, -- rewrite C.associativity, -- rewrite C.associativity, -- erewrite - C.associativity (m.tensorMorphisms A.unit (C.identity X)), -- rewrite - m.interchange_identities, -- rewrite C.associativity, -- rewrite - C.associativity (m.tensorMorphisms A.unit (C.identity (m.tensorObjects A.object Y))), -- rewrite - m.tensor.identities, -- erewrite m.inverse_associator_naturality_0 A.unit (C.identity A.object) (C.identity Y), -- erewrite C.associativity, -- erewrite - m.interchange, -- rewrite A.left_identity, -- <<--- here is the only interesting step! -- simp, dsimp, -- erewrite C.right_identity, -- erewrite - C.associativity, -- erewrite - m.left_unitor.inverse.naturality, -- dunfold IdentityFunctor, dsimp, -- erewrite C.associativity, -- -- PROJECT this needs Proposition 2.2.4 of Etingof's "Tensor Categories" to finish; and that seems awkward to prove in our setup! -- exact sorry -- end, -- right_identity := sorry, -- associativity := sorry -- } -- PROJECT show that after idempotent completing the category of free modules we get the category of modules?? -- PROJECT bimodules -- PROJECT commutative algebras; modules give bimodules end tqft.categories.internal_objects
c96c7dd66ac389ca535b23cd389c6ae72296f9f2
72d99e722771bfc4f845b49212c0f743cf3f08df
/tests/lean/run/1954.lean
e9e000a5634ad125188cd52e3805c6bff80f512a
[ "Apache-2.0" ]
permissive
AtnNn/lean
c79fa061e300e0ebea0186d9f7db971e839e8955
d97d77fd30601f06c751ca376c0cdddd59cf52f9
refs/heads/master
1,583,885,051,450
1,523,730,668,000
1,523,730,668,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
109
lean
def all (p : ℕ → Prop) : Prop := ∀x, p x example {p : ℕ → Prop} (h : all p) : p 0 := ‹all p› 0
7e0154bd428353f35d4383361c2ebbb9a2c55066
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/IR/Basic.lean
a9a84268ada9bcc79738ed046d6e6cb95253ab92
[ "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
26,461
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.KVMap import Lean.Data.Name import Lean.Data.Format import Lean.Compiler.ExternAttr /-! Implements (extended) λPure and λRc proposed in the article "Counting Immutable Beans", Sebastian Ullrich and Leonardo de Moura. The Lean to IR transformation produces λPure code, and this part is implemented in C++. The procedures described in the paper above are implemented in Lean. -/ namespace Lean.IR /-- Function identifier -/ abbrev FunId := Name abbrev Index := Nat /-- Variable identifier -/ structure VarId where idx : Index deriving Inhabited /-- Join point identifier -/ structure JoinPointId where idx : Index deriving Inhabited abbrev Index.lt (a b : Index) : Bool := a < b instance : BEq VarId := ⟨fun a b => a.idx == b.idx⟩ instance : ToString VarId := ⟨fun a => "x_" ++ toString a.idx⟩ instance : ToFormat VarId := ⟨fun a => toString a⟩ instance : Hashable VarId := ⟨fun a => hash a.idx⟩ instance : BEq JoinPointId := ⟨fun a b => a.idx == b.idx⟩ instance : ToString JoinPointId := ⟨fun a => "block_" ++ toString a.idx⟩ instance : ToFormat JoinPointId := ⟨fun a => toString a⟩ instance : Hashable JoinPointId := ⟨fun a => hash a.idx⟩ abbrev MData := KVMap abbrev MData.empty : MData := {} /-- Low Level IR types. Most are self explanatory. - `usize` represents the C++ `size_t` Type. We have it here because it is 32-bit in 32-bit machines, and 64-bit in 64-bit machines, and we want the C++ backend for our Compiler to generate platform independent code. - `irrelevant` for Lean types, propositions and proofs. - `object` a pointer to a value in the heap. - `tobject` a pointer to a value in the heap or tagged pointer (i.e., the least significant bit is 1) storing a scalar value. - `struct` and `union` are used to return small values (e.g., `Option`, `Prod`, `Except`) on the stack. Remark: the RC operations for `tobject` are slightly more expensive because we first need to test whether the `tobject` is really a pointer or not. Remark: the Lean runtime assumes that sizeof(void*) == sizeof(sizeT). Lean cannot be compiled on old platforms where this is not True. Since values of type `struct` and `union` are only used to return values, We assume they must be used/consumed "linearly". We use the term "linear" here to mean "exactly once" in each execution. That is, given `x : S`, where `S` is a struct, then one of the following must hold in each (execution) branch. 1- `x` occurs only at a single `ret x` instruction. That is, it is being consumed by being returned. 2- `x` occurs only at a single `ctor`. That is, it is being "consumed" by being stored into another `struct/union`. 3- We extract (aka project) every single field of `x` exactly once. That is, we are consuming `x` by consuming each of one of its components. Minor refinement: we don't need to consume scalar fields or struct/union fields that do not contain object fields. -/ inductive IRType where | float | uint8 | uint16 | uint32 | uint64 | usize | irrelevant | object | tobject | struct (leanTypeName : Option Name) (types : Array IRType) : IRType | union (leanTypeName : Name) (types : Array IRType) : IRType deriving Inhabited namespace IRType partial def beq : IRType → IRType → Bool | float, float => true | uint8, uint8 => true | uint16, uint16 => true | uint32, uint32 => true | uint64, uint64 => true | usize, usize => true | irrelevant, irrelevant => true | object, object => true | tobject, tobject => true | struct n₁ tys₁, struct n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | union n₁ tys₁, union n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | _, _ => false instance : BEq IRType := ⟨beq⟩ def isScalar : IRType → Bool | float => true | uint8 => true | uint16 => true | uint32 => true | uint64 => true | usize => true | _ => false def isObj : IRType → Bool | object => true | tobject => true | _ => false def isIrrelevant : IRType → Bool | irrelevant => true | _ => false def isStruct : IRType → Bool | struct _ _ => true | _ => false def isUnion : IRType → Bool | union _ _ => true | _ => false end IRType /-- Arguments to applications, constructors, etc. We use `irrelevant` for Lean types, propositions and proofs that have been erased. Recall that for a Function `f`, we also generate `f._rarg` which does not take `irrelevant` arguments. However, `f._rarg` is only safe to be used in full applications. -/ inductive Arg where | var (id : VarId) | irrelevant deriving Inhabited protected def Arg.beq : Arg → Arg → Bool | var x, var y => x == y | irrelevant, irrelevant => true | _, _ => false instance : BEq Arg := ⟨Arg.beq⟩ @[export lean_ir_mk_var_arg] def mkVarArg (id : VarId) : Arg := Arg.var id inductive LitVal where | num (v : Nat) | str (v : String) def LitVal.beq : LitVal → LitVal → Bool | num v₁, num v₂ => v₁ == v₂ | str v₁, str v₂ => v₁ == v₂ | _, _ => false instance : BEq LitVal := ⟨LitVal.beq⟩ /-- Constructor information. - `name` is the Name of the Constructor in Lean. - `cidx` is the Constructor index (aka tag). - `size` is the number of arguments of type `object/tobject`. - `usize` is the number of arguments of type `usize`. - `ssize` is the number of bytes used to store scalar values. Recall that a Constructor object contains a header, then a sequence of pointers to other Lean objects, a sequence of `USize` (i.e., `size_t`) scalar values, and a sequence of other scalar values. -/ structure CtorInfo where name : Name cidx : Nat size : Nat usize : Nat ssize : Nat deriving Repr def CtorInfo.beq : CtorInfo → CtorInfo → Bool | ⟨n₁, cidx₁, size₁, usize₁, ssize₁⟩, ⟨n₂, cidx₂, size₂, usize₂, ssize₂⟩ => n₁ == n₂ && cidx₁ == cidx₂ && size₁ == size₂ && usize₁ == usize₂ && ssize₁ == ssize₂ instance : BEq CtorInfo := ⟨CtorInfo.beq⟩ def CtorInfo.isRef (info : CtorInfo) : Bool := info.size > 0 || info.usize > 0 || info.ssize > 0 def CtorInfo.isScalar (info : CtorInfo) : Bool := !info.isRef inductive Expr where /-- We use `ctor` mainly for constructing Lean object/tobject values `lean_ctor_object` in the runtime. This instruction is also used to creat `struct` and `union` return values. For `union`, only `i.cidx` is relevant. For `struct`, `i` is irrelevant. -/ | ctor (i : CtorInfo) (ys : Array Arg) | reset (n : Nat) (x : VarId) /-- `reuse x in ctor_i ys` instruction in the paper. -/ | reuse (x : VarId) (i : CtorInfo) (updtHeader : Bool) (ys : Array Arg) /-- Extract the `tobject` value at Position `sizeof(void*)*i` from `x`. We also use `proj` for extracting fields from `struct` return values, and casting `union` return values. -/ | proj (i : Nat) (x : VarId) /-- Extract the `Usize` value at Position `sizeof(void*)*i` from `x`. -/ | uproj (i : Nat) (x : VarId) /-- Extract the scalar value at Position `sizeof(void*)*n + offset` from `x`. -/ | sproj (n : Nat) (offset : Nat) (x : VarId) /-- Full application. -/ | fap (c : FunId) (ys : Array Arg) /-- Partial application that creates a `pap` value (aka closure in our nonstandard terminology). -/ | pap (c : FunId) (ys : Array Arg) /-- Application. `x` must be a `pap` value. -/ | ap (x : VarId) (ys : Array Arg) /-- Given `x : ty` where `ty` is a scalar type, this operation returns a value of Type `tobject`. For small scalar values, the Result is a tagged pointer, and no memory allocation is performed. -/ | box (ty : IRType) (x : VarId) /-- Given `x : [t]object`, obtain the scalar value. -/ | unbox (x : VarId) | lit (v : LitVal) /-- Return `1 : uint8` Iff `RC(x) > 1` -/ | isShared (x : VarId) @[export lean_ir_mk_ctor_expr] def mkCtorExpr (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (ys : Array Arg) : Expr := Expr.ctor ⟨n, cidx, size, usize, ssize⟩ ys @[export lean_ir_mk_proj_expr] def mkProjExpr (i : Nat) (x : VarId) : Expr := Expr.proj i x @[export lean_ir_mk_uproj_expr] def mkUProjExpr (i : Nat) (x : VarId) : Expr := Expr.uproj i x @[export lean_ir_mk_sproj_expr] def mkSProjExpr (n : Nat) (offset : Nat) (x : VarId) : Expr := Expr.sproj n offset x @[export lean_ir_mk_fapp_expr] def mkFAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.fap c ys @[export lean_ir_mk_papp_expr] def mkPAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.pap c ys @[export lean_ir_mk_app_expr] def mkAppExpr (x : VarId) (ys : Array Arg) : Expr := Expr.ap x ys @[export lean_ir_mk_num_expr] def mkNumExpr (v : Nat) : Expr := Expr.lit (LitVal.num v) @[export lean_ir_mk_str_expr] def mkStrExpr (v : String) : Expr := Expr.lit (LitVal.str v) structure Param where x : VarId borrow : Bool ty : IRType deriving Inhabited @[export lean_ir_mk_param] def mkParam (x : VarId) (borrow : Bool) (ty : IRType) : Param := ⟨x, borrow, ty⟩ inductive AltCore (FnBody : Type) : Type where | ctor (info : CtorInfo) (b : FnBody) : AltCore FnBody | default (b : FnBody) : AltCore FnBody inductive FnBody where /-- `let x : ty := e; b` -/ | vdecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) /-- Join point Declaration `block_j (xs) := e; b` -/ | jdecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) /-- Store `y` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. This operation is not part of λPure is only used during optimization. -/ | set (x : VarId) (i : Nat) (y : Arg) (b : FnBody) | setTag (x : VarId) (cidx : Nat) (b : FnBody) /-- Store `y : Usize` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. -/ | uset (x : VarId) (i : Nat) (y : VarId) (b : FnBody) /-- Store `y : ty` at Position `sizeof(void*)*i + offset` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. `ty` must not be `object`, `tobject`, `irrelevant` nor `Usize`. -/ | sset (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) /-- RC increment for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | inc (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) /-- RC decrement for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | dec (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) | del (x : VarId) (b : FnBody) | mdata (d : MData) (b : FnBody) | case (tid : Name) (x : VarId) (xType : IRType) (cs : Array (AltCore FnBody)) | ret (x : Arg) /-- Jump to join point `j` -/ | jmp (j : JoinPointId) (ys : Array Arg) | unreachable instance : Inhabited FnBody := ⟨FnBody.unreachable⟩ abbrev FnBody.nil := FnBody.unreachable @[export lean_ir_mk_vdecl] def mkVDecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : FnBody := FnBody.vdecl x ty e b @[export lean_ir_mk_jdecl] def mkJDecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) : FnBody := FnBody.jdecl j xs v b @[export lean_ir_mk_uset] def mkUSet (x : VarId) (i : Nat) (y : VarId) (b : FnBody) : FnBody := FnBody.uset x i y b @[export lean_ir_mk_sset] def mkSSet (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) : FnBody := FnBody.sset x i offset y ty b @[export lean_ir_mk_case] def mkCase (tid : Name) (x : VarId) (cs : Array (AltCore FnBody)) : FnBody := -- Type field `xType` is set by `explicitBoxing` compiler pass. FnBody.case tid x IRType.object cs @[export lean_ir_mk_ret] def mkRet (x : Arg) : FnBody := FnBody.ret x @[export lean_ir_mk_jmp] def mkJmp (j : JoinPointId) (ys : Array Arg) : FnBody := FnBody.jmp j ys @[export lean_ir_mk_unreachable] def mkUnreachable : Unit → FnBody := fun _ => FnBody.unreachable abbrev Alt := AltCore FnBody @[match_pattern] abbrev Alt.ctor := @AltCore.ctor FnBody @[match_pattern] abbrev Alt.default := @AltCore.default FnBody instance : Inhabited Alt := ⟨Alt.default default⟩ def FnBody.isTerminal : FnBody → Bool | FnBody.case _ _ _ _ => true | FnBody.ret _ => true | FnBody.jmp _ _ => true | FnBody.unreachable => true | _ => false def FnBody.body : FnBody → FnBody | FnBody.vdecl _ _ _ b => b | FnBody.jdecl _ _ _ b => b | FnBody.set _ _ _ b => b | FnBody.uset _ _ _ b => b | FnBody.sset _ _ _ _ _ b => b | FnBody.setTag _ _ b => b | FnBody.inc _ _ _ _ b => b | FnBody.dec _ _ _ _ b => b | FnBody.del _ b => b | FnBody.mdata _ b => b | other => other def FnBody.setBody : FnBody → FnBody → FnBody | FnBody.vdecl x t v _, b => FnBody.vdecl x t v b | FnBody.jdecl j xs v _, b => FnBody.jdecl j xs v b | FnBody.set x i y _, b => FnBody.set x i y b | FnBody.uset x i y _, b => FnBody.uset x i y b | FnBody.sset x i o y t _, b => FnBody.sset x i o y t b | FnBody.setTag x i _, b => FnBody.setTag x i b | FnBody.inc x n c p _, b => FnBody.inc x n c p b | FnBody.dec x n c p _, b => FnBody.dec x n c p b | FnBody.del x _, b => FnBody.del x b | FnBody.mdata d _, b => FnBody.mdata d b | other, _ => other @[inline] def FnBody.resetBody (b : FnBody) : FnBody := b.setBody FnBody.nil /-- If b is a non terminal, then return a pair `(c, b')` s.t. `b == c <;> b'`, and c.body == FnBody.nil -/ @[inline] def FnBody.split (b : FnBody) : FnBody × FnBody := let b' := b.body let c := b.resetBody (c, b') def AltCore.body : Alt → FnBody | Alt.ctor _ b => b | Alt.default b => b def AltCore.setBody : Alt → FnBody → Alt | Alt.ctor c _, b => Alt.ctor c b | Alt.default _, b => Alt.default b @[inline] def AltCore.modifyBody (f : FnBody → FnBody) : AltCore FnBody → Alt | Alt.ctor c b => Alt.ctor c (f b) | Alt.default b => Alt.default (f b) @[inline] def AltCore.mmodifyBody {m : Type → Type} [Monad m] (f : FnBody → m FnBody) : AltCore FnBody → m Alt | Alt.ctor c b => Alt.ctor c <$> f b | Alt.default b => Alt.default <$> f b def Alt.isDefault : Alt → Bool | Alt.ctor _ _ => false | Alt.default _ => true def push (bs : Array FnBody) (b : FnBody) : Array FnBody := let b := b.resetBody bs.push b partial def flattenAux (b : FnBody) (r : Array FnBody) : (Array FnBody) × FnBody := if b.isTerminal then (r, b) else flattenAux b.body (push r b) def FnBody.flatten (b : FnBody) : (Array FnBody) × FnBody := flattenAux b #[] partial def reshapeAux (a : Array FnBody) (i : Nat) (b : FnBody) : FnBody := if i == 0 then b else let i := i - 1 let (curr, a) := a.swapAt! i default let b := curr.setBody b reshapeAux a i b def reshape (bs : Array FnBody) (term : FnBody) : FnBody := reshapeAux bs bs.size term @[inline] def modifyJPs (bs : Array FnBody) (f : FnBody → FnBody) : Array FnBody := bs.map fun b => match b with | FnBody.jdecl j xs v k => FnBody.jdecl j xs (f v) k | other => other @[inline] def mmodifyJPs {m : Type → Type} [Monad m] (bs : Array FnBody) (f : FnBody → m FnBody) : m (Array FnBody) := bs.mapM fun b => match b with | FnBody.jdecl j xs v k => return FnBody.jdecl j xs (← f v) k | other => return other @[export lean_ir_mk_alt] def mkAlt (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (b : FnBody) : Alt := Alt.ctor ⟨n, cidx, size, usize, ssize⟩ b /-- Extra information associated with a declaration. -/ structure DeclInfo where /-- If `some <blame>`, then declaration depends on `<blame>` which uses a `sorry` axiom. -/ sorryDep? : Option Name := none inductive Decl where | fdecl (f : FunId) (xs : Array Param) (type : IRType) (body : FnBody) (info : DeclInfo) | extern (f : FunId) (xs : Array Param) (type : IRType) (ext : ExternAttrData) deriving Inhabited namespace Decl def name : Decl → FunId | .fdecl f .. => f | .extern f .. => f def params : Decl → Array Param | .fdecl (xs := xs) .. => xs | .extern (xs := xs) .. => xs def resultType : Decl → IRType | .fdecl (type := t) .. => t | .extern (type := t) .. => t def isExtern : Decl → Bool | .extern .. => true | _ => false def getInfo : Decl → DeclInfo | .fdecl (info := info) .. => info | _ => {} def updateBody! (d : Decl) (bNew : FnBody) : Decl := match d with | Decl.fdecl f xs t _ info => Decl.fdecl f xs t bNew info | _ => panic! "expected definition" end Decl @[export lean_ir_mk_decl] def mkDecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) : Decl := Decl.fdecl f xs ty b {} @[export lean_ir_mk_extern_decl] def mkExternDecl (f : FunId) (xs : Array Param) (ty : IRType) (e : ExternAttrData) : Decl := Decl.extern f xs ty e -- Hack: we use this declaration as a stub for declarations annotated with `implemented_by` or `init` @[export lean_ir_mk_dummy_extern_decl] def mkDummyExternDecl (f : FunId) (xs : Array Param) (ty : IRType) : Decl := Decl.fdecl f xs ty FnBody.unreachable {} /-- Set of variable and join point names -/ abbrev IndexSet := RBTree Index compare instance : Inhabited IndexSet := ⟨{}⟩ def mkIndexSet (idx : Index) : IndexSet := RBTree.empty.insert idx inductive LocalContextEntry where | param : IRType → LocalContextEntry | localVar : IRType → Expr → LocalContextEntry | joinPoint : Array Param → FnBody → LocalContextEntry abbrev LocalContext := RBMap Index LocalContextEntry compare def LocalContext.addLocal (ctx : LocalContext) (x : VarId) (t : IRType) (v : Expr) : LocalContext := ctx.insert x.idx (LocalContextEntry.localVar t v) def LocalContext.addJP (ctx : LocalContext) (j : JoinPointId) (xs : Array Param) (b : FnBody) : LocalContext := ctx.insert j.idx (LocalContextEntry.joinPoint xs b) def LocalContext.addParam (ctx : LocalContext) (p : Param) : LocalContext := ctx.insert p.x.idx (LocalContextEntry.param p.ty) def LocalContext.addParams (ctx : LocalContext) (ps : Array Param) : LocalContext := ps.foldl LocalContext.addParam ctx def LocalContext.isJP (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.joinPoint _ _) => true | _ => false def LocalContext.getJPBody (ctx : LocalContext) (j : JoinPointId) : Option FnBody := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint _ b) => some b | _ => none def LocalContext.getJPParams (ctx : LocalContext) (j : JoinPointId) : Option (Array Param) := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint ys _) => some ys | _ => none def LocalContext.isParam (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.param _) => true | _ => false def LocalContext.isLocalVar (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.localVar _ _) => true | _ => false def LocalContext.contains (ctx : LocalContext) (idx : Index) : Bool := RBMap.contains ctx idx def LocalContext.eraseJoinPointDecl (ctx : LocalContext) (j : JoinPointId) : LocalContext := ctx.erase j.idx def LocalContext.getType (ctx : LocalContext) (x : VarId) : Option IRType := match ctx.find? x.idx with | some (LocalContextEntry.param t) => some t | some (LocalContextEntry.localVar t _) => some t | _ => none def LocalContext.getValue (ctx : LocalContext) (x : VarId) : Option Expr := match ctx.find? x.idx with | some (LocalContextEntry.localVar _ v) => some v | _ => none abbrev IndexRenaming := RBMap Index Index compare class AlphaEqv (α : Type) where aeqv : IndexRenaming → α → α → Bool export AlphaEqv (aeqv) def VarId.alphaEqv (ρ : IndexRenaming) (v₁ v₂ : VarId) : Bool := match ρ.find? v₁.idx with | some v => v == v₂.idx | none => v₁ == v₂ instance : AlphaEqv VarId := ⟨VarId.alphaEqv⟩ def Arg.alphaEqv (ρ : IndexRenaming) : Arg → Arg → Bool | Arg.var v₁, Arg.var v₂ => aeqv ρ v₁ v₂ | Arg.irrelevant, Arg.irrelevant => true | _, _ => false instance : AlphaEqv Arg := ⟨Arg.alphaEqv⟩ def args.alphaEqv (ρ : IndexRenaming) (args₁ args₂ : Array Arg) : Bool := Array.isEqv args₁ args₂ (fun a b => aeqv ρ a b) instance: AlphaEqv (Array Arg) := ⟨args.alphaEqv⟩ def Expr.alphaEqv (ρ : IndexRenaming) : Expr → Expr → Bool | Expr.ctor i₁ ys₁, Expr.ctor i₂ ys₂ => i₁ == i₂ && aeqv ρ ys₁ ys₂ | Expr.reset n₁ x₁, Expr.reset n₂ x₂ => n₁ == n₂ && aeqv ρ x₁ x₂ | Expr.reuse x₁ i₁ u₁ ys₁, Expr.reuse x₂ i₂ u₂ ys₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && u₁ == u₂ && aeqv ρ ys₁ ys₂ | Expr.proj i₁ x₁, Expr.proj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.uproj i₁ x₁, Expr.uproj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.sproj n₁ o₁ x₁, Expr.sproj n₂ o₂ x₂ => n₁ == n₂ && o₁ == o₂ && aeqv ρ x₁ x₂ | Expr.fap c₁ ys₁, Expr.fap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.pap c₁ ys₁, Expr.pap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.ap x₁ ys₁, Expr.ap x₂ ys₂ => aeqv ρ x₁ x₂ && aeqv ρ ys₁ ys₂ | Expr.box ty₁ x₁, Expr.box ty₂ x₂ => ty₁ == ty₂ && aeqv ρ x₁ x₂ | Expr.unbox x₁, Expr.unbox x₂ => aeqv ρ x₁ x₂ | Expr.lit v₁, Expr.lit v₂ => v₁ == v₂ | Expr.isShared x₁, Expr.isShared x₂ => aeqv ρ x₁ x₂ | _, _ => false instance : AlphaEqv Expr:= ⟨Expr.alphaEqv⟩ def addVarRename (ρ : IndexRenaming) (x₁ x₂ : Nat) := if x₁ == x₂ then ρ else ρ.insert x₁ x₂ def addParamRename (ρ : IndexRenaming) (p₁ p₂ : Param) : Option IndexRenaming := if p₁.ty == p₂.ty && p₁.borrow = p₂.borrow then some (addVarRename ρ p₁.x.idx p₂.x.idx) else none def addParamsRename (ρ : IndexRenaming) (ps₁ ps₂ : Array Param) : Option IndexRenaming := do if ps₁.size != ps₂.size then failure else let mut ρ := ρ for i in [:ps₁.size] do ρ ← addParamRename ρ ps₁[i]! ps₂[i]! pure ρ partial def FnBody.alphaEqv : IndexRenaming → FnBody → FnBody → Bool | ρ, FnBody.vdecl x₁ t₁ v₁ b₁, FnBody.vdecl x₂ t₂ v₂ b₂ => t₁ == t₂ && aeqv ρ v₁ v₂ && alphaEqv (addVarRename ρ x₁.idx x₂.idx) b₁ b₂ | ρ, FnBody.jdecl j₁ ys₁ v₁ b₁, FnBody.jdecl j₂ ys₂ v₂ b₂ => match addParamsRename ρ ys₁ ys₂ with | some ρ' => alphaEqv ρ' v₁ v₂ && alphaEqv (addVarRename ρ j₁.idx j₂.idx) b₁ b₂ | none => false | ρ, FnBody.set x₁ i₁ y₁ b₁, FnBody.set x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.uset x₁ i₁ y₁ b₁, FnBody.uset x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.sset x₁ i₁ o₁ y₁ t₁ b₁, FnBody.sset x₂ i₂ o₂ y₂ t₂ b₂ => aeqv ρ x₁ x₂ && i₁ = i₂ && o₁ = o₂ && aeqv ρ y₁ y₂ && t₁ == t₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.setTag x₁ i₁ b₁, FnBody.setTag x₂ i₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.inc x₁ n₁ c₁ p₁ b₁, FnBody.inc x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.dec x₁ n₁ c₁ p₁ b₁, FnBody.dec x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.del x₁ b₁, FnBody.del x₂ b₂ => aeqv ρ x₁ x₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.mdata m₁ b₁, FnBody.mdata m₂ b₂ => m₁ == m₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.case n₁ x₁ _ alts₁, FnBody.case n₂ x₂ _ alts₂ => n₁ == n₂ && aeqv ρ x₁ x₂ && Array.isEqv alts₁ alts₂ (fun alt₁ alt₂ => match alt₁, alt₂ with | Alt.ctor i₁ b₁, Alt.ctor i₂ b₂ => i₁ == i₂ && alphaEqv ρ b₁ b₂ | Alt.default b₁, Alt.default b₂ => alphaEqv ρ b₁ b₂ | _, _ => false) | ρ, FnBody.jmp j₁ ys₁, FnBody.jmp j₂ ys₂ => j₁ == j₂ && aeqv ρ ys₁ ys₂ | ρ, FnBody.ret x₁, FnBody.ret x₂ => aeqv ρ x₁ x₂ | _, FnBody.unreachable, FnBody.unreachable => true | _, _, _ => false def FnBody.beq (b₁ b₂ : FnBody) : Bool := FnBody.alphaEqv ∅ b₁ b₂ instance : BEq FnBody := ⟨FnBody.beq⟩ abbrev VarIdSet := RBTree VarId (fun x y => compare x.idx y.idx) instance : Inhabited VarIdSet := ⟨{}⟩ def mkIf (x : VarId) (t e : FnBody) : FnBody := FnBody.case `Bool x IRType.uint8 #[ Alt.ctor {name := ``Bool.false, cidx := 0, size := 0, usize := 0, ssize := 0} e, Alt.ctor {name := ``Bool.true, cidx := 1, size := 0, usize := 0, ssize := 0} t ] def getUnboxOpName (t : IRType) : String := match t with | IRType.usize => "lean_unbox_usize" | IRType.uint32 => "lean_unbox_uint32" | IRType.uint64 => "lean_unbox_uint64" | IRType.float => "lean_unbox_float" | _ => "lean_unbox" end Lean.IR
f9237d4b280bac6b8beb8830eb063abf2f648887
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/algebra/order.lean
0ef206de403079d2e3959908937a898baf748c4e
[ "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
18,321
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Weak orders "≤", strict orders "<", and structures that include both. -/ import logic.eq logic.connectives algebra.binary algebra.priority open eq eq.ops function variables {A : Type} /- weak orders -/ structure weak_order [class] (A : Type) extends has_le A := (le_refl : ∀a, le a a) (le_trans : ∀a b c, le a b → le b c → le a c) (le_antisymm : ∀a b, le a b → le b a → a = b) section variables [weak_order A] theorem le.refl [refl] (a : A) : a ≤ a := !weak_order.le_refl theorem le_of_eq {a b : A} (H : a = b) : a ≤ b := H ▸ le.refl a theorem le.trans [trans] {a b c : A} : a ≤ b → b ≤ c → a ≤ c := !weak_order.le_trans theorem ge.trans [trans] {a b c : A} (H1 : a ≥ b) (H2: b ≥ c) : a ≥ c := le.trans H2 H1 theorem le.antisymm {a b : A} : a ≤ b → b ≤ a → a = b := !weak_order.le_antisymm -- Alternate syntax. (Abbreviations do not migrate well.) theorem eq_of_le_of_ge {a b : A} : a ≤ b → b ≤ a → a = b := !le.antisymm end structure linear_weak_order [class] (A : Type) extends weak_order A := (le_total : ∀a b, le a b ∨ le b a) section variables [linear_weak_order A] theorem le.total (a b : A) : a ≤ b ∨ b ≤ a := !linear_weak_order.le_total theorem le_of_not_ge {a b : A} (H : ¬ a ≥ b) : a ≤ b := or.resolve_left !le.total H theorem le_by_cases (a b : A) {P : Prop} (H1 : a ≤ b → P) (H2 : b ≤ a → P) : P := begin cases (le.total a b) with H H, { exact H1 H}, { exact H2 H} end end /- strict orders -/ structure strict_order [class] (A : Type) extends has_lt A := (lt_irrefl : ∀a, ¬ lt a a) (lt_trans : ∀a b c, lt a b → lt b c → lt a c) section variable [strict_order A] theorem lt.irrefl (a : A) : ¬ a < a := !strict_order.lt_irrefl theorem not_lt_self (a : A) : ¬ a < a := !lt.irrefl -- alternate syntax theorem lt_self_iff_false (a : A) : a < a ↔ false := iff_false_intro (lt.irrefl a) theorem lt.trans [trans] {a b c : A} : a < b → b < c → a < c := !strict_order.lt_trans theorem gt.trans [trans] {a b c : A} (H1 : a > b) (H2: b > c) : a > c := lt.trans H2 H1 theorem ne_of_lt {a b : A} (lt_ab : a < b) : a ≠ b := assume eq_ab : a = b, show false, from lt.irrefl b (eq_ab ▸ lt_ab) theorem ne_of_gt {a b : A} (gt_ab : a > b) : a ≠ b := ne.symm (ne_of_lt gt_ab) theorem lt.asymm {a b : A} (H : a < b) : ¬ b < a := assume H1 : b < a, lt.irrefl _ (lt.trans H H1) theorem not_lt_of_gt {a b : A} (H : a > b) : ¬ a < b := !lt.asymm H -- alternate syntax end /- well-founded orders -/ structure wf_strict_order [class] (A : Type) extends strict_order A := (wf_rec : ∀P : A → Type, (∀x, (∀y, lt y x → P y) → P x) → ∀x, P x) definition wf.rec_on {A : Type} [s : wf_strict_order A] {P : A → Type} (x : A) (H : ∀x, (∀y, wf_strict_order.lt y x → P y) → P x) : P x := wf_strict_order.wf_rec P H x theorem wf.ind_on.{u v} {A : Type.{u}} [s : wf_strict_order.{u 0} A] {P : A → Prop} (x : A) (H : ∀x, (∀y, wf_strict_order.lt y x → P y) → P x) : P x := wf.rec_on x H /- structures with a weak and a strict order -/ structure order_pair [class] (A : Type) extends weak_order A, has_lt A := (le_of_lt : ∀ a b, lt a b → le a b) (lt_of_lt_of_le : ∀ a b c, lt a b → le b c → lt a c) (lt_of_le_of_lt : ∀ a b c, le a b → lt b c → lt a c) (lt_irrefl : ∀ a, ¬ lt a a) section variable [s : order_pair A] variables {a b c : A} include s theorem le_of_lt : a < b → a ≤ b := !order_pair.le_of_lt theorem lt_of_lt_of_le [trans] : a < b → b ≤ c → a < c := !order_pair.lt_of_lt_of_le theorem lt_of_le_of_lt [trans] : a ≤ b → b < c → a < c := !order_pair.lt_of_le_of_lt private theorem lt_irrefl (s' : order_pair A) (a : A) : ¬ a < a := !order_pair.lt_irrefl private theorem lt_trans (s' : order_pair A) (a b c: A) (lt_ab : a < b) (lt_bc : b < c) : a < c := lt_of_lt_of_le lt_ab (le_of_lt lt_bc) definition order_pair.to_strict_order [trans_instance] : strict_order A := ⦃ strict_order, s, lt_irrefl := lt_irrefl s, lt_trans := lt_trans s ⦄ theorem gt_of_gt_of_ge [trans] (H1 : a > b) (H2 : b ≥ c) : a > c := lt_of_le_of_lt H2 H1 theorem gt_of_ge_of_gt [trans] (H1 : a ≥ b) (H2 : b > c) : a > c := lt_of_lt_of_le H2 H1 theorem not_le_of_gt (H : a > b) : ¬ a ≤ b := assume H1 : a ≤ b, lt.irrefl _ (lt_of_lt_of_le H H1) theorem not_lt_of_ge (H : a ≥ b) : ¬ a < b := assume H1 : a < b, lt.irrefl _ (lt_of_le_of_lt H H1) end structure strong_order_pair [class] (A : Type) extends weak_order A, has_lt A := (le_iff_lt_or_eq : ∀a b, le a b ↔ lt a b ∨ a = b) (lt_irrefl : ∀ a, ¬ lt a a) section strong_order_pair variable [strong_order_pair A] theorem le_iff_lt_or_eq {a b : A} : a ≤ b ↔ a < b ∨ a = b := !strong_order_pair.le_iff_lt_or_eq theorem lt_or_eq_of_le {a b : A} (le_ab : a ≤ b) : a < b ∨ a = b := iff.mp le_iff_lt_or_eq le_ab theorem le_of_lt_or_eq {a b : A} (lt_or_eq : a < b ∨ a = b) : a ≤ b := iff.mpr le_iff_lt_or_eq lt_or_eq private theorem lt_irrefl' (a : A) : ¬ a < a := !strong_order_pair.lt_irrefl private theorem le_of_lt' (a b : A) : a < b → a ≤ b := take Hlt, le_of_lt_or_eq (or.inl Hlt) private theorem lt_iff_le_and_ne {a b : A} : a < b ↔ (a ≤ b ∧ a ≠ b) := iff.intro (take Hlt, and.intro (le_of_lt_or_eq (or.inl Hlt)) (take Hab, absurd (Hab ▸ Hlt) !lt_irrefl')) (take Hand, have Hor : a < b ∨ a = b, from lt_or_eq_of_le (and.left Hand), or_resolve_left Hor (and.right Hand)) theorem lt_of_le_of_ne {a b : A} : a ≤ b → a ≠ b → a < b := take H1 H2, iff.mpr lt_iff_le_and_ne (and.intro H1 H2) private theorem ne_of_lt' {a b : A} (H : a < b) : a ≠ b := and.right ((iff.mp lt_iff_le_and_ne) H) private theorem lt_of_lt_of_le' (a b c : A) : a < b → b ≤ c → a < c := assume lt_ab : a < b, assume le_bc : b ≤ c, have le_ac : a ≤ c, from le.trans (le_of_lt' _ _ lt_ab) le_bc, have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_ba : b ≤ a, from eq_ac⁻¹ ▸ le_bc, have eq_ab : a = b, from le.antisymm (le_of_lt' _ _ lt_ab) le_ba, show false, from ne_of_lt' lt_ab eq_ab, show a < c, from iff.mpr (lt_iff_le_and_ne) (and.intro le_ac ne_ac) theorem lt_of_le_of_lt' (a b c : A) : a ≤ b → b < c → a < c := assume le_ab : a ≤ b, assume lt_bc : b < c, have le_ac : a ≤ c, from le.trans le_ab (le_of_lt' _ _ lt_bc), have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_cb : c ≤ b, from eq_ac ▸ le_ab, have eq_bc : b = c, from le.antisymm (le_of_lt' _ _ lt_bc) le_cb, show false, from ne_of_lt' lt_bc eq_bc, show a < c, from iff.mpr (lt_iff_le_and_ne) (and.intro le_ac ne_ac) end strong_order_pair definition strong_order_pair.to_order_pair [trans_instance] [s : strong_order_pair A] : order_pair A := ⦃ order_pair, s, lt_irrefl := lt_irrefl', le_of_lt := le_of_lt', lt_of_le_of_lt := lt_of_le_of_lt', lt_of_lt_of_le := lt_of_lt_of_le' ⦄ /- linear orders -/ structure linear_order_pair [class] (A : Type) extends order_pair A, linear_weak_order A structure linear_strong_order_pair [class] (A : Type) extends strong_order_pair A, linear_weak_order A definition linear_strong_order_pair.to_linear_order_pair [trans_instance] [s : linear_strong_order_pair A] : linear_order_pair A := ⦃ linear_order_pair, s, strong_order_pair.to_order_pair ⦄ section variable [linear_strong_order_pair A] variables (a b c : A) theorem lt.trichotomy : a < b ∨ a = b ∨ b < a := or.elim (le.total a b) (assume H : a ≤ b, or.elim (iff.mp !le_iff_lt_or_eq H) (assume H1, or.inl H1) (assume H1, or.inr (or.inl H1))) (assume H : b ≤ a, or.elim (iff.mp !le_iff_lt_or_eq H) (assume H1, or.inr (or.inr H1)) (assume H1, or.inr (or.inl (H1⁻¹)))) theorem lt.by_cases {a b : A} {P : Prop} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := or.elim !lt.trichotomy (assume H, H1 H) (assume H, or.elim H (assume H', H2 H') (assume H', H3 H')) definition lt_ge_by_cases {a b : A} {P : Prop} (H1 : a < b → P) (H2 : a ≥ b → P) : P := lt.by_cases H1 (λH, H2 (H ▸ le.refl a)) (λH, H2 (le_of_lt H)) theorem le_of_not_gt {a b : A} (H : ¬ a > b) : a ≤ b := lt.by_cases (assume H', absurd H' H) (assume H', H' ▸ !le.refl) (assume H', le_of_lt H') theorem lt_of_not_ge {a b : A} (H : ¬ a ≥ b) : a < b := lt.by_cases (assume H', absurd (le_of_lt H') H) (assume H', absurd (H' ▸ !le.refl) H) (assume H', H') theorem lt_iff_not_ge : a < b ↔ ¬ a ≥ b := iff.intro (suppose a < b, not_le_of_gt this) (suppose ¬ a ≥ b, lt_of_not_ge this) theorem le_iff_not_gt : a ≤ b ↔ ¬ a > b := iff.intro (suppose a ≤ b, not_lt_of_ge this) (suppose ¬ a > b, le_of_not_gt this) theorem gt_iff_not_le : a > b ↔ ¬ a ≤ b := iff.intro (suppose a > b, not_le_of_gt this) (suppose ¬ a ≤ b, lt_of_not_ge this) theorem ge_iff_not_lt : a ≥ b ↔ ¬ a < b := iff.intro (suppose a ≥ b, not_lt_of_ge this) (suppose ¬ a < b, le_of_not_gt this) theorem lt_or_ge : a < b ∨ a ≥ b := lt.by_cases (assume H1 : a < b, or.inl H1) (assume H1 : a = b, or.inr (H1 ▸ le.refl a)) (assume H1 : a > b, or.inr (le_of_lt H1)) theorem le_or_gt : a ≤ b ∨ a > b := !or.swap (lt_or_ge b a) theorem lt_or_gt_of_ne {a b : A} (H : a ≠ b) : a < b ∨ a > b := lt.by_cases (assume H1, or.inl H1) (assume H1, absurd H1 H) (assume H1, or.inr H1) end open decidable structure decidable_linear_order [class] (A : Type) extends linear_strong_order_pair A := (decidable_lt : decidable_rel lt) section variable [s : decidable_linear_order A] variables {a b c d : A} include s open decidable definition decidable_lt [instance] : decidable (a < b) := @decidable_linear_order.decidable_lt _ _ _ _ definition decidable_le [instance] : decidable (a ≤ b) := by_cases (assume H : a < b, inl (le_of_lt H)) (assume H : ¬ a < b, have H1 : b ≤ a, from le_of_not_gt H, by_cases (assume H2 : b < a, inr (not_le_of_gt H2)) (assume H2 : ¬ b < a, inl (le_of_not_gt H2))) definition has_decidable_eq [instance] : decidable (a = b) := by_cases (assume H : a ≤ b, by_cases (assume H1 : b ≤ a, inl (le.antisymm H H1)) (assume H1 : ¬ b ≤ a, inr (assume H2 : a = b, H1 (H2 ▸ le.refl a)))) (assume H : ¬ a ≤ b, (inr (assume H1 : a = b, H (H1 ▸ !le.refl)))) theorem eq_or_lt_of_not_lt {a b : A} (H : ¬ a < b) : a = b ∨ b < a := if Heq : a = b then or.inl Heq else or.inr (lt_of_not_ge (λ Hge, H (lt_of_le_of_ne Hge Heq))) theorem eq_or_lt_of_le {a b : A} (H : a ≤ b) : a = b ∨ a < b := begin cases eq_or_lt_of_not_lt (not_lt_of_ge H), exact or.inl a_1⁻¹, exact or.inr a_1 end -- testing equality first may result in more definitional equalities definition lt.cases {B : Type} (a b : A) (t_lt t_eq t_gt : B) : B := if a = b then t_eq else (if a < b then t_lt else t_gt) theorem lt.cases_of_eq {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a = b) : lt.cases a b t_lt t_eq t_gt = t_eq := if_pos H theorem lt.cases_of_lt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a < b) : lt.cases a b t_lt t_eq t_gt = t_lt := if_neg (ne_of_lt H) ⬝ if_pos H theorem lt.cases_of_gt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a > b) : lt.cases a b t_lt t_eq t_gt = t_gt := if_neg (ne.symm (ne_of_lt H)) ⬝ if_neg (lt.asymm H) definition min (a b : A) : A := if a ≤ b then a else b definition max (a b : A) : A := if a ≤ b then b else a /- these show min and max form a lattice -/ theorem min_le_left (a b : A) : min a b ≤ a := by_cases (assume H : a ≤ b, by rewrite [↑min, if_pos H]) (assume H : ¬ a ≤ b, by rewrite [↑min, if_neg H]; apply le_of_lt (lt_of_not_ge H)) theorem min_le_right (a b : A) : min a b ≤ b := by_cases (assume H : a ≤ b, by rewrite [↑min, if_pos H]; apply H) (assume H : ¬ a ≤ b, by rewrite [↑min, if_neg H]) theorem le_min {a b c : A} (H₁ : c ≤ a) (H₂ : c ≤ b) : c ≤ min a b := by_cases (assume H : a ≤ b, by rewrite [↑min, if_pos H]; apply H₁) (assume H : ¬ a ≤ b, by rewrite [↑min, if_neg H]; apply H₂) theorem le_max_left (a b : A) : a ≤ max a b := by_cases (assume H : a ≤ b, by rewrite [↑max, if_pos H]; apply H) (assume H : ¬ a ≤ b, by rewrite [↑max, if_neg H]) theorem le_max_right (a b : A) : b ≤ max a b := by_cases (assume H : a ≤ b, by rewrite [↑max, if_pos H]) (assume H : ¬ a ≤ b, by rewrite [↑max, if_neg H]; apply le_of_lt (lt_of_not_ge H)) theorem max_le {a b c : A} (H₁ : a ≤ c) (H₂ : b ≤ c) : max a b ≤ c := by_cases (assume H : a ≤ b, by rewrite [↑max, if_pos H]; apply H₂) (assume H : ¬ a ≤ b, by rewrite [↑max, if_neg H]; apply H₁) theorem le_max_left_iff_true (a b : A) : a ≤ max a b ↔ true := iff_true_intro (le_max_left a b) theorem le_max_right_iff_true (a b : A) : b ≤ max a b ↔ true := iff_true_intro (le_max_right a b) /- these are also proved for lattices, but with inf and sup in place of min and max -/ theorem eq_min {a b c : A} (H₁ : c ≤ a) (H₂ : c ≤ b) (H₃ : ∀{d}, d ≤ a → d ≤ b → d ≤ c) : c = min a b := le.antisymm (le_min H₁ H₂) (H₃ !min_le_left !min_le_right) theorem min.comm (a b : A) : min a b = min b a := eq_min !min_le_right !min_le_left (λ c H₁ H₂, le_min H₂ H₁) theorem min.assoc (a b c : A) : min (min a b) c = min a (min b c) := begin apply eq_min, { apply le.trans, apply min_le_left, apply min_le_left }, { apply le_min, apply le.trans, apply min_le_left, apply min_le_right, apply min_le_right }, { intros [d, H₁, H₂], apply le_min, apply le_min H₁, apply le.trans H₂, apply min_le_left, apply le.trans H₂, apply min_le_right } end theorem min.left_comm (a b c : A) : min a (min b c) = min b (min a c) := binary.left_comm (@min.comm A s) (@min.assoc A s) a b c theorem min.right_comm (a b c : A) : min (min a b) c = min (min a c) b := binary.right_comm (@min.comm A s) (@min.assoc A s) a b c theorem min_self (a : A) : min a a = a := by apply eq.symm; apply eq_min (le.refl a) !le.refl; intros; assumption theorem min_eq_left {a b : A} (H : a ≤ b) : min a b = a := by apply eq.symm; apply eq_min !le.refl H; intros; assumption theorem min_eq_right {a b : A} (H : b ≤ a) : min a b = b := eq.subst !min.comm (min_eq_left H) theorem eq_max {a b c : A} (H₁ : a ≤ c) (H₂ : b ≤ c) (H₃ : ∀{d}, a ≤ d → b ≤ d → c ≤ d) : c = max a b := le.antisymm (H₃ !le_max_left !le_max_right) (max_le H₁ H₂) theorem max.comm (a b : A) : max a b = max b a := eq_max !le_max_right !le_max_left (λ c H₁ H₂, max_le H₂ H₁) theorem max.assoc (a b c : A) : max (max a b) c = max a (max b c) := begin apply eq_max, { apply le.trans, apply le_max_left a b, apply le_max_left }, { apply max_le, apply le.trans, apply le_max_right a b, apply le_max_left, apply le_max_right }, { intros [d, H₁, H₂], apply max_le, apply max_le H₁, apply le.trans !le_max_left H₂, apply le.trans !le_max_right H₂} end theorem max.left_comm (a b c : A) : max a (max b c) = max b (max a c) := binary.left_comm (@max.comm A s) (@max.assoc A s) a b c theorem max.right_comm (a b c : A) : max (max a b) c = max (max a c) b := binary.right_comm (@max.comm A s) (@max.assoc A s) a b c theorem max_self (a : A) : max a a = a := by apply eq.symm; apply eq_max (le.refl a) !le.refl; intros; assumption theorem max_eq_left {a b : A} (H : b ≤ a) : max a b = a := by apply eq.symm; apply eq_max !le.refl H; intros; assumption theorem max_eq_right {a b : A} (H : a ≤ b) : max a b = b := eq.subst !max.comm (max_eq_left H) /- these rely on lt_of_lt -/ theorem min_eq_left_of_lt {a b : A} (H : a < b) : min a b = a := min_eq_left (le_of_lt H) theorem min_eq_right_of_lt {a b : A} (H : b < a) : min a b = b := min_eq_right (le_of_lt H) theorem max_eq_left_of_lt {a b : A} (H : b < a) : max a b = a := max_eq_left (le_of_lt H) theorem max_eq_right_of_lt {a b : A} (H : a < b) : max a b = b := max_eq_right (le_of_lt H) /- these use the fact that it is a linear ordering -/ theorem lt_min {a b c : A} (H₁ : a < b) (H₂ : a < c) : a < min b c := or.elim !le_or_gt (assume H : b ≤ c, by rewrite (min_eq_left H); apply H₁) (assume H : b > c, by rewrite (min_eq_right_of_lt H); apply H₂) theorem max_lt {a b c : A} (H₁ : a < c) (H₂ : b < c) : max a b < c := or.elim !le_or_gt (assume H : a ≤ b, by rewrite (max_eq_right H); apply H₂) (assume H : a > b, by rewrite (max_eq_left_of_lt H); apply H₁) end /- order instances -/ definition weak_order_Prop [instance] : weak_order Prop := ⦃ weak_order, le := λx y, x → y, le_refl := λx, id, le_trans := λa b c H1 H2 x, H2 (H1 x), le_antisymm := λf g H1 H2, propext (and.intro H1 H2) ⦄ definition weak_order_fun [instance] (A B : Type) [weak_order B] : weak_order (A → B) := ⦃ weak_order, le := λx y, ∀b, x b ≤ y b, le_refl := λf b, !le.refl, le_trans := λf g h H1 H2 b, !le.trans (H1 b) (H2 b), le_antisymm := λf g H1 H2, funext (λb, !le.antisymm (H1 b) (H2 b)) ⦄ definition weak_order_dual {A : Type} (wo : weak_order A) : weak_order A := ⦃ weak_order, le := λx y, y ≤ x, le_refl := le.refl, le_trans := take a b c `b ≤ a` `c ≤ b`, le.trans `c ≤ b` `b ≤ a`, le_antisymm := take a b `b ≤ a` `a ≤ b`, le.antisymm `a ≤ b` `b ≤ a` ⦄ lemma le_dual_eq_le {A : Type} (wo : weak_order A) (a b : A) : @le _ (@weak_order.to_has_le _ (weak_order_dual wo)) a b = @le _ (@weak_order.to_has_le _ wo) b a := rfl -- what to do with the strict variants?
ee5cb693f7c2103f65150b39d7d88963e45d8db0
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/ring_theory/jacobson.lean
88735e0a7804e57dcba3a1a8246cbc4fe4652735
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,097
lean
/- Copyright (c) 2020 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Devon Tuma -/ import data.mv_polynomial import ring_theory.ideal.over import ring_theory.jacobson_ideal import ring_theory.localization /-! # Jacobson Rings The following conditions are equivalent for a ring `R`: 1. Every radical ideal `I` is equal to its Jacobson radical 2. Every radical ideal `I` can be written as an intersection of maximal ideals 3. Every prime ideal `I` is equal to its Jacobson radical Any ring satisfying any of these equivalent conditions is said to be Jacobson. Some particular examples of Jacobson rings are also proven. `is_jacobson_quotient` says that the quotient of a Jacobson ring is Jacobson. `is_jacobson_localization` says the localization of a Jacobson ring to a single element is Jacobson. `is_jacobson_polynomial_iff_is_jacobson` says polynomials over a Jacobson ring form a Jacobson ring. ## Main definitions Let `R` be a commutative ring. Jacobson Rings are defined using the first of the above conditions * `is_jacobson R` is the proposition that `R` is a Jacobson ring. It is a class, implemented as the predicate that for any ideal, `I.radical = I` implies `I.jacobson = I`. ## Main statements * `is_jacobson_iff_prime_eq` is the equivalence between conditions 1 and 3 above. * `is_jacobson_iff_Inf_maximal` is the equivalence between conditions 1 and 2 above. * `is_jacobson_of_surjective` says that if `R` is a Jacobson ring and `f : R →+* S` is surjective, then `S` is also a Jacobson ring * `is_jacobson_mv_polynomial` says that multi-variate polynomials over a Jacobson ring are Jacobson. ## Tags Jacobson, Jacobson Ring -/ namespace ideal open polynomial section is_jacobson variables {R S : Type*} [comm_ring R] [comm_ring S] {I : ideal R} /-- A ring is a Jacobson ring if for every radical ideal `I`, the Jacobson radical of `I` is equal to `I`. See `is_jacobson_iff_prime_eq` and `is_jacobson_iff_Inf_maximal` for equivalent definitions. -/ class is_jacobson (R : Type*) [comm_ring R] : Prop := (out' : ∀ (I : ideal R), I.radical = I → I.jacobson = I) theorem is_jacobson_iff {R} [comm_ring R] : is_jacobson R ↔ ∀ (I : ideal R), I.radical = I → I.jacobson = I := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem is_jacobson.out {R} [comm_ring R] : is_jacobson R → ∀ {I : ideal R}, I.radical = I → I.jacobson = I := is_jacobson_iff.1 /-- A ring is a Jacobson ring if and only if for all prime ideals `P`, the Jacobson radical of `P` is equal to `P`. -/ lemma is_jacobson_iff_prime_eq : is_jacobson R ↔ ∀ P : ideal R, is_prime P → P.jacobson = P := begin refine is_jacobson_iff.trans ⟨λ h I hI, h I (is_prime.radical hI), _⟩, refine λ h I hI, le_antisymm (λ x hx, _) (λ x hx, mem_Inf.mpr (λ _ hJ, hJ.left hx)), rw [← hI, radical_eq_Inf I, mem_Inf], intros P hP, rw set.mem_set_of_eq at hP, erw mem_Inf at hx, erw [← h P hP.right, mem_Inf], exact λ J hJ, hx ⟨le_trans hP.left hJ.left, hJ.right⟩ end /-- A ring `R` is Jacobson if and only if for every prime ideal `I`, `I` can be written as the infimum of some collection of maximal ideals. Allowing ⊤ in the set `M` of maximal ideals is equivalent, but makes some proofs cleaner. -/ lemma is_jacobson_iff_Inf_maximal : is_jacobson R ↔ ∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R), (∀ J ∈ M, is_maximal J ∨ J = ⊤) ∧ I = Inf M := ⟨λ H I h, eq_jacobson_iff_Inf_maximal.1 (H.out (is_prime.radical h)), λ H, is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal.2 (H hP))⟩ lemma is_jacobson_iff_Inf_maximal' : is_jacobson R ↔ ∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R), (∀ (J ∈ M) (K : ideal R), J < K → K = ⊤) ∧ I = Inf M := ⟨λ H I h, eq_jacobson_iff_Inf_maximal'.1 (H.out (is_prime.radical h)), λ H, is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal'.2 (H hP))⟩ lemma radical_eq_jacobson [H : is_jacobson R] (I : ideal R) : I.radical = I.jacobson := le_antisymm (le_Inf (λ J ⟨hJ, hJ_max⟩, (is_prime.radical_le_iff hJ_max.is_prime).mpr hJ)) ((H.out (radical_idem I)) ▸ (jacobson_mono le_radical)) /-- Fields have only two ideals, and the condition holds for both of them. -/ @[priority 100] instance is_jacobson_field {K : Type*} [field K] : is_jacobson K := ⟨λ I hI, or.rec_on (eq_bot_or_top I) (λ h, le_antisymm (Inf_le ⟨le_of_eq rfl, (eq.symm h) ▸ bot_is_maximal⟩) ((eq.symm h) ▸ bot_le)) (λ h, by rw [h, jacobson_eq_top_iff])⟩ theorem is_jacobson_of_surjective [H : is_jacobson R] : (∃ (f : R →+* S), function.surjective f) → is_jacobson S := begin rintros ⟨f, hf⟩, rw is_jacobson_iff_Inf_maximal, intros p hp, use map f '' {J : ideal R | comap f p ≤ J ∧ J.is_maximal }, use λ j ⟨J, hJ, hmap⟩, hmap ▸ or.symm (map_eq_top_or_is_maximal_of_surjective f hf hJ.right), have : p = map f ((comap f p).jacobson), from (is_jacobson.out' (comap f p) (by rw [← comap_radical, is_prime.radical hp])).symm ▸ (map_comap_of_surjective f hf p).symm, exact eq.trans this (map_Inf hf (λ J ⟨hJ, _⟩, le_trans (ideal.ker_le_comap f) hJ)), end @[priority 100] instance is_jacobson_quotient [is_jacobson R] : is_jacobson (quotient I) := is_jacobson_of_surjective ⟨quotient.mk I, (by rintro ⟨x⟩; use x; refl)⟩ lemma is_jacobson_iso (e : R ≃+* S) : is_jacobson R ↔ is_jacobson S := ⟨λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e : R →+* S), e.surjective⟩, λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e.symm : S →+* R), e.symm.surjective⟩⟩ lemma is_jacobson_of_is_integral [algebra R S] (hRS : algebra.is_integral R S) (hR : is_jacobson R) : is_jacobson S := begin rw is_jacobson_iff_prime_eq, introsI P hP, by_cases hP_top : comap (algebra_map R S) P = ⊤, { simp [comap_eq_top_iff.1 hP_top] }, { haveI : nontrivial (comap (algebra_map R S) P).quotient := quotient.nontrivial hP_top, rw jacobson_eq_iff_jacobson_quotient_eq_bot, refine eq_bot_of_comap_eq_bot (is_integral_quotient_of_is_integral hRS) _, rw [eq_bot_iff, ← jacobson_eq_iff_jacobson_quotient_eq_bot.1 ((is_jacobson_iff_prime_eq.1 hR) (comap (algebra_map R S) P) (comap_is_prime _ _)), comap_jacobson], refine Inf_le_Inf (λ J hJ, _), simp only [true_and, set.mem_image, bot_le, set.mem_set_of_eq], haveI : J.is_maximal := by simpa using hJ, exact exists_ideal_over_maximal_of_is_integral (is_integral_quotient_of_is_integral hRS) J (comap_bot_le_of_injective _ algebra_map_quotient_injective) } end lemma is_jacobson_of_is_integral' (f : R →+* S) (hf : f.is_integral) (hR : is_jacobson R) : is_jacobson S := @is_jacobson_of_is_integral _ _ _ _ f.to_algebra hf hR end is_jacobson section localization open localization_map submonoid variables {R S : Type*} [comm_ring R] [comm_ring S] {I : ideal R} variables {y : R} (f : away_map y S) lemma disjoint_powers_iff_not_mem (hI : I.radical = I) : disjoint ((submonoid.powers y) : set R) ↑I ↔ y ∉ I.1 := begin refine ⟨λ h, set.disjoint_left.1 h (mem_powers _), λ h, (disjoint_iff).mpr (eq_bot_iff.mpr _)⟩, rintros x ⟨⟨n, rfl⟩, hx'⟩, rw [← hI] at hx', exact absurd (hI ▸ mem_radical_of_pow_mem hx' : y ∈ I.carrier) h end /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y`. This lemma gives the correspondence in the particular case of an ideal and its comap. See `le_rel_iso_of_maximal` for the more general relation isomorphism -/ lemma is_maximal_iff_is_maximal_disjoint [H : is_jacobson R] (J : ideal S) : J.is_maximal ↔ (comap f.to_map J).is_maximal ∧ y ∉ ideal.comap f.to_map J := begin split, { refine λ h, ⟨_, λ hy, h.ne_top (ideal.eq_top_of_is_unit_mem _ hy (map_units f ⟨y, submonoid.mem_powers _⟩))⟩, have hJ : J.is_prime := is_maximal.is_prime h, rw is_prime_iff_is_prime_disjoint f at hJ, have : y ∉ (comap f.to_map J).1 := set.disjoint_left.1 hJ.right (submonoid.mem_powers _), erw [← H.out (is_prime.radical hJ.left), mem_Inf] at this, push_neg at this, rcases this with ⟨I, hI, hI'⟩, convert hI.right, by_cases hJ : J = map f.to_map I, { rw [hJ, comap_map_of_is_prime_disjoint f I (is_maximal.is_prime hI.right)], rwa disjoint_powers_iff_not_mem (is_maximal.is_prime hI.right).radical}, { have hI_p : (map f.to_map I).is_prime, { refine is_prime_of_is_prime_disjoint f I hI.right.is_prime _, rwa disjoint_powers_iff_not_mem (is_maximal.is_prime hI.right).radical }, have : J ≤ map f.to_map I := (map_comap f J) ▸ (map_mono hI.left), exact absurd (h.1.2 _ (lt_of_le_of_ne this hJ)) hI_p.1 } }, { refine λ h, ⟨⟨λ hJ, h.1.ne_top (eq_top_iff.2 _), λ I hI, _⟩⟩, { rwa [eq_top_iff, ← f.order_embedding.le_iff_le] at hJ }, { have := congr_arg (map f.to_map) (h.1.1.2 _ ⟨comap_mono (le_of_lt hI), _⟩), rwa [map_comap f I, map_top f.to_map] at this, refine λ hI', hI.right _, rw [← map_comap f I, ← map_comap f J], exact map_mono hI' } } end /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y`. This lemma gives the correspondence in the particular case of an ideal and its map. See `le_rel_iso_of_maximal` for the more general statement, and the reverse of this implication -/ lemma is_maximal_of_is_maximal_disjoint [is_jacobson R] (I : ideal R) (hI : I.is_maximal) (hy : y ∉ I) : (map f.to_map I).is_maximal := begin rw [is_maximal_iff_is_maximal_disjoint f, comap_map_of_is_prime_disjoint f I (is_maximal.is_prime hI) ((disjoint_powers_iff_not_mem (is_maximal.is_prime hI).radical).2 hy)], exact ⟨hI, hy⟩ end /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y` -/ def order_iso_of_maximal [is_jacobson R] : {p : ideal S // p.is_maximal} ≃o {p : ideal R // p.is_maximal ∧ y ∉ p} := { to_fun := λ p, ⟨ideal.comap f.to_map p.1, (is_maximal_iff_is_maximal_disjoint f p.1).1 p.2⟩, inv_fun := λ p, ⟨ideal.map f.to_map p.1, is_maximal_of_is_maximal_disjoint f p.1 p.2.1 p.2.2⟩, left_inv := λ J, subtype.eq (map_comap f J), right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint f I.1 (is_maximal.is_prime I.2.1) ((disjoint_powers_iff_not_mem I.2.1.is_prime.radical).2 I.2.2)), map_rel_iff' := λ I I', ⟨λ h, (show I.val ≤ I'.val, from (map_comap f I.val) ▸ (map_comap f I'.val) ▸ (ideal.map_mono h)), λ h x hx, h hx⟩ } /-- If `S` is the localization of the Jacobson ring `R` at the submonoid generated by `y : R`, then `S` is Jacobson. -/ lemma is_jacobson_localization [H : is_jacobson R] (f : away_map y S) : is_jacobson S := begin rw is_jacobson_iff_prime_eq, refine λ P' hP', le_antisymm _ le_jacobson, obtain ⟨hP', hPM⟩ := (localization_map.is_prime_iff_is_prime_disjoint f P').mp hP', have hP := H.out (is_prime.radical hP'), refine le_trans (le_trans (le_of_eq (localization_map.map_comap f P'.jacobson).symm) (map_mono _)) (le_of_eq (localization_map.map_comap f P')), have : Inf { I : ideal R | comap f.to_map P' ≤ I ∧ I.is_maximal ∧ y ∉ I } ≤ comap f.to_map P', { intros x hx, have hxy : x * y ∈ (comap f.to_map P').jacobson, { rw [ideal.jacobson, mem_Inf], intros J hJ, by_cases y ∈ J, { exact J.smul_mem x h }, { exact (mul_comm y x) ▸ J.smul_mem y ((mem_Inf.1 hx) ⟨hJ.left, ⟨hJ.right, h⟩⟩) } }, rw hP at hxy, cases hP'.mem_or_mem hxy with hxy hxy, { exact hxy }, { exact (hPM ⟨submonoid.mem_powers _, hxy⟩).elim } }, refine le_trans _ this, rw [ideal.jacobson, comap_Inf', Inf_eq_infi], refine infi_le_infi_of_subset (λ I hI, ⟨map f.to_map I, ⟨_, _⟩⟩), { exact ⟨le_trans (le_of_eq ((localization_map.map_comap f P').symm)) (map_mono hI.1), is_maximal_of_is_maximal_disjoint f _ hI.2.1 hI.2.2⟩ }, { exact localization_map.comap_map_of_is_prime_disjoint f I (is_maximal.is_prime hI.2.1) ((disjoint_powers_iff_not_mem hI.2.1.is_prime.radical).2 hI.2.2) } end end localization namespace polynomial open polynomial section comm_ring variables {R S : Type*} [comm_ring R] [integral_domain S] variables {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] /-- If `I` is a prime ideal of `polynomial R` and `pX ∈ I` is a non-constant polynomial, then the map `R →+* R[x]/I` descends to an integral map when localizing at `pX.leading_coeff`. In particular `X` is integral because it satisfies `pX`, and constants are trivially integral, so integrality of the entire extension follows by closure under addition and multiplication. -/ lemma is_integral_localization_map_polynomial_quotient (P : ideal (polynomial R)) [P.is_prime] (pX : polynomial R) (hpX : pX ∈ P) (ϕ : localization_map (submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff) Rₘ) (ϕ' : localization_map ((submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff).map (quotient_map P C le_rfl) : submonoid P.quotient) Sₘ) : (ϕ.map ((submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff).mem_map_of_mem (quotient_map P C le_rfl : (P.comap C : ideal R).quotient →* P.quotient)) ϕ').is_integral := begin let P' : ideal R := P.comap C, let M : submonoid P'.quotient := submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff, let φ : P'.quotient →+* P.quotient := quotient_map P C le_rfl, let φ' := (ϕ.map (M.mem_map_of_mem (φ : P'.quotient →* P.quotient)) ϕ'), have hφ' : φ.comp (quotient.mk P') = (quotient.mk P).comp C := rfl, intro p, obtain ⟨⟨p', ⟨q, hq⟩⟩, hp⟩ := ϕ'.surj p, suffices : φ'.is_integral_elem (ϕ'.to_map p'), { obtain ⟨q', hq', rfl⟩ := hq, obtain ⟨q'', hq''⟩ := is_unit_iff_exists_inv'.1 (ϕ.map_units ⟨q', hq'⟩), refine φ'.is_integral_of_is_integral_mul_unit p (ϕ'.to_map (φ q')) q'' _ (hp.symm ▸ this), convert trans (trans (φ'.map_mul _ _).symm (congr_arg φ' hq'')) φ'.map_one using 2, rw [← φ'.comp_apply, localization_map.map_comp, ϕ'.to_map.comp_apply, subtype.coe_mk] }, refine is_integral_of_mem_closure'' ((ϕ'.to_map.comp (quotient.mk P)) '' (insert X {p | p.degree ≤ 0})) _ _ _, { rintros x ⟨p, hp, rfl⟩, refine hp.rec_on (λ hy, _) (λ hy, _), { refine hy.symm ▸ (φ.is_integral_elem_localization_at_leading_coeff ((quotient.mk P) X) (pX.map (quotient.mk P')) _ M ⟨1, pow_one _⟩ _ _), rwa [eval₂_map, hφ', ← hom_eval₂, quotient.eq_zero_iff_mem, eval₂_C_X] }, { rw [set.mem_set_of_eq, degree_le_zero_iff] at hy, refine hy.symm ▸ ⟨X - C (ϕ.to_map ((quotient.mk P') (p.coeff 0))), monic_X_sub_C _, _⟩, simp only [eval₂_sub, eval₂_C, eval₂_X], rw [sub_eq_zero_iff_eq, ← φ'.comp_apply, localization_map.map_comp, ring_hom.comp_apply], refl } }, { obtain ⟨p, rfl⟩ := quotient.mk_surjective p', refine polynomial.induction_on p (λ r, subring.subset_closure $ set.mem_image_of_mem _ (or.inr degree_C_le)) (λ _ _ h1 h2, _) (λ n _ hr, _), { convert subring.add_mem _ h1 h2, rw [ring_hom.map_add, ring_hom.map_add] }, { rw [pow_succ X n, mul_comm X, ← mul_assoc, ring_hom.map_mul, ϕ'.to_map.map_mul], exact subring.mul_mem _ hr (subring.subset_closure (set.mem_image_of_mem _ (or.inl rfl))) } }, end /-- If `f : R → S` descends to an integral map in the localization at `x`, and `R` is a Jacobson ring, then the intersection of all maximal ideals in `S` is trivial -/ lemma jacobson_bot_of_integral_localization {R : Type*} [integral_domain R] [is_jacobson R] (φ : R →+* S) (hφ : function.injective φ) (x : R) (hx : x ≠ 0) (ϕ : localization_map (submonoid.powers x) Rₘ) (ϕ' : localization_map ((submonoid.powers x).map φ : submonoid S) Sₘ) (hφ' : (ϕ.map ((submonoid.powers x).mem_map_of_mem (φ : R →* S)) ϕ').is_integral) : (⊥ : ideal S).jacobson = ⊥ := begin have hM : ((submonoid.powers x).map φ : submonoid S) ≤ non_zero_divisors S := map_le_non_zero_divisors_of_injective hφ (powers_le_non_zero_divisors_of_domain hx), letI : integral_domain Sₘ := localization_map.integral_domain_of_le_non_zero_divisors ϕ' hM, let φ' : Rₘ →+* Sₘ := ϕ.map ((submonoid.powers x).mem_map_of_mem (φ : R →* S)) ϕ', suffices : ∀ I : ideal Sₘ, I.is_maximal → (I.comap ϕ'.to_map).is_maximal, { have hϕ' : comap ϕ'.to_map ⊥ = ⊥, { simpa [ring_hom.injective_iff_ker_eq_bot, ring_hom.ker_eq_comap_bot] using ϕ'.injective hM }, refine eq_bot_iff.2 (le_trans _ (le_of_eq hϕ')), have hSₘ : is_jacobson Sₘ := is_jacobson_of_is_integral' φ' hφ' (is_jacobson_localization ϕ), rw [← hSₘ.out radical_bot_of_integral_domain, comap_jacobson], exact Inf_le_Inf (λ j hj, ⟨bot_le, let ⟨J, hJ⟩ := hj in hJ.2 ▸ this J hJ.1.2⟩) }, introsI I hI, -- Remainder of the proof is pulling and pushing ideals around the square and the quotient square haveI : (I.comap ϕ'.to_map).is_prime := comap_is_prime ϕ'.to_map I, haveI : (I.comap φ').is_prime := comap_is_prime φ' I, haveI : (⊥ : ideal (I.comap ϕ'.to_map).quotient).is_prime := bot_prime, have hcomm: φ'.comp ϕ.to_map = ϕ'.to_map.comp φ := ϕ.map_comp _, let f := quotient_map (I.comap ϕ'.to_map) φ le_rfl, let g := quotient_map I ϕ'.to_map le_rfl, have := is_maximal_comap_of_is_integral_of_is_maximal' φ' hφ' I (by convert hI; casesI _inst_4; refl), have := ((is_maximal_iff_is_maximal_disjoint ϕ _).1 this).left, have : ((I.comap ϕ'.to_map).comap φ).is_maximal, { rwa [comap_comap, hcomm, ← comap_comap] at this }, rw ← bot_quotient_is_maximal_iff at this ⊢, refine is_maximal_of_is_integral_of_is_maximal_comap' f _ ⊥ ((eq_bot_iff.2 (comap_bot_le_of_injective f quotient_map_injective)).symm ▸ this), exact f.is_integral_tower_bot_of_is_integral g quotient_map_injective ((comp_quotient_map_eq_of_comp_eq hcomm I).symm ▸ (ring_hom.is_integral_trans _ _ (ring_hom.is_integral_of_surjective _ (localization_map.surjective_quotient_map_of_maximal_of_localization (by rwa [comap_comap, hcomm, ← bot_quotient_is_maximal_iff]))) (ring_hom.is_integral_quotient_of_is_integral _ hφ'))), end /-- Used to bootstrap the proof of `is_jacobson_polynomial_iff_is_jacobson`. That theorem is more general and should be used instead of this one. -/ private lemma is_jacobson_polynomial_of_domain (R : Type*) [integral_domain R] [hR : is_jacobson R] (P : ideal (polynomial R)) [is_prime P] (hP : ∀ (x : R), C x ∈ P → x = 0) : P.jacobson = P := begin by_cases Pb : (P = ⊥), { exact Pb.symm ▸ jacobson_bot_polynomial_of_jacobson_bot (hR.out radical_bot_of_integral_domain) }, { refine jacobson_eq_iff_jacobson_quotient_eq_bot.mpr _, haveI : (P.comap (C : R →+* polynomial R)).is_prime := comap_is_prime C P, obtain ⟨p, pP, p0⟩ := exists_nonzero_mem_of_ne_bot Pb hP, refine jacobson_bot_of_integral_localization (quotient_map P C le_rfl) quotient_map_injective _ _ (localization.of (submonoid.powers (p.map (quotient.mk (P.comap C))).leading_coeff)) (localization.of _) (is_integral_localization_map_polynomial_quotient P _ pP _ _), rwa [ne.def, leading_coeff_eq_zero] } end lemma is_jacobson_polynomial_of_is_jacobson (hR : is_jacobson R) : is_jacobson (polynomial R) := begin refine is_jacobson_iff_prime_eq.mpr (λ I, _), introI hI, let R' : subring I.quotient := ((quotient.mk I).comp C).range, let i : R →+* R' := ((quotient.mk I).comp C).range_restrict, have hi : function.surjective (i : R → R') := ((quotient.mk I).comp C).range_restrict_surjective, have hi' : (polynomial.map_ring_hom i : polynomial R →+* polynomial R').ker ≤ I, { refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _), replace hf := congr_arg (λ (g : polynomial (((quotient.mk I).comp C).range)), g.coeff n) hf, change (polynomial.map ((quotient.mk I).comp C).range_restrict f).coeff n = 0 at hf, rw [coeff_map, subtype.ext_iff] at hf, rwa [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply] }, haveI : (ideal.map (map_ring_hom i) I).is_prime := map_is_prime_of_surjective (map_surjective i hi) hi', suffices : (I.map (polynomial.map_ring_hom i)).jacobson = (I.map (polynomial.map_ring_hom i)), { replace this := congr_arg (comap (polynomial.map_ring_hom i)) this, rw [← map_jacobson_of_surjective _ hi', comap_map_of_surjective _ _, comap_map_of_surjective _ _] at this, refine le_antisymm (le_trans (le_sup_left_of_le le_rfl) (le_trans (le_of_eq this) (sup_le le_rfl hi'))) le_jacobson, all_goals {exact polynomial.map_surjective i hi} }, exact @is_jacobson_polynomial_of_domain R' _ (is_jacobson_of_surjective ⟨i, hi⟩) (map (map_ring_hom i) I) _ (eq_zero_of_polynomial_mem_map_range I), end theorem is_jacobson_polynomial_iff_is_jacobson : is_jacobson (polynomial R) ↔ is_jacobson R := begin refine ⟨_, is_jacobson_polynomial_of_is_jacobson⟩, introI H, exact is_jacobson_of_surjective ⟨eval₂_ring_hom (ring_hom.id _) 1, λ x, ⟨C x, by simp only [coe_eval₂_ring_hom, ring_hom.id_apply, eval₂_C]⟩⟩, end instance [is_jacobson R] : is_jacobson (polynomial R) := is_jacobson_polynomial_iff_is_jacobson.mpr ‹is_jacobson R› end comm_ring section integral_domain variables {R : Type*} [integral_domain R] [is_jacobson R] variables (P : ideal (polynomial R)) [hP : P.is_maximal] include P hP lemma is_maximal_comap_C_of_is_maximal (hP' : ∀ (x : R), C x ∈ P → x = 0) : is_maximal (comap C P : ideal R) := begin haveI hp'_prime : (P.comap C : ideal R).is_prime := comap_is_prime C P, obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_of_maximal P polynomial_not_is_field), have : (m : polynomial R) ≠ 0, rwa [ne.def, submodule.coe_eq_zero], let φ : (P.comap C : ideal R).quotient →+* P.quotient := quotient_map P C le_rfl, let M : submonoid (P.comap C : ideal R).quotient := submonoid.powers ((m : polynomial R).map (quotient.mk (P.comap C : ideal R))).leading_coeff, rw ← bot_quotient_is_maximal_iff at hP ⊢, have hp0 : ((m : polynomial R).map (quotient.mk (P.comap C : ideal R))).leading_coeff ≠ 0 := λ hp0', this $ map_injective (quotient.mk (P.comap C : ideal R)) ((quotient.mk (P.comap C : ideal R)).injective_iff.2 (λ x hx, by rwa [quotient.eq_zero_iff_mem, (by rwa eq_bot_iff : (P.comap C : ideal R) = ⊥)] at hx)) (by simpa only [leading_coeff_eq_zero, map_zero] using hp0'), let ϕ : localization_map M (localization M) := localization.of M, have hM : (0 : ((P.comap C : ideal R)).quotient) ∉ M := λ ⟨n, hn⟩, hp0 (pow_eq_zero hn), suffices : (⊥ : ideal (localization M)).is_maximal, { rw ← ϕ.comap_map_of_is_prime_disjoint ⊥ bot_prime (λ x hx, hM (hx.2 ▸ hx.1)), refine ((is_maximal_iff_is_maximal_disjoint ϕ _).mp _).1, rwa map_bot }, let M' : submonoid P.quotient := M.map φ, have hM' : (0 : P.quotient) ∉ M' := λ ⟨z, hz⟩, hM (quotient_map_injective (trans hz.2 φ.map_zero.symm) ▸ hz.1), letI : integral_domain (localization M') := localization_map.integral_domain_localization (le_non_zero_divisors_of_domain hM'), let ϕ' : localization_map (M.map ↑φ) (localization (M.map ↑φ)) := localization.of (M.map ↑φ), suffices : (⊥ : ideal (localization M')).is_maximal, { rw le_antisymm bot_le (comap_bot_le_of_injective _ (map_injective_of_injective _ quotient_map_injective M ϕ ϕ' (le_non_zero_divisors_of_domain hM'))), refine is_maximal_comap_of_is_integral_of_is_maximal' _ _ ⊥ this, refine is_integral_localization_map_polynomial_quotient P _ (submodule.coe_mem m) ϕ ϕ', }, rw (map_bot.symm : (⊥ : ideal (localization M')) = map ϕ'.to_map ⊥), refine map.is_maximal ϕ'.to_map (localization_map_bijective_of_field hM' _ ϕ') hP, rwa [← quotient.maximal_ideal_iff_is_field_quotient, ← bot_quotient_is_maximal_iff], end /-- Used to bootstrap the more general `quotient_mk_comp_C_is_integral_of_jacobson` -/ private lemma quotient_mk_comp_C_is_integral_of_jacobson' (hR : is_jacobson R) (hP' : ∀ (x : R), C x ∈ P → x = 0) : ((quotient.mk P).comp C : R →+* P.quotient).is_integral := begin refine (is_integral_quotient_map_iff _).mp _, let P' : ideal R := P.comap C, obtain ⟨pX, hpX, hp0⟩ := exists_nonzero_mem_of_ne_bot (ne_of_lt (bot_lt_of_maximal P polynomial_not_is_field)).symm hP', let M : submonoid P'.quotient := submonoid.powers (pX.map (quotient.mk P')).leading_coeff, let φ : P'.quotient →+* P.quotient := quotient_map P C le_rfl, let ϕ' : localization_map (M.map ↑φ) (localization (M.map ↑φ)) := localization.of (M.map ↑φ), haveI hp'_prime : P'.is_prime := comap_is_prime C P, have hM : (0 : P'.quotient) ∉ M := λ ⟨n, hn⟩, hp0 $ leading_coeff_eq_zero.mp (pow_eq_zero hn), refine ((quotient_map P C le_rfl).is_integral_tower_bot_of_is_integral (localization.of (M.map ↑(quotient_map P C le_rfl))).to_map _ _), { refine ϕ'.injective (le_non_zero_divisors_of_domain (λ hM', hM _)), exact (let ⟨z, zM, z0⟩ := hM' in (quotient_map_injective (trans z0 φ.map_zero.symm)) ▸ zM) }, { let ϕ : localization_map M (localization M) := localization.of M, rw ← (ϕ.map_comp _), refine ring_hom.is_integral_trans ϕ.to_map (ϕ.map (M.mem_map_of_mem (φ : P'.quotient →* P.quotient)) ϕ') _ _, { exact ϕ.to_map.is_integral_of_surjective (localization_map_bijective_of_field hM ((quotient.maximal_ideal_iff_is_field_quotient _).mp (is_maximal_comap_C_of_is_maximal P hP')) _).2 }, { exact is_integral_localization_map_polynomial_quotient P pX hpX _ _ } } end /-- If `R` is a Jacobson ring, and `P` is a maximal ideal of `polynomial R`, then `R → (polynomial R)/P` is an integral map. -/ lemma quotient_mk_comp_C_is_integral_of_jacobson : ((quotient.mk P).comp C : R →+* P.quotient).is_integral := begin let P' : ideal R := P.comap C, haveI : P'.is_prime := comap_is_prime C P, let f : polynomial R →+* polynomial P'.quotient := polynomial.map_ring_hom (quotient.mk P'), have hf : function.surjective f := map_surjective (quotient.mk P') quotient.mk_surjective, have hPJ : P = (P.map f).comap f, { rw comap_map_of_surjective _ hf, refine le_antisymm (le_sup_left_of_le le_rfl) (sup_le le_rfl _), refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _), simpa only [coeff_map, coe_map_ring_hom] using (polynomial.ext_iff.mp hp) n }, refine ring_hom.is_integral_tower_bot_of_is_integral _ _ (injective_quotient_le_comap_map P) _, rw ← quotient_mk_maps_eq, refine ring_hom.is_integral_trans _ _ ((quotient.mk P').is_integral_of_surjective quotient.mk_surjective) _, apply quotient_mk_comp_C_is_integral_of_jacobson' _ _ (λ x hx, _), any_goals { exact ideal.is_jacobson_quotient }, { exact or.rec_on (map_eq_top_or_is_maximal_of_surjective f hf hP) (λ h, absurd (trans (h ▸ hPJ : P = comap f ⊤) comap_top : P = ⊤) hP.ne_top) id }, { obtain ⟨z, rfl⟩ := quotient.mk_surjective x, rwa [quotient.eq_zero_iff_mem, mem_comap, hPJ, mem_comap, coe_map_ring_hom, map_C] } end lemma is_maximal_comap_C_of_is_jacobson : (P.comap (C : R →+* polynomial R)).is_maximal := begin rw [← @mk_ker _ _ P, ring_hom.ker_eq_comap_bot, comap_comap], exact is_maximal_comap_of_is_integral_of_is_maximal' _ (quotient_mk_comp_C_is_integral_of_jacobson P) ⊥ ((bot_quotient_is_maximal_iff _).mpr hP), end omit P hP lemma comp_C_integral_of_surjective_of_jacobson {S : Type*} [field S] (f : (polynomial R) →+* S) (hf : function.surjective f) : (f.comp C).is_integral := begin haveI : (f.ker).is_maximal := @comap_is_maximal_of_surjective _ _ _ _ f ⊥ hf bot_is_maximal, let g : f.ker.quotient →+* S := ideal.quotient.lift f.ker f (λ _ h, h), have hfg : (g.comp (quotient.mk f.ker)) = f := ring_hom_ext' rfl rfl, rw [← hfg, ring_hom.comp_assoc], refine ring_hom.is_integral_trans _ g (quotient_mk_comp_C_is_integral_of_jacobson f.ker) (g.is_integral_of_surjective _), --(quotient.lift_surjective f.ker f _ hf)), rw [← hfg] at hf, exact function.surjective.of_comp hf, end end integral_domain end polynomial namespace mv_polynomial open mv_polynomial ring_hom lemma is_jacobson_mv_polynomial_fin {R : Type*} [comm_ring R] [H : is_jacobson R] : ∀ (n : ℕ), is_jacobson (mv_polynomial (fin n) R) | 0 := ((is_jacobson_iso ((ring_equiv_of_equiv R (equiv.equiv_pempty $ fin.elim0)).trans (pempty_ring_equiv R))).mpr H) | (n+1) := (is_jacobson_iso (fin_succ_equiv R n)).2 (polynomial.is_jacobson_polynomial_iff_is_jacobson.2 (is_jacobson_mv_polynomial_fin n)) /-- General form of the nullstellensatz for Jacobson rings, since in a Jacobson ring we have `Inf {P maximal | P ≥ I} = Inf {P prime | P ≥ I} = I.radical`. Fields are always Jacobson, and in that special case this is (most of) the classical Nullstellensatz, since `I(V(I))` is the intersection of maximal ideals containing `I`, which is then `I.radical` -/ instance {R : Type*} [comm_ring R] {ι : Type*} [fintype ι] [is_jacobson R] : is_jacobson (mv_polynomial ι R) := begin haveI := classical.dec_eq ι, obtain ⟨e⟩ := fintype.equiv_fin ι, rw is_jacobson_iso (ring_equiv_of_equiv R e), exact is_jacobson_mv_polynomial_fin _ end variables {n : ℕ} lemma quotient_mk_comp_C_is_integral_of_jacobson {R : Type*} [integral_domain R] [is_jacobson R] (P : ideal (mv_polynomial (fin n) R)) [P.is_maximal] : ((quotient.mk P).comp mv_polynomial.C : R →+* P.quotient).is_integral := begin unfreezingI {induction n with n IH}, { refine ring_hom.is_integral_of_surjective _ (function.surjective.comp quotient.mk_surjective _), exact C_surjective_fin_0 }, { rw [← fin_succ_equiv_comp_C_eq_C, ← ring_hom.comp_assoc, ← ring_hom.comp_assoc, ← quotient_map_comp_mk le_rfl, ring_hom.comp_assoc (polynomial.C), ← quotient_map_comp_mk le_rfl, ring_hom.comp_assoc, ring_hom.comp_assoc, ← quotient_map_comp_mk le_rfl, ← ring_hom.comp_assoc (quotient.mk _)], refine ring_hom.is_integral_trans _ _ _ _, { refine ring_hom.is_integral_trans _ _ (is_integral_of_surjective _ quotient.mk_surjective) _, refine ring_hom.is_integral_trans _ _ _ _, { apply (is_integral_quotient_map_iff _).mpr (IH _), apply polynomial.is_maximal_comap_C_of_is_jacobson _, { exact mv_polynomial.is_jacobson_mv_polynomial_fin n }, { apply comap_is_maximal_of_surjective, exact (fin_succ_equiv R n).symm.surjective } }, { refine (is_integral_quotient_map_iff _).mpr _, rw ← quotient_map_comp_mk le_rfl, refine ring_hom.is_integral_trans _ _ _ ((is_integral_quotient_map_iff _).mpr _), { exact ring_hom.is_integral_of_surjective _ quotient.mk_surjective }, { apply polynomial.quotient_mk_comp_C_is_integral_of_jacobson _, { exact mv_polynomial.is_jacobson_mv_polynomial_fin n }, { exact comap_is_maximal_of_surjective _ (fin_succ_equiv R n).symm.surjective } } } }, { refine (is_integral_quotient_map_iff _).mpr _, refine ring_hom.is_integral_trans _ _ _ (is_integral_of_surjective _ quotient.mk_surjective), exact ring_hom.is_integral_of_surjective _ (fin_succ_equiv R n).symm.surjective } } end lemma comp_C_integral_of_surjective_of_jacobson {R : Type*} [integral_domain R] [is_jacobson R] {σ : Type*} [fintype σ] {S : Type*} [field S] (f : mv_polynomial σ R →+* S) (hf : function.surjective f) : (f.comp C).is_integral := begin haveI := classical.dec_eq σ, obtain ⟨e⟩ := fintype.equiv_fin σ, let f' : mv_polynomial (fin _) R →+* S := f.comp ↑(ring_equiv_of_equiv R e.symm), have hf' : function.surjective f' := ((function.surjective.comp hf (ring_equiv_of_equiv R e.symm).surjective)), have : (f'.comp C).is_integral, { haveI : (f'.ker).is_maximal := @comap_is_maximal_of_surjective _ _ _ _ f' ⊥ hf' bot_is_maximal, let g : f'.ker.quotient →+* S := ideal.quotient.lift f'.ker f' (λ _ h, h), have hfg : (g.comp (quotient.mk f'.ker)) = f' := ring_hom_ext (λ r, rfl) (λ i, rfl), rw [← hfg, ring_hom.comp_assoc], refine ring_hom.is_integral_trans _ g (quotient_mk_comp_C_is_integral_of_jacobson f'.ker) (g.is_integral_of_surjective _), rw ← hfg at hf', exact function.surjective.of_comp hf' }, rw ring_hom.comp_assoc at this, convert this, refine ring_hom.ext (λ x, (rename_C _ _).symm), end end mv_polynomial end ideal
3cc8e25ad34ced0df58a0bee892753ad6a7d63b9
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/von_neumann_algebra/basic.lean
84dc25e66e8befc7e0b1fb114d8d2dd5ab8ac0c4
[ "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
5,306
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import analysis.normed_space.dual import analysis.normed_space.star.basic import analysis.complex.basic import analysis.inner_product_space.adjoint import algebra.star.subalgebra /-! # Von Neumann algebras We give the "abstract" and "concrete" definitions of a von Neumann algebra. We still have a major project ahead of us to show the equivalence between these definitions! An abstract von Neumann algebra `wstar_algebra M` is a C^* algebra with a Banach space predual, per Sakai (1971). A concrete von Neumann algebra `von_neumann_algebra H` (where `H` is a Hilbert space) is a *-closed subalgebra of bounded operators on `H` which is equal to its double commutant. We'll also need to prove the von Neumann double commutant theorem, that the concrete definition is equivalent to a *-closed subalgebra which is weakly closed. -/ universes u v /-- Sakai's definition of a von Neumann algebra as a C^* algebra with a Banach space predual. So that we can unambiguously talk about these "abstract" von Neumann algebras in parallel with the "concrete" ones (weakly closed *-subalgebras of B(H)), we name this definition `wstar_algebra`. Note that for now we only assert the mere existence of predual, rather than picking one. This may later prove problematic, and need to be revisited. Picking one may cause problems with definitional unification of different instances. One the other hand, not picking one means that the weak-* topology (which depends on a choice of predual) must be defined using the choice, and we may be unhappy with the resulting opaqueness of the definition. -/ class wstar_algebra (M : Type u) [normed_ring M] [star_ring M] [cstar_ring M] [module ℂ M] [normed_algebra ℂ M] [star_module ℂ M] := (exists_predual : ∃ (X : Type u) [normed_add_comm_group X] [normed_space ℂ X] [complete_space X], nonempty (normed_space.dual ℂ X ≃ₗᵢ⋆[ℂ] M)) -- TODO: Without this, `von_neumann_algebra` times out. Why? set_option old_structure_cmd true /-- The double commutant definition of a von Neumann algebra, as a *-closed subalgebra of bounded operators on a Hilbert space, which is equal to its double commutant. Note that this definition is parameterised by the Hilbert space on which the algebra faithfully acts, as is standard in the literature. See `wstar_algebra` for the abstract notion (a C^*-algebra with Banach space predual). Note this is a bundled structure, parameterised by the Hilbert space `H`, rather than a typeclass on the type of elements. Thus we can't say that the bounded operators `H →L[ℂ] H` form a `von_neumann_algebra` (although we will later construct the instance `wstar_algebra (H →L[ℂ] H)`), and instead will use `⊤ : von_neumann_algebra H`. -/ @[nolint has_nonempty_instance] structure von_neumann_algebra (H : Type u) [normed_add_comm_group H] [inner_product_space ℂ H] [complete_space H] extends star_subalgebra ℂ (H →L[ℂ] H) := (centralizer_centralizer' : set.centralizer (set.centralizer carrier) = carrier) /-- Consider a von Neumann algebra acting on a Hilbert space `H` as a *-subalgebra of `H →L[ℂ] H`. (That is, we forget that it is equal to its double commutant or equivalently that it is closed in the weak and strong operator topologies.) -/ add_decl_doc von_neumann_algebra.to_star_subalgebra namespace von_neumann_algebra variables {H : Type u} [normed_add_comm_group H] [inner_product_space ℂ H] [complete_space H] instance : set_like (von_neumann_algebra H) (H →L[ℂ] H) := ⟨von_neumann_algebra.carrier, λ S T h, by cases S; cases T; congr'⟩ instance : star_mem_class (von_neumann_algebra H) (H →L[ℂ] H) := { star_mem := λ s a, s.star_mem' } instance : subring_class (von_neumann_algebra H) (H →L[ℂ] H) := { add_mem := add_mem', mul_mem := mul_mem', one_mem := one_mem', zero_mem := zero_mem' , neg_mem := λ s a ha, show -a ∈ s.to_star_subalgebra, from neg_mem ha } @[simp] lemma mem_carrier {S : von_neumann_algebra H} {x : H →L[ℂ] H}: x ∈ S.carrier ↔ x ∈ (S : set (H →L[ℂ] H)) := iff.rfl @[ext] theorem ext {S T : von_neumann_algebra H} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h @[simp] lemma centralizer_centralizer (S : von_neumann_algebra H) : set.centralizer (set.centralizer (S : set (H →L[ℂ] H))) = S := S.centralizer_centralizer' /-- The centralizer of a `von_neumann_algebra`, as a `von_neumann_algebra`.-/ def commutant (S : von_neumann_algebra H) : von_neumann_algebra H := { carrier := set.centralizer (S : set (H →L[ℂ] H)), centralizer_centralizer' := by rw S.centralizer_centralizer, .. star_subalgebra.centralizer ℂ (S : set (H →L[ℂ] H)) (λ a (ha : a ∈ S), (star_mem ha : _)) } @[simp] lemma coe_commutant (S : von_neumann_algebra H) : ↑S.commutant = set.centralizer (S : set (H →L[ℂ] H)) := rfl @[simp] lemma mem_commutant_iff {S : von_neumann_algebra H} {z : H →L[ℂ] H} : z ∈ S.commutant ↔ ∀ g ∈ S, g * z = z * g := iff.rfl @[simp] lemma commutant_commutant (S : von_neumann_algebra H) : S.commutant.commutant = S := set_like.coe_injective S.centralizer_centralizer' end von_neumann_algebra
b6836d3e82b188792c5d3fbec9ade744a8225717
e16d4df4c2baa34ab203178cea2c27905a3b63d3
/src/day2.lean
85429937ba090290bdd347b8701188dec1bc9fd9
[]
no_license
jembishop/advent-of-code-2020
ea29eecb7f1d676dc1fd34b1a66efdbd23248aec
32fd5bc28e7c178277e85dc034b55fce6dd4afce
refs/heads/main
1,675,354,147,711
1,608,705,139,000
1,608,705,139,000
317,705,877
0
0
null
null
null
null
UTF-8
Lean
false
false
1,694
lean
import system.io import tactic import utils open io open nat open list open functor open decidable structure entry := (letter : char) (min_num : ℕ) (max_num : ℕ) (password : string) def entry_to_string : entry → string | e := "letter: " ++ e.letter.to_string ++ " min: " ++ (to_string e.min_num) ++ " max: " ++ (to_string e.max_num) ++ " password: " ++ (to_string e.password) instance : has_to_string entry := ⟨entry_to_string⟩ def line_to_entry (str : string) : option entry := let sp := string.split (=' ') str in do fst ← (nth sp 0), snd ← (nth sp 1), password ← (nth sp 2), let min_max := string.split (='-') fst, min ← (nth min_max 0), max ← (nth min_max 1), letter ← (nth snd.data 0), return (entry.mk letter (min.to_nat) (max.to_nat) password) def parse (str : string) : (option (list entry)) := monad.sequence (functor.map line_to_entry (filter (≠"") (string.split (='\n') str))) def valid_1 : entry → bool | e := let num := length $ filter (=e.letter) e.password.data in num ≤ e.max_num ∧ num ≥ e.min_num def valid_2 : entry → bool | e := let p := e.password.data match (p.nth (e.min_num - 1), p.nth (e.max_num - 1)) with | (some c1, some c2) := xor (c1=e.letter) (c2=e.letter) | (_, _) := false end def num_valid (pred : entry → bool) : list entry → ℕ := length ∘ filter pred def main : io unit := do contents ← fs.read_file "inputs/day2.txt", let parsed := parse contents.to_string, put_str_ln $ to_string $ functor.map (num_valid valid_1) parsed, put_str_ln $ to_string $ functor.map (num_valid valid_2) parsed
20d679ddcc31e67dbfe1e1fa5e82f5455e79647b
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/geom_sum.lean
44410c1ac6311b0f258065bef7f8bebd20aa0fce
[ "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
15,367
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 algebra.group_with_zero.power import algebra.big_operators.order import algebra.big_operators.ring import algebra.big_operators.intervals /-! # Partial sums of geometric series This file determines the values of the geometric series $\sum_{i=0}^{n-1} x^i$ and $\sum_{i=0}^{n-1} x^i y^{n-1-i}$ and variants thereof. We also provide some bounds on the "geometric" sum of `a/b^i` where `a b : ℕ`. ## Main definitions * `geom_sum` defines for each $x$ in a semiring and each natural number $n$ the partial sum $\sum_{i=0}^{n-1} x^i$ of the geometric series. * `geom_sum₂` defines for each $x,y$ in a semiring and each natural number $n$ the partial sum $\sum_{i=0}^{n-1} x^i y^{n-1-i}$ of the geometric series. ## Main statements * `geom_sum_Ico` proves that $\sum_{i=m}^{n-1} x^i=\frac{x^n-x^m}{x-1}$ in a division ring. * `geom_sum₂_Ico` proves that $\sum_{i=m}^{n-1} x^i=\frac{x^n-y^{n-m}x^m}{x-y}$ in a field. Several variants are recorded, generalising in particular to the case of a noncommutative ring in which `x` and `y` commute. Even versions not using division or subtraction, valid in each semiring, are recorded. -/ universe u variable {α : Type u} open finset opposite open_locale big_operators /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i$. -/ def geom_sum [semiring α] (x : α) (n : ℕ) := ∑ i in range n, x ^ i theorem geom_sum_def [semiring α] (x : α) (n : ℕ) : geom_sum x n = ∑ i in range n, x ^ i := rfl @[simp] theorem geom_sum_zero [semiring α] (x : α) : geom_sum x 0 = 0 := rfl @[simp] theorem geom_sum_one [semiring α] (x : α) : geom_sum x 1 = 1 := by { rw [geom_sum_def, sum_range_one, pow_zero] } @[simp] lemma op_geom_sum [ring α] (x : α) (n : ℕ) : op (geom_sum x n) = geom_sum (op x) n := by simp [geom_sum_def] /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i y^{n-1-i}$. -/ def geom_sum₂ [semiring α] (x y : α) (n : ℕ) := ∑ i in range n, x ^ i * (y ^ (n - 1 - i)) theorem geom_sum₂_def [semiring α] (x y : α) (n : ℕ) : geom_sum₂ x y n = ∑ i in range n, x ^ i * y ^ (n - 1 - i) := rfl @[simp] theorem geom_sum₂_zero [semiring α] (x y : α) : geom_sum₂ x y 0 = 0 := rfl @[simp] theorem geom_sum₂_one [semiring α] (x y : α) : geom_sum₂ x y 1 = 1 := by { have : 1 - 1 - 0 = 0 := rfl, rw [geom_sum₂_def, sum_range_one, this, pow_zero, pow_zero, mul_one] } @[simp] lemma op_geom_sum₂ [ring α] (x y : α) (n : ℕ) : op (geom_sum₂ x y n) = geom_sum₂ (op y) (op x) n := begin simp only [geom_sum₂_def, op_sum, op_mul, op_pow], rw ← sum_range_reflect, refine sum_congr rfl (λ j j_in, _), rw [mem_range, nat.lt_iff_add_one_le] at j_in, congr, apply nat.sub_sub_self, exact le_sub_of_add_le_right' j_in end @[simp] theorem geom_sum₂_with_one [semiring α] (x : α) (n : ℕ) : geom_sum₂ x 1 n = geom_sum x n := sum_congr rfl (λ i _, by { rw [one_pow, mul_one] }) /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ protected theorem commute.geom_sum₂_mul_add [semiring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_sum₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := begin let f := λ (m i : ℕ), (x + y) ^ i * y ^ (m - 1 - i), change (∑ i in range n, (f n) i) * x + y ^ n = (x + y) ^ n, induction n with n ih, { rw [range_zero, sum_empty, zero_mul, zero_add, pow_zero, pow_zero] }, { have f_last : f (n + 1) n = (x + y) ^ n := by { dsimp [f], rw [nat.sub_sub, nat.add_comm, nat.sub_self, pow_zero, mul_one] }, have f_succ : ∀ i, i ∈ range n → f (n + 1) i = y * f n i := λ i hi, by { dsimp [f], have : commute y ((x + y) ^ i) := (h.symm.add_right (commute.refl y)).pow_right i, rw [← mul_assoc, this.eq, mul_assoc, ← pow_succ y (n - 1 - i)], congr' 2, rw [nat.add_sub_cancel, nat.sub_sub, add_comm 1 i], have : i + 1 + (n - (i + 1)) = n := nat.add_sub_of_le (mem_range.mp hi), rw [add_comm (i + 1)] at this, rw [← this, nat.add_sub_cancel, add_comm i 1, ← add_assoc, nat.add_sub_cancel] }, rw [pow_succ (x + y), add_mul, sum_range_succ_comm, add_mul, f_last, add_assoc], rw (((commute.refl x).add_right h).pow_right n).eq, congr' 1, rw [sum_congr rfl f_succ, ← mul_sum, pow_succ y, mul_assoc, ← mul_add y, ih] } end theorem geom_sum₂_self {α : Type*} [comm_ring α] (x : α) (n : ℕ) : geom_sum₂ x x n = n * x ^ (n-1) := calc ∑ i in finset.range n, x ^ i * x ^ (n - 1 - i) = ∑ i in finset.range n, x ^ (i + (n - 1 - i)) : by simp_rw [← pow_add] ... = ∑ i in finset.range n, x ^ (n - 1) : finset.sum_congr rfl (λ i hi, congr_arg _ $ add_sub_cancel_of_le $ nat.le_pred_of_lt $ finset.mem_range.1 hi) ... = (finset.range n).card • (x ^ (n - 1)) : finset.sum_const _ ... = n * x ^ (n - 1) : by rw [finset.card_range, nsmul_eq_mul] /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ theorem geom_sum₂_mul_add [comm_semiring α] (x y : α) (n : ℕ) : (geom_sum₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := (commute.all x y).geom_sum₂_mul_add n theorem geom_sum_mul_add [semiring α] (x : α) (n : ℕ) : (geom_sum (x + 1) n) * x + 1 = (x + 1) ^ n := begin have := (commute.one_right x).geom_sum₂_mul_add n, rw [one_pow, geom_sum₂_with_one] at this, exact this end protected theorem commute.geom_sum₂_mul [ring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_sum₂ x y n) * (x - y) = x ^ n - y ^ n := begin have := (h.sub_left (commute.refl y)).geom_sum₂_mul_add n, rw [sub_add_cancel] at this, rw [← this, add_sub_cancel] end lemma commute.mul_neg_geom_sum₂ [ring α] {x y : α} (h : commute x y) (n : ℕ) : (y - x) * (geom_sum₂ x y n) = y ^ n - x ^ n := begin rw ← op_inj_iff, simp only [op_mul, op_sub, op_geom_sum₂, op_pow], exact (commute.op h.symm).geom_sum₂_mul n end lemma commute.mul_geom_sum₂ [ring α] {x y : α} (h : commute x y) (n : ℕ) : (x - y) * (geom_sum₂ x y n) = x ^ n - y ^ n := by rw [← neg_sub (y ^ n), ← h.mul_neg_geom_sum₂, ← neg_mul_eq_neg_mul_symm, neg_sub] theorem geom_sum₂_mul [comm_ring α] (x y : α) (n : ℕ) : (geom_sum₂ x y n) * (x - y) = x ^ n - y ^ n := (commute.all x y).geom_sum₂_mul n theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : (geom_sum x n) * (x - 1) = x ^ n - 1 := begin have := (commute.one_right x).geom_sum₂_mul n, rw [one_pow, geom_sum₂_with_one] at this, exact this end lemma mul_geom_sum [ring α] (x : α) (n : ℕ) : (x - 1) * (geom_sum x n) = x ^ n - 1 := begin rw ← op_inj_iff, simpa using geom_sum_mul (op x) n, end theorem geom_sum_mul_neg [ring α] (x : α) (n : ℕ) : (geom_sum x n) * (1 - x) = 1 - x ^ n := begin have := congr_arg has_neg.neg (geom_sum_mul x n), rw [neg_sub, ← mul_neg_eq_neg_mul_symm, neg_sub] at this, exact this end lemma mul_neg_geom_sum [ring α] (x : α) (n : ℕ) : (1 - x) * (geom_sum x n) = 1 - x ^ n := begin rw ← op_inj_iff, simpa using geom_sum_mul_neg (op x) n, end protected theorem commute.geom_sum₂ [division_ring α] {x y : α} (h' : commute x y) (h : x ≠ y) (n : ℕ) : (geom_sum₂ x y n) = (x ^ n - y ^ n) / (x - y) := have x - y ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← h'.geom_sum₂_mul, mul_div_cancel _ this] theorem geom₂_sum [field α] {x y : α} (h : x ≠ y) (n : ℕ) : (geom_sum₂ x y n) = (x ^ n - y ^ n) / (x - y) := (commute.all x y).geom_sum₂ h n theorem geom_sum_eq [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) : (geom_sum x n) = (x ^ n - 1) / (x - 1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] protected theorem commute.mul_geom_sum₂_Ico [ring α] {x y : α} (h : commute x y) {m n : ℕ} (hmn : m ≤ n) : (x - y) * (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) = x ^ n - x ^ m * y ^ (n - m) := begin rw [sum_Ico_eq_sub _ hmn, ← geom_sum₂_def], have : ∑ k in range m, x ^ k * y ^ (n - 1 - k) = ∑ k in range m, x ^ k * (y ^ (n - m) * y ^ (m - 1 - k)), { refine sum_congr rfl (λ j j_in, _), rw ← pow_add, congr, rw [mem_range, nat.lt_iff_add_one_le, add_comm] at j_in, have h' : n - m + (m - (1 + j)) = n - (1 + j) := sub_add_sub_cancel'' hmn j_in, rw [nat.sub_sub m, h', nat.sub_sub] }, rw this, simp_rw pow_mul_comm y (n-m) _, simp_rw ← mul_assoc, rw [← sum_mul, ← geom_sum₂_def, mul_sub, h.mul_geom_sum₂, ← mul_assoc, h.mul_geom_sum₂, sub_mul, ← pow_add, nat.add_sub_of_le hmn, sub_sub_sub_cancel_right (x ^ n) (x ^ m * y ^ (n - m)) (y ^ n)], end protected theorem commute.geom_sum₂_succ_eq {α : Type u} [ring α] {x y : α} (h : commute x y) {n : ℕ} : geom_sum₂ x y (n + 1) = x ^ n + y * (geom_sum₂ x y n) := begin simp_rw [geom_sum₂, mul_sum, sum_range_succ_comm, nat.add_succ_sub_one, add_zero, nat.sub_self, pow_zero, mul_one, add_right_inj, ←mul_assoc, (h.symm.pow_right _).eq, mul_assoc, ←pow_succ], refine sum_congr rfl (λ i hi, _), suffices : n - 1 - i + 1 = n - i, { rw this }, cases n, { exact absurd (list.mem_range.mp hi) i.not_lt_zero }, { rw [sub_add_eq_add_sub' (nat.le_pred_of_lt (list.mem_range.mp hi)), nat.sub_add_cancel (nat.succ_le_iff.mpr n.succ_pos)] }, end theorem geom_sum₂_succ_eq {α : Type u} [comm_ring α] (x y : α) {n : ℕ} : geom_sum₂ x y (n + 1) = x ^ n + y * (geom_sum₂ x y n) := (commute.all x y).geom_sum₂_succ_eq theorem mul_geom_sum₂_Ico [comm_ring α] (x y : α) {m n : ℕ} (hmn : m ≤ n) : (x - y) * (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) = x ^ n - x ^ m * y ^ (n - m) := (commute.all x y).mul_geom_sum₂_Ico hmn protected theorem commute.geom_sum₂_Ico_mul [ring α] {x y : α} (h : commute x y) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) * (x - y) = x ^ n - y ^ (n - m) * x ^ m := begin rw ← op_inj_iff, simp only [op_sub, op_mul, op_pow, op_sum], have : ∑ k in Ico m n, op y ^ (n - 1 - k) * op x ^ k = ∑ k in Ico m n, op x ^ k * op y ^ (n - 1 - k), { refine sum_congr rfl (λ k k_in, _), apply commute.pow_pow (commute.op h.symm) }, rw this, exact (commute.op h).mul_geom_sum₂_Ico hmn end theorem geom_sum_Ico_mul [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i) * (x - 1) = x^n - x^m := by rw [sum_Ico_eq_sub _ hmn, ← geom_sum_def, ← geom_sum_def, sub_mul, geom_sum_mul, geom_sum_mul, sub_sub_sub_cancel_right] theorem geom_sum_Ico_mul_neg [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i) * (1 - x) = x^m - x^n := by rw [sum_Ico_eq_sub _ hmn, ← geom_sum_def, ← geom_sum_def, sub_mul, geom_sum_mul_neg, geom_sum_mul_neg, sub_sub_sub_cancel_left] protected theorem commute.geom_sum₂_Ico [division_ring α] {x y : α} (h : commute x y) (hxy : x ≠ y) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i) = (x ^ n - y ^ (n - m) * x ^ m ) / (x - y) := have x - y ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← h.geom_sum₂_Ico_mul hmn, mul_div_cancel _ this] theorem geom_sum₂_Ico [field α] {x y : α} (hxy : x ≠ y) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i) = (x ^ n - y ^ (n - m) * x ^ m ) / (x - y) := (commute.all x y).geom_sum₂_Ico hxy hmn theorem geom_sum_Ico [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i = (x ^ n - x ^ m) / (x - 1) := by simp only [sum_Ico_eq_sub _ hmn, (geom_sum_def _ _).symm, geom_sum_eq hx, div_sub_div_same, sub_sub_sub_cancel_right] theorem geom_sum_Ico' [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i = (x ^ m - x ^ n) / (1 - x) := by { simp only [geom_sum_Ico hx hmn], convert neg_div_neg_eq (x^m - x^n) (1-x); abel } lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) : (geom_sum x⁻¹ n) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) := have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul], have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁, have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1, have h₄ : x * (x ^ n)⁻¹ = (x ^ n)⁻¹ * x := nat.rec_on n (by simp) (λ n h, by rw [pow_succ, mul_inv_rev₀, ←mul_assoc, h, mul_assoc, mul_inv_cancel hx0, mul_assoc, inv_mul_cancel hx0]), begin rw [geom_sum_eq h₁, div_eq_iff_mul_eq h₂, ← mul_right_inj' h₃, ← mul_assoc, ← mul_assoc, mul_inv_cancel h₃], simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄, sub_eq_add_neg, add_comm, add_left_comm], end variables {β : Type*} theorem ring_hom.map_geom_sum [semiring α] [semiring β] (x : α) (n : ℕ) (f : α →+* β) : f (geom_sum x n) = geom_sum (f x) n := by simp [geom_sum_def, f.map_sum] theorem ring_hom.map_geom_sum₂ [semiring α] [semiring β] (x y : α) (n : ℕ) (f : α →+* β) : f (geom_sum₂ x y n) = geom_sum₂ (f x) (f y) n := by simp [geom_sum₂_def, f.map_sum] /-! ### Geometric sum with `ℕ`-division -/ lemma nat.pred_mul_geom_sum_le (a b n : ℕ) : (b - 1) * ∑ i in range n.succ, a/b^i ≤ a * b - a/b^n := calc (b - 1) * (∑ i in range n.succ, a/b^i) = ∑ i in range n, a/b^(i + 1) * b + a * b - (∑ i in range n, a/b^i + a/b^n) : by rw [nat.mul_sub_right_distrib, mul_comm, sum_mul, one_mul, sum_range_succ', sum_range_succ, pow_zero, nat.div_one] ... ≤ ∑ i in range n, a/b^i + a * b - (∑ i in range n, a/b^i + a/b^n) : begin refine nat.sub_le_sub_right (add_le_add_right (sum_le_sum $ λ i _, _) _) _, rw [pow_succ', ←nat.div_div_eq_div_mul], exact nat.div_mul_le_self _ _, end ... = a * b - a/b^n : nat.add_sub_add_left _ _ _ lemma nat.geom_sum_le {b : ℕ} (hb : 2 ≤ b) (a n : ℕ) : ∑ i in range n, a/b^i ≤ a * b/(b - 1) := begin refine (nat.le_div_iff_mul_le _ _ $ nat.sub_pos_of_lt hb).2 _, cases n, { rw [sum_range_zero, zero_mul], exact nat.zero_le _ }, rw mul_comm, exact (nat.pred_mul_geom_sum_le a b n).trans sub_le_self', end lemma nat.geom_sum_Ico_le {b : ℕ} (hb : 2 ≤ b) (a n : ℕ) : ∑ i in Ico 1 n, a/b^i ≤ a/(b - 1) := begin cases n, { rw [Ico_eq_empty_of_le zero_le_one, sum_empty], exact nat.zero_le _ }, rw ←add_le_add_iff_left a, calc a + ∑ (i : ℕ) in Ico 1 n.succ, a/b^i = a/b^0 + ∑ (i : ℕ) in Ico 1 n.succ, a/b^i : by rw [pow_zero, nat.div_one] ... = ∑ i in range n.succ, a/b^i : begin rw [range_eq_Ico, ←nat.Ico_insert_succ_left (nat.succ_pos _), sum_insert], exact λ h, zero_lt_one.not_le (mem_Ico.1 h).1, end ... ≤ a * b/(b - 1) : nat.geom_sum_le hb a _ ... = (a * 1 + a * (b - 1))/(b - 1) : by rw [←mul_add, add_sub_cancel_of_le (one_le_two.trans hb)] ... = a + a/(b - 1) : by rw [mul_one, nat.add_mul_div_right _ _ (nat.sub_pos_of_lt hb), add_comm] end
69e5c9a57aba0fa1506129faa22d5135929d2481
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/calculus/formal_multilinear_series.lean
bcbd3eb37859041e884579bd0e892e76fe7bd93f
[ "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
11,361
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.multilinear /-! # Formal multilinear series In this file we define `formal_multilinear_series 𝕜 E F` to be a family of `n`-multilinear maps for all `n`, designed to model the sequence of derivatives of a function. In other files we use this notion to define `C^n` functions (called `cont_diff` in `mathlib`) and analytic functions. ## Notations We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives. ## Tags multilinear, formal series -/ noncomputable theory open set fin open_locale topological_space variables {𝕜 𝕜' E F G : Type*} section variables [comm_ring 𝕜] [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_const_smul 𝕜 E] [add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F] [has_continuous_const_smul 𝕜 F] [add_comm_group G] [module 𝕜 G] [topological_space G] [topological_add_group G] [has_continuous_const_smul 𝕜 G] /-- A formal multilinear series over a field `𝕜`, from `E` to `F`, is given by a family of multilinear maps from `E^n` to `F` for all `n`. -/ @[derive add_comm_group, nolint unused_arguments] def formal_multilinear_series (𝕜 : Type*) (E : Type*) (F : Type*) [ring 𝕜] [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_const_smul 𝕜 E] [add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F] [has_continuous_const_smul 𝕜 F] := Π (n : ℕ), (E [×n]→L[𝕜] F) instance : inhabited (formal_multilinear_series 𝕜 E F) := ⟨0⟩ section module /- `derive` is not able to find the module structure, probably because Lean is confused by the dependent types. We register it explicitly. -/ instance : module 𝕜 (formal_multilinear_series 𝕜 E F) := begin letI : Π n, module 𝕜 (continuous_multilinear_map 𝕜 (λ (i : fin n), E) F) := λ n, by apply_instance, refine pi.module _ _ _, end end module namespace formal_multilinear_series protected lemma ext_iff {p q : formal_multilinear_series 𝕜 E F} : p = q ↔ ∀ n, p n = q n := function.funext_iff protected lemma ne_iff {p q : formal_multilinear_series 𝕜 E F} : p ≠ q ↔ ∃ n, p n ≠ q n := function.ne_iff /-- Killing the zeroth coefficient in a formal multilinear series -/ def remove_zero (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E F | 0 := 0 | (n + 1) := p (n + 1) @[simp] lemma remove_zero_coeff_zero (p : formal_multilinear_series 𝕜 E F) : p.remove_zero 0 = 0 := rfl @[simp] lemma remove_zero_coeff_succ (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : p.remove_zero (n+1) = p (n+1) := rfl lemma remove_zero_of_pos (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (h : 0 < n) : p.remove_zero n = p n := by { rw ← nat.succ_pred_eq_of_pos h, refl } /-- Convenience congruence lemma stating in a dependent setting that, if the arguments to a formal multilinear series are equal, then the values are also equal. -/ lemma congr (p : formal_multilinear_series 𝕜 E F) {m n : ℕ} {v : fin m → E} {w : fin n → E} (h1 : m = n) (h2 : ∀ (i : ℕ) (him : i < m) (hin : i < n), v ⟨i, him⟩ = w ⟨i, hin⟩) : p m v = p n w := by { cases h1, congr' with ⟨i, hi⟩, exact h2 i hi hi } /-- Composing each term `pₙ` in a formal multilinear series with `(u, ..., u)` where `u` is a fixed continuous linear map, gives a new formal multilinear series `p.comp_continuous_linear_map u`. -/ def comp_continuous_linear_map (p : formal_multilinear_series 𝕜 F G) (u : E →L[𝕜] F) : formal_multilinear_series 𝕜 E G := λ n, (p n).comp_continuous_linear_map (λ (i : fin n), u) @[simp] lemma comp_continuous_linear_map_apply (p : formal_multilinear_series 𝕜 F G) (u : E →L[𝕜] F) (n : ℕ) (v : fin n → E) : (p.comp_continuous_linear_map u) n v = p n (u ∘ v) := rfl variables (𝕜) [comm_ring 𝕜'] [has_smul 𝕜 𝕜'] variables [module 𝕜' E] [has_continuous_const_smul 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] variables [module 𝕜' F] [has_continuous_const_smul 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] /-- Reinterpret a formal `𝕜'`-multilinear series as a formal `𝕜`-multilinear series. -/ @[simp] protected def restrict_scalars (p : formal_multilinear_series 𝕜' E F) : formal_multilinear_series 𝕜 E F := λ n, (p n).restrict_scalars 𝕜 end formal_multilinear_series end namespace formal_multilinear_series variables [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F] [normed_add_comm_group G] [normed_space 𝕜 G] variables (p : formal_multilinear_series 𝕜 E F) /-- Forgetting the zeroth term in a formal multilinear series, and interpreting the following terms as multilinear maps into `E →L[𝕜] F`. If `p` corresponds to the Taylor series of a function, then `p.shift` is the Taylor series of the derivative of the function. -/ def shift : formal_multilinear_series 𝕜 E (E →L[𝕜] F) := λn, (p n.succ).curry_right /-- Adding a zeroth term to a formal multilinear series taking values in `E →L[𝕜] F`. This corresponds to starting from a Taylor series for the derivative of a function, and building a Taylor series for the function itself. -/ def unshift (q : formal_multilinear_series 𝕜 E (E →L[𝕜] F)) (z : F) : formal_multilinear_series 𝕜 E F | 0 := (continuous_multilinear_curry_fin0 𝕜 E F).symm z | (n + 1) := continuous_multilinear_curry_right_equiv' 𝕜 n E F (q n) end formal_multilinear_series namespace continuous_linear_map variables [comm_ring 𝕜] [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_const_smul 𝕜 E] [add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F] [has_continuous_const_smul 𝕜 F] [add_comm_group G] [module 𝕜 G] [topological_space G] [topological_add_group G] [has_continuous_const_smul 𝕜 G] /-- Composing each term `pₙ` in a formal multilinear series with a continuous linear map `f` on the left gives a new formal multilinear series `f.comp_formal_multilinear_series p` whose general term is `f ∘ pₙ`. -/ def comp_formal_multilinear_series (f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E G := λ n, f.comp_continuous_multilinear_map (p n) @[simp] lemma comp_formal_multilinear_series_apply (f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : (f.comp_formal_multilinear_series p) n = f.comp_continuous_multilinear_map (p n) := rfl lemma comp_formal_multilinear_series_apply' (f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (v : fin n → E) : (f.comp_formal_multilinear_series p) n v = f (p n v) := rfl end continuous_linear_map namespace formal_multilinear_series section order variables [comm_ring 𝕜] {n : ℕ} [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_const_smul 𝕜 E] [add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F] [has_continuous_const_smul 𝕜 F] {p : formal_multilinear_series 𝕜 E F} /-- The index of the first non-zero coefficient in `p` (or `0` if all coefficients are zero). This is the order of the isolated zero of an analytic function `f` at a point if `p` is the Taylor series of `f` at that point. -/ noncomputable def order (p : formal_multilinear_series 𝕜 E F) : ℕ := Inf { n | p n ≠ 0 } @[simp] lemma order_zero : (0 : formal_multilinear_series 𝕜 E F).order = 0 := by simp [order] lemma ne_zero_of_order_ne_zero (hp : p.order ≠ 0) : p ≠ 0 := λ h, by simpa [h] using hp lemma order_eq_find [decidable_pred (λ n, p n ≠ 0)] (hp : ∃ n, p n ≠ 0) : p.order = nat.find hp := by simp [order, Inf, hp] lemma order_eq_find' [decidable_pred (λ n, p n ≠ 0)] (hp : p ≠ 0) : p.order = nat.find (formal_multilinear_series.ne_iff.mp hp) := order_eq_find _ lemma order_eq_zero_iff (hp : p ≠ 0) : p.order = 0 ↔ p 0 ≠ 0 := begin classical, have : ∃ n, p n ≠ 0 := formal_multilinear_series.ne_iff.mp hp, simp [order_eq_find this, hp] end lemma order_eq_zero_iff' : p.order = 0 ↔ p = 0 ∨ p 0 ≠ 0 := by { by_cases h : p = 0; simp [h, order_eq_zero_iff] } lemma apply_order_ne_zero (hp : p ≠ 0) : p p.order ≠ 0 := begin classical, let h := formal_multilinear_series.ne_iff.mp hp, exact (order_eq_find h).symm ▸ nat.find_spec h end lemma apply_order_ne_zero' (hp : p.order ≠ 0) : p p.order ≠ 0 := apply_order_ne_zero (ne_zero_of_order_ne_zero hp) lemma apply_eq_zero_of_lt_order (hp : n < p.order) : p n = 0 := begin by_cases p = 0, { simp [h] }, { classical, rw [order_eq_find' h] at hp, simpa using nat.find_min _ hp } end end order section coef variables [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] {s : E} {p : formal_multilinear_series 𝕜 𝕜 E} {f : 𝕜 → E} {n : ℕ} {z z₀ : 𝕜} {y : fin n → 𝕜} open_locale big_operators /-- The `n`th coefficient of `p` when seen as a power series. -/ def coeff (p : formal_multilinear_series 𝕜 𝕜 E) (n : ℕ) : E := p n 1 lemma mk_pi_field_coeff_eq (p : formal_multilinear_series 𝕜 𝕜 E) (n : ℕ) : continuous_multilinear_map.mk_pi_field 𝕜 (fin n) (p.coeff n) = p n := (p n).mk_pi_field_apply_one_eq_self @[simp] lemma apply_eq_prod_smul_coeff : p n y = (∏ i, y i) • p.coeff n := begin convert (p n).to_multilinear_map.map_smul_univ y 1, funext; simp only [pi.one_apply, algebra.id.smul_eq_mul, mul_one], end lemma coeff_eq_zero : p.coeff n = 0 ↔ p n = 0 := by rw [← mk_pi_field_coeff_eq p, continuous_multilinear_map.mk_pi_field_eq_zero_iff] @[simp] lemma apply_eq_pow_smul_coeff : p n (λ _, z) = z ^ n • p.coeff n := by simp @[simp] lemma norm_apply_eq_norm_coef : ∥p n∥ = ∥coeff p n∥ := by rw [← mk_pi_field_coeff_eq p, continuous_multilinear_map.norm_mk_pi_field] end coef section fslope variables [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] {p : formal_multilinear_series 𝕜 𝕜 E} {n : ℕ} /-- The formal counterpart of `dslope`, corresponding to the expansion of `(f z - f 0) / z`. If `f` has `p` as a power series, then `dslope f` has `fslope p` as a power series. -/ noncomputable def fslope (p : formal_multilinear_series 𝕜 𝕜 E) : formal_multilinear_series 𝕜 𝕜 E := λ n, (p (n + 1)).curry_left 1 @[simp] lemma coeff_fslope : p.fslope.coeff n = p.coeff (n + 1) := begin have : @fin.cons n (λ _, 𝕜) 1 (1 : fin n → 𝕜) = 1 := fin.cons_self_tail 1, simp only [fslope, coeff, continuous_multilinear_map.curry_left_apply, this], end @[simp] lemma coeff_iterate_fslope (k n : ℕ) : (fslope^[k] p).coeff n = p.coeff (n + k) := by induction k with k ih generalizing p; refl <|> simpa [ih] end fslope end formal_multilinear_series
cded5f74a75b60bc809ec4eadbc9df675b03c08b
02fbe05a45fda5abde7583464416db4366eedfbf
/library/init/data/string/ops.lean
6f2b1b6f5e75cc3e864c7cbd14e8e54cbb0c3b1f
[ "Apache-2.0" ]
permissive
jasonrute/lean
cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154
4be962c167ca442a0ec5e84472d7ff9f5302788f
refs/heads/master
1,672,036,664,637
1,601,642,826,000
1,601,642,826,000
260,777,966
0
0
Apache-2.0
1,588,454,819,000
1,588,454,818,000
null
UTF-8
Lean
false
false
1,751
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.data.bool.lemmas import init.data.string.basic import init.meta.well_founded_tactics namespace string namespace iterator @[simp] lemma next_to_string_mk_iterator (s : string) : s.mk_iterator.next_to_string = s := by induction s; refl @[simp] lemma length_next_to_string_next (it : iterator) : it.next.next_to_string.length = it.next_to_string.length - 1 := by cases it; cases it_snd; simp [iterator.next, iterator.next_to_string, string.length, nat.add_sub_cancel_left] lemma zero_lt_length_next_to_string_of_has_next {it : iterator} : it.has_next → 0 < it.next_to_string.length := by cases it; cases it_snd; simp [iterator.has_next, iterator.next_to_string, string.length, nat.zero_lt_one_add, nat.add_comm] end iterator -- TODO(Sebastian): generalize to something like https://doc.rust-lang.org/std/primitive.str.html#method.split private def split_core (p : char → bool) : iterator → iterator → list string | start stop := if h : stop.has_next then -- wf hint have stop.next_to_string.length - 1 < stop.next_to_string.length, from nat.sub_lt (iterator.zero_lt_length_next_to_string_of_has_next h) dec_trivial, if p stop.curr then let rest := stop.next.next_to_string in (start.extract stop).get_or_else "" :: split_core stop.next stop.next else split_core start stop.next else [start.next_to_string] using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ e, e.2.next_to_string.length)⟩] } def split (p : char → bool) (s : string) : list string := split_core p s.mk_iterator s.mk_iterator end string
60a22f983fd942e14f59599b353b6a7cd57b9fe1
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/stage0/src/Init/System/IO.lean
743abda392190ce70840185bca1e6d8b171538d7
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,784
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch, Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Control.EState import Init.Control.Reader import Init.Data.String import Init.Data.ByteArray import Init.System.IOError import Init.System.FilePath import Init.System.ST /-- Like https://hackage.haskell.org/package/ghc-Prim-0.5.2.0/docs/GHC-Prim.html#t:RealWorld. Makes sure we never reorder `IO` operations. TODO: mark opaque -/ def IO.RealWorld : Type := Unit /- TODO(Leo): mark it as an opaque definition. Reason: prevent functions defined in other modules from accessing `IO.RealWorld`. We don't want action such as ``` def getWorld : IO (IO.RealWorld) := get ``` -/ def EIO (ε : Type) : Type → Type := EStateM ε IO.RealWorld instance monadExceptAdapter {ε ε'} : MonadExceptAdapter ε ε' (EIO ε) (EIO ε') := inferInstanceAs $ MonadExceptAdapter ε ε' (EStateM ε IO.RealWorld) (EStateM ε' IO.RealWorld) @[inline] def EIO.catchExceptions {α ε} (x : EIO ε α) (h : ε → EIO Empty α) : EIO Empty α := fun s => match x s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex s => h ex s instance (ε : Type) : Monad (EIO ε) := inferInstanceAs (Monad (EStateM ε IO.RealWorld)) instance (ε : Type) : MonadFinally (EIO ε) := inferInstanceAs (MonadFinally (EStateM ε IO.RealWorld)) instance (ε : Type) : MonadExceptOf ε (EIO ε) := inferInstanceAs (MonadExceptOf ε (EStateM ε IO.RealWorld)) instance (α ε : Type) : HasOrelse (EIO ε α) := ⟨MonadExcept.orelse⟩ instance {ε : Type} {α : Type} [Inhabited ε] : Inhabited (EIO ε α) := inferInstanceAs (Inhabited (EStateM ε IO.RealWorld α)) abbrev IO : Type → Type := EIO IO.Error @[inline] def EIO.toIO {α ε} (f : ε → IO.Error) (x : EIO ε α) : IO α := x.adaptExcept f @[inline] def IO.toEIO {α ε} (f : IO.Error → ε) (x : IO α) : EIO ε α := x.adaptExcept f section /- After we inline `EState.run'`, the closed term `((), ())` is generated, where the second `()` represents the "initial world". We don't want to cache this closed term. So, we disable the "extract closed terms" optimization. -/ set_option compiler.extract_closed false @[inline] unsafe def unsafeIO {α : Type} (fn : IO α) : Except IO.Error α := match fn.run () with | EStateM.Result.ok a _ => Except.ok a | EStateM.Result.error e _ => Except.error e end @[extern "lean_io_timeit"] constant timeit {α : Type} (msg : @& String) (fn : IO α) : IO α := arbitrary _ @[extern "lean_io_allocprof"] constant allocprof {α : Type} (msg : @& String) (fn : IO α) : IO α := arbitrary _ /- Programs can execute IO actions during initialization that occurs before the `main` function is executed. The attribute `[init <action>]` specifies which IO action is executed to set the value of an opaque constant. The action `initializing` returns `true` iff it is invoked during initialization. -/ @[extern "lean_io_initializing"] constant IO.initializing : IO Bool := arbitrary _ class MonadIO (m : Type → Type) := { liftIO {α} : IO α → m α } export MonadIO (liftIO) instance monadIOTrans (m n) [MonadIO m] [MonadLift m n] : MonadIO n := { liftIO := fun α x => liftM $ (liftIO x : m _) } instance monadIOSelf : MonadIO IO := { liftIO := fun α => id } @[inline] def mkEIOMonadIO {ε ε'} [MonadIO (EIO ε)] (f : ε → ε') : MonadIO (EIO ε') := { liftIO := fun α x => adaptExcept f (liftIO x : EIO ε α) } namespace IO def ofExcept {ε α : Type} [HasToString ε] (e : Except ε α) : IO α := match e with | Except.ok a => pure a | Except.error e => throw (IO.userError (toString e)) def lazyPure {α : Type} (fn : Unit → α) : IO α := pure (fn ()) inductive FS.Mode | read | write | readWrite | append constant FS.Handle : Type := Unit /-- A pure-Lean abstraction of POSIX streams. We use `Stream`s for the standard streams stdin/stdout/stderr so we can capture output of `#eval` commands into memory. -/ structure FS.Stream := (isEof : IO Bool) (flush : IO Unit) (read : forall (bytes : USize), IO ByteArray) (write : ByteArray → IO Unit) (getLine : IO String) (putStr : String → IO Unit) namespace Prim open FS @[extern "lean_get_stdin"] constant getStdin : IO FS.Stream := arbitrary _ @[extern "lean_get_stdout"] constant getStdout : IO FS.Stream := arbitrary _ @[extern "lean_get_stderr"] constant getStderr : IO FS.Stream := arbitrary _ @[extern "lean_get_set_stdin"] constant setStdin : FS.Stream → IO FS.Stream := arbitrary _ @[extern "lean_get_set_stdout"] constant setStdout : FS.Stream → IO FS.Stream := arbitrary _ @[extern "lean_get_set_stderr"] constant setStderr : FS.Stream → IO FS.Stream := arbitrary _ @[specialize] partial def iterate {α β : Type} : α → (α → IO (Sum α β)) → IO β | a, f => do v ← f a; match v with | Sum.inl a => iterate a f | Sum.inr b => pure b -- @[export lean_fopen_flags] def fopenFlags (m : FS.Mode) (b : Bool) : String := let mode := match m with | FS.Mode.read => "r" | FS.Mode.write => "w" | FS.Mode.readWrite => "r+" | FS.Mode.append => "a" ; let bin := if b then "b" else "t"; mode ++ bin @[extern "lean_io_prim_handle_mk"] constant Handle.mk (s : @& String) (mode : @& String) : IO Handle := arbitrary _ @[extern "lean_io_prim_handle_is_eof"] constant Handle.isEof (h : @& Handle) : IO Bool := arbitrary _ @[extern "lean_io_prim_handle_flush"] constant Handle.flush (h : @& Handle) : IO Unit := arbitrary _ @[extern "lean_io_prim_handle_read"] constant Handle.read (h : @& Handle) (bytes : USize) : IO ByteArray := arbitrary _ @[extern "lean_io_prim_handle_write"] constant Handle.write (h : @& Handle) (buffer : @& ByteArray) : IO Unit := arbitrary _ @[extern "lean_io_prim_handle_get_line"] constant Handle.getLine (h : @& Handle) : IO String := arbitrary _ @[extern "lean_io_prim_handle_put_str"] constant Handle.putStr (h : @& Handle) (s : @& String) : IO Unit := arbitrary _ @[extern "lean_io_getenv"] constant getEnv (var : @& String) : IO (Option String) := arbitrary _ @[extern "lean_io_realpath"] constant realPath (fname : String) : IO String := arbitrary _ @[extern "lean_io_is_dir"] constant isDir (fname : @& String) : IO Bool := arbitrary _ @[extern "lean_io_file_exists"] constant fileExists (fname : @& String) : IO Bool := arbitrary _ @[extern "lean_io_app_dir"] constant appPath : IO String := arbitrary _ @[extern "lean_io_current_dir"] constant currentDir : IO String := arbitrary _ end Prim namespace FS variables {m : Type → Type} [Monad m] [MonadIO m] def Handle.mk (s : String) (Mode : Mode) (bin : Bool := true) : m Handle := liftIO (Prim.Handle.mk s (Prim.fopenFlags Mode bin)) @[inline] def withFile {α} (fn : String) (mode : Mode) (f : Handle → m α) : m α := Handle.mk fn mode >>= f /-- returns whether the end of the file has been reached while reading a file. `h.isEof` returns true /after/ the first attempt at reading past the end of `h`. Once `h.isEof` is true, the reading `h` raises `IO.Error.eof`. -/ def Handle.isEof : Handle → m Bool := liftIO ∘ Prim.Handle.isEof def Handle.flush : Handle → m Unit := liftIO ∘ Prim.Handle.flush def Handle.read (h : Handle) (bytes : Nat) : m ByteArray := liftIO (Prim.Handle.read h (USize.ofNat bytes)) def Handle.write (h : Handle) (s : ByteArray) : m Unit := liftIO (Prim.Handle.write h s) def Handle.getLine : Handle → m String := liftIO ∘ Prim.Handle.getLine def Handle.putStr (h : Handle) (s : String) : m Unit := liftIO $ Prim.Handle.putStr h s def Handle.putStrLn (h : Handle) (s : String) : m Unit := h.putStr s *> h.putStr "\n" -- TODO: support for binary files partial def Handle.readToEndAux (h : Handle) : String → m String | s => do line ← h.getLine; if line.length == 0 then pure s else Handle.readToEndAux (s ++ line) -- TODO: support for binary files def Handle.readToEnd (h : Handle) : m String := Handle.readToEndAux h "" -- TODO: support for binary files def readFile (fname : String) : m String := do h ← Handle.mk fname Mode.read false; h.readToEnd partial def linesAux (h : Handle) : Array String → m (Array String) | lines => do line ← h.getLine; if line.length == 0 then pure lines else if line.back == '\n' then let line := line.dropRight 1; let line := if System.Platform.isWindows && line.back == '\x0d' then line.dropRight 1 else line; linesAux $ lines.push line else pure $ lines.push line def lines (fname : String) : m (Array String) := do h ← Handle.mk fname Mode.read false; linesAux h #[] namespace Stream def putStrLn (strm : FS.Stream) (s : String) : m Unit := liftIO (strm.putStr s) *> liftIO (strm.putStr "\n") end Stream end FS section variables {m : Type → Type} [Monad m] [MonadIO m] def getStdin : m FS.Stream := liftIO Prim.getStdin def getStdout : m FS.Stream := liftIO Prim.getStdout def getStderr : m FS.Stream := liftIO Prim.getStderr /-- Replaces the stdin stream of the current thread and returns its previous value. -/ def setStdin : FS.Stream → m FS.Stream := liftIO ∘ Prim.setStdin /-- Replaces the stdout stream of the current thread and returns its previous value. -/ def setStdout : FS.Stream → m FS.Stream := liftIO ∘ Prim.setStdout /-- Replaces the stderr stream of the current thread and returns its previous value. -/ def setStderr : FS.Stream → m FS.Stream := liftIO ∘ Prim.setStderr def withStdin [MonadFinally m] {α} (h : FS.Stream) (x : m α) : m α := do prev ← setStdin h; finally x (discard $ setStdin prev) def withStdout [MonadFinally m] {α} (h : FS.Stream) (x : m α) : m α := do prev ← setStdout h; finally x (discard $ setStdout prev) def withStderr [MonadFinally m] {α} (h : FS.Stream) (x : m α) : m α := do prev ← setStderr h; finally x (discard $ setStderr prev) def print {α} [HasToString α] (s : α) : m Unit := do out ← getStdout; liftIO $ out.putStr $ toString s def println {α} [HasToString α] (s : α) : m Unit := print s *> print "\n" @[export lean_io_println] private def printlnAux (s : String) : IO Unit := println s def eprint {α} [HasToString α] (s : α) : m Unit := do out ← getStderr; liftIO $ out.putStr $ toString s def eprintln {α} [HasToString α] (s : α) : m Unit := eprint s *> eprint "\n" def getEnv : String → m (Option String) := liftIO ∘ Prim.getEnv def realPath : String → m String := liftIO ∘ Prim.realPath def isDir : String → m Bool := liftIO ∘ Prim.isDir def fileExists : String → m Bool := liftIO ∘ Prim.fileExists def appPath : m String := liftIO Prim.appPath def appDir : m String := do p ← appPath; realPath (System.FilePath.dirName p) def currentDir : m String := liftIO Prim.currentDir end namespace Process inductive Stdio | piped | inherit | null def Stdio.toHandleType : Stdio → Type | Stdio.piped => FS.Handle | Stdio.inherit => Unit | Stdio.null => Unit structure StdioConfig := /- Configuration for the process' stdin handle. -/ (stdin := Stdio.inherit) /- Configuration for the process' stdout handle. -/ (stdout := Stdio.inherit) /- Configuration for the process' stderr handle. -/ (stderr := Stdio.inherit) structure SpawnArgs extends StdioConfig := /- Command name. -/ (cmd : String) /- Arguments for the process -/ (args : Array String := #[]) /- Working directory for the process. Inherit from current process if `none`. -/ (cwd : Option String := none) /- Add or remove environment variables for the process. -/ (env : Array (String × Option String) := #[]) -- TODO(Sebastian): constructor must be private structure Child (cfg : StdioConfig) := (stdin : cfg.stdin.toHandleType) (stdout : cfg.stdout.toHandleType) (stderr : cfg.stderr.toHandleType) @[extern "lean_io_process_spawn"] constant spawn (args : SpawnArgs) : IO (Child args.toStdioConfig) := arbitrary _ @[extern "lean_io_process_child_wait"] constant Child.wait {cfg : @& StdioConfig} : @& Child cfg → IO UInt32 := arbitrary _ structure Output := (exitCode : UInt32) (stdout : String) (stderr : String) /-- Run process to completion and caputre output. -/ def output (args : SpawnArgs) : IO Output := do child ← spawn { args with stdout := Stdio.piped, stderr := Stdio.piped }; -- BUG: this will block indefinitely if the process fills the stderr pipe stdout ← child.stdout.readToEnd; stderr ← child.stderr.readToEnd; exitCode ← child.wait; pure { exitCode := exitCode, stdout := stdout, stderr := stderr } /-- Run process to completion and return stdout on success. -/ def run (args : SpawnArgs) : IO String := do out ← output args; when (out.exitCode != 0) $ throw $ IO.userError $ "process '" ++ args.cmd ++ "' exited with code " ++ toString out.exitCode; pure out.stdout end Process structure AccessRight := (read write execution : Bool := false) def AccessRight.flags (acc : AccessRight) : UInt32 := let r : UInt32 := if acc.read then 0x4 else 0; let w : UInt32 := if acc.write then 0x2 else 0; let x : UInt32 := if acc.execution then 0x1 else 0; r.lor $ w.lor x structure FileRight := (user group other : AccessRight := { }) def FileRight.flags (acc : FileRight) : UInt32 := let u : UInt32 := acc.user.flags.shiftLeft 6; let g : UInt32 := acc.group.flags.shiftLeft 3; let o : UInt32 := acc.other.flags; u.lor $ g.lor o @[extern "lean_chmod"] constant Prim.setAccessRights (filename : @& String) (mode : UInt32) : IO Unit := arbitrary _ def setAccessRights (filename : String) (mode : FileRight) : IO Unit := Prim.setAccessRights filename mode.flags /- References -/ abbrev Ref (α : Type) := ST.Ref IO.RealWorld α instance st2eio {ε} : MonadLift (ST IO.RealWorld) (EIO ε) := ⟨fun α x s => match x s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex _ => Empty.rec _ ex⟩ def mkRef {α : Type} {m : Type → Type} [Monad m] [MonadLiftT (ST IO.RealWorld) m] (a : α) : m (IO.Ref α) := ST.mkRef a namespace FS namespace Stream @[export lean_stream_of_handle] def ofHandle (h : Handle) : Stream := { isEof := Prim.Handle.isEof h, flush := Prim.Handle.flush h, read := Prim.Handle.read h, write := Prim.Handle.write h, getLine := Prim.Handle.getLine h, putStr := Prim.Handle.putStr h, } structure Buffer := (data : ByteArray := ByteArray.empty) (pos : Nat := 0) def ofBuffer (r : Ref Buffer) : Stream := { isEof := do b ← r.get; pure $ b.pos >= b.data.size, flush := pure (), read := fun n => r.modifyGet fun b => let data := b.data.extract b.pos (b.pos + n.toNat); (data, { b with pos := b.pos + data.size }), write := fun data => r.modify fun b => -- set `exact` to `false` so that repeatedly writing to the stream does not impose quadratic run time { b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size }, getLine := r.modifyGet fun b => let pos := match b.data.findIdxAux (fun u => u == 0 || u = '\n'.toNat.toUInt8) b.pos with -- include '\n', but not '\0' | some pos => if b.data.get! pos == 0 then pos else pos + 1 | none => b.data.size; (String.fromUTF8Unchecked $ b.data.extract b.pos pos, { b with pos := pos }), putStr := fun s => r.modify fun b => let data := s.toUTF8; { b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size }, } end Stream /-- Run action with `stdin` emptied and `stdout+stderr` captured into a `String`. -/ def withIsolatedStreams {α : Type} (x : IO α) : IO (String × Except IO.Error α) := do bIn ← mkRef { : Stream.Buffer }; bOut ← mkRef { : Stream.Buffer }; r ← withStdin (Stream.ofBuffer bIn) $ withStdout (Stream.ofBuffer bOut) $ withStderr (Stream.ofBuffer bOut) $ observing x; bOut ← bOut.get; let out := String.fromUTF8Unchecked bOut.data; pure (out, r) end FS end IO universe u namespace Lean /-- Typeclass used for presenting the output of an `#eval` command. -/ class HasEval (α : Type u) := -- We default `hideUnit` to `true`, but set it to `false` in the direct call from `#eval` -- so that `()` output is hidden in chained instances such as for some `m Unit`. (eval : α → forall (hideUnit : optParam Bool true), IO Unit) instance HasRepr.hasEval {α : Type u} [HasRepr α] : HasEval α := ⟨fun a _ => IO.println (repr a)⟩ instance Unit.hasEval : HasEval Unit := ⟨fun u hideUnit => if hideUnit then pure () else IO.println (repr u)⟩ instance IO.HasEval {α : Type} [HasEval α] : HasEval (IO α) := ⟨fun x _ => do a ← x; HasEval.eval a⟩ def runEval {α : Type u} [HasEval α] (a : α) : IO (String × Except IO.Error Unit) := IO.FS.withIsolatedStreams (HasEval.eval a false) end Lean
0d36ac79576a6f345491ac7e33c61758f66e123f
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/order/filter/ennreal.lean
744fc1fe6a4078da4b750e445f4db29420d38c5b
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,898
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 data.real.ennreal import order.filter.countable_Inter import order.liminf_limsup /-! # Order properties of extended non-negative reals This file compiles filter-related results about `ennreal` (see data/real/ennreal.lean). -/ open filter open_locale filter namespace ennreal variables {α : Type*} {f : filter α} lemma eventually_le_limsup [countable_Inter_filter f] (u : α → ennreal) : ∀ᶠ y in f, u y ≤ f.limsup u := begin by_cases hx_top : f.limsup u = ⊤, { simp_rw hx_top, exact eventually_of_forall (λ a, le_top), }, have h_forall_le : ∀ᶠ y in f, ∀ n : ℕ, u y < f.limsup u + (1:ennreal)/n, { rw eventually_countable_forall, refine λ n, eventually_lt_of_limsup_lt _, nth_rewrite 0 ←add_zero (f.limsup u), exact (add_lt_add_iff_left (lt_top_iff_ne_top.mpr hx_top)).mpr (by simp), }, refine h_forall_le.mono (λ y hy, le_of_forall_pos_le_add (λ r hr_pos hx_top, _)), have hr_ne_zero : (r : ennreal) ≠ 0, { rw [ne.def, coe_eq_zero], exact (ne_of_lt hr_pos).symm, }, cases (exists_inv_nat_lt hr_ne_zero) with i hi, rw inv_eq_one_div at hi, exact le_trans (le_of_lt (hy i)) (add_le_add_left hi.le (f.limsup u)), end lemma limsup_eq_zero_iff [countable_Inter_filter f] {u : α → ennreal} : f.limsup u = 0 ↔ u =ᶠ[f] 0 := begin split; intro h, { have hu_zero := eventually_le.trans (eventually_le_limsup u) (eventually_of_forall (λ _, le_of_eq h)), exact hu_zero.mono (λ x hx, le_antisymm hx (zero_le _)), }, { rw limsup_congr h, simp_rw [pi.zero_apply, ←ennreal.bot_eq_zero, limsup_const_bot] }, end lemma limsup_const_mul_of_ne_top {u : α → ennreal} {a : ennreal} (ha_top : a ≠ ⊤) : f.limsup (λ (x : α), a * (u x)) = a * f.limsup u := begin by_cases ha_zero : a = 0, { simp_rw [ha_zero, zero_mul, ←ennreal.bot_eq_zero], exact limsup_const_bot, }, let g := λ x : ennreal, a * x, have hg_bij : function.bijective g, from function.bijective_iff_has_inverse.mpr ⟨(λ x, a⁻¹ * x), ⟨λ x, by simp [←mul_assoc, inv_mul_cancel ha_zero ha_top], λ x, by simp [g, ←mul_assoc, mul_inv_cancel ha_zero ha_top]⟩⟩, have hg_mono : strict_mono g, from strict_mono_of_monotone_of_injective (λ _ _ _, by rwa mul_le_mul_left ha_zero ha_top) hg_bij.1, let g_iso := strict_mono.order_iso_of_surjective g hg_mono hg_bij.2, refine (order_iso.limsup_apply g_iso _ _ _ _).symm, all_goals { by is_bounded_default }, end lemma limsup_const_mul [countable_Inter_filter f] {u : α → ennreal} {a : ennreal} : f.limsup (λ (x : α), a * (u x)) = a * f.limsup u := begin by_cases ha_top : a ≠ ⊤, { exact limsup_const_mul_of_ne_top ha_top, }, push_neg at ha_top, by_cases hu : u =ᶠ[f] 0, { have hau : (λ x, a * (u x)) =ᶠ[f] 0, { refine hu.mono (λ x hx, _), rw pi.zero_apply at hx, simp [hx], }, simp only [limsup_congr hu, limsup_congr hau, pi.zero_apply, ← bot_eq_zero, limsup_const_bot], simp, }, { simp_rw [ha_top, top_mul], have hu_mul : ∃ᶠ (x : α) in f, ⊤ ≤ ite (u x = 0) (0 : ennreal) ⊤, { rw [eventually_eq, not_eventually] at hu, refine hu.mono (λ x hx, _), rw pi.zero_apply at hx, simp [hx], }, have h_top_le : f.limsup (λ (x : α), ite (u x = 0) (0 : ennreal) ⊤) = ⊤, from eq_top_iff.mpr (le_limsup_of_frequently_le hu_mul), have hfu : f.limsup u ≠ 0, from mt limsup_eq_zero_iff.1 hu, simp only [h_top_le, hfu, if_false], }, end lemma limsup_add_le [countable_Inter_filter f] (u v : α → ennreal) : f.limsup (u + v) ≤ f.limsup u + f.limsup v := Inf_le ((eventually_le_limsup u).mp ((eventually_le_limsup v).mono (λ _ hxg hxf, add_le_add hxf hxg))) end ennreal
a3c664436355ae558afe192bd06994967ce86a07
00de0c30dd1b090ed139f65c82ea6deb48c3f4c2
/src/order/basic.lean
fb58dae95efea1f8fa8cd7d62122cd928e1941b7
[ "Apache-2.0" ]
permissive
paulvanwamelen/mathlib
4b9c5c19eec71b475f3dd515cd8785f1c8515f26
79e296bdc9f83b9447dc1b81730d36f63a99f72d
refs/heads/master
1,667,766,172,625
1,590,239,595,000
1,590,239,595,000
266,392,625
0
0
Apache-2.0
1,590,257,277,000
1,590,257,277,000
null
UTF-8
Lean
false
false
34,035
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import data.set.basic open function /-! # Basic definitions about `≤` and `<` ## Definitions ### Predicates on functions - `monotone f`: a function between two types equipped with `≤` is monotone if `a ≤ b` implies `f a ≤ f b`. - `strict_mono f` : a function between two types equipped with `<` is strictly monotone if `a < b` implies `f a < f b`. - `order_dual α` : a type tag reversing the meaning of all inequalities. ### Transfering orders - `order.preimage`, `preorder.lift`: transfer a (pre)order on `β` to an order on `α` using a function `f : α → β`. - `partial_order.lift`, `linear_order.lift`, `decidable_linear_order.lift`: transfer a partial (resp., linear, decidable linear) order on `β` to a partial (resp., linear, decidable linear) order on `α` using an injective function `f`. ### Extra classes - `no_top_order`, `no_bot_order`: an order without a maximal/minimal element. - `densely_ordered`: an order with no gaps, i.e. for any two elements `a<b` there exists `c`, `a<c<b`. ## Main theorems - `monotone_of_monotone_nat`: if `f : ℕ → α` and `f n ≤ f (n + 1)` for all `n`, then `f` is monotone; - `strict_mono.nat`: if `f : ℕ → α` and `f n < f (n + 1)` for all `n`, then f is strictly monotone. ## TODO - expand module docs - automatic construction of dual definitions / theorems ## Tags preorder, order, partial order, linear order, monotone, strictly monotone -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} @[nolint ge_or_gt] -- see Note [nolint_ge] theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b := λ h, h ▸ le_refl a theorem is_refl.swap (r) [is_refl α r] : is_refl α (swap r) := ⟨refl_of r⟩ theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨irrefl_of r⟩ theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) := ⟨λ a b c h₁ h₂, trans_of r h₂ h₁⟩ theorem is_antisymm.swap (r) [is_antisymm α r] : is_antisymm α (swap r) := ⟨λ a b h₁ h₂, antisymm h₂ h₁⟩ theorem is_asymm.swap (r) [is_asymm α r] : is_asymm α (swap r) := ⟨λ a b h₁ h₂, asymm_of r h₂ h₁⟩ theorem is_total.swap (r) [is_total α r] : is_total α (swap r) := ⟨λ a b, (total_of r a b).swap⟩ theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) := ⟨λ a b, by simpa [swap, or.comm, or.left_comm] using trichotomous_of r a b⟩ theorem is_preorder.swap (r) [is_preorder α r] : is_preorder α (swap r) := {..@is_refl.swap α r _, ..@is_trans.swap α r _} theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) := {..@is_irrefl.swap α r _, ..@is_trans.swap α r _} theorem is_partial_order.swap (r) [is_partial_order α r] : is_partial_order α (swap r) := {..@is_preorder.swap α r _, ..@is_antisymm.swap α r _} theorem is_total_preorder.swap (r) [is_total_preorder α r] : is_total_preorder α (swap r) := {..@is_preorder.swap α r _, ..@is_total.swap α r _} theorem is_linear_order.swap (r) [is_linear_order α r] : is_linear_order α (swap r) := {..@is_partial_order.swap α r _, ..@is_total.swap α r _} lemma antisymm_of_asymm (r) [is_asymm α r] : is_antisymm α r := ⟨λ x y h₁ h₂, (asymm h₁ h₂).elim⟩ /- Convert algebraic structure style to explicit relation style typeclasses -/ instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] instance [preorder α] : is_refl α (≥) := is_refl.swap _ instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] instance [preorder α] : is_trans α (≥) := is_trans.swap _ instance [preorder α] : is_preorder α (≤) := {} @[nolint ge_or_gt] -- see Note [nolint_ge] instance [preorder α] : is_preorder α (≥) := {} instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] instance [preorder α] : is_irrefl α (>) := is_irrefl.swap _ instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] instance [preorder α] : is_trans α (>) := is_trans.swap _ instance [preorder α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] instance [preorder α] : is_asymm α (>) := is_asymm.swap _ instance [preorder α] : is_antisymm α (<) := antisymm_of_asymm _ @[nolint ge_or_gt] -- see Note [nolint_ge] instance [preorder α] : is_antisymm α (>) := antisymm_of_asymm _ instance [preorder α] : is_strict_order α (<) := {} @[nolint ge_or_gt] -- see Note [nolint_ge] instance [preorder α] : is_strict_order α (>) := {} instance preorder.is_total_preorder [preorder α] [is_total α (≤)] : is_total_preorder α (≤) := {} instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] instance [partial_order α] : is_antisymm α (≥) := is_antisymm.swap _ instance [partial_order α] : is_partial_order α (≤) := {} @[nolint ge_or_gt] -- see Note [nolint_ge] instance [partial_order α] : is_partial_order α (≥) := {} instance [linear_order α] : is_total α (≤) := ⟨le_total⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] instance [linear_order α] : is_total α (≥) := is_total.swap _ instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := by apply_instance @[nolint ge_or_gt] -- see Note [nolint_ge] instance [linear_order α] : is_total_preorder α (≥) := {} instance [linear_order α] : is_linear_order α (≤) := {} @[nolint ge_or_gt] -- see Note [nolint_ge] instance [linear_order α] : is_linear_order α (≥) := {} instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] instance [linear_order α] : is_trichotomous α (>) := is_trichotomous.swap _ theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin resetI, cases A, cases B, congr, { funext x y, exact propext (H x y) }, { funext x y, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] }, end theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := preorder.ext H; cases A; cases B; injection this; congr' theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := partial_order.ext H; cases A; cases B; injection this; congr' /-- Given an order `R` on `β` and a function `f : α → β`, the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique order on `α` making `f` an order embedding (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage /-- The preimage of a decidable order is decidable. -/ instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] : decidable_rel (f ⁻¹'o s) := λ x y, H _ _ section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b protected theorem monotone.comp {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) : monotone (g ∘ f) := assume a b h, m_g (m_f h) protected theorem monotone.iterate {f : α → α} (hf : monotone f) (n : ℕ) : monotone (f^[n]) := nat.rec_on n monotone_id (λ n ihn, ihn.comp hf) lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) : monotone f | n m h := begin induction h, { refl }, { transitivity, assumption, exact hf _ } end lemma reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f) {x x' : α} (h : f x < f x') : x < x' := by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' } end monotone /-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/ def strict_mono [has_lt α] [has_lt β] (f : α → β) : Prop := ∀ ⦃a b⦄, a < b → f a < f b lemma strict_mono_id [has_lt α] : strict_mono (id : α → α) := λ a b, id namespace strict_mono open ordering function lemma comp [has_lt α] [has_lt β] [has_lt γ] {g : β → γ} {f : α → β} (hg : strict_mono g) (hf : strict_mono f) : strict_mono (g ∘ f) := λ a b h, hg (hf h) protected theorem iterate [has_lt α] {f : α → α} (hf : strict_mono f) (n : ℕ) : strict_mono (f^[n]) := nat.rec_on n strict_mono_id (λ n ihn, ihn.comp hf) section variables [linear_order α] [preorder β] {f : α → β} lemma lt_iff_lt (H : strict_mono f) {a b} : f a < f b ↔ a < b := ⟨λ h, ((lt_trichotomy b a) .resolve_left $ λ h', lt_asymm h $ H h') .resolve_left $ λ e, ne_of_gt h $ congr_arg _ e, @H _ _⟩ lemma injective (H : strict_mono f) : injective f | a b e := ((lt_trichotomy a b) .resolve_left $ λ h, ne_of_lt (H h) e) .resolve_right $ λ h, ne_of_gt (H h) e theorem compares (H : strict_mono f) {a b} : ∀ {o}, compares o (f a) (f b) ↔ compares o a b | lt := H.lt_iff_lt | eq := ⟨λ h, H.injective h, congr_arg _⟩ | gt := H.lt_iff_lt lemma le_iff_le (H : strict_mono f) {a b} : f a ≤ f b ↔ a ≤ b := ⟨λ h, le_of_not_gt $ λ h', not_le_of_lt (H h') h, λ h, (lt_or_eq_of_le h).elim (λ h', le_of_lt (H h')) (λ h', h' ▸ le_refl _)⟩ end protected lemma nat {β} [preorder β] {f : ℕ → β} (h : ∀n, f n < f (n+1)) : strict_mono f := by { intros n m hnm, induction hnm with m' hnm' ih, apply h, exact lt.trans ih (h _) } -- `preorder α` isn't strong enough: if the preorder on α is an equivalence relation, -- then `strict_mono f` is vacuously true. lemma monotone [partial_order α] [preorder β] {f : α → β} (H : strict_mono f) : monotone f := λ a b h, (lt_or_eq_of_le h).rec (le_of_lt ∘ (@H _ _)) (by rintro rfl; refl) end strict_mono section open function variables [partial_order α] [partial_order β] {f : α → β} lemma strict_mono_of_monotone_of_injective (h₁ : monotone f) (h₂ : injective f) : strict_mono f := λ a b h, begin rw lt_iff_le_and_ne at ⊢ h, exact ⟨h₁ h.1, λ e, h.2 (h₂ e)⟩ end end /-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/ def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [h : nonempty α] : nonempty (order_dual α) := h instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩ -- `dual_le` and `dual_lt` should not be simp lemmas: -- they cause a loop since `α` and `order_dual α` are definitionally equal lemma dual_le [has_le α] {a b : α} : @has_le.le (order_dual α) _ a b ↔ @has_le.le α _ b a := iff.rfl lemma dual_lt [has_lt α] {a b : α} : @has_lt.lt (order_dual α) _ a b ↔ @has_lt.lt α _ b a := iff.rfl instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, le_trans hbc hab, lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, .. order_dual.has_le α, .. order_dual.has_lt α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, .. order_dual.partial_order α } instance (α : Type*) [decidable_linear_order α] : decidable_linear_order (order_dual α) := { decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance, decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance, .. order_dual.linear_order α } instance : Π [inhabited α], inhabited (order_dual α) := id end order_dual /- order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] theorem monotone.order_dual {f : α → γ} (hf : monotone f) : @monotone (order_dual α) (order_dual γ) _ _ f := λ x y hxy, hf hxy theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone theorem strict_mono.order_dual [has_lt α] [has_lt β] {f : α → β} (hf : strict_mono f) : @strict_mono (order_dual α) (order_dual β) _ _ f := λ x y hxy, hf hxy /-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`. -/ def preorder.lift {α β} (f : α → β) (i : preorder β) : preorder α := by exactI { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } /-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective function `f : α → β`. -/ def partial_order.lift {α β} (f : α → β) (inj : injective f) (i : partial_order β) : partial_order α := by exactI { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f (by apply_instance) } /-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective function `f : α → β`. -/ def linear_order.lift {α β} (f : α → β) (inj : injective f) (i : linear_order β) : linear_order α := by exactI { le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj (by apply_instance) } /-- Transfer a `decidable_linear_order` on `β` to a `decidable_linear_order` on `α` using an injective function `f : α → β`. -/ def decidable_linear_order.lift {α β} (f : α → β) (inj : injective f) (i : decidable_linear_order β) : decidable_linear_order α := by exactI { decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance, decidable_lt := λ x y, show decidable (f x < f y), by apply_instance, decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩, .. linear_order.lift f inj (by apply_instance) } instance subtype.preorder {α} [i : preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val i instance subtype.partial_order {α} [i : partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val subtype.val_injective i instance subtype.linear_order {α} [i : linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val subtype.val_injective i instance subtype.decidable_linear_order {α} [i : decidable_linear_order α] (p : α → Prop) : decidable_linear_order (subtype p) := decidable_linear_order.lift subtype.val subtype.val_injective i instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } /-- The pointwise partial order on a product. (The lexicographic ordering is defined in order/lexicographic.lean, and the instances are available via the type synonym `lex α β = α × β`.) -/ instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb), .. prod.preorder α β } /-! ### Additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot instance order_dual.no_top_order (α : Type u) [preorder α] [no_bot_order α] : no_top_order (order_dual α) := ⟨λ a, @no_bot α _ _ a⟩ instance order_dual.no_bot_order (α : Type u) [preorder α] [no_top_order α] : no_bot_order (order_dual α) := ⟨λ a, @no_top α _ _ a⟩ /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense instance order_dual.densely_ordered (α : Type u) [preorder α] [densely_ordered α] : densely_ordered (order_dual α) := ⟨λ a₁ a₂ ha, (@dense α _ _ _ _ ha).imp $ λ a, and.symm⟩ lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃<a₁, a₂ ≥ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a ≥ a₂) ∧ (∀a<a₂, a ≤ a₁)) := classical.or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ lemma trans_trichotomous_left [is_trans α r] [is_trichotomous α r] {a b c : α} : ¬r b a → r b c → r a c := begin intros h₁ h₂, rcases trichotomous_of r a b with h₃|h₃|h₃, exact trans h₃ h₂, rw h₃, exact h₂, exfalso, exact h₁ h₃ end lemma trans_trichotomous_right [is_trans α r] [is_trichotomous α r] {a b c : α} : r a b → ¬r c b → r a c := begin intros h₁ h₂, rcases trichotomous_of r b c with h₃|h₃|h₃, exact trans h₁ h₃, rw ←h₃, exact h₁, exfalso, exact h₂ h₃ end variables {s : β → β → Prop} {t : γ → γ → Prop} theorem is_irrefl_of_is_asymm [is_asymm α r] : is_irrefl α r := ⟨λ a h, asymm h h⟩ /-- Construct a partial order from a `is_strict_order` relation -/ def partial_order_of_SO (r) [is_strict_order α r] : partial_order α := { le := λ x y, x = y ∨ r x y, lt := r, le_refl := λ x, or.inl rfl, le_trans := λ x y z h₁ h₂, match y, z, h₁, h₂ with | _, _, or.inl rfl, h₂ := h₂ | _, _, h₁, or.inl rfl := h₁ | _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂) end, le_antisymm := λ x y h₁ h₂, match y, h₁, h₂ with | _, or.inl rfl, h₂ := rfl | _, h₁, or.inl rfl := rfl | _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim end, lt_iff_le_not_le := λ x y, ⟨λ h, ⟨or.inr h, not_or (λ e, by rw e at h; exact irrefl _ h) (asymm h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ } section prio set_option default_priority 100 -- see Note [default priority] /-- This is basically the same as `is_strict_total_order`, but that definition is in Type (probably by mistake) and also has redundant assumptions. -/ @[algebra] class is_strict_total_order' (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_order α lt : Prop. end prio /-- Construct a linear order from a `is_strict_total_order'` relation -/ def linear_order_of_STO' (r) [is_strict_total_order' α r] : linear_order α := { le_total := λ x y, match y, trichotomous_of r x y with | y, or.inl h := or.inl (or.inr h) | _, or.inr (or.inl rfl) := or.inl (or.inl rfl) | _, or.inr (or.inr h) := or.inr (or.inr h) end, ..partial_order_of_SO r } /-- Construct a decidable linear order from a `is_strict_total_order'` relation -/ def decidable_linear_order_of_STO' (r) [is_strict_total_order' α r] [decidable_rel r] : decidable_linear_order α := by letI LO := linear_order_of_STO' r; exact { decidable_le := λ x y, decidable_of_iff (¬ r y x) (@not_lt _ _ y x), ..LO } /-- Any `linear_order` is a noncomputable `decidable_linear_order`. This is not marked as an instance to avoid a loop. -/ noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α := { decidable_le := classical.dec_rel _, ..LO } theorem is_strict_total_order'.swap (r) [is_strict_total_order' α r] : is_strict_total_order' α (swap r) := {..is_trichotomous.swap r, ..is_strict_order.swap r} instance [linear_order α] : is_strict_total_order' α (<) := {} /-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`. This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on the constructive reals, and is also known as negative transitivity, since the contrapositive asserts transitivity of the relation `¬ a < b`. -/ @[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop := (conn : ∀ a b c, lt a c → lt a b ∨ lt b c) theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r] {a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c := mt (is_order_connected.conn a b c) $ by simp [h₁, h₂] theorem is_strict_weak_order_of_is_order_connected [is_asymm α r] [is_order_connected α r] : is_strict_weak_order α r := { trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂), incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩, ⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩, ..@is_irrefl_of_is_asymm α r _ } @[priority 100] -- see Note [lower instance priority] instance is_order_connected_of_is_strict_total_order' [is_strict_total_order' α r] : is_order_connected α r := ⟨λ a b c h, (trichotomous _ _).imp_right (λ o, o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩ @[priority 100] -- see Note [lower instance priority] instance is_strict_total_order_of_is_strict_total_order' [is_strict_total_order' α r] : is_strict_total_order α r := {..is_strict_weak_order_of_is_order_connected} instance [linear_order α] : is_strict_total_order α (<) := by apply_instance instance [linear_order α] : is_order_connected α (<) := by apply_instance instance [linear_order α] : is_incomp_trans α (<) := by apply_instance instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance /-- An extensional relation is one in which an element is determined by its set of predecessors. It is named for the `x ∈ y` relation in set theory, whose extensionality is one of the first axioms of ZFC. -/ @[algebra] class is_extensional (α : Type u) (r : α → α → Prop) : Prop := (ext : ∀ a b, (∀ x, r x a ↔ r x b) → a = b) @[priority 100] -- see Note [lower instance priority] instance is_extensional_of_is_strict_total_order' [is_strict_total_order' α r] : is_extensional α r := ⟨λ a b H, ((@trichotomous _ r _ a b) .resolve_left $ mt (H _).2 (irrefl a)) .resolve_right $ mt (H _).1 (irrefl b)⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- A well order is a well-founded linear order. -/ @[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_strict_total_order' α r : Prop := (wf : well_founded r) end prio @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_strict_total_order {α} (r : α → α → Prop) [is_well_order α r] : is_strict_total_order α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_extensional {α} (r : α → α → Prop) [is_well_order α r] : is_extensional α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_trichotomous {α} (r : α → α → Prop) [is_well_order α r] : is_trichotomous α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_trans {α} (r : α → α → Prop) [is_well_order α r] : is_trans α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_irrefl {α} (r : α → α → Prop) [is_well_order α r] : is_irrefl α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_asymm {α} (r : α → α → Prop) [is_well_order α r] : is_asymm α r := by apply_instance /-- Construct a decidable linear order from a well-founded linear order. -/ noncomputable def decidable_linear_order_of_is_well_order (r : α → α → Prop) [is_well_order α r] : decidable_linear_order α := by { haveI := linear_order_of_STO' r, exact classical.DLO α } instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation := { trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim _ _, irrefl := λ a, id, trans := λ a b c, false.elim, wf := ⟨λ a, ⟨_, λ y, false.elim⟩⟩ } instance nat.lt.is_well_order : is_well_order ℕ (<) := ⟨nat.lt_wf⟩ instance sum.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) := { trichotomous := λ a b, by cases a; cases b; simp; apply trichotomous, irrefl := λ a, by cases a; simp; apply irrefl, trans := λ a b c, by cases a; cases b; simp; cases c; simp; apply trans, wf := sum.lex_wf is_well_order.wf is_well_order.wf } instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) := { trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, match @trichotomous _ r _ a₁ b₁ with | or.inl h₁ := or.inl $ prod.lex.left _ _ h₁ | or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ h₁ | or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with | or.inl h := or.inl $ prod.lex.right _ h | or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ h | or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl end end, irrefl := λ ⟨a₁, a₂⟩ h, by cases h with _ _ _ _ h _ _ _ h; [exact irrefl _ h, exact irrefl _ h], trans := λ a b c h₁ h₂, begin cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab; cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc, { exact prod.lex.left _ _ (trans ab bc) }, { exact prod.lex.left _ _ ab }, { exact prod.lex.left _ _ bc }, { exact prod.lex.right _ (trans ab bc) } end, wf := prod.lex_wf is_well_order.wf is_well_order.wf } /-- An unbounded or cofinal set -/ def unbounded (r : α → α → Prop) (s : set α) : Prop := ∀ a, ∃ b ∈ s, ¬ r b a /-- A bounded or final set -/ def bounded (r : α → α → Prop) (s : set α) : Prop := ∃a, ∀ b ∈ s, r b a @[simp] lemma not_bounded_iff {r : α → α → Prop} (s : set α) : ¬bounded r s ↔ unbounded r s := begin classical, simp only [bounded, unbounded, not_forall, not_exists, exists_prop, not_and, not_not] end @[simp] lemma not_unbounded_iff {r : α → α → Prop} (s : set α) : ¬unbounded r s ↔ bounded r s := by { classical, rw [not_iff_comm, not_bounded_iff] } namespace well_founded /-- If `r` is a well-founded relation, then any nonempty set has a minimum element with respect to `r`. -/ theorem has_min {α} {r : α → α → Prop} (H : well_founded r) (s : set α) : s.nonempty → ∃ a ∈ s, ∀ x ∈ s, ¬ r x a | ⟨a, ha⟩ := (acc.rec_on (H.apply a) $ λ x _ IH, classical.not_imp_not.1 $ λ hne hx, hne $ ⟨x, hx, λ y hy hyx, hne $ IH y hyx hy⟩) ha /-- The minimum element of a nonempty set in a well-founded order -/ noncomputable def min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p.nonempty) : α := classical.some (H.has_min p h) theorem min_mem {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p.nonempty) : H.min p h ∈ p := let ⟨h, _⟩ := classical.some_spec (H.has_min p h) in h theorem not_lt_min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p.nonempty) {x} (xp : x ∈ p) : ¬ r x (H.min p h) := let ⟨_, h'⟩ := classical.some_spec (H.has_min p h) in h' _ xp open set /-- The supremum of a bounded, well-founded order -/ protected noncomputable def sup {α} {r : α → α → Prop} (wf : well_founded r) (s : set α) (h : bounded r s) : α := wf.min { x | ∀a ∈ s, r a x } h protected lemma lt_sup {α} {r : α → α → Prop} (wf : well_founded r) {s : set α} (h : bounded r s) {x} (hx : x ∈ s) : r x (wf.sup s h) := min_mem wf { x | ∀a ∈ s, r a x } h x hx section open_locale classical /-- The successor of an element `x` in a well-founded order is the minimum element `y` such that `x < y` if one exists. Otherwise it is `x` itself. -/ protected noncomputable def succ {α} {r : α → α → Prop} (wf : well_founded r) (x : α) : α := if h : ∃y, r x y then wf.min { y | r x y } h else x protected lemma lt_succ {α} {r : α → α → Prop} (wf : well_founded r) {x : α} (h : ∃y, r x y) : r x (wf.succ x) := by { rw [well_founded.succ, dif_pos h], apply min_mem } end protected lemma lt_succ_iff {α} {r : α → α → Prop} [wo : is_well_order α r] {x : α} (h : ∃y, r x y) (y : α) : r y (wo.wf.succ x) ↔ r y x ∨ y = x := begin split, { intro h', have : ¬r x y, { intro hy, rw [well_founded.succ, dif_pos] at h', exact wo.wf.not_lt_min _ h hy h' }, rcases trichotomous_of r x y with hy | hy | hy, exfalso, exact this hy, right, exact hy.symm, left, exact hy }, rintro (hy | rfl), exact trans hy (wo.wf.lt_succ h), exact wo.wf.lt_succ h end end well_founded variable (r) local infix ` ≼ ` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, x ≼ z ∧ y ≼ z theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) := by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl) theorem directed_on_image {s} {f : β → α} : directed_on r (f '' s) ↔ directed_on (f ⁻¹'o r) s := by simp only [directed_on, set.ball_image_iff, set.bex_image_iff, order.preimage] theorem directed_on.mono {s : set α} (h : directed_on r s) {r' : α → α → Prop} (H : ∀ {a b}, r a b → r' a b) : directed_on r' s := λ x hx y hy, let ⟨z, zs, xz, yz⟩ := h x hx y hy in ⟨z, zs, H xz, H yz⟩ theorem directed_comp {ι} (f : ι → β) (g : β → α) : directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl variable {r} theorem directed.mono {s : α → α → Prop} {ι} {f : ι → α} (H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f := λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩ theorem directed.mono_comp {ι} {rb : β → β → Prop} {g : α → β} {f : ι → α} (hg : ∀ ⦃x y⦄, x ≼ y → rb (g x) (g y)) (hf : directed r f) : directed rb (g ∘ f) := (directed_comp rb f g).2 $ hf.mono hg section prio set_option default_priority 100 -- see Note [default priority] /-- A `preorder` is a `directed_order` if for any two elements `i`, `j` there is an element `k` such that `i ≤ k` and `j ≤ k`. -/ class directed_order (α : Type u) extends preorder α := (directed : ∀ i j : α, ∃ k, i ≤ k ∧ j ≤ k) end prio
7eb422aaadfac18be92a983406d2c8744db89885
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/inj1.lean
91ebec82a93dc9560e56ee558d64f5f127fff5a0
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
918
lean
theorem test1 {α} (a b : α) (as bs : List α) (h : a::as = b::bs) : a = b := by { injection h; assumption; } theorem test2 {α} (a b : α) (as bs : List α) (h : a::as = b::bs) : a = b := by { injection h with h1 h2; exact h1 } theorem test3 {α} (a b : α) (as bs : List α) (h : (x : List α) → (y : List α) → x = y) : as = bs := have a::as = b::bs from h (a::as) (b::bs); by { injection this with h1 h2; exact h2 } theorem test4 {α} (a b : α) (as bs : List α) (h : (x : List α) → (y : List α) → x = y) : as = bs := by { injection h (a::as) (b::bs) with h1 h2; exact h2 } theorem test5 {α} (a : α) (as : List α) (h : a::as = []) : 0 > 1 := by { injection h } theorem test6 (n : Nat) (h : n+1 = 0) : 0 > 1 := by { injection h } theorem test7 (n m k : Nat) (h : n + 1 = m + 1) : m = k → n = k := by { injection h with h₁; subst h₁; intro h₂; exact h₂ }
7a958c3bc36bdf67ca78c64754ea5b8899f2d25d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/category/pairwise.lean
c8e946677df267db646c3ca290a8081fda3a17e3
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,404
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import order.complete_lattice import category_theory.category.preorder import category_theory.limits.is_limit /-! # The category of "pairwise intersections". > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given `ι : Type v`, we build the diagram category `pairwise ι` with objects `single i` and `pair i j`, for `i j : ι`, whose only non-identity morphisms are `left : pair i j ⟶ single i` and `right : pair i j ⟶ single j`. We use this later in describing (one formulation of) the sheaf condition. Given any function `U : ι → α`, where `α` is some complete lattice (e.g. `(opens X)ᵒᵖ`), we produce a functor `pairwise ι ⥤ α` in the obvious way, and show that `supr U` provides a colimit cocone over this functor. -/ noncomputable theory universes v u open category_theory open category_theory.limits namespace category_theory /-- An inductive type representing either a single term of a type `ι`, or a pair of terms. We use this as the objects of a category to describe the sheaf condition. -/ inductive pairwise (ι : Type v) | single : ι → pairwise | pair : ι → ι → pairwise variables {ι : Type v} namespace pairwise instance pairwise_inhabited [inhabited ι] : inhabited (pairwise ι) := ⟨single default⟩ /-- Morphisms in the category `pairwise ι`. The only non-identity morphisms are `left i j : single i ⟶ pair i j` and `right i j : single j ⟶ pair i j`. -/ inductive hom : pairwise ι → pairwise ι → Type v | id_single : Π i, hom (single i) (single i) | id_pair : Π i j, hom (pair i j) (pair i j) | left : Π i j, hom (pair i j) (single i) | right : Π i j, hom (pair i j) (single j) open hom instance hom_inhabited [inhabited ι] : inhabited (hom (single (default : ι)) (single default)) := ⟨id_single default⟩ /-- The identity morphism in `pairwise ι`. -/ def id : Π (o : pairwise ι), hom o o | (single i) := id_single i | (pair i j) := id_pair i j /-- Composition of morphisms in `pairwise ι`. -/ def comp : Π {o₁ o₂ o₃ : pairwise ι} (f : hom o₁ o₂) (g : hom o₂ o₃), hom o₁ o₃ | _ _ _ (id_single i) g := g | _ _ _ (id_pair i j) g := g | _ _ _ (left i j) (id_single _) := left i j | _ _ _ (right i j) (id_single _) := right i j section local attribute [tidy] tactic.case_bash instance : category (pairwise ι) := { hom := hom, id := id, comp := λ X Y Z f g, comp f g, } end variables {α : Type v} (U : ι → α) section variables [semilattice_inf α] /-- Auxiliary definition for `diagram`. -/ @[simp] def diagram_obj : pairwise ι → α | (single i) := U i | (pair i j) := U i ⊓ U j /-- Auxiliary definition for `diagram`. -/ @[simp] def diagram_map : Π {o₁ o₂ : pairwise ι} (f : o₁ ⟶ o₂), diagram_obj U o₁ ⟶ diagram_obj U o₂ | _ _ (id_single i) := 𝟙 _ | _ _ (id_pair i j) := 𝟙 _ | _ _ (left i j) := hom_of_le inf_le_left | _ _ (right i j) := hom_of_le inf_le_right /-- Given a function `U : ι → α` for `[semilattice_inf α]`, we obtain a functor `pairwise ι ⥤ α`, sending `single i` to `U i` and `pair i j` to `U i ⊓ U j`, and the morphisms to the obvious inequalities. -/ @[simps] def diagram : pairwise ι ⥤ α := { obj := diagram_obj U, map := λ X Y f, diagram_map U f, } end section -- `complete_lattice` is not really needed, as we only ever use `inf`, -- but the appropriate structure has not been defined. variables [complete_lattice α] /-- Auxiliary definition for `cocone`. -/ def cocone_ι_app : Π (o : pairwise ι), diagram_obj U o ⟶ supr U | (single i) := hom_of_le (le_supr U i) | (pair i j) := hom_of_le inf_le_left ≫ hom_of_le (le_supr U i) /-- Given a function `U : ι → α` for `[complete_lattice α]`, `supr U` provides a cocone over `diagram U`. -/ @[simps] def cocone : cocone (diagram U) := { X := supr U, ι := { app := cocone_ι_app U, } } /-- Given a function `U : ι → α` for `[complete_lattice α]`, `infi U` provides a limit cone over `diagram U`. -/ def cocone_is_colimit : is_colimit (cocone U) := { desc := λ s, hom_of_le begin apply complete_lattice.Sup_le, rintros _ ⟨j, rfl⟩, exact (s.ι.app (single j)).le end } end end pairwise end category_theory
9b394ce0de842bb3db9bec52a0a4fe26024ce9af
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/rat/floor.lean
b5096eae42c9263ee4a570bedce6aeb7fc225ce2
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,694
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Kappelmann -/ import algebra.order.floor import algebra.euclidean_domain.instances import tactic.field_simp /-! # Floor Function for Rational Numbers ## Summary We define the `floor` function and the `floor_ring` instance on `ℚ`. Some technical lemmas relating `floor` to integer division and modulo arithmetic are derived as well as some simple inequalities. ## Tags rat, rationals, ℚ, floor -/ open int namespace rat variables {α : Type*} [linear_ordered_field α] [floor_ring α] /-- `floor q` is the largest integer `z` such that `z ≤ q` -/ protected def floor : ℚ → ℤ | ⟨n, d, h, c⟩ := n / d protected theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ rat.floor r ↔ (z : ℚ) ≤ r | ⟨n, d, h, c⟩ := begin simp [rat.floor], rw [num_denom'], have h' := int.coe_nat_lt.2 h, conv { to_rhs, rw [coe_int_eq_mk, rat.le_def zero_lt_one h', mul_one] }, exact int.le_div_iff_mul_le h' end instance : floor_ring ℚ := floor_ring.of_floor ℚ rat.floor $ λ a z, rat.le_floor.symm protected lemma floor_def {q : ℚ} : ⌊q⌋ = q.num / q.denom := by { cases q, refl } lemma floor_int_div_nat_eq_div {n : ℤ} {d : ℕ} : ⌊(↑n : ℚ) / (↑d : ℚ)⌋ = n / (↑d : ℤ) := begin rw [rat.floor_def], obtain rfl | hd := @eq_zero_or_pos _ _ d, { simp }, set q := (n : ℚ) / d with q_eq, obtain ⟨c, n_eq_c_mul_num, d_eq_c_mul_denom⟩ : ∃ c, n = c * q.num ∧ (d : ℤ) = c * q.denom, by { rw q_eq, exact_mod_cast @rat.exists_eq_mul_div_num_and_eq_mul_div_denom n d (by exact_mod_cast hd.ne') }, rw [n_eq_c_mul_num, d_eq_c_mul_denom], refine (int.mul_div_mul_of_pos _ _ $ pos_of_mul_pos_left _ $ int.coe_nat_nonneg q.denom).symm, rwa [←d_eq_c_mul_denom, int.coe_nat_pos], end @[simp, norm_cast] lemma floor_cast (x : ℚ) : ⌊(x : α)⌋ = ⌊x⌋ := floor_eq_iff.2 (by exact_mod_cast floor_eq_iff.1 (eq.refl ⌊x⌋)) @[simp, norm_cast] lemma ceil_cast (x : ℚ) : ⌈(x : α)⌉ = ⌈x⌉ := by rw [←neg_inj, ←floor_neg, ←floor_neg, ← rat.cast_neg, rat.floor_cast] @[simp, norm_cast] lemma round_cast (x : ℚ) : round (x : α) = round x := have ((x + 1 / 2 : ℚ) : α) = x + 1 / 2, by simp, by rw [round_eq, round_eq, ← this, floor_cast] @[simp, norm_cast] lemma cast_fract (x : ℚ) : (↑(fract x) : α) = fract x := by simp only [fract, cast_sub, cast_coe_int, floor_cast] end rat lemma int.mod_nat_eq_sub_mul_floor_rat_div {n : ℤ} {d : ℕ} : n % d = n - d * ⌊(n : ℚ) / d⌋ := by rw [(eq_sub_of_add_eq $ int.mod_add_div n d), rat.floor_int_div_nat_eq_div] lemma nat.coprime_sub_mul_floor_rat_div_of_coprime {n d : ℕ} (n_coprime_d : n.coprime d) : ((n : ℤ) - d * ⌊(n : ℚ)/ d⌋).nat_abs.coprime d := begin have : (n : ℤ) % d = n - d * ⌊(n : ℚ)/ d⌋, from int.mod_nat_eq_sub_mul_floor_rat_div, rw ←this, have : d.coprime n, from n_coprime_d.symm, rwa [nat.coprime, nat.gcd_rec] at this end namespace rat lemma num_lt_succ_floor_mul_denom (q : ℚ) : q.num < (⌊q⌋ + 1) * q.denom := begin suffices : (q.num : ℚ) < (⌊q⌋ + 1) * q.denom, by exact_mod_cast this, suffices : (q.num : ℚ) < (q - fract q + 1) * q.denom, by { have : (⌊q⌋ : ℚ) = q - fract q, from (eq_sub_of_add_eq $ floor_add_fract q), rwa this }, suffices : (q.num : ℚ) < q.num + (1 - fract q) * q.denom, by { have : (q - fract q + 1) * q.denom = q.num + (1 - fract q) * q.denom, calc (q - fract q + 1) * q.denom = (q + (1 - fract q)) * q.denom : by ring ... = q * q.denom + (1 - fract q) * q.denom : by rw add_mul ... = q.num + (1 - fract q) * q.denom : by simp, rwa this }, suffices : 0 < (1 - fract q) * q.denom, by { rw ←sub_lt_iff_lt_add', simpa }, have : 0 < 1 - fract q, by { have : fract q < 1, from fract_lt_one q, have : 0 + fract q < 1, by simp [this], rwa lt_sub_iff_add_lt }, exact mul_pos this (by exact_mod_cast q.pos) end lemma fract_inv_num_lt_num_of_pos {q : ℚ} (q_pos : 0 < q): (fract q⁻¹).num < q.num := begin -- we know that the numerator must be positive have q_num_pos : 0 < q.num, from rat.num_pos_iff_pos.elim_right q_pos, -- we will work with the absolute value of the numerator, which is equal to the numerator have q_num_abs_eq_q_num : (q.num.nat_abs : ℤ) = q.num, from (int.nat_abs_of_nonneg q_num_pos.le), set q_inv := (q.denom : ℚ) / q.num with q_inv_def, have q_inv_eq : q⁻¹ = q_inv, from rat.inv_def', suffices : (q_inv - ⌊q_inv⌋).num < q.num, by rwa q_inv_eq, suffices : ((q.denom - q.num * ⌊q_inv⌋ : ℚ) / q.num).num < q.num, by field_simp [this, (ne_of_gt q_num_pos)], suffices : (q.denom : ℤ) - q.num * ⌊q_inv⌋ < q.num, by { -- use that `q.num` and `q.denom` are coprime to show that the numerator stays unreduced have : ((q.denom - q.num * ⌊q_inv⌋ : ℚ) / q.num).num = q.denom - q.num * ⌊q_inv⌋, by { suffices : ((q.denom : ℤ) - q.num * ⌊q_inv⌋).nat_abs.coprime q.num.nat_abs, by exact_mod_cast (rat.num_div_eq_of_coprime q_num_pos this), have : (q.num.nat_abs : ℚ) = (q.num : ℚ), by exact_mod_cast q_num_abs_eq_q_num, have tmp := nat.coprime_sub_mul_floor_rat_div_of_coprime q.cop.symm, simpa only [this, q_num_abs_eq_q_num] using tmp }, rwa this }, -- to show the claim, start with the following inequality have q_inv_num_denom_ineq : q⁻¹.num - ⌊q⁻¹⌋ * q⁻¹.denom < q⁻¹.denom, by { have : q⁻¹.num < (⌊q⁻¹⌋ + 1) * q⁻¹.denom, from rat.num_lt_succ_floor_mul_denom q⁻¹, have : q⁻¹.num < ⌊q⁻¹⌋ * q⁻¹.denom + q⁻¹.denom, by rwa [right_distrib, one_mul] at this, rwa [←sub_lt_iff_lt_add'] at this }, -- use that `q.num` and `q.denom` are coprime to show that q_inv is the unreduced reciprocal -- of `q` have : q_inv.num = q.denom ∧ q_inv.denom = q.num.nat_abs, by { have coprime_q_denom_q_num : q.denom.coprime q.num.nat_abs, from q.cop.symm, have : int.nat_abs q.denom = q.denom, by simp, rw ←this at coprime_q_denom_q_num, rw q_inv_def, split, { exact_mod_cast (rat.num_div_eq_of_coprime q_num_pos coprime_q_denom_q_num) }, { suffices : (((q.denom : ℚ) / q.num).denom : ℤ) = q.num.nat_abs, by exact_mod_cast this, rw q_num_abs_eq_q_num, exact_mod_cast (rat.denom_div_eq_of_coprime q_num_pos coprime_q_denom_q_num) } }, rwa [q_inv_eq, this.left, this.right, q_num_abs_eq_q_num, mul_comm] at q_inv_num_denom_ineq end end rat
daab32fc65cb694b531b5fa923d1c3f0494f7a15
94e33a31faa76775069b071adea97e86e218a8ee
/src/set_theory/cardinal/ordinal.lean
edbc5497917ccf311f9f5ddb187de8c47af38c25
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
42,486
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, Floris van Doorn -/ import order.bounded import set_theory.ordinal.principal import tactic.linarith /-! # Cardinals and ordinals Relationships between cardinals and ordinals, properties of cardinals that are proved using ordinals. ## Main definitions * The function `cardinal.aleph'` gives the cardinals listed by their ordinal index, and is the inverse of `cardinal.aleph_idx`. `aleph' n = n`, `aleph' ω = ℵ₀`, `aleph' (ω + 1) = succ ℵ₀`, etc. It is an order isomorphism between ordinals and cardinals. * The function `cardinal.aleph` gives the infinite cardinals listed by their ordinal index. `aleph 0 = ℵ₀`, `aleph 1 = succ ℵ₀` is the first uncountable cardinal, and so on. ## Main Statements * `cardinal.mul_eq_max` and `cardinal.add_eq_max` state that the product (resp. sum) of two infinite cardinals is just their maximum. Several variations around this fact are also given. * `cardinal.mk_list_eq_mk` : when `α` is infinite, `α` and `list α` have the same cardinality. * simp lemmas for inequalities between `bit0 a` and `bit1 b` are registered, making `simp` able to prove inequalities about numeral cardinals. ## Tags cardinal arithmetic (for infinite cardinals) -/ noncomputable theory open function cardinal set equiv order open_locale classical cardinal ordinal universes u v w namespace cardinal section using_ordinals open ordinal theorem ord_is_limit {c} (co : ℵ₀ ≤ c) : (ord c).is_limit := begin refine ⟨λ h, aleph_0_ne_zero _, λ a, lt_imp_lt_of_le_imp_le (λ h, _)⟩, { rw [←ordinal.le_zero, ord_le] at h, simpa only [card_zero, nonpos_iff_eq_zero] using co.trans h }, { rw ord_le at h ⊢, rwa [←@add_one_of_aleph_0_le (card a), ←card_succ], rw [←ord_le, ←le_succ_of_is_limit, ord_le], { exact co.trans h }, { rw ord_aleph_0, exact omega_is_limit } } end /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this definition, we register additionally that this function is an initial segment, i.e., it is order preserving and its range is an initial segment of the ordinals. For the basic function version, see `aleph_idx`. For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) := @rel_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding.lt_embedding /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx : cardinal → ordinal := aleph_idx.initial_seg @[simp] theorem aleph_idx.initial_seg_coe : (aleph_idx.initial_seg : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b := aleph_idx.initial_seg.to_rel_embedding.map_rel_iff @[simp] theorem aleph_idx_le {a b} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b := by rw [← not_lt, ← not_lt, aleph_idx_lt] theorem aleph_idx.init {a b} : b < aleph_idx a → ∃ c, aleph_idx c = b := aleph_idx.initial_seg.init _ _ /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ℵ₀ = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this version, we register additionally that this function is an order isomorphism between cardinals and ordinals. For the basic function version, see `aleph_idx`. -/ def aleph_idx.rel_iso : @rel_iso cardinal.{u} ordinal.{u} (<) (<) := @rel_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $ (initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $ λ ⟨o, e⟩, begin have : ∀ c, aleph_idx c < o := λ c, (e _).2 ⟨_, rfl⟩, refine ordinal.induction_on o _ this, introsI α r _ h, let s := ⨆ a, inv_fun aleph_idx (ordinal.typein r a), apply (lt_succ s).not_le, have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.injective, simpa only [typein_enum, left_inverse_inv_fun I (succ s)] using le_csupr (cardinal.bdd_above_range.{u u} (λ a : α, inv_fun aleph_idx (ordinal.typein r a))) (ordinal.enum r _ (h (succ s))) end @[simp] theorem aleph_idx.rel_iso_coe : (aleph_idx.rel_iso : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem type_cardinal : @type cardinal (<) _ = ordinal.univ.{u (u+1)} := by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.rel_iso⟩ @[simp] theorem mk_cardinal : #cardinal = univ.{u (u+1)} := by simpa only [card_type, card_univ] using congr_arg card type_cardinal /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = succ ℵ₀`, etc. In this version, we register additionally that this function is an order isomorphism between ordinals and cardinals. For the basic function version, see `aleph'`. -/ def aleph'.rel_iso := cardinal.aleph_idx.rel_iso.symm /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = succ ℵ₀`, etc. -/ def aleph' : ordinal → cardinal := aleph'.rel_iso @[simp] theorem aleph'.rel_iso_coe : (aleph'.rel_iso : ordinal → cardinal) = aleph' := rfl @[simp] theorem aleph'_lt {o₁ o₂ : ordinal} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ := aleph'.rel_iso.map_rel_iff @[simp] theorem aleph'_le {o₁ o₂ : ordinal} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph'_lt @[simp] theorem aleph'_aleph_idx (c : cardinal) : aleph' c.aleph_idx = c := cardinal.aleph_idx.rel_iso.to_equiv.symm_apply_apply c @[simp] theorem aleph_idx_aleph' (o : ordinal) : (aleph' o).aleph_idx = o := cardinal.aleph_idx.rel_iso.to_equiv.apply_symm_apply o @[simp] theorem aleph'_zero : aleph' 0 = 0 := by { rw [← nonpos_iff_eq_zero, ← aleph'_aleph_idx 0, aleph'_le], apply ordinal.zero_le } @[simp] theorem aleph'_succ {o : ordinal} : aleph' (succ o) = succ (aleph' o) := begin apply (succ_le_of_lt $ aleph'_lt.2 $ lt_succ o).antisymm' (cardinal.aleph_idx_le.1 $ _), rw [aleph_idx_aleph', succ_le_iff, ← aleph'_lt, aleph'_aleph_idx], apply lt_succ end @[simp] theorem aleph'_nat : ∀ n : ℕ, aleph' n = n | 0 := aleph'_zero | (n+1) := show aleph' (succ n) = n.succ, by rw [aleph'_succ, aleph'_nat, nat_succ] theorem aleph'_le_of_limit {o : ordinal} (l : o.is_limit) {c} : aleph' o ≤ c ↔ ∀ o' < o, aleph' o' ≤ c := ⟨λ h o' h', (aleph'_le.2 $ h'.le).trans h, λ h, begin rw [←aleph'_aleph_idx c, aleph'_le, limit_le l], intros x h', rw [←aleph'_le, aleph'_aleph_idx], exact h _ h' end⟩ @[simp] theorem aleph'_omega : aleph' ω = ℵ₀ := eq_of_forall_ge_iff $ λ c, begin simp only [aleph'_le_of_limit omega_is_limit, lt_omega, exists_imp_distrib, aleph_0_le], exact forall_swap.trans (forall_congr $ λ n, by simp only [forall_eq, aleph'_nat]), end /-- `aleph'` and `aleph_idx` form an equivalence between `ordinal` and `cardinal` -/ @[simp] def aleph'_equiv : ordinal ≃ cardinal := ⟨aleph', aleph_idx, aleph_idx_aleph', aleph'_aleph_idx⟩ /-- The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ℵ₀`, `aleph 1 = succ ℵ₀` is the first uncountable cardinal, and so on. -/ def aleph (o : ordinal) : cardinal := aleph' (ω + o) @[simp] theorem aleph_lt {o₁ o₂ : ordinal} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ := aleph'_lt.trans (add_lt_add_iff_left _) @[simp] theorem aleph_le {o₁ o₂ : ordinal} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph_lt @[simp] theorem max_aleph_eq (o₁ o₂ : ordinal) : max (aleph o₁) (aleph o₂) = aleph (max o₁ o₂) := begin cases le_total (aleph o₁) (aleph o₂) with h h, { rw [max_eq_right h, max_eq_right (aleph_le.1 h)] }, { rw [max_eq_left h, max_eq_left (aleph_le.1 h)] } end @[simp] theorem aleph_succ {o : ordinal} : aleph (succ o) = succ (aleph o) := by { rw [aleph, add_succ, aleph'_succ], refl } @[simp] theorem aleph_zero : aleph 0 = ℵ₀ := by simp only [aleph, add_zero, aleph'_omega] theorem aleph_0_le_aleph' {o : ordinal} : ℵ₀ ≤ aleph' o ↔ ω ≤ o := by rw [← aleph'_omega, aleph'_le] theorem aleph_0_le_aleph (o : ordinal) : ℵ₀ ≤ aleph o := by { rw [aleph, aleph_0_le_aleph'], apply ordinal.le_add_right } theorem aleph'_pos {o : ordinal} (ho : 0 < o) : 0 < aleph' o := by rwa [←aleph'_zero, aleph'_lt] theorem aleph_pos (o : ordinal) : 0 < aleph o := aleph_0_pos.trans_le (aleph_0_le_aleph o) @[simp] theorem aleph_to_nat (o : ordinal) : (aleph o).to_nat = 0 := to_nat_apply_of_aleph_0_le $ aleph_0_le_aleph o @[simp] theorem aleph_to_part_enat (o : ordinal) : (aleph o).to_part_enat = ⊤ := to_part_enat_apply_of_aleph_0_le $ aleph_0_le_aleph o instance nonempty_out_aleph (o : ordinal) : nonempty (aleph o).ord.out.α := begin rw [out_nonempty_iff_ne_zero, ←ord_zero], exact λ h, (ord_injective h).not_gt (aleph_pos o) end theorem ord_aleph_is_limit (o : ordinal) : is_limit (aleph o).ord := ord_is_limit $ aleph_0_le_aleph _ instance (o : ordinal) : no_max_order (aleph o).ord.out.α := out_no_max_of_succ_lt (ord_aleph_is_limit o).2 theorem exists_aleph {c : cardinal} : ℵ₀ ≤ c ↔ ∃ o, c = aleph o := ⟨λ h, ⟨aleph_idx c - ω, by { rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx], rwa [← aleph_0_le_aleph', aleph'_aleph_idx] }⟩, λ ⟨o, e⟩, e.symm ▸ aleph_0_le_aleph _⟩ theorem aleph'_is_normal : is_normal (ord ∘ aleph') := ⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ lt_succ o, λ o l a, by simp only [ord_le, aleph'_le_of_limit l]⟩ theorem aleph_is_normal : is_normal (ord ∘ aleph) := aleph'_is_normal.trans $ add_is_normal ω theorem succ_aleph_0 : succ ℵ₀ = aleph 1 := by rw [←aleph_zero, ←aleph_succ, ordinal.succ_zero] lemma aleph_0_lt_aleph_one : ℵ₀ < aleph 1 := by { rw ←succ_aleph_0, apply lt_succ } lemma countable_iff_lt_aleph_one {α : Type*} (s : set α) : s.countable ↔ #s < aleph 1 := by rw [←succ_aleph_0, lt_succ_iff, mk_set_le_aleph_0] /-- Ordinals that are cardinals are unbounded. -/ theorem ord_card_unbounded : unbounded (<) {b : ordinal | b.card.ord = b} := unbounded_lt_iff.2 $ λ a, ⟨_, ⟨(by { dsimp, rw card_ord }), (lt_ord_succ_card a).le⟩⟩ theorem eq_aleph'_of_eq_card_ord {o : ordinal} (ho : o.card.ord = o) : ∃ a, (aleph' a).ord = o := ⟨cardinal.aleph_idx.rel_iso o.card, by simpa using ho⟩ /-- `ord ∘ aleph'` enumerates the ordinals that are cardinals. -/ theorem ord_aleph'_eq_enum_card : ord ∘ aleph' = enum_ord {b : ordinal | b.card.ord = b} := begin rw [←eq_enum_ord _ ord_card_unbounded, range_eq_iff], exact ⟨aleph'_is_normal.strict_mono, ⟨(λ a, (by { dsimp, rw card_ord })), λ b hb, eq_aleph'_of_eq_card_ord hb⟩⟩ end /-- Infinite ordinals that are cardinals are unbounded. -/ theorem ord_card_unbounded' : unbounded (<) {b : ordinal | b.card.ord = b ∧ ω ≤ b} := (unbounded_lt_inter_le ω).2 ord_card_unbounded theorem eq_aleph_of_eq_card_ord {o : ordinal} (ho : o.card.ord = o) (ho' : ω ≤ o) : ∃ a, (aleph a).ord = o := begin cases eq_aleph'_of_eq_card_ord ho with a ha, use a - ω, unfold aleph, rwa ordinal.add_sub_cancel_of_le, rwa [←aleph_0_le_aleph', ←ord_le_ord, ha, ord_aleph_0] end /-- `ord ∘ aleph` enumerates the infinite ordinals that are cardinals. -/ theorem ord_aleph_eq_enum_card : ord ∘ aleph = enum_ord {b : ordinal | b.card.ord = b ∧ ω ≤ b} := begin rw ←eq_enum_ord _ ord_card_unbounded', use aleph_is_normal.strict_mono, rw range_eq_iff, refine ⟨(λ a, ⟨_, _⟩), λ b hb, eq_aleph_of_eq_card_ord hb.1 hb.2⟩, { rw card_ord }, { rw [←ord_aleph_0, ord_le_ord], exact aleph_0_le_aleph _ } end /-! ### Properties of `mul` -/ /-- If `α` is an infinite type, then `α × α` and `α` have the same cardinality. -/ theorem mul_eq_self {c : cardinal} (h : ℵ₀ ≤ c) : c * c = c := begin refine le_antisymm _ (by simpa only [mul_one] using mul_le_mul_left' (one_le_aleph_0.trans h) c), -- the only nontrivial part is `c * c ≤ c`. We prove it inductively. refine acc.rec_on (cardinal.lt_wf.apply c) (λ c _, quotient.induction_on c $ λ α IH ol, _) h, -- consider the minimal well-order `r` on `α` (a type with cardinality `c`). rcases ord_eq α with ⟨r, wo, e⟩, resetI, letI := linear_order_of_STO' r, haveI : is_well_order α (<) := wo, -- Define an order `s` on `α × α` by writing `(a, b) < (c, d)` if `max a b < max c d`, or -- the max are equal and `a < c`, or the max are equal and `a = c` and `b < d`. let g : α × α → α := λ p, max p.1 p.2, let f : α × α ↪ ordinal × (α × α) := ⟨λ p:α×α, (typein (<) (g p), p), λ p q, congr_arg prod.snd⟩, let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))), -- this is a well order on `α × α`. haveI : is_well_order _ s := (rel_embedding.preimage _ _).is_well_order, /- it suffices to show that this well order is smaller than `r` if it were larger, then `r` would be a strict prefix of `s`. It would be contained in `β × β` for some `β` of cardinality `< c`. By the inductive assumption, this set has the same cardinality as `β` (or it is finite if `β` is finite), so it is `< c`, which is a contradiction. -/ suffices : type s ≤ type r, {exact card_le_card this}, refine le_of_forall_lt (λ o h, _), rcases typein_surj s h with ⟨p, rfl⟩, rw [← e, lt_ord], refine lt_of_le_of_lt (_ : _ ≤ card (succ (typein (<) (g p))) * card (succ (typein (<) (g p)))) _, { have : {q | s q p} ⊆ insert (g p) {x | x < g p} ×ˢ insert (g p) {x | x < g p}, { intros q h, simp only [s, embedding.coe_fn_mk, order.preimage, typein_lt_typein, prod.lex_def, typein_inj] at h, exact max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) }, suffices H : (insert (g p) {x | r x (g p)} : set α) ≃ ({x | r x (g p)} ⊕ punit), { exact ⟨(set.embedding_of_subset _ _ this).trans ((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ }, refine (equiv.set.insert _).trans ((equiv.refl _).sum_congr punit_equiv_punit), apply @irrefl _ r }, cases lt_or_le (card (succ (typein (<) (g p)))) ℵ₀ with qo qo, { exact (mul_lt_aleph_0 qo qo).trans_le ol }, { suffices, {exact (IH _ this qo).trans_lt this}, rw ← lt_ord, apply (ord_is_limit ol).2, rw [mk_def, e], apply typein_lt_type } end end using_ordinals /-- If `α` and `β` are infinite types, then the cardinality of `α × β` is the maximum of the cardinalities of `α` and `β`. -/ theorem mul_eq_max {a b : cardinal} (ha : ℵ₀ ≤ a) (hb : ℵ₀ ≤ b) : a * b = max a b := le_antisymm (mul_eq_self (ha.trans (le_max_left a b)) ▸ mul_le_mul' (le_max_left _ _) (le_max_right _ _)) $ max_le (by simpa only [mul_one] using mul_le_mul_left' (one_le_aleph_0.trans hb) a) (by simpa only [one_mul] using mul_le_mul_right' (one_le_aleph_0.trans ha) b) @[simp] theorem mul_mk_eq_max {α β : Type*} [infinite α] [infinite β] : #α * #β = max (#α) (#β) := mul_eq_max (aleph_0_le_mk α) (aleph_0_le_mk β) @[simp] theorem aleph_mul_aleph (o₁ o₂ : ordinal) : aleph o₁ * aleph o₂ = aleph (max o₁ o₂) := by rw [cardinal.mul_eq_max (aleph_0_le_aleph o₁) (aleph_0_le_aleph o₂), max_aleph_eq] @[simp] theorem aleph_0_mul_eq {a : cardinal} (ha : ℵ₀ ≤ a) : ℵ₀ * a = a := (mul_eq_max le_rfl ha).trans (max_eq_right ha) @[simp] theorem mul_aleph_0_eq {a : cardinal} (ha : ℵ₀ ≤ a) : a * ℵ₀ = a := (mul_eq_max ha le_rfl).trans (max_eq_left ha) @[simp] theorem aleph_0_mul_mk_eq {α : Type*} [infinite α] : ℵ₀ * #α = #α := aleph_0_mul_eq (aleph_0_le_mk α) @[simp] theorem mk_mul_aleph_0_eq {α : Type*} [infinite α] : #α * ℵ₀ = #α := mul_aleph_0_eq (aleph_0_le_mk α) @[simp] theorem aleph_0_mul_aleph (o : ordinal) : ℵ₀ * aleph o = aleph o := aleph_0_mul_eq (aleph_0_le_aleph o) @[simp] theorem aleph_mul_aleph_0 (o : ordinal) : aleph o * ℵ₀ = aleph o := mul_aleph_0_eq (aleph_0_le_aleph o) theorem mul_lt_of_lt {a b c : cardinal} (hc : ℵ₀ ≤ c) (h1 : a < c) (h2 : b < c) : a * b < c := (mul_le_mul' (le_max_left a b) (le_max_right a b)).trans_lt $ (lt_or_le (max a b) ℵ₀).elim (λ h, (mul_lt_aleph_0 h h).trans_le hc) (λ h, by { rw mul_eq_self h, exact max_lt h1 h2 }) lemma mul_le_max_of_aleph_0_le_left {a b : cardinal} (h : ℵ₀ ≤ a) : a * b ≤ max a b := begin convert mul_le_mul' (le_max_left a b) (le_max_right a b), rw mul_eq_self, refine h.trans (le_max_left a b) end lemma mul_eq_max_of_aleph_0_le_left {a b : cardinal} (h : ℵ₀ ≤ a) (h' : b ≠ 0) : a * b = max a b := begin cases le_or_lt ℵ₀ b with hb hb, { exact mul_eq_max h hb }, refine (mul_le_max_of_aleph_0_le_left h).antisymm _, have : b ≤ a, from hb.le.trans h, rw [max_eq_left this], convert mul_le_mul_left' (one_le_iff_ne_zero.mpr h') _, rw [mul_one], end lemma mul_eq_max_of_aleph_0_le_right {a b : cardinal} (h' : a ≠ 0) (h : ℵ₀ ≤ b) : a * b = max a b := begin rw [mul_comm, max_comm], exact mul_eq_max_of_aleph_0_le_left h h' end lemma mul_eq_max' {a b : cardinal} (h : ℵ₀ ≤ a * b) : a * b = max a b := begin rcases aleph_0_le_mul_iff.mp h with ⟨ha, hb, ha' | hb'⟩, { exact mul_eq_max_of_aleph_0_le_left ha' hb }, { exact mul_eq_max_of_aleph_0_le_right ha hb' } end theorem mul_le_max (a b : cardinal) : a * b ≤ max (max a b) ℵ₀ := begin rcases eq_or_ne a 0 with rfl | ha0, { simp }, rcases eq_or_ne b 0 with rfl | hb0, { simp }, cases le_or_lt ℵ₀ a with ha ha, { rw [mul_eq_max_of_aleph_0_le_left ha hb0], exact le_max_left _ _ }, { cases le_or_lt ℵ₀ b with hb hb, { rw [mul_comm, mul_eq_max_of_aleph_0_le_left hb ha0, max_comm], exact le_max_left _ _ }, { exact le_max_of_le_right (mul_lt_aleph_0 ha hb).le } } end lemma mul_eq_left {a b : cardinal} (ha : ℵ₀ ≤ a) (hb : b ≤ a) (hb' : b ≠ 0) : a * b = a := by { rw [mul_eq_max_of_aleph_0_le_left ha hb', max_eq_left hb] } lemma mul_eq_right {a b : cardinal} (hb : ℵ₀ ≤ b) (ha : a ≤ b) (ha' : a ≠ 0) : a * b = b := by { rw [mul_comm, mul_eq_left hb ha ha'] } lemma le_mul_left {a b : cardinal} (h : b ≠ 0) : a ≤ b * a := by { convert mul_le_mul_right' (one_le_iff_ne_zero.mpr h) _, rw [one_mul] } lemma le_mul_right {a b : cardinal} (h : b ≠ 0) : a ≤ a * b := by { rw [mul_comm], exact le_mul_left h } lemma mul_eq_left_iff {a b : cardinal} : a * b = a ↔ ((max ℵ₀ b ≤ a ∧ b ≠ 0) ∨ b = 1 ∨ a = 0) := begin rw max_le_iff, refine ⟨λ h, _, _⟩, { cases le_or_lt ℵ₀ a with ha ha, { have : a ≠ 0, { rintro rfl, exact ha.not_lt aleph_0_pos }, left, use ha, { rw ←not_lt, exact λ hb, ne_of_gt (hb.trans_le (le_mul_left this)) h }, { rintro rfl, apply this, rw mul_zero at h, exact h.symm }}, right, by_cases h2a : a = 0, { exact or.inr h2a }, have hb : b ≠ 0, { rintro rfl, apply h2a, rw mul_zero at h, exact h.symm }, left, rw [←h, mul_lt_aleph_0_iff, lt_aleph_0, lt_aleph_0] at ha, rcases ha with rfl|rfl|⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, contradiction, contradiction, rw ←ne at h2a, rw ←one_le_iff_ne_zero at h2a hb, norm_cast at h2a hb h ⊢, apply le_antisymm _ hb, rw ←not_lt, apply λ h2b, ne_of_gt _ h, conv_lhs { rw ←mul_one n }, rwa mul_lt_mul_left, apply nat.lt_of_succ_le h2a }, { rintro (⟨⟨ha, hab⟩, hb⟩|rfl|rfl), { rw [mul_eq_max_of_aleph_0_le_left ha hb, max_eq_left hab] }, all_goals { simp }} end /-! ### Properties of `add` -/ /-- If `α` is an infinite type, then `α ⊕ α` and `α` have the same cardinality. -/ theorem add_eq_self {c : cardinal} (h : ℵ₀ ≤ c) : c + c = c := le_antisymm (by simpa only [nat.cast_bit0, nat.cast_one, mul_eq_self h, two_mul] using mul_le_mul_right' ((nat_lt_aleph_0 2).le.trans h) c) (self_le_add_left c c) /-- If `α` is an infinite type, then the cardinality of `α ⊕ β` is the maximum of the cardinalities of `α` and `β`. -/ theorem add_eq_max {a b : cardinal} (ha : ℵ₀ ≤ a) : a + b = max a b := le_antisymm (add_eq_self (ha.trans (le_max_left a b)) ▸ add_le_add (le_max_left _ _) (le_max_right _ _)) $ max_le (self_le_add_right _ _) (self_le_add_left _ _) theorem add_eq_max' {a b : cardinal} (ha : ℵ₀ ≤ b) : a + b = max a b := by rw [add_comm, max_comm, add_eq_max ha] @[simp] theorem add_mk_eq_max {α β : Type*} [infinite α] : #α + #β = max (#α) (#β) := add_eq_max (aleph_0_le_mk α) @[simp] theorem add_mk_eq_max' {α β : Type*} [infinite β] : #α + #β = max (#α) (#β) := add_eq_max' (aleph_0_le_mk β) theorem add_le_max (a b : cardinal) : a + b ≤ max (max a b) ℵ₀ := begin cases le_or_lt ℵ₀ a with ha ha, { rw [add_eq_max ha], exact le_max_left _ _ }, { cases le_or_lt ℵ₀ b with hb hb, { rw [add_comm, add_eq_max hb, max_comm], exact le_max_left _ _ }, { exact le_max_of_le_right (add_lt_aleph_0 ha hb).le } } end theorem add_le_of_le {a b c : cardinal} (hc : ℵ₀ ≤ c) (h1 : a ≤ c) (h2 : b ≤ c) : a + b ≤ c := (add_le_add h1 h2).trans $ le_of_eq $ add_eq_self hc theorem add_lt_of_lt {a b c : cardinal} (hc : ℵ₀ ≤ c) (h1 : a < c) (h2 : b < c) : a + b < c := (add_le_add (le_max_left a b) (le_max_right a b)).trans_lt $ (lt_or_le (max a b) ℵ₀).elim (λ h, (add_lt_aleph_0 h h).trans_le hc) (λ h, by rw add_eq_self h; exact max_lt h1 h2) lemma eq_of_add_eq_of_aleph_0_le {a b c : cardinal} (h : a + b = c) (ha : a < c) (hc : ℵ₀ ≤ c) : b = c := begin apply le_antisymm, { rw [← h], apply self_le_add_left }, rw[← not_lt], intro hb, have : a + b < c := add_lt_of_lt hc ha hb, simpa [h, lt_irrefl] using this end lemma add_eq_left {a b : cardinal} (ha : ℵ₀ ≤ a) (hb : b ≤ a) : a + b = a := by { rw [add_eq_max ha, max_eq_left hb] } lemma add_eq_right {a b : cardinal} (hb : ℵ₀ ≤ b) (ha : a ≤ b) : a + b = b := by { rw [add_comm, add_eq_left hb ha] } lemma add_eq_left_iff {a b : cardinal} : a + b = a ↔ (max ℵ₀ b ≤ a ∨ b = 0) := begin rw max_le_iff, refine ⟨λ h, _, _⟩, { cases (le_or_lt ℵ₀ a) with ha ha, { left, use ha, rw ←not_lt, apply λ hb, ne_of_gt _ h, exact hb.trans_le (self_le_add_left b a) }, right, rw [←h, add_lt_aleph_0_iff, lt_aleph_0, lt_aleph_0] at ha, rcases ha with ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, norm_cast at h ⊢, rw [←add_right_inj, h, add_zero] }, { rintro (⟨h1, h2⟩|h3), { rw [add_eq_max h1, max_eq_left h2] }, { rw [h3, add_zero] } } end lemma add_eq_right_iff {a b : cardinal} : a + b = b ↔ (max ℵ₀ a ≤ b ∨ a = 0) := by { rw [add_comm, add_eq_left_iff] } lemma add_one_eq {a : cardinal} (ha : ℵ₀ ≤ a) : a + 1 = a := add_eq_left ha (one_le_aleph_0.trans ha) @[simp] lemma mk_add_one_eq {α : Type*} [infinite α] : #α + 1 = #α := add_one_eq (aleph_0_le_mk α) protected lemma eq_of_add_eq_add_left {a b c : cardinal} (h : a + b = a + c) (ha : a < ℵ₀) : b = c := begin cases le_or_lt ℵ₀ b with hb hb, { have : a < b := ha.trans_le hb, rw [add_eq_right hb this.le, eq_comm] at h, rw [eq_of_add_eq_of_aleph_0_le h this hb] }, { have hc : c < ℵ₀, { rw ←not_le, intro hc, apply lt_irrefl ℵ₀, apply (hc.trans (self_le_add_left _ a)).trans_lt, rw ←h, apply add_lt_aleph_0 ha hb }, rw lt_aleph_0 at *, rcases ha with ⟨n, rfl⟩, rcases hb with ⟨m, rfl⟩, rcases hc with ⟨k, rfl⟩, norm_cast at h ⊢, apply add_left_cancel h } end protected lemma eq_of_add_eq_add_right {a b c : cardinal} (h : a + b = c + b) (hb : b < ℵ₀) : a = c := by { rw [add_comm a b, add_comm c b] at h, exact cardinal.eq_of_add_eq_add_left h hb } @[simp] theorem aleph_add_aleph (o₁ o₂ : ordinal) : aleph o₁ + aleph o₂ = aleph (max o₁ o₂) := by rw [cardinal.add_eq_max (aleph_0_le_aleph o₁), max_aleph_eq] theorem principal_add_ord {c : cardinal} (hc : ℵ₀ ≤ c) : ordinal.principal (+) c.ord := λ a b ha hb, by { rw [lt_ord, ordinal.card_add] at *, exact add_lt_of_lt hc ha hb } theorem principal_add_aleph (o : ordinal) : ordinal.principal (+) (aleph o).ord := principal_add_ord $ aleph_0_le_aleph o /-! ### Properties about power -/ theorem pow_le {κ μ : cardinal.{u}} (H1 : ℵ₀ ≤ κ) (H2 : μ < ℵ₀) : κ ^ μ ≤ κ := let ⟨n, H3⟩ := lt_aleph_0.1 H2 in H3.symm ▸ (quotient.induction_on κ (λ α H1, nat.rec_on n (lt_of_lt_of_le (by { rw [nat.cast_zero, power_zero], exact one_lt_aleph_0 }) H1).le (λ n ih, trans_rel_left _ (by { rw [nat.cast_succ, power_add, power_one], exact mul_le_mul_right' ih _ }) (mul_eq_self H1))) H1) theorem pow_eq {κ μ : cardinal.{u}} (H1 : ℵ₀ ≤ κ) (H2 : 1 ≤ μ) (H3 : μ < ℵ₀) : κ ^ μ = κ := (pow_le H1 H3).antisymm $ self_le_power κ H2 lemma power_self_eq {c : cardinal} (h : ℵ₀ ≤ c) : c ^ c = 2 ^ c := begin apply ((power_le_power_right $ (cantor c).le).trans _).antisymm, { convert power_le_power_right ((nat_lt_aleph_0 2).le.trans h), apply nat.cast_two.symm }, { rw [←power_mul, mul_eq_self h] } end lemma prod_eq_two_power {ι : Type u} [infinite ι] {c : ι → cardinal.{v}} (h₁ : ∀ i, 2 ≤ c i) (h₂ : ∀ i, lift.{u} (c i) ≤ lift.{v} (#ι)) : prod c = 2 ^ lift.{v} (#ι) := begin rw [← lift_id' (prod c), lift_prod, ← lift_two_power], apply le_antisymm, { refine (prod_le_prod _ _ h₂).trans_eq _, rw [prod_const, lift_lift, ← lift_power, power_self_eq (aleph_0_le_mk ι), lift_umax.{u v}] }, { rw [← prod_const', lift_prod], refine prod_le_prod _ _ (λ i, _), rw [lift_two, ← lift_two.{u v}, lift_le], exact h₁ i } end lemma power_eq_two_power {c₁ c₂ : cardinal} (h₁ : ℵ₀ ≤ c₁) (h₂ : 2 ≤ c₂) (h₂' : c₂ ≤ c₁) : c₂ ^ c₁ = 2 ^ c₁ := le_antisymm (power_self_eq h₁ ▸ power_le_power_right h₂') (power_le_power_right h₂) lemma nat_power_eq {c : cardinal.{u}} (h : ℵ₀ ≤ c) {n : ℕ} (hn : 2 ≤ n) : (n : cardinal.{u}) ^ c = 2 ^ c := power_eq_two_power h (by assumption_mod_cast) ((nat_lt_aleph_0 n).le.trans h) lemma power_nat_le {c : cardinal.{u}} {n : ℕ} (h : ℵ₀ ≤ c) : c ^ n ≤ c := pow_le h (nat_lt_aleph_0 n) lemma power_nat_eq {c : cardinal.{u}} {n : ℕ} (h1 : ℵ₀ ≤ c) (h2 : 1 ≤ n) : c ^ n = c := pow_eq h1 (by exact_mod_cast h2) (nat_lt_aleph_0 n) lemma power_nat_le_max {c : cardinal.{u}} {n : ℕ} : c ^ (n : cardinal.{u}) ≤ max c ℵ₀ := begin cases le_or_lt ℵ₀ c with hc hc, { exact le_max_of_le_left (power_nat_le hc) }, { exact le_max_of_le_right ((power_lt_aleph_0 hc (nat_lt_aleph_0 _)).le) } end lemma powerlt_aleph_0 {c : cardinal} (h : ℵ₀ ≤ c) : c ^< ℵ₀ = c := begin apply le_antisymm, { rw powerlt_le, intro c', rw lt_aleph_0, rintro ⟨n, rfl⟩, apply power_nat_le h }, convert le_powerlt c one_lt_aleph_0, rw power_one end lemma powerlt_aleph_0_le (c : cardinal) : c ^< ℵ₀ ≤ max c ℵ₀ := begin cases le_or_lt ℵ₀ c, { rw powerlt_aleph_0 h, apply le_max_left }, rw powerlt_le, exact λ c' hc', (power_lt_aleph_0 h hc').le.trans (le_max_right _ _) end /-! ### Computing cardinality of various types -/ theorem mk_list_eq_mk (α : Type u) [infinite α] : #(list α) = #α := have H1 : ℵ₀ ≤ #α := aleph_0_le_mk α, eq.symm $ le_antisymm ⟨⟨λ x, [x], λ x y H, (list.cons.inj H).1⟩⟩ $ calc #(list α) = sum (λ n : ℕ, #α ^ (n : cardinal.{u})) : mk_list_eq_sum_pow α ... ≤ sum (λ n : ℕ, #α) : sum_le_sum _ _ $ λ n, pow_le H1 $ nat_lt_aleph_0 n ... = #α : by simp [H1] theorem mk_list_eq_aleph_0 (α : Type u) [encodable α] [nonempty α] : #(list α) = ℵ₀ := mk_le_aleph_0.antisymm (aleph_0_le_mk _) theorem mk_list_eq_max_mk_aleph_0 (α : Type u) [nonempty α] : #(list α) = max (#α) ℵ₀ := begin casesI fintype_or_infinite α, { haveI : encodable α := fintype.to_encodable α, rw [mk_list_eq_aleph_0, eq_comm, max_eq_right], exact mk_le_aleph_0 }, { rw [mk_list_eq_mk, eq_comm, max_eq_left], exact aleph_0_le_mk α } end theorem mk_list_le_max (α : Type u) : #(list α) ≤ max ℵ₀ (#α) := begin casesI fintype_or_infinite α, { haveI := fintype.to_encodable α, exact mk_le_aleph_0.trans (le_max_left _ _) }, { rw mk_list_eq_mk, apply le_max_right } end @[simp] theorem mk_finset_of_infinite (α : Type u) [infinite α] : #(finset α) = #α := eq.symm $ le_antisymm (mk_le_of_injective (λ x y, finset.singleton_inj.1)) $ calc #(finset α) ≤ #(list α) : mk_le_of_surjective list.to_finset_surjective ... = #α : mk_list_eq_mk α lemma mk_bounded_set_le_of_infinite (α : Type u) [infinite α] (c : cardinal) : #{t : set α // #t ≤ c} ≤ #α ^ c := begin refine le_trans _ (by rw [←add_one_eq (aleph_0_le_mk α)]), induction c using cardinal.induction_on with β, fapply mk_le_of_surjective, { intro f, use sum.inl ⁻¹' range f, refine le_trans (mk_preimage_of_injective _ _ (λ x y, sum.inl.inj)) _, apply mk_range_le }, rintro ⟨s, ⟨g⟩⟩, use λ y, if h : ∃(x : s), g x = y then sum.inl (classical.some h).val else sum.inr ⟨⟩, apply subtype.eq, ext, split, { rintro ⟨y, h⟩, dsimp only at h, by_cases h' : ∃ (z : s), g z = y, { rw [dif_pos h'] at h, cases sum.inl.inj h, exact (classical.some h').2 }, { rw [dif_neg h'] at h, cases h }}, { intro h, have : ∃(z : s), g z = g ⟨x, h⟩, exact ⟨⟨x, h⟩, rfl⟩, use g ⟨x, h⟩, dsimp only, rw [dif_pos this], congr', suffices : classical.some this = ⟨x, h⟩, exact congr_arg subtype.val this, apply g.2, exact classical.some_spec this } end lemma mk_bounded_set_le (α : Type u) (c : cardinal) : #{t : set α // #t ≤ c} ≤ max (#α) ℵ₀ ^ c := begin transitivity #{t : set (ulift.{u} ℕ ⊕ α) // #t ≤ c}, { refine ⟨embedding.subtype_map _ _⟩, apply embedding.image, use sum.inr, apply sum.inr.inj, intros s hs, exact mk_image_le.trans hs }, apply (mk_bounded_set_le_of_infinite (ulift.{u} ℕ ⊕ α) c).trans, rw [max_comm, ←add_eq_max]; refl end lemma mk_bounded_subset_le {α : Type u} (s : set α) (c : cardinal.{u}) : #{t : set α // t ⊆ s ∧ #t ≤ c} ≤ max (#s) ℵ₀ ^ c := begin refine le_trans _ (mk_bounded_set_le s c), refine ⟨embedding.cod_restrict _ _ _⟩, use λ t, coe ⁻¹' t.1, { rintros ⟨t, ht1, ht2⟩ ⟨t', h1t', h2t'⟩ h, apply subtype.eq, dsimp only at h ⊢, refine (preimage_eq_preimage' _ _).1 h; rw [subtype.range_coe]; assumption }, rintro ⟨t, h1t, h2t⟩, exact (mk_preimage_of_injective _ _ subtype.val_injective).trans h2t end /-! ### Properties of `compl` -/ lemma mk_compl_of_infinite {α : Type*} [infinite α] (s : set α) (h2 : #s < #α) : #(sᶜ : set α) = #α := by { refine eq_of_add_eq_of_aleph_0_le _ h2 (aleph_0_le_mk α), exact mk_sum_compl s } lemma mk_compl_finset_of_infinite {α : Type*} [infinite α] (s : finset α) : #((↑s)ᶜ : set α) = #α := by { apply mk_compl_of_infinite, exact (finset_card_lt_aleph_0 s).trans_le (aleph_0_le_mk α) } lemma mk_compl_eq_mk_compl_infinite {α : Type*} [infinite α] {s t : set α} (hs : #s < #α) (ht : #t < #α) : #(sᶜ : set α) = #(tᶜ : set α) := by { rw [mk_compl_of_infinite s hs, mk_compl_of_infinite t ht] } lemma mk_compl_eq_mk_compl_finite_lift {α : Type u} {β : Type v} [fintype α] {s : set α} {t : set β} (h1 : lift.{max v w} (#α) = lift.{max u w} (#β)) (h2 : lift.{max v w} (#s) = lift.{max u w} (#t)) : lift.{max v w} (#(sᶜ : set α)) = lift.{max u w} (#(tᶜ : set β)) := begin rcases lift_mk_eq.1 h1 with ⟨e⟩, letI : fintype β := fintype.of_equiv α e, replace h1 : fintype.card α = fintype.card β := (fintype.of_equiv_card _).symm, classical, lift s to finset α using s.to_finite, lift t to finset β using t.to_finite, simp only [finset.coe_sort_coe, mk_coe_finset, lift_nat_cast, nat.cast_inj] at h2, simp only [← finset.coe_compl, finset.coe_sort_coe, mk_coe_finset, finset.card_compl, lift_nat_cast, nat.cast_inj, h1, h2] end lemma mk_compl_eq_mk_compl_finite {α β : Type u} [fintype α] {s : set α} {t : set β} (h1 : #α = #β) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set β) := by { rw ← lift_inj, apply mk_compl_eq_mk_compl_finite_lift; rwa [lift_inj] } lemma mk_compl_eq_mk_compl_finite_same {α : Type*} [fintype α] {s t : set α} (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set α) := mk_compl_eq_mk_compl_finite rfl h /-! ### Extending an injection to an equiv -/ theorem extend_function {α β : Type*} {s : set α} (f : s ↪ β) (h : nonempty ((sᶜ : set α) ≃ ((range f)ᶜ : set β))) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin intros, have := h, cases this with g, let h : α ≃ β := (set.sum_compl (s : set α)).symm.trans ((sum_congr (equiv.of_injective f f.2) g).trans (set.sum_compl (range f))), refine ⟨h, _⟩, rintro ⟨x, hx⟩, simp [set.sum_compl_symm_apply_of_mem, hx] end theorem extend_function_finite {α β : Type*} [fintype α] {s : set α} (f : s ↪ β) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin apply extend_function f, cases id h with g, rw [← lift_mk_eq] at h, rw [←lift_mk_eq, mk_compl_eq_mk_compl_finite_lift h], rw [mk_range_eq_lift], exact f.2 end theorem extend_function_of_lt {α β : Type*} {s : set α} (f : s ↪ β) (hs : #s < #α) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin casesI fintype_or_infinite α, { exact extend_function_finite f h }, { apply extend_function f, cases id h with g, haveI := infinite.of_injective _ g.injective, rw [← lift_mk_eq'] at h ⊢, rwa [mk_compl_of_infinite s hs, mk_compl_of_infinite], rwa [← lift_lt, mk_range_eq_of_injective f.injective, ← h, lift_lt] }, end section bit /-! This section proves inequalities for `bit0` and `bit1`, enabling `simp` to solve inequalities for numeral cardinals. The complexity of the resulting algorithm is not good, as in some cases `simp` reduces an inequality to a disjunction of two situations, depending on whether a cardinal is finite or infinite. Since the evaluation of the branches is not lazy, this is bad. It is good enough for practical situations, though. For specific numbers, these inequalities could also be deduced from the corresponding inequalities of natural numbers using `norm_cast`: ``` example : (37 : cardinal) < 42 := by { norm_cast, norm_num } ``` -/ lemma bit0_ne_zero (a : cardinal) : ¬bit0 a = 0 ↔ ¬a = 0 := by simp [bit0] @[simp] lemma bit1_ne_zero (a : cardinal) : ¬bit1 a = 0 := by simp [bit1] @[simp] lemma zero_lt_bit0 (a : cardinal) : 0 < bit0 a ↔ 0 < a := by { rw ←not_iff_not, simp [bit0], } @[simp] lemma zero_lt_bit1 (a : cardinal) : 0 < bit1 a := zero_lt_one.trans_le (self_le_add_left _ _) @[simp] lemma one_le_bit0 (a : cardinal) : 1 ≤ bit0 a ↔ 0 < a := ⟨λ h, (zero_lt_bit0 a).mp (zero_lt_one.trans_le h), λ h, (one_le_iff_pos.mpr h).trans (self_le_add_left a a)⟩ @[simp] lemma one_le_bit1 (a : cardinal) : 1 ≤ bit1 a := self_le_add_left _ _ theorem bit0_eq_self {c : cardinal} (h : ℵ₀ ≤ c) : bit0 c = c := add_eq_self h @[simp] theorem bit0_lt_aleph_0 {c : cardinal} : bit0 c < ℵ₀ ↔ c < ℵ₀ := by simp [bit0, add_lt_aleph_0_iff] @[simp] theorem aleph_0_le_bit0 {c : cardinal} : ℵ₀ ≤ bit0 c ↔ ℵ₀ ≤ c := by { rw ←not_iff_not, simp } @[simp] theorem bit1_eq_self_iff {c : cardinal} : bit1 c = c ↔ ℵ₀ ≤ c := begin by_cases h : ℵ₀ ≤ c, { simp only [bit1, bit0_eq_self h, h, eq_self_iff_true, add_one_of_aleph_0_le] }, { refine iff_of_false (ne_of_gt _) h, rcases lt_aleph_0.1 (not_le.1 h) with ⟨n, rfl⟩, norm_cast, dsimp [bit1, bit0], linarith } end @[simp] theorem bit1_lt_aleph_0 {c : cardinal} : bit1 c < ℵ₀ ↔ c < ℵ₀ := by simp [bit1, bit0, add_lt_aleph_0_iff, one_lt_aleph_0] @[simp] theorem aleph_0_le_bit1 {c : cardinal} : ℵ₀ ≤ bit1 c ↔ ℵ₀ ≤ c := by { rw ←not_iff_not, simp } @[simp] lemma bit0_le_bit0 {a b : cardinal} : bit0 a ≤ bit0 b ↔ a ≤ b := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, refine iff_of_false (λ h, _) (hb.trans_le ha).not_le, have A : bit0 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans_le h) }, { rw bit0_eq_self hb, exact iff_of_true ((bit0_lt_aleph_0.2 ha).le.trans hb) (ha.le.trans hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, exact bit0_le_bit0 } end @[simp] lemma bit0_le_bit1 {a b : cardinal} : bit0 a ≤ bit1 b ↔ a ≤ b := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { rw [bit0_eq_self ha, bit1_eq_self_iff.2 hb] }, { rw bit0_eq_self ha, refine iff_of_false (λ h, _) (hb.trans_le ha).not_le, have A : bit1 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans_le h) }, { rw bit1_eq_self_iff.2 hb, exact iff_of_true ((bit0_lt_aleph_0.2 ha).le.trans hb) (ha.le.trans hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, exact nat.bit0_le_bit1_iff } end @[simp] lemma bit1_le_bit1 {a b : cardinal} : bit1 a ≤ bit1 b ↔ a ≤ b := ⟨λ h, bit0_le_bit1.1 ((self_le_add_right (bit0 a) 1).trans h), λ h, (add_le_add_right (add_le_add_left h a) 1).trans (add_le_add_right (add_le_add_right h b) 1)⟩ @[simp] lemma bit1_le_bit0 {a b : cardinal} : bit1 a ≤ bit0 b ↔ (a < b ∨ (a ≤ b ∧ ℵ₀ ≤ a)) := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { simp only [bit1_eq_self_iff.mpr ha, bit0_eq_self hb, ha, and_true], refine ⟨λ h, or.inr h, λ h, _⟩, cases h, { exact le_of_lt h }, { exact h } }, { rw bit1_eq_self_iff.2 ha, refine iff_of_false (λ h, _) (λ h, _), { have A : bit0 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans_le h) }, { exact not_le_of_lt (hb.trans_le ha) (h.elim le_of_lt and.left) } }, { rw bit0_eq_self hb, exact iff_of_true ((bit1_lt_aleph_0.2 ha).le.trans hb) (or.inl $ ha.trans_le hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, simp [not_le.mpr ha] } end @[simp] lemma bit0_lt_bit0 {a b : cardinal} : bit0 a < bit0 b ↔ a < b := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, refine iff_of_false (λ h, _) (hb.le.trans ha).not_lt, have A : bit0 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans h) }, { rw bit0_eq_self hb, exact iff_of_true ((bit0_lt_aleph_0.2 ha).trans_le hb) (ha.trans_le hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, exact bit0_lt_bit0 } end @[simp] lemma bit1_lt_bit0 {a b : cardinal} : bit1 a < bit0 b ↔ a < b := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { rw [bit1_eq_self_iff.2 ha, bit0_eq_self hb] }, { rw bit1_eq_self_iff.2 ha, refine iff_of_false (λ h, _) (hb.le.trans ha).not_lt, have A : bit0 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans h) }, { rw bit0_eq_self hb, exact iff_of_true ((bit1_lt_aleph_0.2 ha).trans_le hb) (ha.trans_le hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, exact nat.bit1_lt_bit0_iff } end @[simp] lemma bit1_lt_bit1 {a b : cardinal} : bit1 a < bit1 b ↔ a < b := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { rw [bit1_eq_self_iff.2 ha, bit1_eq_self_iff.2 hb] }, { rw bit1_eq_self_iff.2 ha, refine iff_of_false (λ h, _) (hb.le.trans ha).not_lt, have A : bit1 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans h) }, { rw bit1_eq_self_iff.2 hb, exact iff_of_true ((bit1_lt_aleph_0.2 ha).trans_le hb) (ha.trans_le hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, exact bit1_lt_bit1 } end @[simp] lemma bit0_lt_bit1 {a b : cardinal} : bit0 a < bit1 b ↔ (a < b ∨ (a ≤ b ∧ a < ℵ₀)) := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { simp [bit0_eq_self ha, bit1_eq_self_iff.2 hb, not_lt.mpr ha] }, { rw bit0_eq_self ha, refine iff_of_false (λ h, _) (λ h, _), { have A : bit1 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans h) }, { exact (hb.trans_le ha).not_le (h.elim le_of_lt and.left) } }, { rw [bit1_eq_self_iff.2 hb], exact iff_of_true ((bit0_lt_aleph_0.2 ha).trans_le hb) (or.inl $ ha.trans_le hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, simp only [ha, and_true, nat.bit0_lt_bit1_iff, or_iff_right_of_imp le_of_lt] } end lemma one_lt_two : (1 : cardinal) < 2 := -- This strategy works generally to prove inequalities between numerals in `cardinality`. by { norm_cast, norm_num } @[simp] lemma one_lt_bit0 {a : cardinal} : 1 < bit0 a ↔ 0 < a := by simp [←bit1_zero] @[simp] lemma one_lt_bit1 (a : cardinal) : 1 < bit1 a ↔ 0 < a := by simp [←bit1_zero] end bit end cardinal
92472d4aa129d934535f716eb6c115f311b4e931
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/order/basic.lean
c11779aa807be966437265417073785e62fb05ef
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
25,945
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import logic.basic data.sum data.set.basic algebra.order open function /- TODO: automatic construction of dual definitions / theorems -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} protected noncomputable def classical.decidable_linear_order [I : linear_order α] : decidable_linear_order α := { decidable_le := classical.dec_rel _, ..I } theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b := λ h, h ▸ le_refl a theorem is_refl.swap (r) [is_refl α r] : is_refl α (swap r) := ⟨refl_of r⟩ theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨irrefl_of r⟩ theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) := ⟨λ a b c h₁ h₂, trans_of r h₂ h₁⟩ theorem is_antisymm.swap (r) [is_antisymm α r] : is_antisymm α (swap r) := ⟨λ a b h₁ h₂, antisymm h₂ h₁⟩ theorem is_asymm.swap (r) [is_asymm α r] : is_asymm α (swap r) := ⟨λ a b h₁ h₂, asymm_of r h₂ h₁⟩ theorem is_total.swap (r) [is_total α r] : is_total α (swap r) := ⟨λ a b, (total_of r a b).swap⟩ theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) := ⟨λ a b, by simpa [swap, or.comm, or.left_comm] using trichotomous_of r a b⟩ theorem is_preorder.swap (r) [is_preorder α r] : is_preorder α (swap r) := {..@is_refl.swap α r _, ..@is_trans.swap α r _} theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) := {..@is_irrefl.swap α r _, ..@is_trans.swap α r _} theorem is_partial_order.swap (r) [is_partial_order α r] : is_partial_order α (swap r) := {..@is_preorder.swap α r _, ..@is_antisymm.swap α r _} theorem is_total_preorder.swap (r) [is_total_preorder α r] : is_total_preorder α (swap r) := {..@is_preorder.swap α r _, ..@is_total.swap α r _} theorem is_linear_order.swap (r) [is_linear_order α r] : is_linear_order α (swap r) := {..@is_partial_order.swap α r _, ..@is_total.swap α r _} def antisymm_of_asymm (r) [is_asymm α r] : is_antisymm α r := ⟨λ x y h₁ h₂, (asymm h₁ h₂).elim⟩ /- Convert algebraic structure style to explicit relation style typeclasses -/ instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩ instance [preorder α] : is_refl α (≥) := is_refl.swap _ instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩ instance [preorder α] : is_trans α (≥) := is_trans.swap _ instance [preorder α] : is_preorder α (≤) := {} instance [preorder α] : is_preorder α (≥) := {} instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩ instance [preorder α] : is_irrefl α (>) := is_irrefl.swap _ instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩ instance [preorder α] : is_trans α (>) := is_trans.swap _ instance [preorder α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩ instance [preorder α] : is_asymm α (>) := is_asymm.swap _ instance [preorder α] : is_antisymm α (<) := antisymm_of_asymm _ instance [preorder α] : is_antisymm α (>) := antisymm_of_asymm _ instance [preorder α] : is_strict_order α (<) := {} instance [preorder α] : is_strict_order α (>) := {} instance preorder.is_total_preorder [preorder α] [is_total α (≤)] : is_total_preorder α (≤) := {} instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩ instance [partial_order α] : is_antisymm α (≥) := is_antisymm.swap _ instance [partial_order α] : is_partial_order α (≤) := {} instance [partial_order α] : is_partial_order α (≥) := {} instance [linear_order α] : is_total α (≤) := ⟨le_total⟩ instance [linear_order α] : is_total α (≥) := is_total.swap _ instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := by apply_instance instance [linear_order α] : is_total_preorder α (≥) := {} instance [linear_order α] : is_linear_order α (≤) := {} instance [linear_order α] : is_linear_order α (≥) := {} instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩ instance [linear_order α] : is_trichotomous α (>) := is_trichotomous.swap _ theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin resetI, cases A, cases B, congr, { funext x y, exact propext (H x y) }, { funext x y, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] }, end theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := preorder.ext H; cases A; cases B; injection this; congr' theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := partial_order.ext H; cases A; cases B; injection this; congr' /-- Given an order `R` on `β` and a function `f : α → β`, the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique order on `α` making `f` an order embedding (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b theorem monotone_comp {f : α → β} {g : β → γ} (m_f : monotone f) (m_g : monotone g) : monotone (g ∘ f) := assume a b h, m_g (m_f h) lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) : monotone f | n m h := begin induction h, { refl }, { transitivity, assumption, exact hf _ } end lemma reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f) {x x' : α} (h : f x < f x') : x < x' := by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' } end monotone def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩ instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, le_trans hbc hab, lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, .. order_dual.has_le α, .. order_dual.has_lt α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, .. order_dual.partial_order α } instance (α : Type*) [decidable_linear_order α] : decidable_linear_order (order_dual α) := { decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance, decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance, .. order_dual.linear_order α } instance : Π [inhabited α], inhabited (order_dual α) := id end order_dual /- order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] [preorder γ] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone def preorder.lift {α β} (f : α → β) (i : preorder β) : preorder α := by exactI { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } def partial_order.lift {α β} (f : α → β) (inj : injective f) (i : partial_order β) : partial_order α := by exactI { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f (by apply_instance) } def linear_order.lift {α β} (f : α → β) (inj : injective f) (i : linear_order β) : linear_order α := by exactI { le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj (by apply_instance) } def decidable_linear_order.lift {α β} (f : α → β) (inj : injective f) (i : decidable_linear_order β) : decidable_linear_order α := by exactI { decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance, decidable_lt := λ x y, show decidable (f x < f y), by apply_instance, decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩, .. linear_order.lift f inj (by apply_instance) } instance subtype.preorder {α} [i : preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val i instance subtype.partial_order {α} [i : partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val subtype.val_injective i instance subtype.linear_order {α} [i : linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val subtype.val_injective i instance subtype.decidable_linear_order {α} [i : decidable_linear_order α] (p : α → Prop) : decidable_linear_order (subtype p) := decidable_linear_order.lift subtype.val subtype.val_injective i instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } /-- The pointwise partial order on a product. (The lexicographic ordering is defined in order/lexicographic.lean, and the instances are available via the type synonym `lex α β = α × β`.) -/ instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb), .. prod.preorder α β } /- additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}(h : ∀a₃<a₁, a₂ ≥ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ lemma dense_or_discrete [linear_order α] {a₁ a₂ : α} (h : a₁ < a₂) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a ≥ a₂) ∧ (∀a<a₂, a ≤ a₁)) := classical.or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ lemma trans_trichotomous_left [is_trans α r] [is_trichotomous α r] {a b c : α} : ¬r b a → r b c → r a c := begin intros h₁ h₂, rcases trichotomous_of r a b with h₃|h₃|h₃, exact trans h₃ h₂, rw h₃, exact h₂, exfalso, exact h₁ h₃ end lemma trans_trichotomous_right [is_trans α r] [is_trichotomous α r] {a b c : α} : r a b → ¬r c b → r a c := begin intros h₁ h₂, rcases trichotomous_of r b c with h₃|h₃|h₃, exact trans h₁ h₃, rw ←h₃, exact h₁, exfalso, exact h₂ h₃ end variables {s : β → β → Prop} {t : γ → γ → Prop} theorem is_irrefl_of_is_asymm [is_asymm α r] : is_irrefl α r := ⟨λ a h, asymm h h⟩ /-- Construct a partial order from a `is_strict_order` relation -/ def partial_order_of_SO (r) [is_strict_order α r] : partial_order α := { le := λ x y, x = y ∨ r x y, lt := r, le_refl := λ x, or.inl rfl, le_trans := λ x y z h₁ h₂, match y, z, h₁, h₂ with | _, _, or.inl rfl, h₂ := h₂ | _, _, h₁, or.inl rfl := h₁ | _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂) end, le_antisymm := λ x y h₁ h₂, match y, h₁, h₂ with | _, or.inl rfl, h₂ := rfl | _, h₁, or.inl rfl := rfl | _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim end, lt_iff_le_not_le := λ x y, ⟨λ h, ⟨or.inr h, not_or (λ e, by rw e at h; exact irrefl _ h) (asymm h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ } /-- This is basically the same as `is_strict_total_order`, but that definition is in Type (probably by mistake) and also has redundant assumptions. -/ @[algebra] class is_strict_total_order' (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_order α lt : Prop. /-- Construct a linear order from a `is_strict_total_order'` relation -/ def linear_order_of_STO' (r) [is_strict_total_order' α r] : linear_order α := { le_total := λ x y, match y, trichotomous_of r x y with | y, or.inl h := or.inl (or.inr h) | _, or.inr (or.inl rfl) := or.inl (or.inl rfl) | _, or.inr (or.inr h) := or.inr (or.inr h) end, ..partial_order_of_SO r } /-- Construct a decidable linear order from a `is_strict_total_order'` relation -/ def decidable_linear_order_of_STO' (r) [is_strict_total_order' α r] [decidable_rel r] : decidable_linear_order α := by letI LO := linear_order_of_STO' r; exact { decidable_le := λ x y, decidable_of_iff (¬ r y x) (@not_lt _ _ y x), ..LO } noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α := { decidable_le := classical.dec_rel _, ..LO } theorem is_strict_total_order'.swap (r) [is_strict_total_order' α r] : is_strict_total_order' α (swap r) := {..is_trichotomous.swap r, ..is_strict_order.swap r} instance [linear_order α] : is_strict_total_order' α (<) := {} /-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`. This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on the constructive reals, and is also known as negative transitivity, since the contrapositive asserts transitivity of the relation `¬ a < b`. -/ @[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop := (conn : ∀ a b c, lt a c → lt a b ∨ lt b c) theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r] {a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c := mt (is_order_connected.conn a b c) $ by simp [h₁, h₂] theorem is_strict_weak_order_of_is_order_connected [is_asymm α r] [is_order_connected α r] : is_strict_weak_order α r := { trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂), incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩, ⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩, ..@is_irrefl_of_is_asymm α r _ } instance is_order_connected_of_is_strict_total_order' [is_strict_total_order' α r] : is_order_connected α r := ⟨λ a b c h, (trichotomous _ _).imp_right (λ o, o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩ instance is_strict_total_order_of_is_strict_total_order' [is_strict_total_order' α r] : is_strict_total_order α r := {..is_strict_weak_order_of_is_order_connected} instance [linear_order α] : is_strict_total_order α (<) := by apply_instance instance [linear_order α] : is_order_connected α (<) := by apply_instance instance [linear_order α] : is_incomp_trans α (<) := by apply_instance instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance /-- An extensional relation is one in which an element is determined by its set of predecessors. It is named for the `x ∈ y` relation in set theory, whose extensionality is one of the first axioms of ZFC. -/ @[algebra] class is_extensional (α : Type u) (r : α → α → Prop) : Prop := (ext : ∀ a b, (∀ x, r x a ↔ r x b) → a = b) instance is_extensional_of_is_strict_total_order' [is_strict_total_order' α r] : is_extensional α r := ⟨λ a b H, ((@trichotomous _ r _ a b) .resolve_left $ mt (H _).2 (irrefl a)) .resolve_right $ mt (H _).1 (irrefl b)⟩ /-- A well order is a well-founded linear order. -/ @[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_strict_total_order' α r : Prop := (wf : well_founded r) instance is_well_order.is_strict_total_order {α} (r : α → α → Prop) [is_well_order α r] : is_strict_total_order α r := by apply_instance instance is_well_order.is_extensional {α} (r : α → α → Prop) [is_well_order α r] : is_extensional α r := by apply_instance instance is_well_order.is_trichotomous {α} (r : α → α → Prop) [is_well_order α r] : is_trichotomous α r := by apply_instance instance is_well_order.is_trans {α} (r : α → α → Prop) [is_well_order α r] : is_trans α r := by apply_instance instance is_well_order.is_irrefl {α} (r : α → α → Prop) [is_well_order α r] : is_irrefl α r := by apply_instance instance is_well_order.is_asymm {α} (r : α → α → Prop) [is_well_order α r] : is_asymm α r := by apply_instance noncomputable def decidable_linear_order_of_is_well_order (r : α → α → Prop) [is_well_order α r] : decidable_linear_order α := by { haveI := linear_order_of_STO' r, exact classical.DLO α } instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation := { trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim _ _, irrefl := λ a, id, trans := λ a b c, false.elim, wf := ⟨λ a, ⟨_, λ y, false.elim⟩⟩ } instance nat.lt.is_well_order : is_well_order ℕ (<) := ⟨nat.lt_wf⟩ instance sum.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) := { trichotomous := λ a b, by cases a; cases b; simp; apply trichotomous, irrefl := λ a, by cases a; simp; apply irrefl, trans := λ a b c, by cases a; cases b; simp; cases c; simp; apply trans, wf := sum.lex_wf (is_well_order.wf r) (is_well_order.wf s) } instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) := { trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, match @trichotomous _ r _ a₁ b₁ with | or.inl h₁ := or.inl $ prod.lex.left _ _ _ h₁ | or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ _ h₁ | or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with | or.inl h := or.inl $ prod.lex.right _ _ h | or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ _ h | or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl end end, irrefl := λ ⟨a₁, a₂⟩ h, by cases h with _ _ _ _ h _ _ _ h; [exact irrefl _ h, exact irrefl _ h], trans := λ a b c h₁ h₂, begin cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab; cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc, { exact prod.lex.left _ _ _ (trans ab bc) }, { exact prod.lex.left _ _ _ ab }, { exact prod.lex.left _ _ _ bc }, { exact prod.lex.right _ _ (trans ab bc) } end, wf := prod.lex_wf (is_well_order.wf r) (is_well_order.wf s) } /-- An unbounded or cofinal set -/ def unbounded (r : α → α → Prop) (s : set α) : Prop := ∀ a, ∃ b ∈ s, ¬ r b a /-- A bounded or final set -/ def bounded (r : α → α → Prop) (s : set α) : Prop := ∃a, ∀ b ∈ s, r b a @[simp] lemma not_bounded_iff {r : α → α → Prop} (s : set α) : ¬bounded r s ↔ unbounded r s := begin classical, simp only [bounded, unbounded, not_forall, not_exists, exists_prop, not_and, not_not] end @[simp] lemma not_unbounded_iff {r : α → α → Prop} (s : set α) : ¬unbounded r s ↔ bounded r s := by { classical, rw [not_iff_comm, not_bounded_iff] } namespace well_founded theorem has_min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) : p ≠ ∅ → ∃ a ∈ p, ∀ x ∈ p, ¬ r x a := by classical; exact not_imp_comm.1 (λ he, set.eq_empty_iff_forall_not_mem.2 $ λ a, acc.rec_on (H.apply a) $ λ a H IH h, he ⟨_, h, λ y, imp_not_comm.1 (IH y)⟩) /-- The minimum element of a nonempty set in a well-founded order -/ noncomputable def min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) : α := classical.some (H.has_min p h) theorem min_mem {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) : H.min p h ∈ p := let ⟨h, _⟩ := classical.some_spec (H.has_min p h) in h theorem not_lt_min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) {x} (xp : x ∈ p) : ¬ r x (H.min p h) := let ⟨_, h'⟩ := classical.some_spec (H.has_min p h) in h' _ xp open set protected noncomputable def sup {α} {r : α → α → Prop} (wf : well_founded r) (s : set α) (h : bounded r s) : α := wf.min { x | ∀a ∈ s, r a x } (ne_empty_iff_exists_mem.mpr h) protected def lt_sup {α} {r : α → α → Prop} (wf : well_founded r) {s : set α} (h : bounded r s) {x} (hx : x ∈ s) : r x (wf.sup s h) := min_mem wf { x | ∀a ∈ s, r a x } (ne_empty_iff_exists_mem.mpr h) x hx section local attribute [instance, priority 0] classical.prop_decidable protected noncomputable def succ {α} {r : α → α → Prop} (wf : well_founded r) (x : α) : α := if h : ∃y, r x y then wf.min { y | r x y } (ne_empty_iff_exists_mem.mpr h) else x protected lemma lt_succ {α} {r : α → α → Prop} (wf : well_founded r) {x : α} (h : ∃y, r x y) : r x (wf.succ x) := by { rw [well_founded.succ, dif_pos h], apply min_mem } end protected lemma lt_succ_iff {α} {r : α → α → Prop} [wo : is_well_order α r] {x : α} (h : ∃y, r x y) (y : α) : r y (wo.wf.succ x) ↔ r y x ∨ y = x := begin split, { intro h', have : ¬r x y, { intro hy, rw [well_founded.succ, dif_pos] at h', exact wo.wf.not_lt_min _ (ne_empty_iff_exists_mem.mpr h) hy h' }, rcases trichotomous_of r x y with hy | hy | hy, exfalso, exact this hy, right, exact hy.symm, left, exact hy }, rintro (hy | rfl), exact trans hy (wo.wf.lt_succ h), exact wo.wf.lt_succ h end end well_founded variable (r) local infix ` ≼ ` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, x ≼ z ∧ y ≼ z theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) := by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl) theorem directed_comp {ι} (f : ι → β) (g : β → α) : directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl theorem directed_mono {s : α → α → Prop} {ι} (f : ι → α) (H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f := λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩ class directed_order (α : Type u) extends preorder α := (directed : ∀ i j : α, ∃ k, i ≤ k ∧ j ≤ k)
3b1cb6cfecf5d4880f730d0ef6af7e3c3f1d4f23
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/order/order_iso.lean
c5b93cb816af135dffeda1a3dfeb0ba9612b4d7a
[ "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
13,845
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import order.basic logic.embedding data.nat.basic open function universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} /-- An increasing function is injective -/ lemma injective_of_increasing (r : α → α → Prop) (s : β → β → Prop) [is_trichotomous α r] [is_irrefl β s] (f : α → β) (hf : ∀{x y}, r x y → s (f x) (f y)) : injective f := begin intros x y hxy, rcases trichotomous_of r x y with h | h | h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this, exact h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this end /-- An order embedding with respect to a given pair of orders `r` and `s` is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. -/ structure order_embedding {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ↪ β := (ord : ∀ {a b}, r a b ↔ s (to_embedding a) (to_embedding b)) infix ` ≼o `:25 := order_embedding /-- the induced order on a subtype is an embedding under the natural inclusion. -/ definition subtype.order_embedding {X : Type*} (r : X → X → Prop) (p : X → Prop) : ((subtype.val : subtype p → X) ⁻¹'o r) ≼o r := ⟨⟨subtype.val,subtype.val_injective⟩,by intros;refl⟩ theorem preimage_equivalence {α β} (f : α → β) {s : β → β → Prop} (hs : equivalence s) : equivalence (f ⁻¹'o s) := ⟨λ a, hs.1 _, λ a b h, hs.2.1 h, λ a b c h₁ h₂, hs.2.2 h₁ h₂⟩ namespace order_embedding instance : has_coe_to_fun (r ≼o s) := ⟨λ _, α → β, λ o, o.to_embedding⟩ theorem ord' : ∀ (f : r ≼o s) {a b}, r a b ↔ s (f a) (f b) | ⟨f, o⟩ := @o @[simp] theorem coe_fn_mk (f : α ↪ β) (o) : (@order_embedding.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_embedding (f : r ≼o s) : (f.to_embedding : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : r ≼o s}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨⟨f₁, h₁⟩, o₁⟩ ⟨⟨f₂, h₂⟩, o₂⟩ h := by congr; exact h @[refl] protected def refl (r : α → α → Prop) : r ≼o r := ⟨embedding.refl _, λ a b, iff.rfl⟩ @[trans] protected def trans (f : r ≼o s) (g : s ≼o t) : r ≼o t := ⟨f.1.trans g.1, λ a b, by rw [f.2, g.2]; simp⟩ @[simp] theorem refl_apply (x : α) : order_embedding.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≼o s) (g : s ≼o t) (a : α) : (f.trans g) a = g (f a) := rfl /-- An order embedding is also an order embedding between dual orders. -/ def rsymm (f : r ≼o s) : swap r ≼o swap s := ⟨f.to_embedding, λ a b, f.ord'⟩ /-- If `f` is injective, then it is an order embedding from the preimage order of `s` to `s`. -/ def preimage (f : α ↪ β) (s : β → β → Prop) : f ⁻¹'o s ≼o s := ⟨f, λ a b, iff.rfl⟩ theorem eq_preimage (f : r ≼o s) : r = f ⁻¹'o s := by funext a b; exact propext f.ord' protected theorem is_irrefl : ∀ (f : r ≼o s) [is_irrefl β s], is_irrefl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a h, H _ (o.1 h)⟩ protected theorem is_refl : ∀ (f : r ≼o s) [is_refl β s], is_refl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a, o.2 (H _)⟩ protected theorem is_symm : ∀ (f : r ≼o s) [is_symm β s], is_symm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h, o.2 (H _ _ (o.1 h))⟩ protected theorem is_asymm : ∀ (f : r ≼o s) [is_asymm β s], is_asymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, H _ _ (o.1 h₁) (o.1 h₂)⟩ protected theorem is_antisymm : ∀ (f : r ≼o s) [is_antisymm β s], is_antisymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, f.inj' (H _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_trans : ∀ (f : r ≼o s) [is_trans β s], is_trans α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b c h₁ h₂, o.2 (H _ _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_total : ∀ (f : r ≼o s) [is_total β s], is_total α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o o).2 (H _ _)⟩ protected theorem is_preorder : ∀ (f : r ≼o s) [is_preorder β s], is_preorder α r | f H := by exactI {..f.is_refl, ..f.is_trans} protected theorem is_partial_order : ∀ (f : r ≼o s) [is_partial_order β s], is_partial_order α r | f H := by exactI {..f.is_preorder, ..f.is_antisymm} protected theorem is_linear_order : ∀ (f : r ≼o s) [is_linear_order β s], is_linear_order α r | f H := by exactI {..f.is_partial_order, ..f.is_total} protected theorem is_strict_order : ∀ (f : r ≼o s) [is_strict_order β s], is_strict_order α r | f H := by exactI {..f.is_irrefl, ..f.is_trans} protected theorem is_trichotomous : ∀ (f : r ≼o s) [is_trichotomous β s], is_trichotomous α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o (or_congr f.inj'.eq_iff.symm o)).2 (H _ _)⟩ protected theorem is_strict_total_order' : ∀ (f : r ≼o s) [is_strict_total_order' β s], is_strict_total_order' α r | f H := by exactI {..f.is_trichotomous, ..f.is_strict_order} protected theorem acc (f : r ≼o s) (a : α) : acc s (f a) → acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, λ a' h, IH (f a') (f.ord'.1 h) _ rfl⟩ end protected theorem well_founded : ∀ (f : r ≼o s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ protected theorem is_well_order : ∀ (f : r ≼o s) [is_well_order β s], is_well_order α r | f H := by exactI {wf := f.well_founded H.wf, ..f.is_strict_total_order'} /-- It suffices to prove `f` is monotone between strict orders to show it is an order embedding. -/ def of_monotone [is_trichotomous α r] [is_asymm β s] (f : α → β) (H : ∀ a b, r a b → s (f a) (f b)) : r ≼o s := begin haveI := @is_irrefl_of_is_asymm β s _, refine ⟨⟨f, λ a b e, _⟩, λ a b, ⟨H _ _, λ h, _⟩⟩, { refine ((@trichotomous _ r _ a b).resolve_left _).resolve_right _; exact λ h, @irrefl _ s _ _ (by simpa [e] using H _ _ h) }, { refine (@trichotomous _ r _ a b).resolve_right (or.rec (λ e, _) (λ h', _)), { subst e, exact irrefl _ h }, { exact asymm (H _ _ h') h } } end @[simp] theorem of_monotone_coe [is_trichotomous α r] [is_asymm β s] (f : α → β) (H) : (@of_monotone _ _ r s _ _ f H : α → β) = f := rfl -- If le is preserved by an order embedding of preorders, then lt is too def lt_embedding_of_le_embedding [preorder α] [preorder β] (f : (has_le.le : α → α → Prop) ≼o (has_le.le : β → β → Prop)) : (has_lt.lt : α → α → Prop) ≼o (has_lt.lt : β → β → Prop) := { to_fun := f, inj := f.inj, ord := by intros; simp [lt_iff_le_not_le,f.ord] } def nat_lt [is_strict_order α r] (f : ℕ → α) (H : ∀ n:ℕ, r (f n) (f (n+1))) : ((<) : ℕ → ℕ → Prop) ≼o r := of_monotone f $ λ a b h, begin induction b with b IH, {exact (nat.not_lt_zero _ h).elim}, cases nat.lt_succ_iff_lt_or_eq.1 h with h e, { exact trans (IH h) (H _) }, { subst b, apply H } end def nat_gt [is_strict_order α r] (f : ℕ → α) (H : ∀ n:ℕ, r (f (n+1)) (f n)) : ((>) : ℕ → ℕ → Prop) ≼o r := by haveI := is_strict_order.swap r; exact rsymm (nat_lt f H) theorem well_founded_iff_no_descending_seq [is_strict_order α r] : well_founded r ↔ ¬ nonempty (((>) : ℕ → ℕ → Prop) ≼o r) := ⟨λ ⟨h⟩ ⟨⟨f, o⟩⟩, suffices ∀ a, acc r a → ∀ n, a ≠ f n, from this (f 0) (h _) 0 rfl, λ a ac, begin induction ac with a _ IH, intros n h, subst a, exact IH (f (n+1)) (o.1 (nat.lt_succ_self _)) _ rfl end, λ N, ⟨λ a, classical.by_contradiction $ λ na, let ⟨f, h⟩ := classical.axiom_of_choice $ show ∀ x : {a // ¬ acc r a}, ∃ y : {a // ¬ acc r a}, r y.1 x.1, from λ ⟨x, h⟩, classical.by_contradiction $ λ hn, h $ ⟨_, λ y h, classical.by_contradiction $ λ na, hn ⟨⟨y, na⟩, h⟩⟩ in N ⟨nat_gt (λ n, (f^[n] ⟨a, na⟩).1) $ λ n, by rw nat.iterate_succ'; apply h⟩⟩⟩ end order_embedding /-- The inclusion map `fin n → ℕ` is an order embedding. -/ def fin.val.order_embedding (n) : @order_embedding (fin n) ℕ (<) (<) := ⟨⟨fin.val, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩ /-- The inclusion map `fin m → fin n` is an order embedding. -/ def fin_fin.order_embedding {m n} (h : m ≤ n) : @order_embedding (fin m) (fin n) (<) (<) := ⟨⟨λ ⟨x, h'⟩, ⟨x, lt_of_lt_of_le h' h⟩, λ ⟨a, _⟩ ⟨b, _⟩ h, by congr; injection h⟩, by intros; cases a; cases b; refl⟩ instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) := (fin.val.order_embedding _).is_well_order /-- An order isomorphism is an equivalence that is also an order embedding. -/ structure order_iso {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ≃ β := (ord : ∀ {a b}, r a b ↔ s (to_equiv a) (to_equiv b)) infix ` ≃o `:25 := order_iso namespace order_iso def to_order_embedding (f : r ≃o s) : r ≼o s := ⟨f.to_equiv.to_embedding, f.ord⟩ instance : has_coe (r ≃o s) (r ≼o s) := ⟨to_order_embedding⟩ theorem coe_coe_fn (f : r ≃o s) : ((f : r ≼o s) : α → β) = f := rfl @[simp] lemma to_equiv_to_fun (f : r ≃o s) (x : α) : f.to_equiv.to_fun x = f x := rfl theorem ord' : ∀ (f : r ≃o s) {a b}, r a b ↔ s (f a) (f b) | ⟨f, o⟩ := @o lemma ord'' {r : α → α → Prop} {s : β → β → Prop} (f : r ≃o s) {x y : α} : r x y ↔ s ((↑f : r ≼o s) x) ((↑f : r ≼o s) y) := f.ord' @[simp] theorem coe_fn_mk (f : α ≃ β) (o) : (@order_iso.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_equiv (f : r ≃o s) : (f.to_equiv : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : r ≃o s}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨e₁, o₁⟩ ⟨e₂, o₂⟩ h := by congr; exact equiv.eq_of_to_fun_eq h @[refl] protected def refl (r : α → α → Prop) : r ≃o r := ⟨equiv.refl _, λ a b, iff.rfl⟩ @[symm] protected def symm (f : r ≃o s) : s ≃o r := ⟨f.to_equiv.symm, λ a b, by cases f with f o; rw o; simp⟩ @[trans] protected def trans (f₁ : r ≃o s) (f₂ : s ≃o t) : r ≃o t := ⟨f₁.to_equiv.trans f₂.to_equiv, λ a b, by cases f₁ with f₁ o₁; cases f₂ with f₂ o₂; rw [o₁, o₂]; simp⟩ @[simp] theorem coe_fn_symm_mk (f o) : ((@order_iso.mk _ _ r s f o).symm : β → α) = f.symm := rfl @[simp] theorem refl_apply (x : α) : order_iso.refl r x = x := rfl @[simp] theorem trans_apply : ∀ (f : r ≃o s) (g : s ≃o t) (a : α), (f.trans g) a = g (f a) | ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ a := equiv.trans_apply _ _ _ @[simp] theorem apply_symm_apply : ∀ (e : r ≃o s) (x : β), e (e.symm x) = x | ⟨f₁, o₁⟩ x := by simp @[simp] theorem symm_apply_apply : ∀ (e : r ≃o s) (x : α), e.symm (e x) = x | ⟨f₁, o₁⟩ x := by simp /-- Any equivalence lifts to an order isomorphism between `s` and its preimage. -/ def preimage (f : α ≃ β) (s : β → β → Prop) : f ⁻¹'o s ≃o s := ⟨f, λ a b, iff.rfl⟩ noncomputable def of_surjective (f : r ≼o s) (H : surjective f) : r ≃o s := ⟨equiv.of_bijective ⟨f.inj, H⟩, by simp [f.ord']⟩ @[simp] theorem of_surjective_coe (f : r ≼o s) (H) : (of_surjective f H : α → β) = f := by delta of_surjective; simp def sum_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) : sum.lex r₁ s₁ ≃o sum.lex r₂ s₂ := ⟨equiv.sum_congr e₁.to_equiv e₂.to_equiv, λ a b, by cases e₁ with f hf; cases e₂ with g hg; cases a; cases b; simp [hf, hg]⟩ def prod_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) : prod.lex r₁ s₁ ≃o prod.lex r₂ s₂ := ⟨equiv.prod_congr e₁.to_equiv e₂.to_equiv, λ a b, begin cases e₁ with f hf; cases e₂ with g hg, cases a with a₁ a₂; cases b with b₁ b₂, suffices : prod.lex r₁ s₁ (a₁, a₂) (b₁, b₂) ↔ prod.lex r₂ s₂ (f a₁, g a₂) (f b₁, g b₂), {simpa [hf, hg]}, split, { intro h, cases h with _ _ _ _ h _ _ _ h, { left, exact hf.1 h }, { right, exact hg.1 h } }, { generalize e : f b₁ = fb₁, intro h, cases h with _ _ _ _ h _ _ _ h, { subst e, left, exact hf.2 h }, { have := f.injective e, subst b₁, right, exact hg.2 h } } end⟩ end order_iso /-- A subset `p : set α` embeds into `α` -/ def set_coe_embedding {α : Type*} (p : set α) : p ↪ α := ⟨subtype.val, @subtype.eq _ _⟩ /-- `subrel r p` is the inherited relation on a subset. -/ def subrel (r : α → α → Prop) (p : set α) : p → p → Prop := @subtype.val _ p ⁻¹'o r @[simp] theorem subrel_val (r : α → α → Prop) (p : set α) {a b} : subrel r p a b ↔ r a.1 b.1 := iff.rfl namespace subrel protected def order_embedding (r : α → α → Prop) (p : set α) : subrel r p ≼o r := ⟨set_coe_embedding _, λ a b, iff.rfl⟩ @[simp] theorem order_embedding_apply (r : α → α → Prop) (p a) : subrel.order_embedding r p a = a.1 := rfl instance (r : α → α → Prop) [is_well_order α r] (p : set α) : is_well_order p (subrel r p) := order_embedding.is_well_order (subrel.order_embedding r p) end subrel /-- Restrict the codomain of an order embedding -/ def order_embedding.cod_restrict (p : set β) (f : r ≼o s) (H : ∀ a, f a ∈ p) : r ≼o subrel s p := ⟨f.to_embedding.cod_restrict p H, f.ord⟩ @[simp] theorem order_embedding.cod_restrict_apply (p) (f : r ≼o s) (H a) : order_embedding.cod_restrict p f H a = ⟨f a, H a⟩ := rfl
f9fcaeb99c3bc368f5349aa7ef3263f70d0ce71f
3ed5a65c1ab3ce5d1a094edce8fa3287980f197b
/src/herstein/ex2_5/Q_04.lean
c9a2d769b3ebf4284cf233a8649d8bc85baee66a
[]
no_license
group-study-group/herstein
35d32e77158efa2cc303c84e1ee5e3bc80831137
f5a1a72eb56fa19c19ece0cb3ab6cf7ffd161f66
refs/heads/master
1,586,202,191,519
1,548,969,759,000
1,548,969,759,000
157,746,953
0
0
null
1,542,412,901,000
1,542,302,366,000
Lean
UTF-8
Lean
false
false
1,527
lean
import algebra.group import group_theory.subgroup variables {G: Type*} {H: set G} {a: G} theorem Q_04a [hG: group G] [hH: is_subgroup H]: is_subgroup ((λ h, a * h * a⁻¹) '' H) := { inv_mem := λ g ⟨h, ⟨hH, ha⟩⟩, begin -- inverse of aha⁻¹ is ah⁻¹a⁻¹ ... have inv_g: g⁻¹ = a * h⁻¹ * a⁻¹, from ha ▸ calc (a * h * a⁻¹)⁻¹ = (a⁻¹)⁻¹ * h⁻¹ * a⁻¹ : by rw [mul_inv_rev, mul_inv_rev, ←mul_assoc] ... = a * h⁻¹ * a⁻¹ : by rw inv_inv, -- ... and ah⁻¹a⁻¹ is in aHa⁻¹. have t: a * h⁻¹ * a⁻¹ ∈ ((λ h, a * h * a⁻¹) '' H), from ⟨h⁻¹, ⟨is_subgroup.inv_mem hH, rfl⟩⟩, exact inv_g.symm ▸ t, end, -- the identity is in aHa⁻¹: 1 = a1a⁻¹. one_mem := ⟨1, ⟨ hH.one_mem, calc a * 1 * a⁻¹ = 1: by rw [mul_one, mul_right_inv a] ⟩⟩, -- multiplication in aHa⁻¹ is closed because ah₁a⁻¹ * ah₂a⁻¹ = ah₁h₂a⁻¹. mul_mem := λ g₁ g₂ ⟨h₁, ⟨hh₁, hg₁⟩⟩ ⟨h₂, ⟨hh₂, hg₂⟩⟩, ⟨h₁ * h₂, ⟨ is_submonoid.mul_mem hh₁ hh₂, hg₁ ▸ hg₂ ▸ calc a * (h₁ * h₂) * a⁻¹ = a * h₁ * 1 * (h₂ * a⁻¹) : by rw [←mul_assoc, mul_assoc, mul_one] ... = a * h₁ * (a⁻¹ * a) * (h₂ * a⁻¹) : by rw mul_left_inv ... = (a * h₁ * a⁻¹) * a * (h₂ * a⁻¹) : by rw ←(mul_assoc (a * h₁) a⁻¹ a) ... = (a * h₁ * a⁻¹) * (a * h₂ * a⁻¹) : by rw [mul_assoc, mul_assoc a h₂ a⁻¹], ⟩⟩, }
5bc16c4dba128f1ce0a323d8d0736ed05dd7079a
7c2dd01406c42053207061adb11703dc7ce0b5e5
/src/solutions/06_sub_sequences.lean
cb7e921172f3aaeb186463742816b2181f778ae1
[ "Apache-2.0" ]
permissive
leanprover-community/tutorials
50ec79564cbf2ad1afd1ac43d8ee3c592c2883a8
79a6872a755c4ae0c2aca57e1adfdac38b1d8bb1
refs/heads/master
1,687,466,144,386
1,672,061,276,000
1,672,061,276,000
189,169,918
186
81
Apache-2.0
1,686,350,300,000
1,559,113,678,000
Lean
UTF-8
Lean
false
false
4,803
lean
import tuto_lib /- This file continues the elementary study of limits of sequences. It can be skipped if the previous file was too easy, it won't introduce any new tactic or trick. Remember useful lemmas: abs_le {x y : ℝ} : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y abs_add (x y : ℝ) : |x + y| ≤ |x| + |y| abs_sub_comm (x y : ℝ) : |x - y| = |y - x| ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q le_max_left p q : p ≤ max p q le_max_right p q : q ≤ max p q and the definition: def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε You can also use a property proved in the previous file: unique_limit : seq_limit u l → seq_limit u l' → l = l' def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m -/ variable { φ : ℕ → ℕ} /- The next lemma is proved by an easy induction, but we haven't seen induction in this tutorial. If you did the natural number game then you can delete the proof below and try to reconstruct it. -/ /-- An extraction is greater than id -/ lemma id_le_extraction' : extraction φ → ∀ n, n ≤ φ n := begin intros hyp n, induction n with n hn, { exact nat.zero_le _ }, { exact nat.succ_le_of_lt (by linarith [hyp n (n+1) (by linarith)]) }, end /-- Extractions take arbitrarily large values for arbitrarily large inputs. -/ -- 0039 lemma extraction_ge : extraction φ → ∀ N N', ∃ n ≥ N', φ n ≥ N := begin -- sorry intros h N N', use max N N', split, apply le_max_right, calc N ≤ max N N' : by apply le_max_left ... ≤ φ (max N N') : by apply id_le_extraction' h -- sorry end /-- A real number `a` is a cluster point of a sequence `u` if `u` has a subsequence converging to `a`. def cluster_point (u : ℕ → ℝ) (a : ℝ) := ∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a -/ variables {u : ℕ → ℝ} {a l : ℝ} /- In the exercise, we use `∃ n ≥ N, ...` which is the abbreviation of `∃ n, n ≥ N ∧ ...`. Lean can read this abbreviation, but displays it as the confusing: `∃ (n : ℕ) (H : n ≥ N)` One gets used to it. Alternatively, one can get rid of it using the lemma exists_prop {p q : Prop} : (∃ (h : p), q) ↔ p ∧ q -/ /-- If `a` is a cluster point of `u` then there are values of `u` arbitrarily close to `a` for arbitrarily large input. -/ -- 0040 lemma near_cluster : cluster_point u a → ∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε := begin -- sorry intros hyp ε ε_pos N, rcases hyp with ⟨φ, φ_extr, hφ⟩, cases hφ ε ε_pos with N' hN', rcases extraction_ge φ_extr N N' with ⟨q, hq, hq'⟩, exact ⟨φ q, hq', hN' _ hq⟩, -- sorry end /- The above exercice can be done in five lines. Hint: you can use the anonymous constructor syntax when proving existential statements. -/ /-- If `u` tends to `l` then its subsequences tend to `l`. -/ -- 0041 lemma subseq_tendsto_of_tendsto' (h : seq_limit u l) (hφ : extraction φ) : seq_limit (u ∘ φ) l := begin -- sorry intros ε ε_pos, cases h ε ε_pos with N hN, use N, intros n hn, apply hN, calc N ≤ n : hn ... ≤ φ n : id_le_extraction' hφ n, -- sorry end /-- If `u` tends to `l` all its cluster points are equal to `l`. -/ -- 0042 lemma cluster_limit (hl : seq_limit u l) (ha : cluster_point u a) : a = l := begin -- sorry rcases ha with ⟨φ, φ_extr, lim_u_φ⟩, have lim_u_φ' : seq_limit (u ∘ φ) l, from subseq_tendsto_of_tendsto' hl φ_extr, exact unique_limit lim_u_φ lim_u_φ', -- sorry end /-- Cauchy_sequence sequence -/ def cauchy_sequence (u : ℕ → ℝ) := ∀ ε > 0, ∃ N, ∀ p q, p ≥ N → q ≥ N → |u p - u q| ≤ ε -- 0043 example : (∃ l, seq_limit u l) → cauchy_sequence u := begin -- sorry intro hyp, cases hyp with l hl, intros ε ε_pos, cases hl (ε/2) (by linarith) with N hN, use N, intros p q hp hq, calc |u p - u q| = |(u p - l) + (l - u q)| : by ring_nf ... ≤ |u p - l| + |l - u q| : by apply abs_add ... = |u p - l| + |u q - l| : by rw abs_sub_comm (u q) l ... ≤ ε : by linarith [hN p hp, hN q hq], -- sorry end /- In the next exercise, you can reuse near_cluster : cluster_point u a → ∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε -/ -- 0044 example (hu : cauchy_sequence u) (hl : cluster_point u l) : seq_limit u l := begin -- sorry intros ε ε_pos, cases hu (ε/2) (by linarith) with N hN, use N, have clef : ∃ N' ≥ N, |u N' - l| ≤ ε/2, apply near_cluster hl (ε/2) (by linarith), cases clef with N' h, cases h with hNN' hN', intros n hn, calc |u n - l| = |(u n - u N') + (u N' - l)| : by ring ... ≤ |u n - u N'| + |u N' - l| : by apply abs_add ... ≤ ε : by linarith [hN n N' (by linarith) hNN'], -- sorry end
c743834edcabe9d2e5902879df04564d2d36bec5
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/multiset/basic.lean
b82baf002f6e9b6a41f4e2281b378388244fad48
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
87,331
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.list.perm import algebra.group_power /-! # Multisets These are implemented as the quotient of a list by permutations. ## Notation We define the global infix notation `::ₘ` for `multiset.cons`. -/ open list subtype nat variables {α : Type*} {β : Type*} {γ : Type*} /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.is_setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /-- defines a size for a multiset by referring to the size of the underlying list -/ protected def sizeof [has_sizeof α] (s : multiset α) : ℕ := quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩ /- empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /- cons -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound (p.cons a)) infixr ` ::ₘ `:67 := multiset.cons instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a ::ₘ s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a ::ₘ l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a ::ₘ 0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a ::ₘ s = b ::ₘ s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a ::ₘ s = a ::ₘ t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, h.rec_heq (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a ::ₘ m)} {C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a ::ₘ m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b ::ₘ s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a ::ₘ s := mem_cons.2 (or.inl rfl) theorem forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} : (∀ x ∈ (a ::ₘ s), p x) ↔ p a ∧ ∀ x ∈ s, p x := quotient.induction_on' s $ λ L, list.forall_mem_cons theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a ::ₘ t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s := ⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩ theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a ::ₘ m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a ::ₘ m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a ::ₘ as = b ::ₘ bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b ::ₘ cs ∧ bs = a ::ₘ cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b ::ₘ bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a ::ₘ as = b ::ₘ a ::ₘ cs, by simp [eq, hcs], have : a ::ₘ as = a ::ₘ b ::ₘ cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /- subset -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a ::ₘ s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset section to_list /-- Produces a list of the elements in the multiset using choice. -/ @[reducible] noncomputable def to_list {α : Type*} (s : multiset α) := classical.some (quotient.exists_rep s) @[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] := (multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero)) lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s := classical.some_spec (quotient.exists_rep _) lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s := by rw [←multiset.mem_coe, multiset.coe_to_list] end to_list /- multiset order -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, (nil_sublist l).subperm theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a ::ₘ s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨(sublist_cons _ _).subperm, λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a ::ₘ s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a ::ₘ s ≤ a ::ₘ t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a ::ₘ t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a ::ₘ s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ ((sublist_or_mem_of_sublist s).resolve_right m₁).subperm) end /- cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm.length_eq @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[simp] theorem card_cons (a : α) (s : multiset α) : card (a ::ₘ s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a ::ₘ 0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a ::ₘ s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a ::ₘ s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /- singleton -/ instance : has_singleton α (multiset α) := ⟨λ a, a ::ₘ 0⟩ instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a ::ₘ 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a ::ₘ 0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a ::ₘ 0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a ::ₘ 0 = b ::ₘ 0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a ::ₘ 0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a ::ₘ 0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a ::ₘ 0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /- add -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a ::ₘ s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_add_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } @[simp] theorem cons_add (a : α) (s t : multiset α) : a ::ₘ s + t = a ::ₘ (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a ::ₘ t = a ::ₘ (s + t) := by rw [add_comm, cons_add, add_comm] theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append lemma card_smul (s : multiset α) (n : ℕ) : (n •ℕ s).card = n * s.card := by induction n; simp [succ_nsmul, *, nat.succ_mul]; cc @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_add_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, bot := 0, bot_le := multiset.zero_le, ..multiset.ordered_cancel_add_comm_monoid } /- repeat -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a ::ₘ repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a ::ₘ 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a ::ₘ 0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩ /- erase -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (p.erase a)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a ::ₘ s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp, priority 990] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b ::ₘ s).erase a = b ::ₘ s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp, priority 980] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp, priority 980] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a ::ₘ s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, (erase_sublist a l).subperm @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a ::ₘ t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s := λ h, card_lt_of_lt (erase_lt.mpr h) theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s := card_le_of_le (erase_le a s) end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- map -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (p.map f)) theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} : (∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) := quotient.induction_on' s $ λ L, list.forall_mem_map_iff @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a ::ₘ s) = f a ::ₘ map f s := quot.induction_on s $ λ l, rfl lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by { induction k, simp, simpa } @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ instance (f : α → β) : is_add_monoid_hom (map f) := { map_add := map_add _, map_zero := map_zero _ } theorem map_nsmul (f : α → β) (n s) : map f (n •ℕ s) = n •ℕ map f s := (add_monoid_hom.of (map f)).map_nsmul _ _ @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ @[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero] theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_injective H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /- fold -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, p.foldl_eq H b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a ::ₘ s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, p.foldr_eq H b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a ::ₘ s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ @[to_additive] def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 @[to_additive] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ attribute [norm_cast] coe_prod coe_sum @[simp, to_additive] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a ::ₘ s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive] theorem prod_singleton [comm_monoid α] (a : α) : prod (a ::ₘ 0) = a := by simp @[simp, to_additive] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) := { map_add := sum_add, map_zero := sum_zero } lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) : ∀n, (n •ℕ m).prod = m.prod ^ n | 0 := rfl | (n + 1) := by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_smul n] @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n •ℕ a := @prod_repeat (multiplicative α) _ attribute [to_additive] prod_repeat lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := by simp lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := by simp attribute [to_additive] prod_map_one @[simp, to_additive] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) theorem prod_ne_zero {R : Type*} [integral_domain R] {m : multiset R} : (∀ x ∈ m, (x : _) ≠ 0) → m.prod ≠ 0 := multiset.induction_on m (λ _, one_ne_zero) $ λ hd tl ih H, by { rw forall_mem_cons at H, rw prod_cons, exact mul_ne_zero H.1 (ih H.2) } lemma prod_eq_zero {α : Type*} [comm_semiring α] {s : multiset α} (h : (0 : α) ∈ s) : multiset.prod s = 0 := begin rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩, simp [hs', multiset.prod_cons] end @[to_additive] lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α →* β) : (s.map f).prod = f s.prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod] @[to_additive] theorem prod_hom_rel [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (s.map f).prod (s.map g).prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod] lemma dvd_prod [comm_monoid α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a theorem prod_eq_zero_iff [comm_cancel_monoid_with_zero α] [nontrivial α] {s : multiset α} : s.prod = 0 ↔ (0 : α) ∈ s := multiset.induction_on s (by simp) $ assume a s, by simp [mul_eq_zero, @eq_comm _ 0 a] {contextual := tt} @[to_additive sum_nonneg] lemma one_le_prod_of_one_le [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → 1 ≤ m.prod := quotient.induction_on m $ λ l hl, by simpa using list.one_le_prod_of_one_le hl @[to_additive] lemma single_le_prod [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → ∀ x ∈ m, x ≤ m.prod := quotient.induction_on m $ λ l hl x hx, by simpa using list.single_le_prod hl x hx @[to_additive all_zero_of_le_zero_le_of_sum_eq_zero] lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → m.prod = 1 → (∀ x ∈ m, x = (1 : α)) := begin apply quotient.induction_on m, simp only [quot_mk_to_coe, coe_prod, mem_coe], intros l hl₁ hl₂ x hx, apply all_one_of_le_one_le_of_prod_eq_one hl₁ hl₂ _ hx, end lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] {m : multiset α} : m.sum = 0 ↔ ∀ x ∈ m, x = (0 : α) := quotient.induction_on m $ λ l, by simpa using list.sum_eq_zero_iff l 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 : multiset α) : f s.sum ≤ (s.map f).sum := multiset.induction_on s (le_of_eq h_zero) $ assume a s ih, by rw [sum_cons, map_cons, sum_cons]; from le_trans (h_add a s.sum) (add_le_add_left ih _) lemma abs_sum_le_sum_abs [linear_ordered_field α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum := multiset.induction_on s (λ _, dvd_zero _) (λ x s ih h, by rw sum_cons; exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy))))) @[simp] theorem sum_map_singleton (s : multiset α) : (s.map (λ a, a ::ₘ 0)).sum = s := multiset.induction_on s (by simp) (by simp) /-! ### Join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s ::ₘ S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /- bind -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a ::ₘ s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a ::ₘ g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /- product -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a ::ₘ s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a ::ₘ 0) (b ::ₘ 0) = (a,b) ::ₘ 0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp; cc @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /- sigma -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a ::ₘ s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a ::ₘ 0).sigma (λ a, b a ::ₘ 0) = ⟨a, b a⟩ ::ₘ 0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp; cc @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /- map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ pp.pmap f @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a ::ₘ m, p b), pmap f (a ::ₘ m) h = f a (h a (mem_cons_self a m)) ::ₘ pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) : sizeof x < sizeof s := by { induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl } theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a ::ₘ m).attach = ⟨a, mem_cons_self a m⟩ ::ₘ (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /- subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.diff p₂ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) } @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a ::ₘ t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] @[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) @[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /- union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /- inter -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.bag_inter p₂ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a ::ₘ s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, (bag_inter_sublist_left _ _).subperm theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∪ t) = (a ::ₘ s) ∪ (a ::ₘ t) := by simpa using add_union_distrib (a ::ₘ 0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∩ t) = (a ::ₘ s) ∩ (a ::ₘ t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /- filter -/ section variables {p : α → Prop} [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ h.filter p) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a ::ₘ s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, (filter_sublist _).subperm @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, (filter_sublist_filter h).subperm theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩ @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a ::ₘ erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter $ inter_le_left _ _) (filter_le_filter $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _) (filter_le _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter l theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] /- filter_map -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $ h.filter_map f) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a ::ₘ s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a ::ₘ s) = b ::ₘ filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm /-! ### countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a ::ₘ s) = countp p s + 1 := quot.induction_on s countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a ::ₘ s) = countp p s := quot.induction_on s countp_cons_of_neg theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) := { map_add := countp_add, map_zero := countp_zero _ } theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h) @[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] end /- count -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a ::ₘ s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b ::ₘ s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b ::ₘ s) := count_le_of_le _ (le_cons_self _ _) theorem count_cons (a b : α) (s : multiset α) : count a (b ::ₘ s) = count a s + (if a = b then 1 else 0) := by by_cases h : a = b; simp [h] theorem count_singleton (a : α) : count a (a ::ₘ 0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) := countp.is_add_monoid_hom @[simp] theorem count_smul (a : α) (n s) : count a (n •ℕ s) = n * count a s := by induction n; simp [*, succ_nsmul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s := by simp [ne.def, count_eq_zero] @[simp] theorem count_repeat_self (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] theorem count_repeat (a b : α) (n : ℕ) : count a (repeat b n) = if (a = b) then n else 0 := begin split_ifs with h₁, { rw [h₁, count_repeat_self] }, { rw [count_eq_zero], apply mt eq_of_mem_repeat h₁ }, end @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a ::ₘ erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp, priority 980] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_sum {m : multiset β} {f : β → multiset α} {a : α} : count a (map f m).sum = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) ( by simp) lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := count_sum theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter_of_pos {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h @[simp] theorem count_filter_of_neg {p} [decidable_pred p] {a} {s : multiset α} (h : ¬ p a) : count a (filter p s) = 0 := multiset.count_eq_zero_of_not_mem (λ t, h (of_mem_filter t)) theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[ext] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp only [max_min_distrib_left, multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter], ..multiset.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } end /- relator -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a ::ₘ as) (b ::ₘ bs) mk_iff_of_inductive_prop multiset.rel multiset.rel_iff variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a ::ₘ as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b ::ₘ bs') := begin split, { generalize hm : a ::ₘ as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b ::ₘ bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b ::ₘ bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a ::ₘ as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono h lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff] theorem map_injective {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a ::ₘ t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /- disjoint -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp, priority 1100] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a ::ₘ 0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp, priority 1100] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a ::ₘ 0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := by rw [disjoint_comm, disjoint_add_left]; tauto @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a ::ₘ s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a ::ₘ 0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a ::ₘ t) ↔ a ∉ s ∧ disjoint s t := by rw [disjoint_comm, disjoint_cons_left]; tauto theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := begin simp [disjoint], split, from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm, from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁) end /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h) (assume h, ⟨l, rfl, h⟩) end multiset namespace multiset section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns that `a`. -/ def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose variable (α) /-- The equivalence between lists and multisets of a subsingleton type. -/ def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } end multiset @[to_additive] theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) : f s.prod = (s.map f).prod := (s.prod_hom f).symm
6276547f5ceffeb89e57eefbc573e4cb59d296f6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/creates.lean
d76fccd7697586e77c10dee949b9c5127e516eac
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
28,477
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.preserves.basic /-! # Creating (co)limits We say that `F` creates limits of `K` if, given any limit cone `c` for `K ⋙ F` (i.e. below) we can lift it to a cone "above", and further that `F` reflects limits for `K`. -/ open category_theory category_theory.limits noncomputable theory namespace category_theory universes w' w v₁ v₂ v₃ u₁ u₂ u₃ variables {C : Type u₁} [category.{v₁} C] section creates variables {D : Type u₂} [category.{v₂} D] variables {J : Type w} [category.{w'} J] {K : J ⥤ C} /-- Define the lift of a cone: For a cone `c` for `K ⋙ F`, give a cone for `K` which is a lift of `c`, i.e. the image of it under `F` is (iso) to `c`. We will then use this as part of the definition of creation of limits: every limit cone has a lift. Note this definition is really only useful when `c` is a limit already. -/ structure liftable_cone (K : J ⥤ C) (F : C ⥤ D) (c : cone (K ⋙ F)) := (lifted_cone : cone K) (valid_lift : F.map_cone lifted_cone ≅ c) /-- Define the lift of a cocone: For a cocone `c` for `K ⋙ F`, give a cocone for `K` which is a lift of `c`, i.e. the image of it under `F` is (iso) to `c`. We will then use this as part of the definition of creation of colimits: every limit cocone has a lift. Note this definition is really only useful when `c` is a colimit already. -/ structure liftable_cocone (K : J ⥤ C) (F : C ⥤ D) (c : cocone (K ⋙ F)) := (lifted_cocone : cocone K) (valid_lift : F.map_cocone lifted_cocone ≅ c) /-- Definition 3.3.1 of [Riehl]. We say that `F` creates limits of `K` if, given any limit cone `c` for `K ⋙ F` (i.e. below) we can lift it to a cone "above", and further that `F` reflects limits for `K`. If `F` reflects isomorphisms, it suffices to show only that the lifted cone is a limit - see `creates_limit_of_reflects_iso`. -/ class creates_limit (K : J ⥤ C) (F : C ⥤ D) extends reflects_limit K F := (lifts : Π c, is_limit c → liftable_cone K F c) /-- `F` creates limits of shape `J` if `F` creates the limit of any diagram `K : J ⥤ C`. -/ class creates_limits_of_shape (J : Type w) [category.{w'} J] (F : C ⥤ D) := (creates_limit : Π {K : J ⥤ C}, creates_limit K F . tactic.apply_instance) /-- `F` creates limits if it creates limits of shape `J` for any `J`. -/ @[nolint check_univs] -- This should be used with explicit universe variables. class creates_limits_of_size (F : C ⥤ D) := (creates_limits_of_shape : Π {J : Type w} [category.{w'} J], creates_limits_of_shape J F . tactic.apply_instance) /-- `F` creates small limits if it creates limits of shape `J` for any small `J`. -/ abbreviation creates_limits (F : C ⥤ D) := creates_limits_of_size.{v₂ v₂} F /-- Dual of definition 3.3.1 of [Riehl]. We say that `F` creates colimits of `K` if, given any limit cocone `c` for `K ⋙ F` (i.e. below) we can lift it to a cocone "above", and further that `F` reflects limits for `K`. If `F` reflects isomorphisms, it suffices to show only that the lifted cocone is a limit - see `creates_limit_of_reflects_iso`. -/ class creates_colimit (K : J ⥤ C) (F : C ⥤ D) extends reflects_colimit K F := (lifts : Π c, is_colimit c → liftable_cocone K F c) /-- `F` creates colimits of shape `J` if `F` creates the colimit of any diagram `K : J ⥤ C`. -/ class creates_colimits_of_shape (J : Type w) [category.{w'} J] (F : C ⥤ D) := (creates_colimit : Π {K : J ⥤ C}, creates_colimit K F . tactic.apply_instance) /-- `F` creates colimits if it creates colimits of shape `J` for any small `J`. -/ @[nolint check_univs] -- This should be used with explicit universe variables. class creates_colimits_of_size (F : C ⥤ D) := (creates_colimits_of_shape : Π {J : Type w} [category.{w'} J], creates_colimits_of_shape J F . tactic.apply_instance) /-- `F` creates small colimits if it creates colimits of shape `J` for any small `J`. -/ abbreviation creates_colimits (F : C ⥤ D) := creates_colimits_of_size.{v₂ v₂} F attribute [instance, priority 100] -- see Note [lower instance priority] creates_limits_of_shape.creates_limit creates_limits_of_size.creates_limits_of_shape creates_colimits_of_shape.creates_colimit creates_colimits_of_size.creates_colimits_of_shape /- Interface to the `creates_limit` class. -/ /-- `lift_limit t` is the cone for `K` given by lifting the limit `t` for `K ⋙ F`. -/ def lift_limit {K : J ⥤ C} {F : C ⥤ D} [creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) : cone K := (creates_limit.lifts c t).lifted_cone /-- The lifted cone has an image isomorphic to the original cone. -/ def lifted_limit_maps_to_original {K : J ⥤ C} {F : C ⥤ D} [creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) : F.map_cone (lift_limit t) ≅ c := (creates_limit.lifts c t).valid_lift /-- The lifted cone is a limit. -/ def lifted_limit_is_limit {K : J ⥤ C} {F : C ⥤ D} [creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) : is_limit (lift_limit t) := reflects_limit.reflects (is_limit.of_iso_limit t (lifted_limit_maps_to_original t).symm) /-- If `F` creates the limit of `K` and `K ⋙ F` has a limit, then `K` has a limit. -/ lemma has_limit_of_created (K : J ⥤ C) (F : C ⥤ D) [has_limit (K ⋙ F)] [creates_limit K F] : has_limit K := has_limit.mk { cone := lift_limit (limit.is_limit (K ⋙ F)), is_limit := lifted_limit_is_limit _ } /-- If `F` creates limits of shape `J`, and `D` has limits of shape `J`, then `C` has limits of shape `J`. -/ lemma has_limits_of_shape_of_has_limits_of_shape_creates_limits_of_shape (F : C ⥤ D) [has_limits_of_shape J D] [creates_limits_of_shape J F] : has_limits_of_shape J C := ⟨λ G, has_limit_of_created G F⟩ /-- If `F` creates limits, and `D` has all limits, then `C` has all limits. -/ lemma has_limits_of_has_limits_creates_limits (F : C ⥤ D) [has_limits_of_size.{w w'} D] [creates_limits_of_size.{w w'} F] : has_limits_of_size.{w w'} C := ⟨λ J I, by exactI has_limits_of_shape_of_has_limits_of_shape_creates_limits_of_shape F⟩ /- Interface to the `creates_colimit` class. -/ /-- `lift_colimit t` is the cocone for `K` given by lifting the colimit `t` for `K ⋙ F`. -/ def lift_colimit {K : J ⥤ C} {F : C ⥤ D} [creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) : cocone K := (creates_colimit.lifts c t).lifted_cocone /-- The lifted cocone has an image isomorphic to the original cocone. -/ def lifted_colimit_maps_to_original {K : J ⥤ C} {F : C ⥤ D} [creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) : F.map_cocone (lift_colimit t) ≅ c := (creates_colimit.lifts c t).valid_lift /-- The lifted cocone is a colimit. -/ def lifted_colimit_is_colimit {K : J ⥤ C} {F : C ⥤ D} [creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) : is_colimit (lift_colimit t) := reflects_colimit.reflects (is_colimit.of_iso_colimit t (lifted_colimit_maps_to_original t).symm) /-- If `F` creates the limit of `K` and `K ⋙ F` has a limit, then `K` has a limit. -/ lemma has_colimit_of_created (K : J ⥤ C) (F : C ⥤ D) [has_colimit (K ⋙ F)] [creates_colimit K F] : has_colimit K := has_colimit.mk { cocone := lift_colimit (colimit.is_colimit (K ⋙ F)), is_colimit := lifted_colimit_is_colimit _ } /-- If `F` creates colimits of shape `J`, and `D` has colimits of shape `J`, then `C` has colimits of shape `J`. -/ lemma has_colimits_of_shape_of_has_colimits_of_shape_creates_colimits_of_shape (F : C ⥤ D) [has_colimits_of_shape J D] [creates_colimits_of_shape J F] : has_colimits_of_shape J C := ⟨λ G, has_colimit_of_created G F⟩ /-- If `F` creates colimits, and `D` has all colimits, then `C` has all colimits. -/ lemma has_colimits_of_has_colimits_creates_colimits (F : C ⥤ D) [has_colimits_of_size.{w w'} D] [creates_colimits_of_size.{w w'} F] : has_colimits_of_size.{w w'} C := ⟨λ J I, by exactI has_colimits_of_shape_of_has_colimits_of_shape_creates_colimits_of_shape F⟩ @[priority 10] instance reflects_limits_of_shape_of_creates_limits_of_shape (F : C ⥤ D) [creates_limits_of_shape J F] : reflects_limits_of_shape J F := {} @[priority 10] instance reflects_limits_of_creates_limits (F : C ⥤ D) [creates_limits_of_size.{w w'} F] : reflects_limits_of_size.{w w'} F := {} @[priority 10] instance reflects_colimits_of_shape_of_creates_colimits_of_shape (F : C ⥤ D) [creates_colimits_of_shape J F] : reflects_colimits_of_shape J F := {} @[priority 10] instance reflects_colimits_of_creates_colimits (F : C ⥤ D) [creates_colimits_of_size.{w w'} F] : reflects_colimits_of_size.{w w'} F := {} /-- A helper to show a functor creates limits. In particular, if we can show that for any limit cone `c` for `K ⋙ F`, there is a lift of it which is a limit and `F` reflects isomorphisms, then `F` creates limits. Usually, `F` creating limits says that _any_ lift of `c` is a limit, but here we only need to show that our particular lift of `c` is a limit. -/ structure lifts_to_limit (K : J ⥤ C) (F : C ⥤ D) (c : cone (K ⋙ F)) (t : is_limit c) extends liftable_cone K F c := (makes_limit : is_limit lifted_cone) /-- A helper to show a functor creates colimits. In particular, if we can show that for any limit cocone `c` for `K ⋙ F`, there is a lift of it which is a limit and `F` reflects isomorphisms, then `F` creates colimits. Usually, `F` creating colimits says that _any_ lift of `c` is a colimit, but here we only need to show that our particular lift of `c` is a colimit. -/ structure lifts_to_colimit (K : J ⥤ C) (F : C ⥤ D) (c : cocone (K ⋙ F)) (t : is_colimit c) extends liftable_cocone K F c := (makes_colimit : is_colimit lifted_cocone) /-- If `F` reflects isomorphisms and we can lift any limit cone to a limit cone, then `F` creates limits. In particular here we don't need to assume that F reflects limits. -/ def creates_limit_of_reflects_iso {K : J ⥤ C} {F : C ⥤ D} [reflects_isomorphisms F] (h : Π c t, lifts_to_limit K F c t) : creates_limit K F := { lifts := λ c t, (h c t).to_liftable_cone, to_reflects_limit := { reflects := λ (d : cone K) (hd : is_limit (F.map_cone d)), begin let d' : cone K := (h (F.map_cone d) hd).to_liftable_cone.lifted_cone, let i : F.map_cone d' ≅ F.map_cone d := (h (F.map_cone d) hd).to_liftable_cone.valid_lift, let hd' : is_limit d' := (h (F.map_cone d) hd).makes_limit, let f : d ⟶ d' := hd'.lift_cone_morphism d, have : (cones.functoriality K F).map f = i.inv := (hd.of_iso_limit i.symm).uniq_cone_morphism, haveI : is_iso ((cones.functoriality K F).map f) := (by { rw this, apply_instance }), haveI : is_iso f := is_iso_of_reflects_iso f (cones.functoriality K F), exact is_limit.of_iso_limit hd' (as_iso f).symm, end } } /-- When `F` is fully faithful, to show that `F` creates the limit for `K` it suffices to exhibit a lift of a limit cone for `K ⋙ F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cone maps, -- so the constructed limits may not be ideal, definitionally. def creates_limit_of_fully_faithful_of_lift' {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] {l : cone (K ⋙ F)} (hl : is_limit l) (c : cone K) (i : F.map_cone c ≅ l) : creates_limit K F := creates_limit_of_reflects_iso (λ c' t, { lifted_cone := c, valid_lift := i ≪≫ is_limit.unique_up_to_iso hl t, makes_limit := is_limit.of_faithful F (is_limit.of_iso_limit hl i.symm) _ (λ s, F.image_preimage _) }) /-- When `F` is fully faithful, and `has_limit (K ⋙ F)`, to show that `F` creates the limit for `K` it suffices to exhibit a lift of the chosen limit cone for `K ⋙ F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cone maps, -- so the constructed limits may not be ideal, definitionally. def creates_limit_of_fully_faithful_of_lift {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] [has_limit (K ⋙ F)] (c : cone K) (i : F.map_cone c ≅ limit.cone (K ⋙ F)) : creates_limit K F := creates_limit_of_fully_faithful_of_lift' (limit.is_limit _) c i /-- When `F` is fully faithful, to show that `F` creates the limit for `K` it suffices to show that a limit point is in the essential image of `F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cone maps, -- so the constructed limits may not be ideal, definitionally. def creates_limit_of_fully_faithful_of_iso' {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] {l : cone (K ⋙ F)} (hl : is_limit l) (X : C) (i : F.obj X ≅ l.X) : creates_limit K F := creates_limit_of_fully_faithful_of_lift' hl ({ X := X, π := { app := λ j, F.preimage (i.hom ≫ l.π.app j), naturality' := λ Y Z f, F.map_injective $ by { dsimp, simpa using (l.w f).symm } } }) (cones.ext i (λ j, by simp only [functor.image_preimage, functor.map_cone_π_app])) /-- When `F` is fully faithful, and `has_limit (K ⋙ F)`, to show that `F` creates the limit for `K` it suffices to show that the chosen limit point is in the essential image of `F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cone maps, -- so the constructed limits may not be ideal, definitionally. def creates_limit_of_fully_faithful_of_iso {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] [has_limit (K ⋙ F)] (X : C) (i : F.obj X ≅ limit (K ⋙ F)) : creates_limit K F := creates_limit_of_fully_faithful_of_iso' (limit.is_limit _) X i /-- `F` preserves the limit of `K` if it creates the limit and `K ⋙ F` has the limit. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_limit_of_creates_limit_and_has_limit (K : J ⥤ C) (F : C ⥤ D) [creates_limit K F] [has_limit (K ⋙ F)] : preserves_limit K F := { preserves := λ c t, is_limit.of_iso_limit (limit.is_limit _) ((lifted_limit_maps_to_original (limit.is_limit _)).symm ≪≫ ((cones.functoriality K F).map_iso ((lifted_limit_is_limit (limit.is_limit _)).unique_up_to_iso t))) } /-- `F` preserves the limit of shape `J` if it creates these limits and `D` has them. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape (F : C ⥤ D) [creates_limits_of_shape J F] [has_limits_of_shape J D] : preserves_limits_of_shape J F := {} /-- `F` preserves limits if it creates limits and `D` has limits. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_limits_of_creates_limits_and_has_limits (F : C ⥤ D) [creates_limits_of_size.{w w'} F] [has_limits_of_size.{w w'} D] : preserves_limits_of_size.{w w'} F := {} /-- If `F` reflects isomorphisms and we can lift any colimit cocone to a colimit cocone, then `F` creates colimits. In particular here we don't need to assume that F reflects colimits. -/ def creates_colimit_of_reflects_iso {K : J ⥤ C} {F : C ⥤ D} [reflects_isomorphisms F] (h : Π c t, lifts_to_colimit K F c t) : creates_colimit K F := { lifts := λ c t, (h c t).to_liftable_cocone, to_reflects_colimit := { reflects := λ (d : cocone K) (hd : is_colimit (F.map_cocone d)), begin let d' : cocone K := (h (F.map_cocone d) hd).to_liftable_cocone.lifted_cocone, let i : F.map_cocone d' ≅ F.map_cocone d := (h (F.map_cocone d) hd).to_liftable_cocone.valid_lift, let hd' : is_colimit d' := (h (F.map_cocone d) hd).makes_colimit, let f : d' ⟶ d := hd'.desc_cocone_morphism d, have : (cocones.functoriality K F).map f = i.hom := (hd.of_iso_colimit i.symm).uniq_cocone_morphism, haveI : is_iso ((cocones.functoriality K F).map f) := (by { rw this, apply_instance }), haveI := is_iso_of_reflects_iso f (cocones.functoriality K F), exact is_colimit.of_iso_colimit hd' (as_iso f), end } } /-- When `F` is fully faithful, to show that `F` creates the colimit for `K` it suffices to exhibit a lift of a colimit cocone for `K ⋙ F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cocone maps, -- so the constructed colimits may not be ideal, definitionally. def creates_colimit_of_fully_faithful_of_lift' {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] {l : cocone (K ⋙ F)} (hl : is_colimit l) (c : cocone K) (i : F.map_cocone c ≅ l) : creates_colimit K F := creates_colimit_of_reflects_iso (λ c' t, { lifted_cocone := c, valid_lift := i ≪≫ is_colimit.unique_up_to_iso hl t, makes_colimit := is_colimit.of_faithful F (is_colimit.of_iso_colimit hl i.symm) _ (λ s, F.image_preimage _) }) /-- When `F` is fully faithful, and `has_colimit (K ⋙ F)`, to show that `F` creates the colimit for `K` it suffices to exhibit a lift of the chosen colimit cocone for `K ⋙ F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cocone maps, -- so the constructed colimits may not be ideal, definitionally. def creates_colimit_of_fully_faithful_of_lift {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] [has_colimit (K ⋙ F)] (c : cocone K) (i : F.map_cocone c ≅ colimit.cocone (K ⋙ F)) : creates_colimit K F := creates_colimit_of_fully_faithful_of_lift' (colimit.is_colimit _) c i /-- When `F` is fully faithful, to show that `F` creates the colimit for `K` it suffices to show that a colimit point is in the essential image of `F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cocone maps, -- so the constructed colimits may not be ideal, definitionally. def creates_colimit_of_fully_faithful_of_iso' {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] {l : cocone (K ⋙ F)} (hl : is_colimit l) (X : C) (i : F.obj X ≅ l.X) : creates_colimit K F := creates_colimit_of_fully_faithful_of_lift' hl ({ X := X, ι := { app := λ j, F.preimage (l.ι.app j ≫ i.inv), naturality' := λ Y Z f, F.map_injective $ by { dsimp, simpa [← cancel_mono i.hom] using (l.w f) } } }) (cocones.ext i (λ j, by simp)) /-- When `F` is fully faithful, and `has_colimit (K ⋙ F)`, to show that `F` creates the colimit for `K` it suffices to show that the chosen colimit point is in the essential image of `F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cocone maps, -- so the constructed colimits may not be ideal, definitionally. def creates_colimit_of_fully_faithful_of_iso {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] [has_colimit (K ⋙ F)] (X : C) (i : F.obj X ≅ colimit (K ⋙ F)) : creates_colimit K F := creates_colimit_of_fully_faithful_of_iso' (colimit.is_colimit _) X i /-- `F` preserves the colimit of `K` if it creates the colimit and `K ⋙ F` has the colimit. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_colimit_of_creates_colimit_and_has_colimit (K : J ⥤ C) (F : C ⥤ D) [creates_colimit K F] [has_colimit (K ⋙ F)] : preserves_colimit K F := { preserves := λ c t, is_colimit.of_iso_colimit (colimit.is_colimit _) ((lifted_colimit_maps_to_original (colimit.is_colimit _)).symm ≪≫ ((cocones.functoriality K F).map_iso ((lifted_colimit_is_colimit (colimit.is_colimit _)).unique_up_to_iso t))) } /-- `F` preserves the colimit of shape `J` if it creates these colimits and `D` has them. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_colimit_of_shape_of_creates_colimits_of_shape_and_has_colimits_of_shape (F : C ⥤ D) [creates_colimits_of_shape J F] [has_colimits_of_shape J D] : preserves_colimits_of_shape J F := {} /-- `F` preserves limits if it creates limits and `D` has limits. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_colimits_of_creates_colimits_and_has_colimits (F : C ⥤ D) [creates_colimits_of_size.{w w'} F] [has_colimits_of_size.{w w'} D] : preserves_colimits_of_size.{w w'} F := {} /-- Transfer creation of limits along a natural isomorphism in the diagram. -/ def creates_limit_of_iso_diagram {K₁ K₂ : J ⥤ C} (F : C ⥤ D) (h : K₁ ≅ K₂) [creates_limit K₁ F] : creates_limit K₂ F := { lifts := λ c t, let t' := (is_limit.postcompose_inv_equiv (iso_whisker_right h F : _) c).symm t in { lifted_cone := (cones.postcompose h.hom).obj (lift_limit t'), valid_lift := F.map_cone_postcompose ≪≫ (cones.postcompose (iso_whisker_right h F).hom).map_iso (lifted_limit_maps_to_original t') ≪≫ cones.ext (iso.refl _) (λ j, by { dsimp, rw [category.assoc, ←F.map_comp], simp }) } ..reflects_limit_of_iso_diagram F h } /-- If `F` creates the limit of `K` and `F ≅ G`, then `G` creates the limit of `K`. -/ def creates_limit_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_limit K F] : creates_limit K G := { lifts := λ c t, { lifted_cone := lift_limit ((is_limit.postcompose_inv_equiv (iso_whisker_left K h : _) c).symm t), valid_lift := begin refine (is_limit.map_cone_equiv h _).unique_up_to_iso t, apply is_limit.of_iso_limit _ ((lifted_limit_maps_to_original _).symm), apply (is_limit.postcompose_inv_equiv _ _).symm t, end }, to_reflects_limit := reflects_limit_of_nat_iso _ h } /-- If `F` creates limits of shape `J` and `F ≅ G`, then `G` creates limits of shape `J`. -/ def creates_limits_of_shape_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_limits_of_shape J F] : creates_limits_of_shape J G := { creates_limit := λ K, creates_limit_of_nat_iso h } /-- If `F` creates limits and `F ≅ G`, then `G` creates limits. -/ def creates_limits_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_limits_of_size.{w w'} F] : creates_limits_of_size.{w w'} G := { creates_limits_of_shape := λ J 𝒥₁, by exactI creates_limits_of_shape_of_nat_iso h } /-- Transfer creation of colimits along a natural isomorphism in the diagram. -/ def creates_colimit_of_iso_diagram {K₁ K₂ : J ⥤ C} (F : C ⥤ D) (h : K₁ ≅ K₂) [creates_colimit K₁ F] : creates_colimit K₂ F := { lifts := λ c t, let t' := (is_colimit.precompose_hom_equiv (iso_whisker_right h F : _) c).symm t in { lifted_cocone := (cocones.precompose h.inv).obj (lift_colimit t'), valid_lift := F.map_cocone_precompose ≪≫ (cocones.precompose (iso_whisker_right h F).inv).map_iso (lifted_colimit_maps_to_original t') ≪≫ cocones.ext (iso.refl _) (λ j, by { dsimp, rw ←F.map_comp_assoc, simp }) }, ..reflects_colimit_of_iso_diagram F h } /-- If `F` creates the colimit of `K` and `F ≅ G`, then `G` creates the colimit of `K`. -/ def creates_colimit_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_colimit K F] : creates_colimit K G := { lifts := λ c t, { lifted_cocone := lift_colimit ((is_colimit.precompose_hom_equiv (iso_whisker_left K h : _) c).symm t), valid_lift := begin refine (is_colimit.map_cocone_equiv h _).unique_up_to_iso t, apply is_colimit.of_iso_colimit _ ((lifted_colimit_maps_to_original _).symm), apply (is_colimit.precompose_hom_equiv _ _).symm t, end }, to_reflects_colimit := reflects_colimit_of_nat_iso _ h } /-- If `F` creates colimits of shape `J` and `F ≅ G`, then `G` creates colimits of shape `J`. -/ def creates_colimits_of_shape_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_colimits_of_shape J F] : creates_colimits_of_shape J G := { creates_colimit := λ K, creates_colimit_of_nat_iso h } /-- If `F` creates colimits and `F ≅ G`, then `G` creates colimits. -/ def creates_colimits_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_colimits_of_size.{w w'} F] : creates_colimits_of_size.{w w'} G := { creates_colimits_of_shape := λ J 𝒥₁, by exactI creates_colimits_of_shape_of_nat_iso h } -- For the inhabited linter later. /-- If F creates the limit of K, any cone lifts to a limit. -/ def lifts_to_limit_of_creates (K : J ⥤ C) (F : C ⥤ D) [creates_limit K F] (c : cone (K ⋙ F)) (t : is_limit c) : lifts_to_limit K F c t := { lifted_cone := lift_limit t, valid_lift := lifted_limit_maps_to_original t, makes_limit := lifted_limit_is_limit t } -- For the inhabited linter later. /-- If F creates the colimit of K, any cocone lifts to a colimit. -/ def lifts_to_colimit_of_creates (K : J ⥤ C) (F : C ⥤ D) [creates_colimit K F] (c : cocone (K ⋙ F)) (t : is_colimit c) : lifts_to_colimit K F c t := { lifted_cocone := lift_colimit t, valid_lift := lifted_colimit_maps_to_original t, makes_colimit := lifted_colimit_is_colimit t } /-- Any cone lifts through the identity functor. -/ def id_lifts_cone (c : cone (K ⋙ 𝟭 C)) : liftable_cone K (𝟭 C) c := { lifted_cone := { X := c.X, π := c.π ≫ K.right_unitor.hom }, valid_lift := cones.ext (iso.refl _) (by tidy) } /-- The identity functor creates all limits. -/ instance id_creates_limits : creates_limits_of_size.{w w'} (𝟭 C) := { creates_limits_of_shape := λ J 𝒥, by exactI { creates_limit := λ F, { lifts := λ c t, id_lifts_cone c } } } /-- Any cocone lifts through the identity functor. -/ def id_lifts_cocone (c : cocone (K ⋙ 𝟭 C)) : liftable_cocone K (𝟭 C) c := { lifted_cocone := { X := c.X, ι := K.right_unitor.inv ≫ c.ι }, valid_lift := cocones.ext (iso.refl _) (by tidy) } /-- The identity functor creates all colimits. -/ instance id_creates_colimits : creates_colimits_of_size.{w w'} (𝟭 C) := { creates_colimits_of_shape := λ J 𝒥, by exactI { creates_colimit := λ F, { lifts := λ c t, id_lifts_cocone c } } } /-- Satisfy the inhabited linter -/ instance inhabited_liftable_cone (c : cone (K ⋙ 𝟭 C)) : inhabited (liftable_cone K (𝟭 C) c) := ⟨id_lifts_cone c⟩ instance inhabited_liftable_cocone (c : cocone (K ⋙ 𝟭 C)) : inhabited (liftable_cocone K (𝟭 C) c) := ⟨id_lifts_cocone c⟩ /-- Satisfy the inhabited linter -/ instance inhabited_lifts_to_limit (K : J ⥤ C) (F : C ⥤ D) [creates_limit K F] (c : cone (K ⋙ F)) (t : is_limit c) : inhabited (lifts_to_limit _ _ _ t) := ⟨lifts_to_limit_of_creates K F c t⟩ instance inhabited_lifts_to_colimit (K : J ⥤ C) (F : C ⥤ D) [creates_colimit K F] (c : cocone (K ⋙ F)) (t : is_colimit c) : inhabited (lifts_to_colimit _ _ _ t) := ⟨lifts_to_colimit_of_creates K F c t⟩ section comp variables {E : Type u₃} [ℰ : category.{v₃} E] variables (F : C ⥤ D) (G : D ⥤ E) instance comp_creates_limit [creates_limit K F] [creates_limit (K ⋙ F) G] : creates_limit K (F ⋙ G) := { lifts := λ c t, { lifted_cone := lift_limit (lifted_limit_is_limit t), valid_lift := (cones.functoriality (K ⋙ F) G).map_iso (lifted_limit_maps_to_original (lifted_limit_is_limit t)) ≪≫ (lifted_limit_maps_to_original t) } } instance comp_creates_limits_of_shape [creates_limits_of_shape J F] [creates_limits_of_shape J G] : creates_limits_of_shape J (F ⋙ G) := { creates_limit := infer_instance } instance comp_creates_limits [creates_limits_of_size.{w w'} F] [creates_limits_of_size.{w w'} G] : creates_limits_of_size.{w w'} (F ⋙ G) := { creates_limits_of_shape := infer_instance } instance comp_creates_colimit [creates_colimit K F] [creates_colimit (K ⋙ F) G] : creates_colimit K (F ⋙ G) := { lifts := λ c t, { lifted_cocone := lift_colimit (lifted_colimit_is_colimit t), valid_lift := (cocones.functoriality (K ⋙ F) G).map_iso (lifted_colimit_maps_to_original (lifted_colimit_is_colimit t)) ≪≫ (lifted_colimit_maps_to_original t) } } instance comp_creates_colimits_of_shape [creates_colimits_of_shape J F] [creates_colimits_of_shape J G] : creates_colimits_of_shape J (F ⋙ G) := { creates_colimit := infer_instance } instance comp_creates_colimits [creates_colimits_of_size.{w w'} F] [creates_colimits_of_size.{w w'} G] : creates_colimits_of_size.{w w'} (F ⋙ G) := { creates_colimits_of_shape := infer_instance } end comp end creates end category_theory
e085a7eb872504895c940e5575f3b10e1a96c265
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/run/fun_info1.lean
f670a1927dbd275298ef3cf7d6d2f11976568b74
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
568
lean
open tactic set_option pp.binder_types true noncomputable definition foo (A : Type) : A → A := sorry example (a : nat) (H : foo unit () = ()) : true := by do (lhs, rhs) ← get_local `H >>= infer_type >>= match_eq , get_spec_subsingleton_info lhs >>= trace, trace "-----------", trace "ite information:", c ← mk_const `ite, get_fun_info c >>= trace, trace "eq.rec information:", c ← mk_const `eq.rec, get_fun_info c >>= trace, trace "and.intro information:", c ← mk_const `and.intro, get_fun_info c >>= trace, mk_const `trivial >>= exact
47e7a4011119dccedbed5106193c6556302dbaec
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/data/multiset/basic.lean
47f415e0799367d7c2b3c85d7502e8e6cb301876
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
86,311
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.list.perm import algebra.group_power /-! # Multisets These are implemented as the quotient of a list by permutations. -/ open list subtype nat variables {α : Type*} {β : Type*} {γ : Type*} /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.is_setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /-- defines a size for a multiset by referring to the size of the underlying list -/ protected def sizeof [has_sizeof α] (s : multiset α) : ℕ := quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩ /- empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /- cons -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound (p.cons a)) notation a :: b := cons a b instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a::s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a::l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a::s = b::s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, h.rec_heq (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)} {C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s := mem_cons.2 (or.inl rfl) theorem forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} : (∀ x ∈ (a :: s), p x) ↔ p a ∧ ∀ x ∈ s, p x := quotient.induction_on' s $ λ L, list.forall_mem_cons theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s := ⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩ theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a :: as = b :: a :: cs, by simp [eq, hcs], have : a :: as = a :: b :: cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /- subset -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset section to_list /-- Produces a list of the elements in the multiset using choice. -/ @[reducible] noncomputable def to_list {α : Type*} (s : multiset α) := classical.some (quotient.exists_rep s) @[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] := (multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero)) lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s := classical.some_spec (quotient.exists_rep _) lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s := by rw [←multiset.mem_coe, multiset.coe_to_list] end to_list /- multiset order -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, (nil_sublist l).subperm theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨(sublist_cons _ _).subperm, λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ ((sublist_or_mem_of_sublist s).resolve_right m₁).subperm) end /- cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm.length_eq @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /- singleton -/ instance : has_singleton α (multiset α) := ⟨λ a, a::0⟩ instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /- add -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_add_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } @[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) := by rw [add_comm, cons_add, add_comm] theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append lemma card_smul (s : multiset α) (n : ℕ) : (n •ℕ s).card = n * s.card := by induction n; simp [succ_nsmul, *, nat.succ_mul]; cc @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_add_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, bot := 0, bot_le := multiset.zero_le, ..multiset.ordered_cancel_add_comm_monoid } /- repeat -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩ /- erase -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (p.erase a)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp, priority 990] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp, priority 980] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp, priority 980] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, (erase_sublist a l).subperm @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s := λ h, card_lt_of_lt (erase_lt.mpr h) theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s := card_le_of_le (erase_le a s) end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- map -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (p.map f)) theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} : (∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) := quotient.induction_on' s $ λ L, list.forall_mem_map_iff @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s := quot.induction_on s $ λ l, rfl lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by { induction k, simp, simpa } @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ instance (f : α → β) : is_add_monoid_hom (map f) := { map_add := map_add _, map_zero := map_zero _ } @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ @[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero] theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_injective H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /- fold -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, p.foldl_eq H b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, p.foldr_eq H b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ @[to_additive] def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 @[to_additive] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ attribute [norm_cast] coe_prod coe_sum @[simp, to_additive] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive] theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp @[simp, to_additive] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) := { map_add := sum_add, map_zero := sum_zero } lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) : ∀n, (n •ℕ m).prod = m.prod ^ n | 0 := rfl | (n + 1) := by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_smul n] @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n •ℕ a := @prod_repeat (multiplicative α) _ attribute [to_additive] prod_repeat lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := by simp lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := by simp attribute [to_additive] prod_map_one @[simp, to_additive] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) theorem prod_ne_zero {R : Type*} [integral_domain R] {m : multiset R} : (∀ x ∈ m, (x : _) ≠ 0) → m.prod ≠ 0 := multiset.induction_on m (λ _, one_ne_zero) $ λ hd tl ih H, by { rw forall_mem_cons at H, rw prod_cons, exact mul_ne_zero H.1 (ih H.2) } lemma prod_eq_zero {α : Type*} [comm_semiring α] {s : multiset α} (h : (0 : α) ∈ s) : multiset.prod s = 0 := begin rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩, simp [hs', multiset.prod_cons] end @[to_additive] lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α →* β) : (s.map f).prod = f s.prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod] @[to_additive] theorem prod_hom_rel [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (s.map f).prod (s.map g).prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod] lemma dvd_prod [comm_monoid α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a theorem prod_eq_zero_iff [comm_cancel_monoid_with_zero α] [nontrivial α] {s : multiset α} : s.prod = 0 ↔ (0 : α) ∈ s := multiset.induction_on s (by simp) $ assume a s, by simp [mul_eq_zero, @eq_comm _ 0 a] {contextual := tt} @[to_additive sum_nonneg] lemma one_le_prod_of_one_le [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → 1 ≤ m.prod := quotient.induction_on m $ λ l hl, by simpa using list.one_le_prod_of_one_le hl @[to_additive] lemma single_le_prod [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → ∀ x ∈ m, x ≤ m.prod := quotient.induction_on m $ λ l hl x hx, by simpa using list.single_le_prod hl x hx @[to_additive all_zero_of_le_zero_le_of_sum_eq_zero] lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → m.prod = 1 → (∀ x ∈ m, x = (1 : α)) := begin apply quotient.induction_on m, simp only [quot_mk_to_coe, coe_prod, mem_coe], intros l hl₁ hl₂ x hx, apply all_one_of_le_one_le_of_prod_eq_one hl₁ hl₂ _ hx, end lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] {m : multiset α} : m.sum = 0 ↔ ∀ x ∈ m, x = (0 : α) := quotient.induction_on m $ λ l, by simpa using list.sum_eq_zero_iff l 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 : multiset α) : f s.sum ≤ (s.map f).sum := multiset.induction_on s (le_of_eq h_zero) $ assume a s ih, by rw [sum_cons, map_cons, sum_cons]; from le_trans (h_add a s.sum) (add_le_add_left ih _) lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum := multiset.induction_on s (λ _, dvd_zero _) (λ x s ih h, by rw sum_cons; exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy))))) /- join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /- bind -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a :: g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /- product -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a :: s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp; cc @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /- sigma -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp; cc @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /- map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ pp.pmap f @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a::m, p b), pmap f (a :: m) h = f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) : sizeof x < sizeof s := by { induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl } theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /- subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.diff p₂ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) } @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] @[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) @[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /- union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /- inter -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.bag_inter p₂ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a :: s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, (bag_inter_sublist_left _ _).subperm theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) := by simpa using add_union_distrib (a::0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /- filter -/ section variables {p : α → Prop} [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ h.filter p) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, (filter_sublist _).subperm @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, (filter_sublist_filter h).subperm theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩ @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter $ inter_le_left _ _) (filter_le_filter $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _) (filter_le _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter l theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] /- filter_map -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $ h.filter_map f) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a :: s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a :: s) = b :: filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm /-! ### countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 := quot.induction_on s countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s := quot.induction_on s countp_cons_of_neg theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) := { map_add := countp_add, map_zero := countp_zero _ } theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h) @[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] end /- count -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) := count_le_of_le _ (le_cons_self _ _) theorem count_singleton (a : α) : count a (a::0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) := countp.is_add_monoid_hom @[simp] theorem count_smul (a : α) (n s) : count a (n •ℕ s) = n * count a s := by induction n; simp [*, succ_nsmul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s := by simp [ne.def, count_eq_zero] @[simp] theorem count_repeat_self (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] theorem count_repeat (a b : α) (n : ℕ) : count a (repeat b n) = if (a = b) then n else 0 := begin split_ifs with h₁, { rw [h₁, count_repeat_self] }, { rw [count_eq_zero], apply mt eq_of_mem_repeat h₁ }, end @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a::erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp, priority 980] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_sum {m : multiset β} {f : β → multiset α} {a : α} : count a (map f m).sum = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) ( by simp) lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := count_sum theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter_of_pos {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h @[simp] theorem count_filter_of_neg {p} [decidable_pred p] {a} {s : multiset α} (h : ¬ p a) : count a (filter p s) = 0 := multiset.count_eq_zero_of_not_mem (λ t, h (of_mem_filter t)) theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[ext] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp only [max_min_distrib_left, multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter], ..multiset.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } end /- relator -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs) mk_iff_of_inductive_prop multiset.rel multiset.rel_iff variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') := begin split, { generalize hm : a :: as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono h lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff] theorem map_injective {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /- disjoint -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp, priority 1100] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp, priority 1100] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := by rw [disjoint_comm, disjoint_add_left]; tauto @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a::0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t := by rw [disjoint_comm, disjoint_cons_left]; tauto theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := begin simp [disjoint], split, from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm, from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁) end /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h) (assume h, ⟨l, rfl, h⟩) end multiset namespace multiset section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns that `a`. -/ def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose variable (α) /-- The equivalence between lists and multisets of a subsingleton type. -/ def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } end multiset @[to_additive] theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) : f s.prod = (s.map f).prod := (s.prod_hom f).symm
859cc8a296ebe452c7f9f76cdaf4a09ac3492585
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/nontriviality.lean
949df5b1696183a591ab9d8589fe8151b1ab476e
[ "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,516
lean
import logic.nontrivial import algebra.ordered_ring import data.nat.basic /-! ### Test `nontriviality` with inequality hypotheses -/ example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : 0 < a := begin nontriviality, guard_hyp _inst : nontrivial R, assumption, end /-! ### Test `nontriviality` with equality or non-strict inequality goals -/ example {R : Type} [comm_ring R] {r s : R} : r * s = s * r := begin nontriviality, guard_hyp _inst : nontrivial R, apply mul_comm, end /-! ### Test deducing `nontriviality` by instance search -/ example {R : Type} [ordered_ring R] : 0 ≤ (1 : R) := begin nontriviality R, guard_hyp _inst : nontrivial R, exact zero_le_one, end example {R : Type} [ordered_ring R] : 0 ≤ (1 : R) := begin nontriviality ℕ, guard_hyp _inst : nontrivial ℕ, exact zero_le_one, end example {R : Type} [ordered_ring R] : 0 ≤ (2 : R) := begin success_if_fail { nontriviality punit }, exact zero_le_two, end example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : 2 ∣ 4 := begin nontriviality R, guard_hyp _inst : nontrivial R, dec_trivial end /-! Test using `@[nontriviality]` lemmas in `nontriviality and custom `simp` lemmas -/ def empty_or_univ {α : Type*} (s : set α) : Prop := s = ∅ ∨ s = set.univ lemma subsingleton.set_empty_or_univ {α} [subsingleton α] (s : set α) : s = ∅ ∨ s = set.univ := subsingleton.set_cases (or.inl rfl) (or.inr rfl) s lemma subsingleton.set_empty_or_univ' {α} [subsingleton α] (s : set α) : empty_or_univ s := subsingleton.set_empty_or_univ s example {α : Type*} (s : set α) (hs : s = ∅ ∪ set.univ) : empty_or_univ s := begin success_if_fail { nontriviality α }, rw [set.empty_union] at hs, exact or.inr hs end section local attribute [nontriviality] subsingleton.set_empty_or_univ example {α : Type*} (s : set α) (hs : s = ∅ ∪ set.univ) : empty_or_univ s := begin success_if_fail { nontriviality α }, nontriviality α using [subsingleton.set_empty_or_univ'], rw [set.empty_union] at hs, exact or.inr hs end end local attribute [nontriviality] subsingleton.set_empty_or_univ' example {α : Type*} (s : set α) (hs : s = ∅ ∪ set.univ) : empty_or_univ s := begin nontriviality α, rw [set.empty_union] at hs, exact or.inr hs end /-! Test with nonatomic type argument -/ example (α : ℕ → Type) (a b : α 0) (h : a = b) : a = b := begin nontriviality α 0 using [nat.zero_lt_one], guard_hyp _inst : nontrivial (α 0), exact h end
fb7306333d00eaf4d5c7b0fcf4dea3e097ab799a
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/hidingInaccessibleNames.lean
ee590f1edc9216647204d92d84fbe1cdab8f8a4d
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
619
lean
def f : (xs : List Nat) → Nat → xs ≠ [] → Nat | [], _, _ => _ | [a,b], _, _ => _ | _, _, _ => _ set_option pp.inaccessibleNames true in def f' : (xs : List Nat) → Nat → xs ≠ [] → Nat | [], _, _ => _ | [a,b], _, _ => _ | _, _, _ => _ theorem ex1 : p ∨ q → q ∨ p := by intro h cases h traceState apply Or.inr assumption apply Or.inl assumption done theorem ex2 : {p : Prop} → [Decidable p] → p → decide p = true | _, isTrue _, _ => _ | _, isFalse h₁, h₂ => absurd h₂ h₁ theorem ex3 : ∀ {c d : Char}, c = d → c.val = d.val | _, _, rfl => _
d2d3b2994445557493e3951c6607c48e8dc197fb
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/polynomial/cyclotomic.lean
805a77db1880f033783b04fedacf5372d4518714
[ "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
30,701
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import field_theory.splitting_field import ring_theory.roots_of_unity import algebra.polynomial.big_operators import number_theory.arithmetic_function import data.polynomial.lifts import analysis.complex.roots_of_unity import field_theory.separable /-! # Cyclotomic polynomials. For `n : ℕ` and an integral domain `R`, we define a modified version of the `n`-th cyclotomic polynomial with coefficients in `R`, denoted `cyclotomic' n R`, as `∏ (X - μ)`, where `μ` varies over the primitive `n`th roots of unity. If there is a primitive `n`th root of unity in `R` then this the standard definition. We then define the standard cyclotomic polynomial `cyclotomic n R` with coefficients in any ring `R`. ## Main definition * `cyclotomic n R` : the `n`-th cyclotomic polynomial with coefficients in `R`. ## Main results * `int_coeff_of_cycl` : If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. * `deg_of_cyclotomic` : The degree of `cyclotomic n` is `totient n`. * `prod_cyclotomic_eq_X_pow_sub_one` : `X ^ n - 1 = ∏ (cyclotomic i)`, where `i` divides `n`. * `cyclotomic_eq_prod_X_pow_sub_one_pow_moebius` : The Möbius inversion formula for `cyclotomic n R` over an abstract fraction field for `polynomial R`. * `cyclotomic.irreducible` : `cyclotomic n ℤ` is irreducible. ## Implementation details Our definition of `cyclotomic' n R` makes sense in any integral domain `R`, but the interesting results hold if there is a primitive `n`-th root of unity in `R`. In particular, our definition is not the standard one unless there is a primitive `n`th root of unity in `R`. For example, `cyclotomic' 3 ℤ = 1`, since there are no primitive cube roots of unity in `ℤ`. The main example is `R = ℂ`, we decided to work in general since the difficulties are essentially the same. To get the standard cyclotomic polynomials, we use `int_coeff_of_cycl`, with `R = ℂ`, to get a polynomial with integer coefficients and then we map it to `polynomial R`, for any ring `R`. To prove `cyclotomic.irreducible`, the irreducibility of `cyclotomic n ℤ`, we show in `minpoly_primitive_root_eq_cyclotomic` that `cyclotomic n ℤ` is the minimal polynomial of any `n`-th primitive root of unity `μ : K`, where `K` is a field of characteristic `0`. -/ open_locale classical big_operators noncomputable theory universe u namespace polynomial section cyclotomic' section integral_domain variables {R : Type*} [integral_domain R] /-- The modified `n`-th cyclotomic polynomial with coefficients in `R`, it is the usual cyclotomic polynomial if there is a primitive `n`-th root of unity in `R`. -/ def cyclotomic' (n : ℕ) (R : Type*) [integral_domain R] : polynomial R := ∏ μ in primitive_roots n R, (X - C μ) /-- The zeroth modified cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic'_zero (R : Type*) [integral_domain R] : cyclotomic' 0 R = 1 := by simp only [cyclotomic', finset.prod_empty, is_primitive_root.primitive_roots_zero] /-- The first modified cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic'_one (R : Type*) [integral_domain R] : cyclotomic' 1 R = X - 1 := begin simp only [cyclotomic', finset.prod_singleton, ring_hom.map_one, is_primitive_root.primitive_roots_one] end /-- The second modified cyclotomic polyomial is `X + 1` if the characteristic of `R` is not `2`. -/ @[simp] lemma cyclotomic'_two (R : Type*) [integral_domain R] (p : ℕ) [char_p R p] (hp : p ≠ 2) : cyclotomic' 2 R = X + 1 := begin rw [cyclotomic'], have prim_root_two : primitive_roots 2 R = {(-1 : R)}, { apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.neg_one p hp, nat.succ_pos', mem_primitive_roots] }, { intros x hx, rw [mem_primitive_roots zero_lt_two] at hx, exact is_primitive_root.eq_neg_one_of_two_right hx } }, simp only [prim_root_two, finset.prod_singleton, ring_hom.map_neg, ring_hom.map_one, sub_neg_eq_add] end /-- `cyclotomic' n R` is monic. -/ lemma cyclotomic'.monic (n : ℕ) (R : Type*) [integral_domain R] : (cyclotomic' n R).monic := monic_prod_of_monic _ _ $ λ z hz, monic_X_sub_C _ /-- `cyclotomic' n R` is different from `0`. -/ lemma cyclotomic'_ne_zero (n : ℕ) (R : Type*) [integral_domain R] : cyclotomic' n R ≠ 0 := (cyclotomic'.monic n R).ne_zero /-- The natural degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma nat_degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).nat_degree = nat.totient n := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, cyclotomic'_zero, nat.totient_zero, nat_degree_one] }, rw [cyclotomic'], rw nat_degree_prod (primitive_roots n R) (λ (z : R), (X - C z)), simp only [is_primitive_root.card_primitive_roots h hpos, mul_one, nat_degree_X_sub_C, nat.cast_id, finset.sum_const, nsmul_eq_mul], intros z hz, exact X_sub_C_ne_zero z end /-- The degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).degree = nat.totient n := by simp only [degree_eq_nat_degree (cyclotomic'_ne_zero n R), nat_degree_cyclotomic' h] /-- The roots of `cyclotomic' n R` are the primitive `n`-th roots of unity. -/ lemma roots_of_cyclotomic (n : ℕ) (R : Type*) [integral_domain R] : (cyclotomic' n R).roots = (primitive_roots n R).val := by { rw cyclotomic', exact roots_prod_X_sub_C (primitive_roots n R) } end integral_domain section field variables {K : Type*} [field K] /-- If there is a primitive `n`th root of unity in `K`, then `X ^ n - 1 = ∏ (X - μ)`, where `μ` varies over the `n`-th roots of unity. -/ lemma X_pow_sub_one_eq_prod {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : X ^ n - 1 = ∏ ζ in nth_roots_finset n K, (X - C ζ) := begin rw [nth_roots_finset, ← multiset.to_finset_eq (is_primitive_root.nth_roots_nodup h)], simp only [finset.prod_mk, ring_hom.map_one], rw [nth_roots], have hmonic : (X ^ n - C (1 : K)).monic := monic_X_pow_sub_C (1 : K) (ne_of_lt hpos).symm, symmetry, apply prod_multiset_X_sub_C_of_monic_of_roots_card_eq hmonic, rw [@nat_degree_X_pow_sub_C K _ _ n 1, ← nth_roots], exact is_primitive_root.card_nth_roots h end /-- `cyclotomic' n K` splits. -/ lemma cyclotomic'_splits (n : ℕ) : splits (ring_hom.id K) (cyclotomic' n K) := begin apply splits_prod (ring_hom.id K), intros z hz, simp only [splits_X_sub_C (ring_hom.id K)] end /-- If there is a primitive `n`-th root of unity in `K`, then `X ^ n - 1`splits. -/ lemma X_pow_sub_one_splits {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : splits (ring_hom.id K) (X ^ n - C (1 : K)) := begin by_cases hzero : n = 0, { simp only [hzero, ring_hom.map_one, splits_zero, pow_zero, sub_self] }, rw [splits_iff_card_roots, ← nth_roots, is_primitive_root.card_nth_roots h, nat_degree_X_pow_sub_C], end /-- If there is a primitive `n`-th root of unity in `K`, then `∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1`. -/ lemma prod_cyclotomic'_eq_X_pow_sub_one {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : ∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1 := begin rw [X_pow_sub_one_eq_prod hpos h], have rwcyc : ∀ i ∈ nat.divisors n, cyclotomic' i K = ∏ μ in primitive_roots i K, (X - C μ), { intros i hi, simp only [cyclotomic'] }, conv_lhs { apply_congr, skip, simp [rwcyc, H] }, rw ← finset.prod_bUnion, { simp only [is_primitive_root.nth_roots_one_eq_bUnion_primitive_roots hpos h] }, intros x hx y hy hdiff, simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hx hy, refine is_primitive_root.disjoint _ _ hdiff, { exact @nat.pos_of_mem_divisors n x (nat.mem_divisors.2 hx) }, { exact @nat.pos_of_mem_divisors n y (nat.mem_divisors.2 hy) } end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic' i K)`. -/ lemma cyclotomic'_eq_X_pow_sub_one_div {ζ : K} {n : ℕ} (hpos: 0 < n) (h : is_primitive_root ζ n) : cyclotomic' n K = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic' i K) := begin rw [←prod_cyclotomic'_eq_X_pow_sub_one hpos h, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic' i K).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic'.monic i K }, rw (div_mod_by_monic_unique (cyclotomic' n K) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. -/ lemma int_coeff_of_cyclotomic {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : (∃ (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K ∧ P.degree = (cyclotomic' n K).degree ∧ P.monic) := begin refine lifts_and_degree_eq_and_monic _ (cyclotomic'.monic n K), revert h ζ, apply nat.strong_induction_on n, intros k hk z hzeta, cases nat.eq_zero_or_pos k with hzero hpos, { use 1, simp only [hzero, cyclotomic'_zero, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, map_one, ring_hom.coe_of, and_self], }, by_cases hone : k = 1, { use X - 1, simp only [hone, cyclotomic'_one K, set.mem_univ, pnat.one_coe, subsemiring.coe_top, eq_self_iff_true, map_X, map_one, ring_hom.coe_of, and_self, map_sub] }, let B : polynomial K := ∏ i in nat.proper_divisors k, cyclotomic' i K, have Bmo : B.monic, { apply monic_prod_of_monic, intros i hi, exact (cyclotomic'.monic i K) }, have Bint : B ∈ lifts (int.cast_ring_hom K), { refine subsemiring.prod_mem (lifts (int.cast_ring_hom K)) _, intros x hx, have xsmall := (nat.mem_proper_divisors.1 hx).2, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hx).1, rw [mul_comm] at hd, exact hk x xsmall (is_primitive_root.pow hpos hzeta hd) }, replace Bint := lifts_and_degree_eq_and_monic Bint Bmo, obtain ⟨B₁, hB₁, hB₁deg, hB₁mo⟩ := Bint, let Q₁ : polynomial ℤ := (X ^ k - 1) /ₘ B₁, have huniq : 0 + B * cyclotomic' k K = X ^ k - 1 ∧ (0 : polynomial K).degree < B.degree, { split, { rw [zero_add, mul_comm, ←(prod_cyclotomic'_eq_X_pow_sub_one hpos hzeta), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], simp only [true_and, finset.prod_insert, not_lt, nat.mem_proper_divisors, dvd_refl] }, rw [degree_zero, bot_lt_iff_ne_bot], intro habs, exact (monic.ne_zero Bmo) (degree_eq_bot.1 habs) }, replace huniq := div_mod_by_monic_unique (cyclotomic' k K) (0 : polynomial K) Bmo huniq, simp only [lifts, ring_hom.coe_of, ring_hom.mem_srange], use Q₁, rw [(map_div_by_monic (int.cast_ring_hom K) hB₁mo), hB₁, ← huniq.1], simp end /-- If `K` is of characteristic `0` and there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K` comes from a unique polynomial with integer coefficients. -/ lemma unique_int_coeff_of_cycl [char_zero K] {ζ : K} {n : ℕ+} (h : is_primitive_root ζ n) : (∃! (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K) := begin obtain ⟨P, hP⟩ := int_coeff_of_cyclotomic h, rw exists_unique, use [P, hP.1], intros Q hQ, have mapinj : function.injective (map (int.cast_ring_hom K)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, rw [function.injective] at mapinj, apply mapinj, rw [hP.1, hQ] end end field end cyclotomic' section cyclotomic /-- The `n`-th cyclotomic polynomial with coefficients in `R`. -/ def cyclotomic (n : ℕ) (R : Type*) [ring R] : polynomial R := if h : n = 0 then 1 else map (int.cast_ring_hom R) (classical.some (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n h))) lemma int_cyclotomic_rw {n : ℕ} (h : n ≠ 0) : cyclotomic n ℤ = (classical.some (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n h))) := begin simp only [cyclotomic, h, dif_neg, not_false_iff], ext i, simp only [coeff_map, int.cast_id, ring_hom.eq_int_cast] end /-- `cyclotomic n R` comes from `cyclotomic n ℤ`. -/ lemma map_cyclotomic_int (n : ℕ) (R : Type*) [ring R] : map (int.cast_ring_hom R) (cyclotomic n ℤ) = cyclotomic n R := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, dif_pos, map_one] }, simp only [cyclotomic, int_cyclotomic_rw, hzero, ne.def, dif_neg, not_false_iff] end lemma int_cyclotomic_spec (n : ℕ) : map (int.cast_ring_hom ℂ) (cyclotomic n ℤ) = cyclotomic' n ℂ ∧ (cyclotomic n ℤ).degree = (cyclotomic' n ℂ).degree ∧ (cyclotomic n ℤ).monic := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, degree_one, monic_one, cyclotomic'_zero, dif_pos, eq_self_iff_true, map_one, and_self] }, rw int_cyclotomic_rw hzero, exact classical.some_spec (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n hzero)) end lemma int_cyclotomic_unique {n : ℕ} {P : polynomial ℤ} (h : map (int.cast_ring_hom ℂ) P = cyclotomic' n ℂ) : P = cyclotomic n ℤ := begin have mapinj : function.injective (map (int.cast_ring_hom ℂ)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, apply mapinj, rw [h, (int_cyclotomic_spec n).1] end /-- The definition of `cyclotomic n R` commutes with any ring homomorphism. -/ @[simp] lemma map_cyclotomic (n : ℕ) {R S : Type*} [ring R] [ring S] (f : R →+* S) : map f (cyclotomic n R) = cyclotomic n S := begin rw [←map_cyclotomic_int n R, ←map_cyclotomic_int n S], ext i, simp only [coeff_map, ring_hom.eq_int_cast, ring_hom.map_int_cast] end /-- The zeroth cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic_zero (R : Type*) [ring R] : cyclotomic 0 R = 1 := by simp only [cyclotomic, dif_pos] /-- The first cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic_one (R : Type*) [ring R] : cyclotomic 1 R = X - 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X - 1) = cyclotomic' 1 ℂ, { simp only [cyclotomic'_one, pnat.one_coe, map_X, map_one, map_sub] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_X, map_one, map_sub] end /-- The second cyclotomic polyomial is `X + 1`. -/ @[simp] lemma cyclotomic_two (R : Type*) [ring R] : cyclotomic 2 R = X + 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X + 1) = cyclotomic' 2 ℂ, { simp only [cyclotomic'_two ℂ 0 two_ne_zero.symm, map_add, map_X, map_one] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_add, map_X, map_one] end /-- `cyclotomic n` is monic. -/ lemma cyclotomic.monic (n : ℕ) (R : Type*) [ring R] : (cyclotomic n R).monic := begin rw ←map_cyclotomic_int, apply monic_map, exact (int_cyclotomic_spec n).2.2 end /-- `cyclotomic n R` is different from `0`. -/ lemma cyclotomic_ne_zero (n : ℕ) (R : Type*) [ring R] [nontrivial R] : cyclotomic n R ≠ 0 := monic.ne_zero (cyclotomic.monic n R) /-- The degree of `cyclotomic n` is `totient n`. -/ lemma degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).degree = nat.totient n := begin rw ←map_cyclotomic_int, rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom R) _, { cases n with k, { simp only [cyclotomic, degree_one, dif_pos, nat.totient_zero, with_top.coe_zero]}, rw [←degree_cyclotomic' (complex.is_primitive_root_exp k.succ (nat.succ_ne_zero k))], exact (int_cyclotomic_spec k.succ).2.1 }, simp only [(int_cyclotomic_spec n).right.right, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] end /-- The natural degree of `cyclotomic n` is `totient n`. -/ lemma nat_degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).nat_degree = nat.totient n := begin have hdeg := degree_cyclotomic n R, rw degree_eq_nat_degree (cyclotomic_ne_zero n R) at hdeg, norm_cast at hdeg, exact hdeg end /-- The degree of `cyclotomic n R` is positive. -/ lemma degree_cyclotomic_pos (n : ℕ) (R : Type*) (hpos : 0 < n) [ring R] [nontrivial R] : 0 < (cyclotomic n R).degree := by { rw degree_cyclotomic n R; exact_mod_cast (nat.totient_pos hpos) } /-- `∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1`. -/ lemma prod_cyclotomic_eq_X_pow_sub_one {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] : ∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1 := begin have integer : ∏ i in nat.divisors n, cyclotomic i ℤ = X ^ n - 1, { have mapinj : function.injective (map (int.cast_ring_hom ℂ)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, apply mapinj, rw map_prod (int.cast_ring_hom ℂ) (λ i, cyclotomic i ℤ), simp only [int_cyclotomic_spec, map_pow, nat.cast_id, map_X, map_one, ring_hom.coe_of, map_sub], exact prod_cyclotomic'_eq_X_pow_sub_one hpos (complex.is_primitive_root_exp n (ne_of_lt hpos).symm) }, have coerc : X ^ n - 1 = map (int.cast_ring_hom R) (X ^ n - 1), { simp only [map_pow, map_X, map_one, map_sub] }, have h : ∀ i ∈ n.divisors, cyclotomic i R = map (int.cast_ring_hom R) (cyclotomic i ℤ), { intros i hi, exact (map_cyclotomic_int i R).symm }, rw [finset.prod_congr (refl n.divisors) h, coerc, ←map_prod (int.cast_ring_hom R) (λ i, cyclotomic i ℤ), integer] end section arithmetic_function open nat.arithmetic_function open_locale arithmetic_function /-- `cyclotomic n R` can be expressed as a product in a fraction field of `polynomial R` using Möbius inversion. -/ lemma cyclotomic_eq_prod_X_pow_sub_one_pow_moebius {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] [nontrivial R] {K : Type*} [field K] (f : fraction_map (polynomial R) K) : f.to_map (cyclotomic n R) = ∏ i in n.divisors_antidiagonal, (f.to_map (X ^ i.snd - 1)) ^ μ i.fst := begin have h : ∀ (n : ℕ), 0 < n → ∏ i in nat.divisors n, f.to_map (cyclotomic i R) = f.to_map (X ^ n - 1), { intros n hn, rw [← prod_cyclotomic_eq_X_pow_sub_one hn R, ring_hom.map_prod] }, rw (prod_eq_iff_prod_pow_moebius_eq_of_nonzero (λ n hn, _) (λ n hn, _)).1 h n hpos; rw [ne.def, fraction_map.to_map_eq_zero_iff], { apply cyclotomic_ne_zero }, { apply monic.ne_zero, apply monic_X_pow_sub_C _ (ne_of_gt hn) } end end arithmetic_function /-- We have `cyclotomic n R = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic i K)`. -/ lemma cyclotomic_eq_X_pow_sub_one_div {R : Type*} [comm_ring R] [nontrivial R] {n : ℕ} (hpos: 0 < n) : cyclotomic n R = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic i R) := begin rw [←prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw (div_mod_by_monic_unique (cyclotomic n R) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If `m` is a proper divisor of `n`, then `X ^ m - 1` divides `∏ i in nat.proper_divisors n, cyclotomic i R`. -/ lemma X_pow_sub_one_dvd_prod_cyclotomic (R : Type*) [comm_ring R] {n m : ℕ} (hpos : 0 < n) (hm : m ∣ n) (hdiff : m ≠ n) : X ^ m - 1 ∣ ∏ i in nat.proper_divisors n, cyclotomic i R := begin replace hm := nat.mem_proper_divisors.2 ⟨hm, lt_of_le_of_ne (nat.divisor_le (nat.mem_divisors.2 ⟨hm, (ne_of_lt hpos).symm⟩)) hdiff⟩, rw [← finset.sdiff_union_of_subset (nat.divisors_subset_proper_divisors (ne_of_lt hpos).symm (nat.mem_proper_divisors.1 hm).1 (ne_of_lt (nat.mem_proper_divisors.1 hm).2)), finset.prod_union finset.sdiff_disjoint, prod_cyclotomic_eq_X_pow_sub_one (nat.pos_of_mem_proper_divisors hm)], exact ⟨(∏ (x : ℕ) in n.proper_divisors \ m.divisors, cyclotomic x R), by rw mul_comm⟩ end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K = ∏ μ in primitive_roots n R, (X - C μ)`. In particular, `cyclotomic n K = cyclotomic' n K` -/ lemma cyclotomic_eq_prod_X_sub_primitive_roots {K : Type*} [field K] {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : cyclotomic n K = ∏ μ in primitive_roots n K, (X - C μ) := begin rw ←cyclotomic', revert h ζ, apply nat.strong_induction_on n, intros k hk z hz, cases nat.eq_zero_or_pos k with hzero hpos, { simp only [hzero, cyclotomic'_zero, cyclotomic_zero] }, have h : ∀ i ∈ k.proper_divisors, cyclotomic i K = cyclotomic' i K, { intros i hi, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hi).1, rw mul_comm at hd, exact hk i (nat.mem_proper_divisors.1 hi).2 (is_primitive_root.pow hpos hz hd) }, rw [@cyclotomic_eq_X_pow_sub_one_div _ _ (field.to_nontrivial K) _ hpos, cyclotomic'_eq_X_pow_sub_one_div hpos hz, finset.prod_congr (refl k.proper_divisors) h] end /-- Any `n`-th primitive root of unity is a root of `cyclotomic n ℤ`.-/ lemma is_root_cyclotomic {n : ℕ} {K : Type*} [field K] (hpos : 0 < n) {μ : K} (h : is_primitive_root μ n) : is_root (cyclotomic n K) μ := begin rw [← mem_roots (cyclotomic_ne_zero n K), cyclotomic_eq_prod_X_sub_primitive_roots h, roots_prod_X_sub_C, ← finset.mem_def], rwa [← mem_primitive_roots hpos] at h, end lemma eq_cyclotomic_iff {R : Type*} [comm_ring R] [nontrivial R] {n : ℕ} (hpos: 0 < n) (P : polynomial R) : P = cyclotomic n R ↔ P * (∏ i in nat.proper_divisors n, polynomial.cyclotomic i R) = X ^ n - 1 := begin split, { intro hcycl, rw [hcycl, ← finset.prod_insert (@nat.proper_divisors.not_self_mem n), ← nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], exact prod_cyclotomic_eq_X_pow_sub_one hpos R }, { intro hP, have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw [@cyclotomic_eq_X_pow_sub_one_div R _ _ _ hpos, (div_mod_by_monic_unique P 0 prod_monic _).1], split, { rwa [zero_add, mul_comm] }, rw [degree_zero, bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) }, end /-- If `p` is prime, then `cyclotomic p R = geom_sum X p`. -/ lemma cyclotomic_eq_geom_sum {R : Type*} [comm_ring R] [nontrivial R] {p : ℕ} (hp : nat.prime p) : cyclotomic p R = geom_sum X p := begin symmetry, refine (eq_cyclotomic_iff hp.pos _).mpr _, simp only [nat.prime.proper_divisors hp, geom_sum_mul, finset.prod_singleton, cyclotomic_one], end /-- The constant term of `cyclotomic n R` is `1` if `2 ≤ n`. -/ lemma cyclotomic_coeff_zero (R : Type*) [comm_ring R] {n : ℕ} (hn : 2 ≤ n) : (cyclotomic n R).coeff 0 = 1 := begin induction n using nat.strong_induction_on with n hi, have hprod : (∏ i in nat.proper_divisors n, (polynomial.cyclotomic i R).coeff 0) = -1, { rw [←finset.insert_erase (nat.one_mem_proper_divisors_iff_one_lt.2 (lt_of_lt_of_le one_lt_two hn)), finset.prod_insert (finset.not_mem_erase 1 _), cyclotomic_one R], have hleq : ∀ j ∈ n.proper_divisors.erase 1, 2 ≤ j, { intros j hj, apply nat.succ_le_of_lt, exact (ne.le_iff_lt ((finset.mem_erase.1 hj).1).symm).mp (nat.succ_le_of_lt (nat.pos_of_mem_proper_divisors (finset.mem_erase.1 hj).2)) }, have hcongr : ∀ j ∈ n.proper_divisors.erase 1, (cyclotomic j R).coeff 0 = 1, { intros j hj, exact hi j (nat.mem_proper_divisors.1 (finset.mem_erase.1 hj).2).2 (hleq j hj) }, have hrw : ∏ (x : ℕ) in n.proper_divisors.erase 1, (cyclotomic x R).coeff 0 = 1, { rw finset.prod_congr (refl (n.proper_divisors.erase 1)) hcongr, simp only [finset.prod_const_one] }, simp only [hrw, mul_one, zero_sub, coeff_one_zero, coeff_X_zero, coeff_sub] }, have heq : (X ^ n - 1).coeff 0 = -(cyclotomic n R).coeff 0, { rw [←prod_cyclotomic_eq_X_pow_sub_one (lt_of_lt_of_le zero_lt_two hn), nat.divisors_eq_proper_divisors_insert_self_of_pos (lt_of_lt_of_le zero_lt_two hn), finset.prod_insert nat.proper_divisors.not_self_mem, mul_coeff_zero, coeff_zero_prod, hprod, mul_neg_eq_neg_mul_symm, mul_one] }, have hzero : (X ^ n - 1).coeff 0 = (-1 : R), { rw coeff_zero_eq_eval_zero _, simp only [zero_pow (lt_of_lt_of_le zero_lt_two hn), eval_X, eval_one, zero_sub, eval_pow, eval_sub] }, rw hzero at heq, exact neg_inj.mp (eq.symm heq) end /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime, then `a` and `p` are coprime. -/ lemma coprime_of_root_cyclotomic {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : a.coprime p := begin apply nat.coprime.symm, rw [hprime.1.coprime_iff_not_dvd], by_contra h, replace h := (zmod.nat_coe_zmod_eq_zero_iff_dvd a p).2 h, rw [is_root.def, ring_hom.eq_nat_cast, h, ← coeff_zero_eq_eval_zero] at hroot, by_cases hone : n = 1, { simp only [hone, cyclotomic_one, zero_sub, coeff_one_zero, coeff_X_zero, neg_eq_zero, one_ne_zero, coeff_sub] at hroot, exact hroot }, rw [cyclotomic_coeff_zero (zmod p) (nat.succ_le_of_lt (lt_of_le_of_ne (nat.succ_le_of_lt hpos) (ne.symm hone)))] at hroot, exact one_ne_zero hroot end end cyclotomic section order /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, then the multiplicative order of `a` modulo `p` divides `n`. -/ lemma order_of_root_cyclotomic_dvd {n : ℕ} (hpos : 0 < n) {p : ℕ} [fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) ∣ n := begin apply order_of_dvd_of_pow_eq_one, suffices hpow : eval (nat.cast_ring_hom (zmod p) a) (X ^ n - 1 : polynomial (zmod p)) = 0, { simp only [eval_X, eval_one, eval_pow, eval_sub, ring_hom.eq_nat_cast] at hpow, apply units.coe_eq_one.1, simp only [sub_eq_zero.mp hpow, zmod.coe_unit_of_coprime, units.coe_pow] }, rw [is_root.def] at hroot, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos (zmod p), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, eval_mul, hroot, zero_mul] end /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime that does not divide `n`, then the multiplicative order of `a` modulo `p` is exactly `n`. -/ lemma order_of_root_cyclotomic {n : ℕ} (hpos : 0 < n) {p : ℕ} [fact p.prime] {a : ℕ} (hn : ¬ p ∣ n) (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) = n := begin set m := order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)), have ha := coprime_of_root_cyclotomic hpos hroot, have hdivcycl : map (int.cast_ring_hom (zmod p)) (X - a) ∣ (cyclotomic n (zmod p)), { replace hrootdiv := dvd_iff_is_root.2 hroot, simp only [C_eq_nat_cast, ring_hom.eq_nat_cast] at hrootdiv, simp only [hrootdiv, map_nat_cast, map_X, map_sub] }, by_contra hdiff, have hdiv : map (int.cast_ring_hom (zmod p)) (X - a) ∣ ∏ i in nat.proper_divisors n, cyclotomic i (zmod p), { suffices hdivm : map (int.cast_ring_hom (zmod p)) (X - a) ∣ X ^ m - 1, { exact dvd_trans hdivm (X_pow_sub_one_dvd_prod_cyclotomic (zmod p) hpos (order_of_root_cyclotomic_dvd hpos hroot) hdiff) }, rw [map_sub, map_X, map_nat_cast, ← C_eq_nat_cast, dvd_iff_is_root, is_root.def, eval_sub, eval_pow, eval_one, eval_X, sub_eq_zero, ← zmod.coe_unit_of_coprime a ha, ← units.coe_pow, units.coe_eq_one], exact pow_order_of_eq_one (zmod.unit_of_coprime a ha) }, have habs : (map (int.cast_ring_hom (zmod p)) (X - a)) ^ 2 ∣ X ^ n - 1, { obtain ⟨P, hP⟩ := hdivcycl, obtain ⟨Q, hQ⟩ := hdiv, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, hP, hQ], exact ⟨P * Q, by ring⟩ }, have hnzero : ↑n ≠ (0 : (zmod p)), { intro ha, exact hn (int.coe_nat_dvd.1 ((zmod.int_coe_zmod_eq_zero_iff_dvd n p).1 ha)) }, rw [sq] at habs, replace habs := squarefree_X_pow_sub_C (1 : (zmod p)) hnzero one_ne_zero (map (int.cast_ring_hom (zmod p)) (X - a)) habs, simp only [map_nat_cast, map_X, map_sub] at habs, replace habs := degree_eq_zero_of_is_unit habs, rw [← C_eq_nat_cast, degree_X_sub_C] at habs, norm_cast at habs end end order end polynomial section minpoly open is_primitive_root polynomial complex /-- The minimal polynomial of a primitive `n`-th root of unity `μ` divides `cyclotomic n ℤ`. -/ lemma minpoly_primitive_root_dvd_cyclotomic {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : minpoly ℤ μ ∣ cyclotomic n ℤ := begin apply minpoly.integer_dvd (is_integral h hpos) (cyclotomic.monic n ℤ).is_primitive, simpa [aeval_def, eval₂_eq_eval_map, is_root.def] using is_root_cyclotomic hpos h end /-- `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma cyclotomic_eq_minpoly {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : cyclotomic n ℤ = minpoly ℤ μ := begin refine eq_of_monic_of_dvd_of_nat_degree_le (minpoly.monic (is_integral h hpos)) (cyclotomic.monic n ℤ) (minpoly_primitive_root_dvd_cyclotomic h hpos) _, simpa [nat_degree_cyclotomic n ℤ] using totient_le_degree_minpoly h hpos end /-- `cyclotomic n ℤ` is irreducible. -/ lemma cyclotomic.irreducible {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℤ) := begin have h0 := (ne_of_lt hpos).symm, rw [cyclotomic_eq_minpoly (is_primitive_root_exp n h0) hpos], apply minpoly.irreducible, exact (is_primitive_root_exp n h0).is_integral hpos, end end minpoly
1c16b014afa1a877574442ee937b172170f8e9eb
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Init/Prelude.lean
76354368af66d6d676bac76a54f34d45b3fe50c1
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
70,063
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude universes u v w @[inline] def id {α : Sort u} (a : α) : α := a /- The kernel definitional equality test (t =?= s) has special support for idDelta applications. It implements the following rules 1) (idDelta t) =?= t 2) t =?= (idDelta t) 3) (idDelta t) =?= s IF (unfoldOf t) =?= s 4) t =?= idDelta s IF t =?= (unfoldOf s) This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel. We use idDelta applications to address performance problems when Type checking theorems generated by the equation Compiler. -/ @[inline] def idDelta {α : Sort u} (a : α) : α := a /- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/ @[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a @[reducible] def inferInstance {α : Type u} [i : α] : α := i @[reducible] def inferInstanceAs (α : Type u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u where | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop where | intro : True inductive False : Prop inductive Empty : Type def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop where | refl {} : Eq a a abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where | refl {} : HEq a a @[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b from fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) where fst : α snd : β attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) where fst : α snd : β /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) where fst : α snd : β structure And (a b : Prop) : Prop where intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop where | inl (h : a) : Or a b | inr (h : b) : Or a b inductive Bool : Type where | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) where val : α property : p val /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ @[extern "lean_sorry", neverExtract] axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) where mk {} :: (default : α) constant arbitrary [Inhabited α] : α := Inhabited.default instance : Inhabited (Sort u) where default := PUnit instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where default := fun _ => arbitrary instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where default := fun _ => arbitrary /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u where up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType where (type : Type u) (val : type) instance : Inhabited PointedType.{u} where default := { type := PUnit.{u+1}, val := ⟨⟩ } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) where up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) where | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decideEqTrue : {p : Prop} → [s : Decidable p] → p → Eq (decide p) true | _, isTrue _, _ => rfl | _, isFalse h₁, h₂ => absurd h₂ h₁ theorem decideEqFalse : {p : Prop} → [s : Decidable p] → Not p → Eq (decide p) false | _, isTrue h₁, h₂ => absurd h₁ h₂ | _, isFalse h, _ => rfl theorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true → p := fun h => match s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁)) theorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false → Not p := fun h => match s with | isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) where beq : α → α → Bool open BEq (beq) instance {α : Type u} [DecidableEq α] : BEq α where beq a b := decide (Eq a b) -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t /- if-then-else -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance {p} [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /- Boolean operators -/ @[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α := match c with | true => x | false => y @[macroInline] def or (x y : Bool) : Bool := match x with | true => true | false => y @[macroInline] def and (x y : Bool) : Bool := match x with | false => false | true => y @[inline] def not : Bool → Bool | true => false | false => true inductive Nat where | zero : Nat | succ (n : Nat) : Nat instance : Inhabited Nat where default := Nat.zero /- For numeric literals notation -/ class OfNat (α : Type u) (n : Nat) where ofNat : α @[defaultInstance 100] /- low prio -/ instance (n : Nat) : OfNat Nat n where ofNat := n class HasLessEq (α : Type u) where LessEq : α → α → Prop class HasLess (α : Type u) where Less : α → α → Prop export HasLess (Less) export HasLessEq (LessEq) class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAdd : α → β → γ class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where hSub : α → β → γ class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMul : α → β → γ class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where hDiv : α → β → γ class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMod : α → β → γ class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where hPow : α → β → γ class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAppend : α → β → γ class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOrElse : α → β → γ class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAndThen : α → β → γ class Add (α : Type u) where add : α → α → α class Sub (α : Type u) where sub : α → α → α class Mul (α : Type u) where mul : α → α → α class Neg (α : Type u) where neg : α → α class Div (α : Type u) where div : α → α → α class Mod (α : Type u) where mod : α → α → α class Pow (α : Type u) where pow : α → α → α class Append (α : Type u) where append : α → α → α class OrElse (α : Type u) where orElse : α → α → α class AndThen (α : Type u) where andThen : α → α → α @[defaultInstance] instance [Add α] : HAdd α α α where hAdd a b := Add.add a b @[defaultInstance] instance [Sub α] : HSub α α α where hSub a b := Sub.sub a b @[defaultInstance] instance [Mul α] : HMul α α α where hMul a b := Mul.mul a b @[defaultInstance] instance [Div α] : HDiv α α α where hDiv a b := Div.div a b @[defaultInstance] instance [Mod α] : HMod α α α where hMod a b := Mod.mod a b @[defaultInstance] instance [Pow α] : HPow α α α where hPow a b := Pow.pow a b @[defaultInstance] instance [Append α] : HAppend α α α where hAppend a b := Append.append a b @[defaultInstance] instance [OrElse α] : HOrElse α α α where hOrElse a b := OrElse.orElse a b @[defaultInstance] instance [AndThen α] : HAndThen α α α where hAndThen a b := AndThen.andThen a b open HAdd (hAdd) open HMul (hMul) open HPow (hPow) open HAppend (hAppend) @[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := LessEq b a @[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := Less b a set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat where add := Nat.add /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat where mul := Nat.mul set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat where pow := Nat.pow set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_dec_eq"] def Nat.beq : Nat → Nat → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem Nat.eqOfBeqEqTrue : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have Eq (beq n m) true from h have Eq n m from eqOfBeqEqTrue this this ▸ rfl theorem Nat.neOfBeqEqFalse : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have Eq (beq n m) false from h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (neOfBeqEqFalse this)) @[extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eqOfBeqEqTrue h) | false => isFalse (neOfBeqEqFalse h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_dec_le"] def Nat.ble : Nat → Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected def Nat.le (n m : Nat) : Prop := Eq (ble n m) true instance : HasLessEq Nat where LessEq := Nat.le protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : HasLess Nat where Less := Nat.lt theorem Nat.notSuccLeZero : ∀ (n : Nat), LessEq (succ n) 0 → False | 0, h => nomatch h | succ n, h => nomatch h theorem Nat.notLtZero (n : Nat) : Not (Less n 0) := notSuccLeZero n @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LessEq n m) := decEq (Nat.ble n m) true @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (Less n m) := decLe (succ n) m theorem Nat.zeroLe : (n : Nat) → LessEq 0 n | zero => rfl | succ n => rfl theorem Nat.succLeSucc {n m : Nat} (h : LessEq n m) : LessEq (succ n) (succ m) := h theorem Nat.zeroLtSucc (n : Nat) : Less 0 (succ n) := succLeSucc (zeroLe n) theorem Nat.leStep : {n m : Nat} → LessEq n m → LessEq n (succ m) | zero, zero, h => rfl | zero, succ n, h => rfl | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h have LessEq n (succ m) from leStep this succLeSucc this set_option pp.raw true protected theorem Nat.leTrans : {n m k : Nat} → LessEq n m → LessEq m k → LessEq n k | zero, m, k, h₁, h₂ => zeroLe _ | succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁ | succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, succ k, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m k from h₂ show LessEq n k from Nat.leTrans h₁' h₂' protected theorem Nat.ltTrans {n m k : Nat} (h₁ : Less n m) : Less m k → Less n k := Nat.leTrans (leStep h₁) theorem Nat.leSucc : (n : Nat) → LessEq n (succ n) | zero => rfl | succ n => leSucc n theorem Nat.leSuccOfLe {n m : Nat} (h : LessEq n m) : LessEq n (succ m) := Nat.leTrans h (leSucc m) protected theorem Nat.eqOrLtOfLe : {n m: Nat} → LessEq n m → Or (Eq n m) (Less n m) | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr (zeroLe n) | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h match Nat.eqOrLtOfLe this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succLeSucc h) protected def Nat.leRefl : (n : Nat) → LessEq n n | zero => rfl | succ n => Nat.leRefl n protected theorem Nat.ltOrGe (n m : Nat) : Or (Less n m) (GreaterEq n m) := match m with | zero => Or.inr (zeroLe n) | succ m => match Nat.ltOrGe n m with | Or.inl h => Or.inl (leSuccOfLe h) | Or.inr h => match Nat.eqOrLtOfLe h with | Or.inl h1 => Or.inl (h1 ▸ Nat.leRefl _) | Or.inr h1 => Or.inr h1 protected theorem Nat.leAntisymm : {n m : Nat} → LessEq n m → LessEq m n → Eq n m | zero, zero, h₁, h₂ => rfl | succ n, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m n from h₂ (Nat.leAntisymm h₁' h₂') ▸ rfl protected theorem Nat.ltOfLeOfNe {n m : Nat} (h₁ : LessEq n m) (h₂ : Not (Eq n m)) : Less n m := match Nat.ltOrGe n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.leAntisymm h₁ h₃) h₂ set_option bootstrap.gen_matcher_code false in @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : Nat → Nat | 0 => 0 | succ a => a set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_sub"] protected def Nat.sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, succ b => pred (Nat.sub a b) instance : Sub Nat where sub := Nat.sub theorem Nat.predLePred : {n m : Nat} → LessEq n m → LessEq (pred n) (pred m) | zero, zero, h => rfl | zero, succ n, h => zeroLe n | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => h theorem Nat.leOfSuccLeSucc {n m : Nat} : LessEq (succ n) (succ m) → LessEq n m := predLePred theorem Nat.leOfLtSucc {m n : Nat} : Less m (succ n) → LessEq m n := leOfSuccLeSucc @[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBitsEq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property structure Fin (n : Nat) where val : Nat isLt : Less val n theorem Fin.eqOfVeq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Fin.veqOfEq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.neOfVne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (veqOfEq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eqOfVeq h) | isFalse h => isFalse (Fin.neOfVne h) instance {n} : HasLess (Fin n) where Less a b := Less a.val b.val instance {n} : HasLessEq (Fin n) where LessEq a b := LessEq a.val b.val instance Fin.decLt {n} (a b : Fin n) : Decidable (Less a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LessEq a b) := Nat.decLe .. def UInt8.size : Nat := 256 structure UInt8 where val : Fin UInt8.size attribute [extern "lean_uint8_of_nat"] UInt8.mk attribute [extern "lean_uint8_to_nat"] UInt8.val @[extern "lean_uint8_of_nat"] def UInt8.ofNatCore (n : @& Nat) (h : Less n UInt8.size) : UInt8 := { val := { val := n, isLt := h } } set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 where default := UInt8.ofNatCore 0 decide! def UInt16.size : Nat := 65536 structure UInt16 where val : Fin UInt16.size attribute [extern "lean_uint16_of_nat"] UInt16.mk attribute [extern "lean_uint16_to_nat"] UInt16.val @[extern "lean_uint16_of_nat"] def UInt16.ofNatCore (n : @& Nat) (h : Less n UInt16.size) : UInt16 := { val := { val := n, isLt := h } } set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 where default := UInt16.ofNatCore 0 decide! def UInt32.size : Nat := 4294967296 structure UInt32 where val : Fin UInt32.size attribute [extern "lean_uint32_of_nat"] UInt32.mk attribute [extern "lean_uint32_to_nat"] UInt32.val @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : Less n UInt32.size) : UInt32 := { val := { val := n, isLt := h } } @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 where default := UInt32.ofNatCore 0 decide! instance : HasLess UInt32 where Less a b := Less a.val b.val instance : HasLessEq UInt32 where LessEq a b := LessEq a.val b.val set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 < #2"] def UInt32.decLt (a b : UInt32) : Decidable (Less a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (Less n m)) set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 <= #2"] def UInt32.decLe (a b : UInt32) : Decidable (LessEq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LessEq n m)) instance (a b : UInt32) : Decidable (Less a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LessEq a b) := UInt32.decLe a b def UInt64.size : Nat := 18446744073709551616 structure UInt64 where val : Fin UInt64.size attribute [extern "lean_uint64_of_nat"] UInt64.mk attribute [extern "lean_uint64_to_nat"] UInt64.val @[extern "lean_uint64_of_nat"] def UInt64.ofNatCore (n : @& Nat) (h : Less n UInt64.size) : UInt64 := { val := { val := n, isLt := h } } set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 where default := UInt64.ofNatCore 0 decide! def USize.size : Nat := hPow 2 System.Platform.numBits theorem usizeSzEq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) := show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBitsEq with | _, Or.inl rfl => Or.inl (decide! : (Eq (hPow 2 32) (4294967296:Nat))) | _, Or.inr rfl => Or.inr (decide! : (Eq (hPow 2 64) (18446744073709551616:Nat))) structure USize where val : Fin USize.size attribute [extern "lean_usize_of_nat"] USize.mk attribute [extern "lean_usize_to_nat"] USize.val @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : Less n USize.size) : USize := { val := { val := n, isLt := h } } set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize where default := USize.ofNatCore 0 (match USize.size, usizeSzEq with | _, Or.inl rfl => decide! | _, Or.inr rfl => decide!) @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : Less n 4294967296) : USize := { val := { val := n, isLt := match USize.size, usizeSzEq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.ltTrans h (decide! : Less 4294967296 18446744073709551616) } } abbrev Nat.isValidChar (n : Nat) : Prop := Or (Less n 0xd800) (And (Less 0xdfff n) (Less n 0x110000)) abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char where val : UInt32 valid : val.isValidChar private theorem validCharIsUInt32 {n : Nat} (h : n.isValidChar) : Less n UInt32.size := match h with | Or.inl h => Nat.ltTrans h (decide! : Less 55296 UInt32.size) | Or.inr ⟨_, h⟩ => Nat.ltTrans h (decide! : Less 1114112 UInt32.size) @[extern "lean_uint32_of_nat"] private def Char.ofNatAux (n : Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := validCharIsUInt32 h }⟩, valid := h } @[noinline, matchPattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := decide! }⟩, valid := Or.inl decide! }) theorem Char.eqOfVeq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Char.veqOfEq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.neOfVne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (veqOfEq h') h theorem Char.vneOfNe {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eqOfVeq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eqOfVeq h) | isFalse h => isFalse (Char.neOfVne h) def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LessEq v (UInt32.ofNatCore 0x7F decide!)) (UInt32.ofNatCore 1 decide!) (ite (LessEq v (UInt32.ofNatCore 0x7FF decide!)) (UInt32.ofNatCore 2 decide!) (ite (LessEq v (UInt32.ofNatCore 0xFFFF decide!)) (UInt32.ofNatCore 3 decide!) (UInt32.ofNatCore 4 decide!))) inductive Option (α : Type u) where | none : Option α | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) where default := none inductive List (α : Type u) where | nil : List α | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) where default := List.nil protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons a as, nil => isFalse (fun h => List.noConfusion h) | nil, cons b bs => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l def List.set : List α → Nat → α → List α | cons a as, 0, b => cons b as | cons a as, Nat.succ n, b => cons a (set as n b) | nil, _, _ => nil def List.lengthAux {α : Type u} : List α → Nat → Nat | nil, n => n | cons a as, n => lengthAux as (Nat.succ n) def List.length {α : Type u} (as : List α) : Nat := lengthAux as 0 theorem List.lengthConsEq {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ := let rec aux (a : α) (as : List α) : (n : Nat) → Eq ((cons a as).lengthAux n) (as.lengthAux n).succ := match as with | nil => fun _ => rfl | cons a as => fun n => aux a as n.succ aux a as 0 def List.concat {α : Type u} : List α → α → List α | nil, b => cons b nil | cons a as, b => cons a (concat as b) def List.get {α : Type u} : (as : List α) → (i : Nat) → Less i as.length → α | nil, i, h => absurd h (Nat.notLtZero _) | cons a as, 0, h => a | cons a as, Nat.succ i, h => have Less i.succ as.length.succ from lengthConsEq .. ▸ h get as i (Nat.leOfSuccLeSucc this) structure String where data : List Char attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ abbrev String.Pos := Nat structure Substring where str : String startPos : String.Pos stopPos : String.Pos def String.csize (c : Char) : Nat := c.utf8Size.toNat private def String.utf8ByteSizeAux : List Char → Nat → Nat | List.nil, r => r | List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c)) @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => utf8ByteSizeAux s 0 @[inline] def String.bsize (s : String) : Nat := utf8ByteSize s @[inline] def String.toSubstring (s : String) : Substring := { str := s, startPos := 0, stopPos := s.bsize } @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panic {α : Type u} [Inhabited α] (msg : String) : α /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) where data : List α attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_mk"] Array.mk /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := { data := List.nil } def Array.empty {α : Type u} : Array α := mkEmpty 0 @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.data.length @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data.get i.val i.isLt @[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α := dite (Less i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀) /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := Array.getD a i arbitrary def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α := self.get! idx @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α := { data := List.concat a.data v } @[extern "lean_array_fset"] def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := { data := a.data.set i.val v } @[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α := dite (Less i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a) @[extern "lean_array_set"] def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α := Array.setD a i v -- Slower `Array.append` used in quotations. protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α := let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α := dite (Less j bs.size) (fun hlt => match i with | 0 => as | Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩))) (fun _ => as) loop bs.size 0 as class Bind (m : Type u → Type v) where bind : {α β : Type u} → m α → (α → m β) → m β export Bind (bind) class Pure (f : Type u → Type v) where pure {α : Type u} : α → f α export Pure (pure) class Functor (f : Type u → Type v) : Type (max (u+1) v) where map : {α β : Type u} → (α → β) → f α → f β mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) class Seq (f : Type u → Type v) : Type (max (u+1) v) where seq : {α β : Type u} → f (α → β) → f α → f β class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where seqLeft : {α : Type u} → f α → f PUnit → f α class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where seqRight : {β : Type u} → f PUnit → f β → f β class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where map := fun x y => Seq.seq (pure x) y seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where map := fun f x => bind x (Function.comp pure f) seq := fun f x => bind f fun y => Functor.map y x seqLeft := fun x y => bind x fun a => bind y (fun _ => pure a) seqRight := fun x y => bind x fun _ => y instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where default := pure instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where default := pure arbitrary -- A fusion of Haskell's `sequence` and `map` def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) := let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) := dite (Less j as.size) (fun hlt => match i with | 0 => pure bs | Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b)) (fun _ => bs) loop as.size 0 Array.empty /-- A Function for lifting a computation from an inner Monad to an outer Monad. Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html), but `n` does not have to be a monad transformer. Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α export MonadLiftT (monadLift) abbrev liftM := @monadLift instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where monadLift x := MonadLift.monadLift (m := n) (monadLift x) instance (m) : MonadLiftT m m where monadLift x := x /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html), but not restricted to monad transformers. Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : (∀ {β}, m β → m β) → n α → n α /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : (∀ {β}, m β → m β) → n α → n α export MonadFunctorT (monadMap) instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f) instance monadFunctorRefl (m) : MonadFunctorT m m where monadMap f := f inductive Except (ε : Type u) (α : Type v) where | error : ε → Except ε α | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where default := Except.error arbitrary /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α export MonadExcept (throw tryCatch) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where throw := throwThe ε tryCatch := tryCatchThe ε namespace MonadExcept variables {ε : Type u} {m : Type v → Type w} @[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α := tryCatch t₁ fun _ => t₂ instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where orElse := MonadExcept.orelse end MonadExcept /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where default := fun _ => arbitrary @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r @[reducible] def Reader (ρ : Type u) := ReaderT ρ id namespace ReaderT section variables {ρ : Type u} {m : Type u → Type v} {α : Type u} instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where throw e := liftM (m := m) (throw e) tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) end section variables {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => Functor.map f (x r) instance : Monad (ReaderT ρ m) where pure := ReaderT.pure bind := ReaderT.bind map := ReaderT.map instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where monadMap f x := fun ctx => f (x ctx) @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where lift {α : Type u} : (∀ {m : Type u → Type u} [Monad m], ReaderT ρ m α) → n α ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where read : m ρ @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where read : m ρ export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where read := readThe ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where read := liftM (m := m) read instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where read := ReaderT.read class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where withReader := withTheReader ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where withReader f := monadMap (m := m) (withTheReader ρ f) instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where withReader f x := fun ctx => x (f ctx) /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) where /- Obtain the top-most State of a Monad stack. -/ get : m σ /- Set the top-most State of a Monad stack. -/ set : σ → m PUnit /- Map the top-most State of a Monad stack. Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a` because the latter does not use the State linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadStateOf (set) abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where get : m σ set : σ → m PUnit modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where set := MonadStateOf.set get := getThe σ modifyGet := fun f => MonadStateOf.modifyGet f @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where get := liftM (m := m) MonadStateOf.get set := fun s => liftM (m := m) (MonadStateOf.set s) modifyGet := fun f => monadLift (m := m) (MonadState.modifyGet f) namespace EStateM inductive Result (ε σ α : Type u) where | ok : α → σ → Result ε σ α | error : ε → σ → Result ε σ α variables {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where default := Result.error arbitrary arbitrary end EStateM open EStateM (Result) in def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variables {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) where default := fun s => Result.error arbitrary s @[inline] protected def pure (a : α) : EStateM ε σ α := fun s => Result.ok a s @[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ => Result.ok ⟨⟩ s @[inline] protected def get : EStateM ε σ σ := fun s => Result.ok s s @[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s => match f s with | (a, s) => Result.ok a s @[inline] protected def throw (e : ε) : EStateM ε σ α := fun s => Result.error e s /-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/ class Backtrackable (δ : outParam (Type u)) (σ : Type u) where save : σ → δ restore : σ → δ → σ @[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s match x s with | Result.error e s => handle e (Backtrackable.restore s d) | ok => ok @[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ (Backtrackable.restore s d) | ok => ok @[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s => match x s with | Result.error e s => Result.error (f e) s | Result.ok a s => Result.ok a s @[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok a s => f a s | Result.error e s => Result.error e s @[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s => match x s with | Result.ok a s => Result.ok (f a) s | Result.error e s => Result.error e s @[inline] protected def seqRight (x : EStateM ε σ PUnit) (y : EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y s | Result.error e s => Result.error e s instance : Monad (EStateM ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where orElse := EStateM.orElse instance : MonadStateOf σ (EStateM ε σ) where set := EStateM.set get := EStateM.get modifyGet := EStateM.modifyGet instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where throw := EStateM.throw tryCatch := EStateM.tryCatch @[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s @[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error _ _ => none @[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩ @[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s /- Dummy default instance -/ instance nonBacktrackable : Backtrackable PUnit σ where save := dummySave restore := dummyRestore end EStateM class Hashable (α : Type u) where hash : α → USize export Hashable (hash) @[extern "lean_usize_mix_hash"] constant mixHash (u₁ u₂ : USize) : USize @[extern "lean_string_hash"] protected constant String.hash (s : @& String) : USize instance : Hashable String where hash := String.hash namespace Lean /- Hierarchical names -/ inductive Name where | anonymous : Name | str : Name → String → USize → Name | num : Name → Nat → USize → Name instance : Inhabited Name where default := Name.anonymous protected def Name.hash : Name → USize | Name.anonymous => USize.ofNat32 1723 decide! | Name.str p s h => h | Name.num p v h => h instance : Hashable Name where hash := Name.hash namespace Name @[export lean_name_mk_string] def mkStr (p : Name) (s : String) : Name := Name.str p s (mixHash (hash p) (hash s)) @[export lean_name_mk_numeral] def mkNum (p : Name) (v : Nat) : Name := Name.num p v (mixHash (hash p) (dite (Less v USize.size) (fun h => USize.ofNatCore v h) (fun _ => USize.ofNat32 17 decide!))) def mkSimple (s : String) : Name := mkStr Name.anonymous s @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name where beq := Name.beq protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => Name.mkStr (Name.append n p) s | n, num p d _ => Name.mkNum (Name.append n p) d instance : Append Name where append := Name.append end Name /- Syntax -/ /-- Source information of syntax atoms. All information is generally set for unquoted syntax and unset for syntax in syntax quotations, but syntax transformations might want to invalidate only one side to make the pretty printer reformat it. In the special case of the delaborator, we also use purely synthetic position information without whitespace information. -/ structure SourceInfo where /- Will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ leading : Option Substring := none pos : Option String.Pos := none trailing : Option Substring := none instance : Inhabited SourceInfo := ⟨{}⟩ abbrev SyntaxNodeKind := Name /- Syntax AST -/ inductive Syntax where | missing : Syntax | node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax instance : Inhabited Syntax where default := Syntax.missing /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def scientificLitKind : SyntaxNodeKind := `scientificLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident _ _ _ _ => identKind def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node _ args => Syntax.node k args | _ => stx def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ args => args.getD i Syntax.missing | _ => Syntax.missing -- Add `stx[i]` as sugar for `stx.getArg i` @[inline] def getOp (self : Syntax) (idx : Nat) : Syntax := self.getArg idx def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ args => args | _ => Array.empty def getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ args => args.size | _ => 0 def setArgs (stx : Syntax) (args : Array Syntax) : Syntax := match stx with | node k _ => node k args | stx => stx def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax := match stx with | node k args => node k (args.setD i arg) | stx => stx /-- Retrieve the left-most leaf's info in the Syntax tree. -/ partial def getHeadInfo : Syntax → Option SourceInfo | atom info _ => some info | ident info _ _ _ => some info | node _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (Less i args.size) with | true => match getHeadInfo (args.get! i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _ => none def getPos (stx : Syntax) : Option String.Pos := match stx.getHeadInfo with | some info => info.pos | _ => none /-- An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically remove/insert the separators. -/ structure SepArray (sep : String) where elemsAndSeps : Array Syntax end Syntax def mkAtomFrom (src : Syntax) (val : String) : Syntax := match src.getHeadInfo with | some info => Syntax.atom info val | none => Syntax.atom {} val /- Parser descriptions -/ inductive ParserDescr where | const (name : Name) | unary (name : Name) (p : ParserDescr) | binary (name : Name) (p₁ p₂ : ParserDescr) | node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | trailingNode (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | symbol (val : String) | nonReservedSymbol (val : String) (includeIdent : Bool) | cat (catName : Name) (rbp : Nat) | parser (declName : Name) | nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr) | sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) | sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) instance : Inhabited ParserDescr where default := ParserDescr.symbol "" abbrev TrailingParserDescr := ParserDescr /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := hAdd reservedMacroScope 1 class MonadRef (m : Type → Type) where getRef : m Syntax withRef {α} : Syntax → m α → m α export MonadRef (getRef) instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where getRef := liftM (getRef : m _) withRef := fun ref x => monadMap (m := m) (MonadRef.withRef ref) x def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos with | some _ => ref | _ => oldRef @[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position. -/ class MonadQuotation (m : Type → Type) extends MonadRef m where -- Get the fresh scope of the current macro invocation getCurrMacroScope : m MacroScope getMainModule : m Name /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do return { pos := (← getRef).getPos } instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where getCurrMacroScope := liftM (m := m) getCurrMacroScope getMainModule := liftM (m := m) getMainModule withFreshMacroScope := monadMap (m := m) withFreshMacroScope /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | str _ s _ => beq s "_hyg" | num p _ _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p s _ => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => Name.anonymous @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n structure MacroScopesView where name : Name imported : Name mainModule : Name scopes : List MacroScope instance : Inhabited MacroScopesView where default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | List.nil, acc => acc | List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s) | List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n) | _, acc => panic "Error: unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "Error: unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "Error: unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "Error: unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule), mainModule := mainModule, scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) def defaultMaxRecDepth := 512 def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Macro /- References -/ constant MacroEnvPointed : PointedType.{0} def MacroEnv : Type := MacroEnvPointed.type instance : Inhabited MacroEnv where default := MacroEnvPointed.val structure Context where macroEnv : MacroEnv mainModule : Name currMacroScope : MacroScope currRecDepth : Nat := 0 maxRecDepth : Nat := defaultMaxRecDepth ref : Syntax inductive Exception where | error : Syntax → String → Exception | unsupportedSyntax : Exception end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception MacroScope) abbrev Macro := Syntax → MacroM Syntax namespace Macro instance : MonadRef MacroM where getRef := bind read fun ctx => pure ctx.ref withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax def throwError {α} (msg : String) : MacroM α := bind getRef fun ref => throw (Exception.error ref msg) def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α := withRef ref (throwError msg) @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s, hAdd s 1))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM where getCurrMacroScope := fun ctx => pure ctx.currMacroScope getMainModule := fun ctx => pure ctx.mainModule withFreshMacroScope := Macro.withFreshMacroScope unsafe def mkMacroEnvImp (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv := unsafeCast expandMacro? @[implementedBy mkMacroEnvImp] constant mkMacroEnv (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv def expandMacroNotAvailable? (stx : Syntax) : MacroM (Option Syntax) := throwErrorAt stx "expandMacro has not been set" def mkMacroEnvSimple : MacroEnv := mkMacroEnv expandMacroNotAvailable? unsafe def expandMacro?Imp (stx : Syntax) : MacroM (Option Syntax) := bind read fun ctx => let f : Syntax → MacroM (Option Syntax) := unsafeCast (ctx.macroEnv) f stx /-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ @[implementedBy expandMacro?Imp] constant expandMacro? : Syntax → MacroM (Option Syntax) end Macro export Macro (expandMacro?) namespace PrettyPrinter abbrev UnexpandM := EStateM Unit Unit /-- Function that tries to reverse macro expansions as a post-processing step of delaboration. While less general than an arbitrary delaborator, it can be declared without importing `Lean`. Used by the `[appUnexpander]` attribute. -/ -- a `kindUnexpander` could reasonably be added later abbrev Unexpander := Syntax → UnexpandM Syntax -- unexpanders should not need to introduce new names instance : MonadQuotation UnexpandM where getRef := pure Syntax.missing withRef := fun _ => id getCurrMacroScope := pure 0 getMainModule := pure `_fakeMod withFreshMacroScope := id end PrettyPrinter end Lean
39974873544ca4f206c3822b0c8e99bd9520eeb4
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/LeanInit.lean
56593e32501fc67123f4e4d0a97c1d8ee756d353
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
28,472
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura and Sebastian Ullrich -/ prelude import Init.Data.String.Basic import Init.Data.Array.Basic import Init.Data.UInt import Init.Data.Hashable import Init.Control.Reader import Init.Control.EState namespace Lean /- Basic Lean types used to implement builtin commands and extensions. Note that this file is part of the Lean `Init` library instead of `Lean` actual implementation. The idea is to allow users to implement simple parsers, macros and tactics without importing the whole `Lean` module. It also allow us to use extensions to develop the `Init` library. -/ /- Valid identifier names -/ def isGreek (c : Char) : Bool := 0x391 ≤ c.val && c.val ≤ 0x3dd def isLetterLike (c : Char) : Bool := (0x3b1 ≤ c.val && c.val ≤ 0x3c9 && c.val ≠ 0x3bb) || -- Lower greek, but lambda (0x391 ≤ c.val && c.val ≤ 0x3A9 && c.val ≠ 0x3A0 && c.val ≠ 0x3A3) || -- Upper greek, but Pi and Sigma (0x3ca ≤ c.val && c.val ≤ 0x3fb) || -- Coptic letters (0x1f00 ≤ c.val && c.val ≤ 0x1ffe) || -- Polytonic Greek Extended Character Set (0x2100 ≤ c.val && c.val ≤ 0x214f) || -- Letter like block (0x1d49c ≤ c.val && c.val ≤ 0x1d59f) -- Latin letters, Script, Double-struck, Fractur def isSubScriptAlnum (c : Char) : Bool := (0x2080 ≤ c.val && c.val ≤ 0x2089) || -- numeric subscripts (0x2090 ≤ c.val && c.val ≤ 0x209c) || (0x1d62 ≤ c.val && c.val ≤ 0x1d6a) def isIdFirst (c : Char) : Bool := c.isAlpha || c = '_' || isLetterLike c def isIdRest (c : Char) : Bool := c.isAlphanum || c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c def idBeginEscape := '«' def idEndEscape := '»' def isIdBeginEscape (c : Char) : Bool := c = idBeginEscape def isIdEndEscape (c : Char) : Bool := c = idEndEscape /- Hierarchical names -/ inductive Name | anonymous : Name | str : Name → String → USize → Name | num : Name → Nat → USize → Name instance Name.inhabited : Inhabited Name := ⟨Name.anonymous⟩ protected def Name.hash : Name → USize | Name.anonymous => 1723 | Name.str p s h => h | Name.num p v h => h instance Name.hashable : Hashable Name := ⟨Name.hash⟩ @[export lean_name_mk_string] def mkNameStr (p : Name) (s : String) : Name := Name.str p s $ mixHash (hash p) (hash s) @[export lean_name_mk_numeral] def mkNameNum (p : Name) (v : Nat) : Name := Name.num p v $ mixHash (hash p) (hash v) def mkNameSimple (s : String) : Name := mkNameStr Name.anonymous s namespace Name @[extern "lean_name_eq"] protected def Name.beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => s₁ == s₂ && Name.beq p₁ p₂ | num p₁ n₁ _, num p₂ n₂ _ => n₁ == n₂ && Name.beq p₁ p₂ | _, _ => false instance : HasBeq Name := ⟨Name.beq⟩ def toStringWithSep (sep : String) : Name → String | anonymous => "[anonymous]" | str anonymous s _ => s | num anonymous v _ => toString v | str n s _ => toStringWithSep n ++ sep ++ s | num n v _ => toStringWithSep n ++ sep ++ repr v protected def toString : Name → String := toStringWithSep "." instance : HasToString Name := ⟨Name.toString⟩ protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => mkNameStr (append n p) s | n, num p d _ => mkNameNum (append n p) d instance : HasAppend Name := ⟨Name.append⟩ end Name structure NameGenerator := (namePrefix : Name := `_uniq) (idx : Nat := 1) namespace NameGenerator instance : Inhabited NameGenerator := ⟨{}⟩ @[inline] def curr (g : NameGenerator) : Name := mkNameNum g.namePrefix g.idx @[inline] def next (g : NameGenerator) : NameGenerator := { idx := g.idx + 1, .. g } @[inline] def mkChild (g : NameGenerator) : NameGenerator × NameGenerator := ({ namePrefix := mkNameNum g.namePrefix g.idx, idx := 1 }, { idx := g.idx + 1, .. g }) end NameGenerator /- Small DSL for describing parsers. We implement an interpreter for it at `Parser.lean` -/ inductive ParserDescr | andthen : ParserDescr → ParserDescr → ParserDescr | orelse : ParserDescr → ParserDescr → ParserDescr | optional : ParserDescr → ParserDescr | lookahead : ParserDescr → ParserDescr | try : ParserDescr → ParserDescr | many : ParserDescr → ParserDescr | many1 : ParserDescr → ParserDescr | sepBy : ParserDescr → ParserDescr → ParserDescr | sepBy1 : ParserDescr → ParserDescr → ParserDescr | node : Name → ParserDescr → ParserDescr | trailingNode : Name → ParserDescr → ParserDescr | symbol : String → Option Nat → ParserDescr | nonReservedSymbol : String → Bool → ParserDescr | numLit : ParserDescr | strLit : ParserDescr | charLit : ParserDescr | nameLit : ParserDescr | ident : ParserDescr | parser : Name → Nat → ParserDescr instance ParserDescr.inhabited : Inhabited ParserDescr := ⟨ParserDescr.symbol "" none⟩ abbrev TrailingParserDescr := ParserDescr /- Syntax -/ structure SourceInfo := /- Will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ (leading : Substring) (pos : String.Pos) (trailing : Substring) instance SourceInfo.inhabited : Inhabited SourceInfo := ⟨⟨"".toSubstring, arbitrary _, "".toSubstring⟩⟩ abbrev SyntaxNodeKind := Name /- Syntax AST -/ inductive Syntax | missing {} : Syntax | node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom {} (info : Option SourceInfo) (val : String) : Syntax | ident {} (info : Option SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Name × List String)) : Syntax instance Syntax.inhabited : Inhabited Syntax := ⟨Syntax.missing⟩ /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => mkNameSimple v | Syntax.ident _ _ _ _ => identKind def isOfKind : Syntax → SyntaxNodeKind → Bool | stx, k => stx.getKind == k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ args => args.get! i | _ => arbitrary _ def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ args => args | _ => #[] /-- Retrieve the left-most leaf's info in the Syntax tree. -/ partial def getHeadInfo : Syntax → Option SourceInfo | atom info _ => info | ident info _ _ _ => info | node _ args => args.findSome? getHeadInfo | _ => none end Syntax /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := reservedMacroScope + 1 /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). -/ class MonadQuotation (m : Type → Type) := -- Get the fresh scope of the current macro invocation (getCurrMacroScope {} : m MacroScope) (getMainModule {} : m Name) /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ (withFreshMacroScope {α : Type} : m α → m α) export MonadQuotation /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | Name.str _ str _ => str == "_hyg" | Name.num p _ _ => Name.hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p str _ => if str == "_@" then p else eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => unreachable! def Name.eraseMacroScopes (n : Name) : Name := if n.hasMacroScopes then eraseMacroScopesAux n else n structure MacroScopesView := (name : Name) (imported : Name) (mainModule : Name) (scopes : List MacroScope) instance MacroScopesView.inhabited : Inhabited MacroScopesView := ⟨⟨arbitrary _, arbitrary _, arbitrary _, arbitrary _⟩⟩ def MacroScopesView.review (view : MacroScopesView) : Name := if view.scopes.isEmpty then view.name else let base := (mkNameStr ((mkNameStr view.name "_@") ++ view.imported ++ view.mainModule) "_hyg"); view.scopes.foldl mkNameNum base private def assembleParts : List Name → Name → Name | [], acc => acc | (Name.str _ s _) :: ps, acc => assembleParts ps (mkNameStr acc s) | (Name.num _ n _) :: ps, acc => assembleParts ps (mkNameNum acc n) | _, _ => unreachable! private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => if str == "_@" then { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } else extractImported p (n :: parts) | n@(Name.num p str _), parts => extractImported p (n :: parts) | _, _ => unreachable! private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => if str == "_@" then { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } else extractMainModule p (n :: parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n [] | _, _ => unreachable! private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (scp::acc) | Name.str p str _, acc => extractMainModule acc p [] -- str must be "_hyg" | _, _ => unreachable! /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := if n.hasMacroScopes then extractMacroScopesAux n [] else { name := n, scopes := [], imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := if n.hasMacroScopes then let view := extractMacroScopes n; if view.mainModule == mainModule then mkNameNum n scp else { imported := view.scopes.foldl mkNameNum (view.imported ++ view.mainModule), mainModule := mainModule, scopes := [scp], .. view }.review else mkNameNum (mkNameStr (mkNameStr n "_@" ++ mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := do mainModule ← getMainModule; scp ← getCurrMacroScope; pure $ addMacroScope mainModule n scp namespace Macro structure Context := (mainModule : Name) (currMacroScope : MacroScope) inductive Exception | error : Syntax → String → Exception | unsupportedSyntax : Exception end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception MacroScope) def Macro.addMacroScope (n : Name) : MacroM Name := do ctx ← read; pure $ Lean.addMacroScope ctx.mainModule n ctx.currMacroScope def Macro.throwUnsupported {α} : MacroM α := throw Macro.Exception.unsupportedSyntax def Macro.throwError {α} (ref : Syntax) (msg : String) : MacroM α := throw $ Macro.Exception.error ref msg @[inline] protected def Macro.withFreshMacroScope {α} (x : MacroM α) : MacroM α := do fresh ← modifyGet (fun s => (s, s+1)); adaptReader (fun (ctx : Macro.Context) => { currMacroScope := fresh, .. ctx }) x instance MacroM.monadQuotation : MonadQuotation MacroM := { getCurrMacroScope := fun ctx => pure ctx.currMacroScope, getMainModule := fun ctx => pure ctx.mainModule, withFreshMacroScope := @Macro.withFreshMacroScope } instance monadQuotationTrans {m n : Type → Type} [MonadQuotation m] [HasMonadLift m n] [MonadFunctorT m m n n] : MonadQuotation n := { getCurrMacroScope := liftM (getCurrMacroScope : m MacroScope), getMainModule := liftM (getMainModule : m Name), withFreshMacroScope := fun α => monadMap (fun α => (withFreshMacroScope : m α → m α)) } abbrev Macro := Syntax → MacroM Syntax /- Helper functions for processing Syntax programmatically -/ /-- Create an identifier using `SourceInfo` from `src`. To refer to a specific constant, use `mkCIdentFrom` instead. -/ def mkIdentFrom (src : Syntax) (val : Name) : Syntax := let info := src.getHeadInfo; Syntax.ident info (toString val).toSubstring val [] /-- Create an identifier referring to a constant `c` using `SourceInfo` from `src`. This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally be captured. -/ def mkCIdentFrom (src : Syntax) (c : Name) : Syntax := let info := src.getHeadInfo; -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend let id := addMacroScope `_internal c reservedMacroScope; Syntax.ident info (toString id).toSubstring id [(c, [])] def mkAtomFrom (src : Syntax) (val : String) : Syntax := let info := src.getHeadInfo; Syntax.atom info val def Syntax.identToAtom (stx : Syntax) : Syntax := match stx with | Syntax.ident info _ val _ => Syntax.atom info val.eraseMacroScopes.toString | _ => stx @[export lean_mk_syntax_ident] def mkIdent (val : Name) : Syntax := Syntax.ident none (toString val).toSubstring val [] @[inline] def mkNullNode (args : Array Syntax := #[]) : Syntax := Syntax.node nullKind args def mkSepStx (a : Array Syntax) (sep : Syntax) : Syntax := mkNullNode $ a.iterate #[] $ fun i a r => if i.val > 0 then (r.push sep).push a else r.push a def mkOptionalNode (arg : Option Syntax) : Syntax := match arg with | some arg => Syntax.node nullKind #[arg] | none => Syntax.node nullKind #[] /-- Create syntax representing a Lean term application -/ def mkAppStx (fn : Syntax) (args : Array Syntax) : Syntax := Syntax.node `Lean.Parser.Term.app #[fn, mkNullNode args] def mkHole (ref : Syntax) : Syntax := Syntax.node `Lean.Parser.Term.hole #[mkAtomFrom ref "_"] /-- Convert a `Syntax.ident` into a `Lean.Parser.Term.id` node -/ def mkTermIdFromIdent (ident : Syntax) : Syntax := match ident with | Syntax.ident _ _ _ _ => Syntax.node `Lean.Parser.Term.id #[ident, mkNullNode] | _ => unreachable! /-- Create a simple `Lean.Parser.Term.id` syntax using position information from `ref` and name `n`. By simple, we mean that `optional (explicitUniv <|> namedPattern)` is none. To refer to a specific constant, use `mkCTermIdFrom` instead. -/ def mkTermIdFrom (ref : Syntax) (n : Name) : Syntax := mkTermIdFromIdent (mkIdentFrom ref n) /-- Variant of `mkTermIdFrom` that makes sure that the identifier cannot accidentally be captured. -/ def mkCTermIdFrom (ref : Syntax) (c : Name) : Syntax := mkTermIdFromIdent (mkCIdentFrom ref c) def mkTermId (n : Name) : Syntax := mkTermIdFrom Syntax.missing n def mkCTermId (c : Name) : Syntax := mkCTermIdFrom Syntax.missing c def mkCAppStx (fn : Name) (args : Array Syntax) : Syntax := mkAppStx (mkCTermId fn) args def mkStxLit (kind : SyntaxNodeKind) (val : String) (info : Option SourceInfo := none) : Syntax := let atom : Syntax := Syntax.atom info val; Syntax.node kind #[atom] def mkStxStrLit (val : String) (info : Option SourceInfo := none) : Syntax := mkStxLit strLitKind (repr val) info def mkStxNumLit (val : String) (info : Option SourceInfo := none) : Syntax := mkStxLit numLitKind val info namespace Syntax /- Recall that we don't have special Syntax constructors for storing numeric and string atoms. The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or different ways of representing them. So, our atoms contain just the parsed string. The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded in binary, octal, decimal and hexadecimal format. `isNatLit` implements a "decoder" for Syntax objects representing these numerals. -/ private partial def decodeBinLitAux (s : String) : String.Pos → Nat → Option Nat | i, val => if s.atEnd i then some val else let c := s.get i; if c == '0' then decodeBinLitAux (s.next i) (2*val) else if c == '1' then decodeBinLitAux (s.next i) (2*val + 1) else none private partial def decodeOctalLitAux (s : String) : String.Pos → Nat → Option Nat | i, val => if s.atEnd i then some val else let c := s.get i; if '0' ≤ c && c ≤ '7' then decodeOctalLitAux (s.next i) (8*val + c.toNat - '0'.toNat) else none private def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat × String.Pos) := let c := s.get i; let i := s.next i; if '0' ≤ c && c ≤ '9' then some (c.toNat - '0'.toNat, i) else if 'a' ≤ c && c ≤ 'f' then some (10 + c.toNat - 'a'.toNat, i) else if 'A' ≤ c && c ≤ 'F' then some (10 + c.toNat - 'A'.toNat, i) else none private partial def decodeHexLitAux (s : String) : String.Pos → Nat → Option Nat | i, val => if s.atEnd i then some val else match decodeHexDigit s i with | some (d, i) => decodeHexLitAux i (16*val + d) | none => none private partial def decodeDecimalLitAux (s : String) : String.Pos → Nat → Option Nat | i, val => if s.atEnd i then some val else let c := s.get i; if '0' ≤ c && c ≤ '9' then decodeDecimalLitAux (s.next i) (10*val + c.toNat - '0'.toNat) else none def decodeNatLitVal (s : String) : Option Nat := let len := s.length; if len == 0 then none else let c := s.get 0; if c == '0' then if len == 1 then some 0 else let c := s.get 1; if c == 'x' || c == 'X' then decodeHexLitAux s 2 0 else if c == 'b' || c == 'B' then decodeBinLitAux s 2 0 else if c == 'o' || c == 'O' then decodeOctalLitAux s 2 0 else if c.isDigit then decodeDecimalLitAux s 0 0 else none else if c.isDigit then decodeDecimalLitAux s 0 0 else none def isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String := match stx with | Syntax.node k args => if k == litKind && args.size == 1 then match args.get! 0 with | (Syntax.atom _ val) => some val | _ => none else none | _ => none def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat := match isLit? litKind stx with | some val => decodeNatLitVal val | _ => none def isNatLit? (s : Syntax) : Option Nat := isNatLitAux numLitKind s def isFieldIdx? (s : Syntax) : Option Nat := isNatLitAux fieldIdxKind s def isIdOrAtom? : Syntax → Option String | Syntax.atom _ val => some val | Syntax.ident _ rawVal _ _ => some rawVal.toString | _ => none def toNat (stx : Syntax) : Nat := match stx.isNatLit? with | some val => val | none => 0 private def decodeQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := let c := s.get i; let i := s.next i; if c == '\\' then pure ('\\', i) else if c = '\"' then pure ('\"', i) else if c = '\'' then pure ('\'', i) else if c = 'n' then pure ('\n', i) else if c = 't' then pure ('\t', i) else if c = 'x' then do (d₁, i) ← decodeHexDigit s i; (d₂, i) ← decodeHexDigit s i; pure (Char.ofNat (16*d₁ + d₂), i) else if c = 'u' then do (d₁, i) ← decodeHexDigit s i; (d₂, i) ← decodeHexDigit s i; (d₃, i) ← decodeHexDigit s i; (d₄, i) ← decodeHexDigit s i; pure $ (Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄), i) else none partial def decodeStrLitAux (s : String) : String.Pos → String → Option String | i, acc => do let c := s.get i; let i := s.next i; if c == '\"' then pure acc else if c == '\\' then do (c, i) ← decodeQuotedChar s i; decodeStrLitAux i (acc.push c) else decodeStrLitAux i (acc.push c) def decodeStrLit (s : String) : Option String := decodeStrLitAux s 1 "" def isStrLit? (stx : Syntax) : Option String := match isLit? strLitKind stx with | some val => decodeStrLit val | _ => none def decodeCharLit (s : String) : Option Char := let c := s.get 1; if c == '\\' then do (c, _) ← decodeQuotedChar s 2; pure c else pure c def isCharLit? (stx : Syntax) : Option Char := match isLit? charLitKind stx with | some val => decodeCharLit val | _ => none private partial def decodeNameLitAux (s : String) : Nat → Name → Option Name | i, r => let continue? (i : Nat) (r : Name) : Option Name := if s.get i == '.' then decodeNameLitAux (s.next i) r else if s.atEnd i then pure r else none; let curr := s.get i; if isIdBeginEscape curr then let startPart := s.next i; let stopPart := s.nextUntil isIdEndEscape startPart; if !isIdEndEscape (s.get stopPart) then none else continue? (s.next stopPart) (mkNameStr r (s.extract startPart stopPart)) else if isIdFirst curr then let startPart := i; let stopPart := s.nextWhile isIdRest startPart; continue? stopPart (mkNameStr r (s.extract startPart stopPart)) else none def decodeNameLit (s : String) : Option Name := if s.get 0 == '`' then decodeNameLitAux s 1 Name.anonymous else none def isNameLit? (stx : Syntax) : Option Name := match isLit? nameLitKind stx with | some val => decodeNameLit val | _ => none def hasArgs : Syntax → Bool | Syntax.node _ args => args.size > 0 | _ => false def identToStrLit (stx : Syntax) : Syntax := match stx with | Syntax.ident info _ val _ => mkStxStrLit val.toString info | _ => stx def strLitToAtom (stx : Syntax) : Syntax := match stx.isStrLit? with | none => stx | some val => Syntax.atom stx.getHeadInfo val def isAtom : Syntax → Bool | atom _ _ => true | _ => false def isIdent : Syntax → Bool | ident _ _ _ _ => true | _ => false def getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous def isNone (stx : Syntax) : Bool := match stx with | Syntax.node k args => k == nullKind && args.size == 0 | _ => false def getOptional? (stx : Syntax) : Option Syntax := match stx with | Syntax.node k args => if k == nullKind && args.size == 1 then some (args.get! 0) else none | _ => none def getOptionalIdent? (stx : Syntax) : Option Name := match stx.getOptional? with | some stx => some stx.getId | none => none /-- Return `some (id, opt)` if `stx` is a Lean term id. The `Lean.Parser.Term.id` parser is `ident >> optional (explicitUniv <|> namedPattern)`. If `relaxed == true` and `stx` is a raw identifier `<id>`, it returns `some (<id>, noneStx)`. This feature is useful when we want to implement elaboration functions and macros that have support for raw identifiers where a term is expected. -/ def isTermId? (stx : Syntax) (relaxed : Bool := false) : Option (Syntax × Syntax) := match stx with | Syntax.node k args => if k == `Lean.Parser.Term.id && args.size == 2 then some (args.get! 0, args.get! 1) else none | id@(Syntax.ident _ _ _ _) => if relaxed then some (id, mkNullNode) else none | _ => none /-- Similar to `isTermId?`, but succeeds only if the optional part is a `none`. -/ def isSimpleTermId? (stx : Syntax) (relaxed : Bool := false) : Option Syntax := match stx.isTermId? relaxed with | some (id, opt) => if opt.isNone then some id else none | none => none partial def findAux (p : Syntax → Bool) : Syntax → Option Syntax | stx@(Syntax.node _ args) => if p stx then some stx else args.findSome? findAux | stx => if p stx then some stx else none def find? (stx : Syntax) (p : Syntax → Bool) : Option Syntax := findAux p stx end Syntax end Lean namespace Array abbrev getSepElems := @getEvenElems open Lean private partial def filterSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : Nat → Array Syntax → m (Array Syntax) | i, acc => if h : i < a.size then let stx := a.get ⟨i, h⟩; condM (p stx) (if acc.isEmpty then filterSepElemsMAux (i+2) (acc.push stx) else if hz : i ≠ 0 then have i.pred < i from Nat.predLt hz; let sepStx := a.get ⟨i.pred, Nat.ltTrans this h⟩; filterSepElemsMAux (i+2) ((acc.push sepStx).push stx) else filterSepElemsMAux (i+2) (acc.push stx)) (filterSepElemsMAux (i+2) acc) else pure acc def filterSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : m (Array Syntax) := filterSepElemsMAux a p 0 #[] def filterSepElems (a : Array Syntax) (p : Syntax → Bool) : Array Syntax := Id.run $ a.filterSepElemsM p private partial def mapSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : Nat → Array Syntax → m (Array Syntax) | i, acc => if h : i < a.size then do let stx := a.get ⟨i, h⟩; if i % 2 == 0 then do stx ← f stx; mapSepElemsMAux (i+1) (acc.push stx) else mapSepElemsMAux (i+1) (acc.push stx) else pure acc def mapSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : m (Array Syntax) := mapSepElemsMAux a f 0 #[] def mapSepElems (a : Array Syntax) (f : Syntax → Syntax) : Array Syntax := Id.run $ a.mapSepElemsM f end Array /-- Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses the given tactic. Like `optParam`, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ abbrev autoParam.{u} (α : Sort u) (tactic : Lean.Syntax) : Sort u := α
c9aefaea5354ed063bda183f35359f6f474e4d90
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/category_theory/discrete_category.lean
6bf8178f99fdf7b829065f397e6aa364d97e41c5
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
2,932
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Floris van Doorn -/ import data.ulift import data.fintype import category_theory.opposites category_theory.equivalence namespace category_theory universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation -- We only work in `Type`, rather than `Sort`, as we need to use `ulift`. def discrete (α : Type u₁) := α instance {α : Type u₁} [fintype α] : fintype (discrete α) := by { dsimp [discrete], apply_instance } instance discrete_category (α : Type u₁) : small_category (discrete α) := { hom := λ X Y, ulift (plift (X = Y)), id := λ X, ulift.up (plift.up rfl), comp := λ X Y Z g f, by { rcases f with ⟨⟨rfl⟩⟩, exact g } } namespace discrete variables {α : Type u₁} @[simp] lemma id_def (X : discrete α) : ulift.up (plift.up (eq.refl X)) = 𝟙 X := rfl end discrete variables {C : Type u₂} [𝒞 : category.{v₂} C] include 𝒞 namespace functor def of_function {I : Type u₁} (F : I → C) : (discrete I) ⥤ C := { obj := F, map := λ X Y f, begin cases f, cases f, cases f, exact 𝟙 (F X) end } @[simp] lemma of_function_obj {I : Type u₁} (F : I → C) (i : I) : (of_function F).obj i = F i := rfl @[simp] lemma of_function_map {I : Type u₁} (F : I → C) {i : discrete I} (f : i ⟶ i) : (of_function F).map f = 𝟙 (F i) := by { cases f, cases f, cases f, refl } end functor namespace nat_trans def of_homs {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ⟶ G.obj i) : F ⟶ G := { app := f } def of_function {I : Type u₁} {F G : I → C} (f : Π i : I, F i ⟶ G i) : (functor.of_function F) ⟶ (functor.of_function G) := of_homs f @[simp] lemma of_function_app {I : Type u₁} {F G : I → C} (f : Π i : I, F i ⟶ G i) (i : I) : (of_function f).app i = f i := rfl end nat_trans namespace nat_iso def of_isos {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) : F ≅ G := of_components f (by tidy) end nat_iso namespace discrete variables {J : Type v₁} omit 𝒞 def lift {α : Type u₁} {β : Type u₂} (f : α → β) : (discrete α) ⥤ (discrete β) := functor.of_function f open opposite protected def opposite (α : Type u₁) : (discrete α)ᵒᵖ ≌ discrete α := let F : discrete α ⥤ (discrete α)ᵒᵖ := functor.of_function (λ x, op x) in begin refine equivalence.mk (functor.left_op F) F _ (nat_iso.of_isos $ λ X, by simp [F]), refine nat_iso.of_components (λ X, by simp [F]) _, tidy end include 𝒞 @[simp] lemma functor_map_id (F : discrete J ⥤ C) {j : discrete J} (f : j ⟶ j) : F.map f = 𝟙 (F.obj j) := begin have h : f = 𝟙 j, cases f, cases f, ext, rw h, simp, end end discrete end category_theory
473695e843bed5c74ec7ad293c055a085537648e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/deprecated/submonoid.lean
d8887860703e054416dd919f7643e5910e7aa0b4
[ "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
16,232
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard -/ import group_theory.submonoid.basic import algebra.big_operators.basic import deprecated.group /-! # Unbundled submonoids (deprecated) > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file is deprecated, and is no longer imported by anything in mathlib other than other deprecated files, and test files. You should not need to import it. This file defines unbundled multiplicative and additive submonoids. Instead of using this file, please use `submonoid G` and `add_submonoid A`, defined in `group_theory.submonoid.basic`. ## Main definitions `is_add_submonoid (S : set M)` : the predicate that `S` is the underlying subset of an additive submonoid of `M`. The bundled variant `add_submonoid M` should be used in preference to this. `is_submonoid (S : set M)` : the predicate that `S` is the underlying subset of a submonoid of `M`. The bundled variant `submonoid M` should be used in preference to this. ## Tags submonoid, submonoids, is_submonoid -/ open_locale big_operators variables {M : Type*} [monoid M] {s : set M} variables {A : Type*} [add_monoid A] {t : set A} /-- `s` is an additive submonoid: a set containing 0 and closed under addition. Note that this structure is deprecated, and the bundled variant `add_submonoid A` should be preferred. -/ structure is_add_submonoid (s : set A) : Prop := (zero_mem : (0:A) ∈ s) (add_mem {a b} : a ∈ s → b ∈ s → a + b ∈ s) /-- `s` is a submonoid: a set containing 1 and closed under multiplication. Note that this structure is deprecated, and the bundled variant `submonoid M` should be preferred. -/ @[to_additive] structure is_submonoid (s : set M) : Prop := (one_mem : (1:M) ∈ s) (mul_mem {a b} : a ∈ s → b ∈ s → a * b ∈ s) lemma additive.is_add_submonoid {s : set M} : ∀ (is : is_submonoid s), @is_add_submonoid (additive M) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem additive.is_add_submonoid_iff {s : set M} : @is_add_submonoid (additive M) _ s ↔ is_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, additive.is_add_submonoid⟩ lemma multiplicative.is_submonoid {s : set A} : ∀ (is : is_add_submonoid s), @is_submonoid (multiplicative A) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem multiplicative.is_submonoid_iff {s : set A} : @is_submonoid (multiplicative A) _ s ↔ is_add_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, multiplicative.is_submonoid⟩ /-- The intersection of two submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The intersection of two `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of M."] lemma is_submonoid.inter {s₁ s₂ : set M} (is₁ : is_submonoid s₁) (is₂ : is_submonoid s₂) : is_submonoid (s₁ ∩ s₂) := { one_mem := ⟨is₁.one_mem, is₂.one_mem⟩, mul_mem := λ x y hx hy, ⟨is₁.mul_mem hx.1 hy.1, is₂.mul_mem hx.2 hy.2⟩ } /-- The intersection of an indexed set of submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The intersection of an indexed set of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`."] lemma is_submonoid.Inter {ι : Sort*} {s : ι → set M} (h : ∀ y : ι, is_submonoid (s y)) : is_submonoid (set.Inter s) := { one_mem := set.mem_Inter.2 $ λ y, (h y).one_mem, mul_mem := λ x₁ x₂ h₁ h₂, set.mem_Inter.2 $ λ y, (h y).mul_mem (set.mem_Inter.1 h₁ y) (set.mem_Inter.1 h₂ y) } /-- The union of an indexed, directed, nonempty set of submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The union of an indexed, directed, nonempty set of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`. "] lemma is_submonoid_Union_of_directed {ι : Type*} [hι : nonempty ι] {s : ι → set M} (hs : ∀ i, is_submonoid (s i)) (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_submonoid (⋃i, s i) := { one_mem := let ⟨i⟩ := hι in set.mem_Union.2 ⟨i, (hs i).one_mem⟩, mul_mem := λ a b ha hb, let ⟨i, hi⟩ := set.mem_Union.1 ha in let ⟨j, hj⟩ := set.mem_Union.1 hb in let ⟨k, hk⟩ := directed i j in set.mem_Union.2 ⟨k, (hs k).mul_mem (hk.1 hi) (hk.2 hj)⟩ } section powers /-- The set of natural number powers `1, x, x², ...` of an element `x` of a monoid. -/ @[to_additive multiples "The set of natural number multiples `0, x, 2x, ...` of an element `x` of an `add_monoid`."] def powers (x : M) : set M := {y | ∃ n:ℕ, x^n = y} /-- 1 is in the set of natural number powers of an element of a monoid. -/ @[to_additive "0 is in the set of natural number multiples of an element of an `add_monoid`."] lemma powers.one_mem {x : M} : (1 : M) ∈ powers x := ⟨0, pow_zero _⟩ /-- An element of a monoid is in the set of that element's natural number powers. -/ @[to_additive "An element of an `add_monoid` is in the set of that element's natural number multiples."] lemma powers.self_mem {x : M} : x ∈ powers x := ⟨1, pow_one _⟩ /-- The set of natural number powers of an element of a monoid is closed under multiplication. -/ @[to_additive "The set of natural number multiples of an element of an `add_monoid` is closed under addition."] lemma powers.mul_mem {x y z : M} : (y ∈ powers x) → (z ∈ powers x) → (y * z ∈ powers x) := λ ⟨n₁, h₁⟩ ⟨n₂, h₂⟩, ⟨n₁ + n₂, by simp only [pow_add, *]⟩ /-- The set of natural number powers of an element of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The set of natural number multiples of an element of an `add_monoid` `M` is an `add_submonoid` of `M`."] lemma powers.is_submonoid (x : M) : is_submonoid (powers x) := { one_mem := powers.one_mem, mul_mem := λ y z, powers.mul_mem } /-- A monoid is a submonoid of itself. -/ @[to_additive "An `add_monoid` is an `add_submonoid` of itself."] lemma univ.is_submonoid : is_submonoid (@set.univ M) := by split; simp /-- The preimage of a submonoid under a monoid hom is a submonoid of the domain. -/ @[to_additive "The preimage of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the domain."] lemma is_submonoid.preimage {N : Type*} [monoid N] {f : M → N} (hf : is_monoid_hom f) {s : set N} (hs : is_submonoid s) : is_submonoid (f ⁻¹' s) := { one_mem := show f 1 ∈ s, by rw is_monoid_hom.map_one hf; exact hs.one_mem, mul_mem := λ a b (ha : f a ∈ s) (hb : f b ∈ s), show f (a * b) ∈ s, by rw is_monoid_hom.map_mul hf; exact hs.mul_mem ha hb } /-- The image of a submonoid under a monoid hom is a submonoid of the codomain. -/ @[to_additive "The image of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the codomain."] lemma is_submonoid.image {γ : Type*} [monoid γ] {f : M → γ} (hf : is_monoid_hom f) {s : set M} (hs : is_submonoid s) : is_submonoid (f '' s) := { one_mem := ⟨1, hs.one_mem, hf.map_one⟩, mul_mem := λ a b ⟨x, hx⟩ ⟨y, hy⟩, ⟨x * y, hs.mul_mem hx.1 hy.1, by rw [hf.map_mul, hx.2, hy.2]⟩ } /-- The image of a monoid hom is a submonoid of the codomain. -/ @[to_additive "The image of an `add_monoid` hom is an `add_submonoid` of the codomain."] lemma range.is_submonoid {γ : Type*} [monoid γ] {f : M → γ} (hf : is_monoid_hom f) : is_submonoid (set.range f) := by { rw ← set.image_univ, exact univ.is_submonoid.image hf } /-- Submonoids are closed under natural powers. -/ @[to_additive is_add_submonoid.smul_mem "An `add_submonoid` is closed under multiplication by naturals."] lemma is_submonoid.pow_mem {a : M} (hs : is_submonoid s) (h : a ∈ s) : ∀ {n : ℕ}, a ^ n ∈ s | 0 := by { rw pow_zero, exact hs.one_mem } | (n + 1) := by { rw pow_succ, exact hs.mul_mem h is_submonoid.pow_mem } /-- The set of natural number powers of an element of a submonoid is a subset of the submonoid. -/ @[to_additive is_add_submonoid.multiples_subset "The set of natural number multiples of an element of an `add_submonoid` is a subset of the `add_submonoid`."] lemma is_submonoid.power_subset {a : M} (hs : is_submonoid s) (h : a ∈ s) : powers a ⊆ s := assume x ⟨n, hx⟩, hx ▸ hs.pow_mem h end powers namespace is_submonoid /-- The product of a list of elements of a submonoid is an element of the submonoid. -/ @[to_additive "The sum of a list of elements of an `add_submonoid` is an element of the `add_submonoid`."] lemma list_prod_mem (hs : is_submonoid s) : ∀{l : list M}, (∀x∈l, x ∈ s) → l.prod ∈ s | [] h := hs.one_mem | (a::l) h := suffices a * l.prod ∈ s, by simpa, have a ∈ s ∧ (∀x∈l, x ∈ s), by simpa using h, hs.mul_mem this.1 (list_prod_mem this.2) /-- The product of a multiset of elements of a submonoid of a `comm_monoid` is an element of the submonoid. -/ @[to_additive "The sum of a multiset of elements of an `add_submonoid` of an `add_comm_monoid` is an element of the `add_submonoid`. "] lemma multiset_prod_mem {M} [comm_monoid M] {s : set M} (hs : is_submonoid s) (m : multiset M) : (∀a∈m, a ∈ s) → m.prod ∈ s := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact list_prod_mem hs hl end /-- The product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is an element of the submonoid. -/ @[to_additive "The sum of elements of an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is an element of the `add_submonoid`."] lemma finset_prod_mem {M A} [comm_monoid M] {s : set M} (hs : is_submonoid s) (f : A → M) : ∀(t : finset A), (∀b∈t, f b ∈ s) → ∏ b in t, f b ∈ s | ⟨m, hm⟩ _ := multiset_prod_mem hs _ (by simpa) end is_submonoid namespace add_monoid /-- The inductively defined membership predicate for the submonoid generated by a subset of a monoid. -/ inductive in_closure (s : set A) : A → Prop | basic {a : A} : a ∈ s → in_closure a | zero : in_closure 0 | add {a b : A} : in_closure a → in_closure b → in_closure (a + b) end add_monoid namespace monoid /-- The inductively defined membership predicate for the `submonoid` generated by a subset of an monoid. -/ @[to_additive] inductive in_closure (s : set M) : M → Prop | basic {a : M} : a ∈ s → in_closure a | one : in_closure 1 | mul {a b : M} : in_closure a → in_closure b → in_closure (a * b) /-- The inductively defined submonoid generated by a subset of a monoid. -/ @[to_additive "The inductively defined `add_submonoid` genrated by a subset of an `add_monoid`."] def closure (s : set M) : set M := {a | in_closure s a } @[to_additive] lemma closure.is_submonoid (s : set M) : is_submonoid (closure s) := { one_mem := in_closure.one, mul_mem := assume a b, in_closure.mul } /-- A subset of a monoid is contained in the submonoid it generates. -/ @[to_additive "A subset of an `add_monoid` is contained in the `add_submonoid` it generates."] theorem subset_closure {s : set M} : s ⊆ closure s := assume a, in_closure.basic /-- The submonoid generated by a set is contained in any submonoid that contains the set. -/ @[to_additive "The `add_submonoid` generated by a set is contained in any `add_submonoid` that contains the set."] theorem closure_subset {s t : set M} (ht : is_submonoid t) (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, is_submonoid.one_mem, is_submonoid.mul_mem] /-- Given subsets `t` and `s` of a monoid `M`, if `s ⊆ t`, the submonoid of `M` generated by `s` is contained in the submonoid generated by `t`. -/ @[to_additive "Given subsets `t` and `s` of an `add_monoid M`, if `s ⊆ t`, the `add_submonoid` of `M` generated by `s` is contained in the `add_submonoid` generated by `t`."] theorem closure_mono {s t : set M} (h : s ⊆ t) : closure s ⊆ closure t := closure_subset (closure.is_submonoid t) $ set.subset.trans h subset_closure /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ @[to_additive "The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element."] theorem closure_singleton {x : M} : closure ({x} : set M) = powers x := set.eq_of_subset_of_subset (closure_subset (powers.is_submonoid x) $ set.singleton_subset_iff.2 $ powers.self_mem) $ is_submonoid.power_subset (closure.is_submonoid _) $ set.singleton_subset_iff.1 $ subset_closure /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set under the monoid hom. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set under the `add_monoid` hom."] lemma image_closure {A : Type*} [monoid A] {f : M → A} (hf : is_monoid_hom f) (s : set M) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [hf.map_one], apply is_submonoid.one_mem (closure.is_submonoid (f '' s))}, { rw [hf.map_mul], solve_by_elim [(closure.is_submonoid _).mul_mem] } end (closure_subset (is_submonoid.image hf (closure.is_submonoid _)) $ set.image_subset _ subset_closure) /-- Given an element `a` of the submonoid of a monoid `M` generated by a set `s`, there exists a list of elements of `s` whose product is `a`. -/ @[to_additive "Given an element `a` of the `add_submonoid` of an `add_monoid M` generated by a set `s`, there exists a list of elements of `s` whose sum is `a`."] theorem exists_list_of_mem_closure {s : set M} {a : M} (h : a ∈ closure s) : (∃l:list M, (∀x∈l, x ∈ s) ∧ l.prod = a) := begin induction h, case in_closure.basic : a ha { existsi ([a]), simp [ha] }, case in_closure.one { existsi ([]), simp }, case in_closure.mul : a b _ _ ha hb { rcases ha with ⟨la, ha, eqa⟩, rcases hb with ⟨lb, hb, eqb⟩, existsi (la ++ lb), simp [eqa.symm, eqb.symm, or_imp_distrib], exact assume a, ⟨ha a, hb a⟩ } end /-- Given sets `s, t` of a commutative monoid `M`, `x ∈ M` is in the submonoid of `M` generated by `s ∪ t` iff there exists an element of the submonoid generated by `s` and an element of the submonoid generated by `t` whose product is `x`. -/ @[to_additive "Given sets `s, t` of a commutative `add_monoid M`, `x ∈ M` is in the `add_submonoid` of `M` generated by `s ∪ t` iff there exists an element of the `add_submonoid` generated by `s` and an element of the `add_submonoid` generated by `t` whose sum is `x`."] theorem mem_closure_union_iff {M : Type*} [comm_monoid M] {s t : set M} {x : M} : x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x := ⟨λ hx, let ⟨L, HL1, HL2⟩ := exists_list_of_mem_closure hx in HL2 ▸ list.rec_on L (λ _, ⟨1, (closure.is_submonoid _).one_mem, 1, (closure.is_submonoid _).one_mem, mul_one _⟩) (λ hd tl ih HL1, let ⟨y, hy, z, hz, hyzx⟩ := ih (list.forall_mem_of_forall_mem_cons HL1) in or.cases_on (HL1 hd $ list.mem_cons_self _ _) (λ hs, ⟨hd * y, (closure.is_submonoid _).mul_mem (subset_closure hs) hy, z, hz, by rw [mul_assoc, list.prod_cons, ← hyzx]; refl⟩) (λ ht, ⟨y, hy, z * hd, (closure.is_submonoid _).mul_mem hz (subset_closure ht), by rw [← mul_assoc, list.prod_cons, ← hyzx, mul_comm hd]; refl⟩)) HL1, λ ⟨y, hy, z, hz, hyzx⟩, hyzx ▸ (closure.is_submonoid _).mul_mem (closure_mono (set.subset_union_left _ _) hy) (closure_mono (set.subset_union_right _ _) hz)⟩ end monoid /-- Create a bundled submonoid from a set `s` and `[is_submonoid s]`. -/ @[to_additive "Create a bundled additive submonoid from a set `s` and `[is_add_submonoid s]`."] def submonoid.of {s : set M} (h : is_submonoid s) : submonoid M := ⟨s, λ _ _, h.2, h.1⟩ @[to_additive] lemma submonoid.is_submonoid (S : submonoid M) : is_submonoid (S : set M) := ⟨S.3, λ _ _, S.2⟩
e4f96020beb62a98e71468a83e015506ac7d5669
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/smodeq.lean
69617c9324411f3a7bc28ba888805dbea01aba5a
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
2,924
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.polynomial.eval import ring_theory.ideal.quotient /-! # modular equivalence for submodule -/ open submodule variables {R : Type*} [ring R] variables {M : Type*} [add_comm_group M] [module R M] (U U₁ U₂ : submodule R M) variables {x x₁ x₂ y y₁ y₂ z z₁ z₂ : M} variables {N : Type*} [add_comm_group N] [module R N] (V V₁ V₂ : submodule R N) /-- A predicate saying two elements of a module are equivalent modulo a submodule. -/ def smodeq (x y : M) : Prop := (submodule.quotient.mk x : M ⧸ U) = submodule.quotient.mk y notation x ` ≡ `:50 y ` [SMOD `:50 N `]`:0 := smodeq N x y variables {U U₁ U₂} protected lemma smodeq.def : x ≡ y [SMOD U] ↔ (submodule.quotient.mk x : M ⧸ U) = submodule.quotient.mk y := iff.rfl namespace smodeq lemma sub_mem : x ≡ y [SMOD U] ↔ x - y ∈ U := by rw [smodeq.def, submodule.quotient.eq] @[simp] theorem top : x ≡ y [SMOD (⊤ : submodule R M)] := (submodule.quotient.eq ⊤).2 mem_top @[simp] theorem bot : x ≡ y [SMOD (⊥ : submodule R M)] ↔ x = y := by rw [smodeq.def, submodule.quotient.eq, mem_bot, sub_eq_zero] @[mono] theorem mono (HU : U₁ ≤ U₂) (hxy : x ≡ y [SMOD U₁]) : x ≡ y [SMOD U₂] := (submodule.quotient.eq U₂).2 $ HU $ (submodule.quotient.eq U₁).1 hxy @[refl] theorem refl : x ≡ x [SMOD U] := eq.refl _ @[symm] theorem symm (hxy : x ≡ y [SMOD U]) : y ≡ x [SMOD U] := hxy.symm @[trans] theorem trans (hxy : x ≡ y [SMOD U]) (hyz : y ≡ z [SMOD U]) : x ≡ z [SMOD U] := hxy.trans hyz theorem add (hxy₁ : x₁ ≡ y₁ [SMOD U]) (hxy₂ : x₂ ≡ y₂ [SMOD U]) : x₁ + x₂ ≡ y₁ + y₂ [SMOD U] := by { rw smodeq.def at hxy₁ hxy₂ ⊢, simp_rw [quotient.mk_add, hxy₁, hxy₂] } theorem smul (hxy : x ≡ y [SMOD U]) (c : R) : c • x ≡ c • y [SMOD U] := by { rw smodeq.def at hxy ⊢, simp_rw [quotient.mk_smul, hxy] } theorem zero : x ≡ 0 [SMOD U] ↔ x ∈ U := by rw [smodeq.def, submodule.quotient.eq, sub_zero] theorem map (hxy : x ≡ y [SMOD U]) (f : M →ₗ[R] N) : f x ≡ f y [SMOD U.map f] := (submodule.quotient.eq _).2 $ f.map_sub x y ▸ mem_map_of_mem $ (submodule.quotient.eq _).1 hxy theorem comap {f : M →ₗ[R] N} (hxy : f x ≡ f y [SMOD V]) : x ≡ y [SMOD V.comap f] := (submodule.quotient.eq _).2 $ show f (x - y) ∈ V, from (f.map_sub x y).symm ▸ (submodule.quotient.eq _).1 hxy lemma eval {R : Type*} [comm_ring R] {I : ideal R} {x y : R} (h : x ≡ y [SMOD I]) (f : polynomial R) : f.eval x ≡ f.eval y [SMOD I] := begin rw [smodeq.def] at h ⊢, show ideal.quotient.mk I (f.eval x) = ideal.quotient.mk I (f.eval y), change ideal.quotient.mk I x = ideal.quotient.mk I y at h, rw [← polynomial.eval₂_at_apply, ← polynomial.eval₂_at_apply, h], end end smodeq
97f298fc2519d74181bf2e24b8fc8b8ba61d0408
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/char_zero.lean
3d4ceb9f2393b4d0826a7d184a1e4446e432382e
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
3,386
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import data.nat.cast import data.fintype.basic import tactic.wlog /-- Typeclass for monoids with characteristic zero. (This is usually stated on fields but it makes sense for any additive monoid with 1.) -/ class char_zero (R : Type*) [add_monoid R] [has_one R] : Prop := (cast_injective : function.injective (coe : ℕ → R)) theorem char_zero_of_inj_zero {R : Type*} [add_left_cancel_monoid R] [has_one R] (H : ∀ n:ℕ, (n:R) = 0 → n = 0) : char_zero R := ⟨λ m n, begin assume h, wlog hle : m ≤ n, cases nat.le.dest hle with k e, suffices : k = 0, by rw [← e, this, add_zero], apply H, apply @add_left_cancel R _ n, rw [← h, ← nat.cast_add, e, add_zero, h] end⟩ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_char_zero {R : Type*} [linear_ordered_semiring R] : char_zero R := char_zero_of_inj_zero $ λ n h, nat.eq_zero_of_le_zero $ (@nat.cast_le R _ _ _).1 (le_of_eq h) namespace nat variables {R : Type*} [add_monoid R] [has_one R] [char_zero R] theorem cast_injective : function.injective (coe : ℕ → R) := char_zero.cast_injective @[simp, norm_cast] theorem cast_inj {m n : ℕ} : (m : R) = n ↔ m = n := cast_injective.eq_iff @[simp, norm_cast] theorem cast_eq_zero {n : ℕ} : (n : R) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] @[norm_cast] theorem cast_ne_zero {n : ℕ} : (n : R) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero lemma cast_add_one_ne_zero (n : ℕ) : (n + 1 : R) ≠ 0 := by exact_mod_cast n.succ_ne_zero @[simp, norm_cast] theorem cast_dvd_char_zero {k : Type*} [field k] [char_zero k] {m n : ℕ} (n_dvd : n ∣ m) : ((m / n : ℕ) : k) = m / n := begin by_cases hn : n = 0, { subst hn, simp }, { exact cast_dvd n_dvd (cast_ne_zero.mpr hn), }, end end nat @[priority 100] -- see Note [lower instance priority] instance char_zero.infinite (α : Type*) [add_monoid α] [has_one α] [char_zero α] : infinite α := infinite.of_injective coe nat.cast_injective @[field_simps] lemma two_ne_zero' {α : Type*} [add_monoid α] [has_one α] [char_zero α] : (2:α) ≠ 0 := have ((2:ℕ):α) ≠ 0, from nat.cast_ne_zero.2 dec_trivial, by rwa [nat.cast_succ, nat.cast_one] at this section variables {R : Type*} [semiring R] [no_zero_divisors R] [char_zero R] lemma add_self_eq_zero {a : R} : a + a = 0 ↔ a = 0 := by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or] lemma bit0_eq_zero {a : R} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero end section variables {R : Type*} [division_ring R] [char_zero R] @[simp] lemma half_add_self (a : R) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero'] @[simp] lemma add_halves' (a : R) : a / 2 + a / 2 = a := by rw [← add_div, half_add_self] lemma sub_half (a : R) : a - a / 2 = a / 2 := by rw [sub_eq_iff_eq_add, add_halves'] lemma half_sub (a : R) : a / 2 - a = - (a / 2) := by rw [← neg_sub, sub_half] end namespace with_top instance {R : Type*} [add_monoid R] [has_one R] [char_zero R] : char_zero (with_top R) := { cast_injective := λ m n h, by rwa [← coe_nat, ← coe_nat n, coe_eq_coe, nat.cast_inj] at h } end with_top
0722195abf4e4a019b8c278eba981e27a8fbed7e
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/measure_theory/probability_mass_function.lean
7a9d1c09e62ae7bfc3066e0623eb8159641e81b1
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,095
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ import topology.instances.ennreal /-! # Probability mass functions This file is about probability mass functions or discrete probability measures: a function `α → ℝ≥0` such that the values have (infinite) sum `1`. This file features the monadic structure of `pmf` and the Bernoulli distribution ## Implementation Notes This file is not yet connected to the `measure_theory` library in any way. At some point we need to define a `measure` from a `pmf` and prove the appropriate lemmas about that. ## Tags probability mass function, discrete probability measure, bernoulli distribution -/ noncomputable theory variables {α : Type*} {β : Type*} {γ : Type*} open_locale classical big_operators nnreal ennreal /-- A probability mass function, or discrete probability measures is a function `α → ℝ≥0` such that the values have (infinite) sum `1`. -/ def {u} pmf (α : Type u) : Type u := { f : α → ℝ≥0 // has_sum f 1 } namespace pmf instance : has_coe_to_fun (pmf α) := ⟨λ p, α → ℝ≥0, λ p a, p.1 a⟩ @[ext] protected lemma ext : ∀ {p q : pmf α}, (∀ a, p a = q a) → p = q | ⟨f, hf⟩ ⟨g, hg⟩ eq := subtype.eq $ funext eq lemma has_sum_coe_one (p : pmf α) : has_sum p 1 := p.2 lemma summable_coe (p : pmf α) : summable p := (p.has_sum_coe_one).summable @[simp] lemma tsum_coe (p : pmf α) : ∑' a, p a = 1 := p.has_sum_coe_one.tsum_eq /-- The support of a `pmf` is the set where it is nonzero. -/ def support (p : pmf α) : set α := {a | p.1 a ≠ 0} @[simp] lemma mem_support_iff (p : pmf α) (a : α) : a ∈ p.support ↔ p a ≠ 0 := iff.rfl /-- The pure `pmf` is the `pmf` where all the mass lies in one point. The value of `pure a` is `1` at `a` and `0` elsewhere. -/ def pure (a : α) : pmf α := ⟨λ a', if a' = a then 1 else 0, has_sum_ite_eq _ _⟩ @[simp] lemma pure_apply (a a' : α) : pure a a' = (if a' = a then 1 else 0) := rfl instance [inhabited α] : inhabited (pmf α) := ⟨pure (default α)⟩ lemma coe_le_one (p : pmf α) (a : α) : p a ≤ 1 := has_sum_le (by intro b; split_ifs; simp [h]; exact le_refl _) (has_sum_ite_eq a (p a)) p.2 protected lemma bind.summable (p : pmf α) (f : α → pmf β) (b : β) : summable (λ a : α, p a * f a b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, suffices : p a * f a b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a).coe_le_one _) (p a).2 end /-- The monadic bind operation for `pmf`. -/ def bind (p : pmf α) (f : α → pmf β) : pmf β := ⟨λ b, ∑'a, p a * f a b, begin apply ennreal.has_sum_coe.1, simp only [ennreal.coe_tsum (bind.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp [ennreal.tsum_mul_left, (ennreal.coe_tsum (f _).summable_coe).symm, (ennreal.coe_tsum p.summable_coe).symm] end⟩ @[simp] lemma bind_apply (p : pmf α) (f : α → pmf β) (b : β) : p.bind f b = ∑'a, p a * f a b := rfl lemma coe_bind_apply (p : pmf α) (f : α → pmf β) (b : β) : (p.bind f b : ℝ≥0∞) = ∑'a, p a * f a b := eq.trans (ennreal.coe_tsum $ bind.summable p f b) $ by simp @[simp] lemma pure_bind (a : α) (f : α → pmf β) : (pure a).bind f = f a := have ∀ b a', ite (a' = a) 1 0 * f a' b = ite (a' = a) (f a b) 0, from assume b a', by split_ifs; simp; subst h; simp, by ext b; simp [this] @[simp] lemma bind_pure (p : pmf α) : p.bind pure = p := have ∀ a a', (p a * ite (a' = a) 1 0) = ite (a = a') (p a') 0, from assume a a', begin split_ifs; try { subst a }; try { subst a' }; simp * at * end, by ext b; simp [this] @[simp] lemma bind_bind (p : pmf α) (f : α → pmf β) (g : β → pmf γ) : (p.bind f).bind g = p.bind (λ a, (f a).bind g) := begin ext1 b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end lemma bind_comm (p : pmf α) (q : pmf β) (f : α → β → pmf γ) : p.bind (λ a, q.bind (f a)) = q.bind (λ b, p.bind (λ a, f a b)) := begin ext1 b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end /-- The functorial action of a function on a `pmf`. -/ def map (f : α → β) (p : pmf α) : pmf β := bind p (pure ∘ f) lemma bind_pure_comp (f : α → β) (p : pmf α) : bind p (pure ∘ f) = map f p := rfl lemma map_id (p : pmf α) : map id p = p := by simp [map] lemma map_comp (p : pmf α) (f : α → β) (g : β → γ) : (p.map f).map g = p.map (g ∘ f) := by simp [map] lemma pure_map (a : α) (f : α → β) : (pure a).map f = pure (f a) := by simp [map] /-- The monadic sequencing operation for `pmf`. -/ def seq (f : pmf (α → β)) (p : pmf α) : pmf β := f.bind (λ m, p.bind $ λ a, pure (m a)) /-- Given a non-empty multiset `s` we construct the `pmf` which sends `a` to the fraction of elements in `s` that are `a`. -/ def of_multiset (s : multiset α) (hs : s ≠ 0) : pmf α := ⟨λ a, s.count a / s.card, have ∑ a in s.to_finset, (s.count a : ℝ) / s.card = 1, by simp [div_eq_inv_mul, finset.mul_sum.symm, (finset.sum_nat_cast _ _).symm, hs], have ∑ a in s.to_finset, (s.count a : ℝ≥0) / s.card = 1, by rw [← nnreal.eq_iff, nnreal.coe_one, ← this, nnreal.coe_sum]; simp, begin rw ← this, apply has_sum_sum_of_ne_finset_zero, simp {contextual := tt}, end⟩ /-- Given a finite type `α` and a function `f : α → ℝ≥0` with sum 1, we get a `pmf`. -/ def of_fintype [fintype α] (f : α → ℝ≥0) (h : ∑ x, f x = 1) : pmf α := ⟨f, h ▸ has_sum_sum_of_ne_finset_zero (by simp)⟩ /-- Given a `f` with non-zero sum, we get a `pmf` by normalizing `f` by its `tsum` -/ def normalize (f : α → ℝ≥0) (hf0 : tsum f ≠ 0) : pmf α := ⟨λ a, f a * (∑' x, f x)⁻¹, (mul_inv_cancel hf0) ▸ has_sum.mul_right (∑' x, f x)⁻¹ (not_not.mp (mt tsum_eq_zero_of_not_summable hf0 : ¬¬summable f)).has_sum⟩ lemma normalize_apply {f : α → ℝ≥0} (hf0 : tsum f ≠ 0) (a : α) : (normalize f hf0) a = f a * (∑' x, f x)⁻¹ := rfl /-- Create new `pmf` by filtering on a set with non-zero measure and normalizing -/ def filter (p : pmf α) (s : set α) (h : ∃ a ∈ s, p a ≠ 0) : pmf α := pmf.normalize (s.indicator p) $ nnreal.tsum_indicator_ne_zero p.2.summable h lemma filter_apply (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) {a : α} : (p.filter s h) a = (s.indicator p a) * (∑' x, (s.indicator p) x)⁻¹ := by rw [filter, normalize_apply] lemma filter_apply_eq_zero_of_not_mem (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) {a : α} (ha : a ∉ s) : (p.filter s h) a = 0 := by rw [filter_apply, set.indicator_apply_eq_zero.mpr (λ ha', absurd ha' ha), zero_mul] lemma filter_apply_eq_zero_iff (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) (a : α) : (p.filter s h) a = 0 ↔ a ∉ (p.support ∩ s) := begin rw [set.mem_inter_iff, p.mem_support_iff, not_and_distrib, not_not], split; intro ha, { rw [filter_apply, mul_eq_zero] at ha, refine ha.by_cases (λ ha, (em (a ∈ s)).by_cases (λ h, or.inl ((set.indicator_apply_eq_zero.mp ha) h)) or.inr) (λ ha, absurd (inv_eq_zero.1 ha) (nnreal.tsum_indicator_ne_zero p.2.summable h)) }, { rw [filter_apply, set.indicator_apply_eq_zero.2 (λ h, ha.by_cases id (absurd h)), zero_mul] } end lemma filter_apply_ne_zero_iff (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) (a : α) : (p.filter s h) a ≠ 0 ↔ a ∈ (p.support ∩ s) := by rw [← not_iff, filter_apply_eq_zero_iff, not_iff, not_not] /-- A `pmf` which assigns probability `p` to `tt` and `1 - p` to `ff`. -/ def bernoulli (p : ℝ≥0) (h : p ≤ 1) : pmf bool := of_fintype (λ b, cond b p (1 - p)) (nnreal.eq $ by simp [h]) end pmf
e117a453d4e66e5ef030ff33730e5b80edea3918
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/data/complex/basic.lean
e470fa8627481df2e86482fb7ad794531f5b832b
[ "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
19,822
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import data.real.basic /-! # The complex numbers The complex numbers are modelled as ℝ^2 in the obvious way. -/ /-! ### Definition and basic arithmmetic -/ /-- Complex numbers consist of two `real`s: a real part `re` and an imaginary part `im`. -/ structure complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex noncomputable instance : decidable_eq ℂ := classical.dec_eq _ /-- The equivalence between the complex numbers and `ℝ × ℝ`. -/ def equiv_real_prod : ℂ ≃ (ℝ × ℝ) := { to_fun := λ z, ⟨z.re, z.im⟩, inv_fun := λ p, ⟨p.1, p.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } @[simp] theorem equiv_real_prod_apply (z : ℂ) : equiv_real_prod z = (z.re, z.im) := rfl theorem equiv_real_prod_symm_re (x y : ℝ) : (equiv_real_prod.symm (x, y)).re = x := rfl theorem equiv_real_prod_symm_im (x y : ℝ) : (equiv_real_prod.symm (x, y)).im = y := rfl @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨a, b⟩ := rfl @[ext] theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩ @[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl @[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congr_arg re, congr_arg _⟩ instance : has_zero ℂ := ⟨(0 : ℝ)⟩ instance : inhabited ℂ := ⟨0⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero instance : has_one ℂ := ⟨(1 : ℝ)⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl @[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl @[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl @[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _ @[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _ @[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0] @[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1] instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩ @[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp lemma smul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp lemma smul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ def I : ℂ := ⟨0, 1⟩ @[simp] lemma I_re : I.re = 0 := rfl @[simp] lemma I_im : I.im = 1 := rfl @[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := ext_iff.2 $ by simp @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := ext_iff.2 $ by simp /-! ### Commutative ring instance and lemmas -/ instance : comm_ring ℂ := by refine { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), ..}; { intros, apply ext_iff.2; split; simp; ring } instance re.is_add_group_hom : is_add_group_hom complex.re := { map_add := complex.add_re } instance im.is_add_group_hom : is_add_group_hom complex.im := { map_add := complex.add_im } /-! ### Complex conjugation -/ /-- The complex conjugate. -/ def conj : ℂ →+* ℂ := begin refine_struct { to_fun := λ z : ℂ, (⟨z.re, -z.im⟩ : ℂ), .. }; { intros, ext; simp [add_comm], }, end @[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl @[simp] lemma conj_of_real (r : ℝ) : conj r = r := ext_iff.2 $ by simp [conj] @[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp @[simp] lemma conj_bit0 (z : ℂ) : conj (bit0 z) = bit0 (conj z) := ext_iff.2 $ by simp [bit0] @[simp] lemma conj_bit1 (z : ℂ) : conj (bit1 z) = bit1 (conj z) := ext_iff.2 $ by simp [bit0] @[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp @[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z := ext_iff.2 $ by simp lemma conj_involutive : function.involutive conj := conj_conj lemma conj_bijective : function.bijective conj := conj_involutive.bijective lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff @[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 := by simpa using @conj_inj z 0 lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r := ⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩, λ ⟨h, e⟩, by rw [e, conj_of_real]⟩ lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ /-! ### Norm squared -/ /-- The norm squared function. -/ @[pp_nodot] def norm_sq (z : ℂ) : ℝ := z.re * z.re + z.im * z.im @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp [norm_sq] @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := by simp [norm_sq] @[simp] lemma norm_sq_one : norm_sq 1 = 1 := by simp [norm_sq] @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 := ⟨λ h, ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h), λ h, h.symm ▸ norm_sq_zero⟩ @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := by dsimp [norm_sq]; ring lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by dsimp [norm_sq]; ring lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := ext_iff.2 $ by simp [two_mul] /-- The coercion `ℝ → ℂ` as a `ring_hom`. -/ def of_real : ℝ →+* ℂ := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl @[simp] lemma I_sq : I ^ 2 = -1 := by rw [pow_two, I_mul_I] @[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp, norm_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := ext_iff.2 $ by simp [two_mul, sub_eq_add_neg] lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * (z * conj w).re := by rw [sub_eq_add_neg, norm_sq_add]; simp [-mul_re, add_comm, add_left_comm, sub_eq_add_neg] /-! ### Inversion -/ noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl @[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def] @[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def] @[simp, norm_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ := ext_iff.2 $ begin simp, by_cases r = 0, { simp [h] }, { rw [← div_div_eq_div_mul, div_self h, one_div_eq_inv] }, end protected lemma inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul, mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] /-! ### Field instance and lemmas -/ noncomputable instance : field ℂ := { inv := has_inv.inv, zero_ne_one := mt (congr_arg re) zero_ne_one, mul_inv_cancel := @complex.mul_inv_cancel, inv_zero := complex.inv_zero, ..complex.comm_ring } lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] @[simp, norm_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := ring_hom.map_div of_real @[simp, norm_cast] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := ring_hom.map_fpow of_real r n @[simp] lemma div_I (z : ℂ) : z / I = -(z * I) := (div_eq_iff_mul_eq I_ne_zero).2 $ by simp [mul_assoc] @[simp] lemma inv_I : I⁻¹ = -I := by simp [inv_eq_one_div] @[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := if h : z = 0 then by simp [h] else (domain.mul_left_inj (mt norm_sq_eq_zero.1 h)).1 $ by rw [← norm_sq_mul]; simp [h, -norm_sq_mul] @[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w := by rw [division_def, norm_sq_mul, norm_sq_inv]; refl /-! ### Cast lemmas -/ @[simp, norm_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n := of_real.map_nat_cast n @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, norm_cast] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : ℂ) = n := of_real.map_int_cast n @[simp, norm_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n := by rw [← of_real_int_cast, of_real_re] @[simp, norm_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, norm_cast] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : ℂ) = n := of_real.map_rat_cast n @[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q := by rw [← of_real_rat_cast, of_real_re] @[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ instance char_zero_complex : char_zero ℂ := add_group.char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by rw [add_conj]; simp; rw [mul_div_cancel_left (z.re:ℂ) two_ne_zero'] /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ @[pp_nodot] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs @[simp] lemma abs_of_real (r : ℝ) : abs r = abs' r := by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : complex.abs n = n := calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast] ... = _ : abs_of_nonneg (nat.cast_nonneg n) lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : abs 0 = 0 := by simp [abs] @[simp] lemma abs_one : abs 1 = 1 := by simp [abs] @[simp] lemma abs_I : abs I = 1 := by simp [abs] @[simp] lemma abs_two : abs 2 = 2 := calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero @[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : ℂ) : abs' z.re ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : ℂ) : abs' z.im ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : ℂ) : z.im ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@two_pos ℝ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value abs := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : ℂ) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs lemma abs_sub : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ abs' z.re + abs' z.im := by simpa [re_add_im] using abs_add z.re (z.im * I) lemma abs_re_div_abs_le_one (z : ℂ) : abs' (z.re / z.abs) ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_re_le_abs _) lemma abs_im_div_abs_le_one (z : ℂ) : abs' (z.im / z.abs) ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_im_le_abs _) @[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) /-- The real part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ /-- The limit of a Cauchy sequence of complex numbers. -/ noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ := ⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩ theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := λ ε ε0, (exists_forall_ge_and (cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0)) (cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $ λ i H j ij, begin cases H _ ij with H₁ H₂, apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _), dsimp [lim_aux] at *, have := add_lt_add H₁ H₂, rwa add_halves at this, end noncomputable instance : cau_seq.is_complete ℂ abs := ⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩ open cau_seq lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f = ↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I := lim_eq_of_equiv_const $ calc f ≈ _ : equiv_lim_aux f ... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) : cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im])) lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) := λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in ⟨i, λ j hj, by rw [← conj.map_sub, abs_conj]; exact hi j hj⟩ /-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/ noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩ lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) := complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re]) (by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl) /-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_abs f.2⟩ lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) := lim_eq_of_equiv_const (λ ε ε0, let ⟨i, hi⟩ := equiv_lim f ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩) end complex
2ad6d0b5fc3b7b5193a892566756a853eb2ad571
f2fbd9ce3f46053c664b74a5294d7d2f584e72d3
/src/for_mathlib/misc.lean
c48f3d33eb3be01c3258a1385311c335c0c95edf
[ "Apache-2.0" ]
permissive
jcommelin/lean-perfectoid-spaces
c656ae26a2338ee7a0072dab63baf577f079ca12
d5ed816bcc116fd4cde5ce9aaf03905d00ee391c
refs/heads/master
1,584,610,432,107
1,538,491,594,000
1,538,491,594,000
136,299,168
0
0
null
1,528,274,452,000
1,528,274,452,000
null
UTF-8
Lean
false
false
632
lean
/- Lemmas in this file are currently not used in the perfectoid spaces project, but they were once thought to be useful, and could be PR'ed into mathlib anyway. -/ import analysis.topology.topological_space import for_mathlib.completion section uniform_space open uniform_space variables {α : Type*} [uniform_space α] local attribute [instance] separation_setoid instance inhabited_separation_space [h : inhabited α] : inhabited (quotient (separation_setoid α)) := ⟨⟦h.default⟧⟩ instance inhabited_completion [inhabited α] : inhabited (completion α) := by unfold completion; apply_instance end uniform_space
fe4de91c2f90a678208fc73e405444a294179677
dc253be9829b840f15d96d986e0c13520b085033
/algebra/short_five.hlean
bc371f6a53be693d8dc428ef24277bce86e2f392
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
5,339
hlean
/- Author: Jeremy Avigad -/ import .module_chain_complex open eq pointed sigma fiber equiv is_equiv sigma.ops is_trunc nat trunc open algebra function succ_str open left_module section short_five variable {R : Ring} variables {A₀ B₀ C₀ A₁ B₁ C₁ : LeftModule R} variables {f₀ : A₀ →lm B₀} {g₀ : B₀ →lm C₀} variables {f₁ : A₁ →lm B₁} {g₁ : B₁ →lm C₁} variables {h : A₀ →lm A₁} {k : B₀ →lm B₁} {l : C₀ →lm C₁} premise (short_exact₀ : is_short_exact f₀ g₀) premise (short_exact₁ : is_short_exact f₁ g₁) premise (hsquare₁ : hsquare f₀ f₁ h k) premise (hsquare₂ : hsquare g₀ g₁ k l) include short_exact₀ short_exact₁ hsquare₁ hsquare₂ open algebra.is_short_exact lemma short_five_mono [embh : is_embedding h] [embl : is_embedding l] : is_embedding k := have is_embedding f₁, from is_emb short_exact₁, is_embedding_of_is_add_hom k (take b, suppose k b = 0, have l (g₀ b) = 0, by rewrite [hsquare₂, ▸*, this, respect_zero], have g₀ b = 0, from eq_zero_of_eq_zero_of_is_embedding this, image.elim (ker_in_im short_exact₀ _ this) (take a, suppose f₀ a = b, have f₁ (h a) = 0, by rewrite [-hsquare₁, ▸*, this]; assumption, have h a = 0, from eq_zero_of_eq_zero_of_is_embedding this, have a = 0, from eq_zero_of_eq_zero_of_is_embedding this, show b = 0, by rewrite [-`f₀ a = b`, this, respect_zero])) lemma short_five_epi (surjh : is_surjective h) (surjl : is_surjective l) : is_surjective k := have surjg₀ : is_surjective g₀, from is_surj short_exact₀, take b₁ : B₁, image.elim (surjl (g₁ b₁)) ( take c₀ : C₀, assume lc₀ : l c₀ = g₁ b₁, image.elim (surjg₀ c₀) ( take b₀ : B₀, assume g₀b₀ : g₀ b₀ = c₀, have g₁ (k b₀ - b₁) = 0, by rewrite [respect_sub, -hsquare₂, ▸*, g₀b₀, lc₀, sub_self], image.elim (ker_in_im short_exact₁ _ this) ( take a₁ : A₁, assume f₁a₁ : f₁ a₁ = k b₀ - b₁, image.elim (surjh a₁) ( take a₀ : A₀, assume ha₀ : h a₀ = a₁, have k (f₀ a₀) = k b₀ - b₁, by rewrite [hsquare₁, ▸*, ha₀, f₁a₁], have k (b₀ - f₀ a₀) = b₁, by rewrite [respect_sub, this, sub_sub_self], image.mk _ this)))) end short_five section short_exact open module_chain_complex variables {R : Ring} {N : succ_str} record is_short_exact_at (C : module_chain_complex R N) (n : N) := (is_contr_0 : is_contr (C n)) (is_exact_at_1 : is_exact_at_m C n) (is_exact_at_2 : is_exact_at_m C (S n)) (is_exact_at_3 : is_exact_at_m C (S (S n))) (is_contr_4 : is_contr (C (S (S (S (S n)))))) /- TODO: show that this gives rise to a short exact sequence in the sense above -/ end short_exact section short_five_redux open module_chain_complex variables {R : Ring} {N : succ_str} /- TODO: restate short five in these terms -/ end short_five_redux /- TODO: state and prove strong_four, adapting the template below. section strong_four variables {R : Type} [ring R] variables {A B C D A' B' C' D' : Type} variables [left_module R A] [left_module R B] [left_module R C] [left_module R D] variables [left_module R A'] [left_module R B'] [left_module R C'] [left_module R D'] variables (ρ : A → B) [is_module_hom R ρ] variables (σ : B → C) [is_module_hom R σ] variables (τ : C → D) [is_module_hom R τ] variable (chainρσ : ∀ a, σ (ρ a) = 0) variable (exactρσ : ∀ {b}, σ b = 0 → ∃ a, ρ a = b) variable (chainστ : ∀ b, τ (σ b) = 0) variable (exactστ : ∀ {c}, τ c = 0 → ∃ b, σ b = c) variables (ρ' : A' → B') [is_module_hom R ρ'] variables (σ' : B' → C') [is_module_hom R σ'] variables (τ' : C' → D') [is_module_hom R τ'] variable (chainρ'σ' : ∀ a', σ' (ρ' a') = 0) variable (exactρ'σ' : ∀ {b'}, σ' b' = 0 → ∃ a', ρ' a' = b') variable (chainσ'τ' : ∀ b', τ' (σ' b') = 0) variable (exactσ'τ' : ∀ {c'}, τ' c' = 0 → ∃ b', σ' b' = c') variables (α : A → A') [is_module_hom R α] variables (β : B → B') [is_module_hom R β] variables (γ : C → C') [is_module_hom R γ] variables (δ : D → D') [is_module_hom R δ] variables (sq₁ : comm_square ρ ρ' α β) variables (sq₂ : comm_square σ σ' β γ) variables (sq₃ : comm_square τ τ' γ δ) include sq₃ σ' sq₂ exactρ'σ' sq₁ chainρσ theorem strong_four_a (epiα : is_surjective α) (monoδ : is_embedding δ) (c : C) (γc0 : γ c = 0) : Σ b, (β b = 0 × σ b = c) := have δ (τ c) = 0, by rewrite [sq₃, γc0, hom_zero], have τ c = 0, from eq_zero_of_eq_zero_of_is_embedding this, obtain b (σbc : σ b = c), from exactστ this, have σ' (β b) = 0, by rewrite [-sq₂, σbc, γc0], obtain a' (ρ'a'βb : ρ' a' = β b), from exactρ'σ' this, obtain a (αaa' : α a = a'), from epiα a', exists.intro (b - ρ a) (pair (show β (b - ρ a) = 0, by rewrite [hom_sub, -ρ'a'βb, sq₁, αaa', sub_self]) (show σ (b - ρ a) = c, from calc σ (b - ρ a) = σ b - σ (ρ a) : hom_sub _ ... = σ b : by rewrite [chainρσ, sub_zero] ... = c : σbc)) end strong_four -/
bf7ad9a61e994c2064bdfe8f7215f4be0325b86a
0d4c30038160d9c35586ce4dace36fe26a35023b
/src/analysis/complex/exponential.lean
3f97f0589f9434f3cff70f852d8c18fd31e77ea2
[ "Apache-2.0" ]
permissive
b-mehta/mathlib
b0c8ec929ec638447e4262f7071570d23db52e14
ce72cde867feabe5bb908cf9e895acc0e11bf1eb
refs/heads/master
1,599,457,264,781
1,586,969,260,000
1,586,969,260,000
220,672,634
0
0
Apache-2.0
1,583,944,480,000
1,573,317,991,000
Lean
UTF-8
Lean
false
false
88,515
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 tactic.linarith data.complex.exponential analysis.specific_limits group_theory.quotient_group analysis.complex.basic /-! # Exponential ## Main definitions This file contains the following definitions: * π, arcsin, arccos, arctan * argument of a complex number * logarithm on real and complex numbers * complex and real power function ## Main statements The following functions are shown to be continuous: * complex and real exponential function * sin, cos, tan, sinh, cosh * logarithm on real numbers * real power function * square root function The following functions are shown to be differentiable, and their derivatives are computed: * complex and real exponential function * sin, cos, sinh, cosh ## Tags exp, log, sin, cos, tan, arcsin, arccos, arctan, angle, argument, power, square root, -/ noncomputable theory open finset filter metric asymptotics open_locale classical open_locale topological_space namespace complex /-- The complex exponential is everywhere differentiable, with the derivative `exp x`. -/ lemma has_deriv_at_exp (x : ℂ) : has_deriv_at exp (exp x) x := begin rw has_deriv_at_iff_is_o_nhds_zero, have : (1 : ℕ) < 2 := by norm_num, refine is_O.trans_is_o ⟨∥exp x∥, _⟩ (is_o_pow_id this), have : metric.ball (0 : ℂ) 1 ∈ nhds (0 : ℂ) := metric.ball_mem_nhds 0 zero_lt_one, apply filter.mem_sets_of_superset this (λz hz, _), simp only [metric.mem_ball, dist_zero_right] at hz, simp only [exp_zero, mul_one, one_mul, add_comm, normed_field.norm_pow, zero_add, set.mem_set_of_eq], calc ∥exp (x + z) - exp x - z * exp x∥ = ∥exp x * (exp z - 1 - z)∥ : by { congr, rw [exp_add], ring } ... = ∥exp x∥ * ∥exp z - 1 - z∥ : normed_field.norm_mul _ _ ... ≤ ∥exp x∥ * ∥z∥^2 : mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le (le_of_lt hz)) (norm_nonneg _) end lemma differentiable_exp : differentiable ℂ exp := λx, (has_deriv_at_exp x).differentiable_at @[simp] lemma deriv_exp : deriv exp = exp := funext $ λ x, (has_deriv_at_exp x).deriv @[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp | 0 := rfl | (n+1) := by rw [nat.iterate_succ, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous end complex lemma has_deriv_at.cexp {f : ℂ → ℂ} {f' x : ℂ} (hf : has_deriv_at f f' x) : has_deriv_at (complex.exp ∘ f) (complex.exp (f x) * f') x := (complex.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.cexp {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (complex.exp ∘ f) (complex.exp (f x) * f') s x := (complex.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf namespace complex /-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/ lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x := begin simp only [cos, div_eq_mul_inv], convert ((((has_deriv_at_id x).neg.mul_const I).cexp.sub ((has_deriv_at_id x).mul_const I).cexp).mul_const I).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], rw [sub_mul, mul_assoc, mul_assoc, I_mul_I, neg_one_mul, neg_neg, mul_one, one_mul, mul_assoc, I_mul_I, mul_neg_one, sub_neg_eq_add, add_comm] end lemma differentiable_sin : differentiable ℂ sin := λx, (has_deriv_at_sin x).differentiable_at @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous /-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/ lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x := begin simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul], convert (((has_deriv_at_id x).mul_const I).cexp.add ((has_deriv_at_id x).neg.mul_const I).cexp).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], ring end lemma differentiable_cos : differentiable ℂ cos := λx, (has_deriv_at_cos x).differentiable_at lemma deriv_cos {x : ℂ} : deriv cos x = -sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, -sin x) := funext $ λ x, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) /-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `sinh x`. -/ lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x := begin simp only [cosh, div_eq_mul_inv], convert ((has_deriv_at_exp x).sub (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, neg_neg] end lemma differentiable_sinh : differentiable ℂ sinh := λx, (has_deriv_at_sinh x).differentiable_at @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous /-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `cosh x`. -/ lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x := begin simp only [sinh, div_eq_mul_inv], convert ((has_deriv_at_exp x).add (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, sub_eq_add_neg] end lemma differentiable_cosh : differentiable ℂ cosh := λx, (has_deriv_at_cosh x).differentiable_at @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous end complex namespace real variables {x y z : ℝ} lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_exp x) lemma differentiable_exp : differentiable ℝ exp := λx, (has_deriv_at_exp x).differentiable_at @[simp] lemma deriv_exp : deriv exp = exp := funext $ λ x, (has_deriv_at_exp x).deriv @[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp | 0 := rfl | (n+1) := by rw [nat.iterate_succ, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sin x) lemma differentiable_sin : differentiable ℝ sin := λx, (has_deriv_at_sin x).differentiable_at @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x := (has_deriv_at_real_of_complex (complex.has_deriv_at_cos x) : _) lemma differentiable_cos : differentiable ℝ cos := λx, (has_deriv_at_cos x).differentiable_at lemma deriv_cos : deriv cos x = - sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, - sin x) := funext $ λ _, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := by simp only [tan_eq_sin_div_cos]; exact (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sinh x) lemma differentiable_sinh : differentiable ℝ sinh := λx, (has_deriv_at_sinh x).differentiable_at @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_cosh x) lemma differentiable_cosh : differentiable ℝ cosh := λx, (has_deriv_at_cosh x).differentiable_at @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x := have ∀ {z:ℝ}, 1 ≤ z → z ∈ set.range exp, from λ z hz, intermediate_value_univ 0 (z - 1) continuous_exp ⟨by simpa, by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hz)⟩, match le_total x 1 with | (or.inl hx1) := let ⟨y, hy⟩ := this (one_le_inv hx hx1) in ⟨-y, by rw [exp_neg, hy, inv_inv']⟩ | (or.inr hx1) := this hx1 end /-- The real logarithm function, equal to `0` for `x ≤ 0` and to the inverse of the exponential for `x > 0`. -/ 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 log_lt_log (hx : 0 < x) : x < y → log x < log y := by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] } lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y := by { rw [← exp_lt_exp, exp_log hx, exp_log hy] } lemma log_pos_iff (x : ℝ) : 0 < log x ↔ 1 < x := begin by_cases h : 0 < x, { rw ← log_one, exact log_lt_log_iff (by norm_num) h }, { rw [log, dif_neg], split, repeat {intro, linarith} } end lemma log_pos : 1 < x → 0 < log x := (log_pos_iff x).2 lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 := by { rw ← log_one, exact log_lt_log_iff h (by norm_num) } lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1 lemma log_nonneg : 1 ≤ x → 0 ≤ log x := by { intro, rwa [← log_one, log_le_log], norm_num, linarith } lemma log_nonpos : x ≤ 1 → log x ≤ 0 := begin intro, by_cases hx : 0 < x, { rwa [← log_one, log_le_log], exact hx, norm_num }, { simp [log, dif_neg hx] } end section prove_log_is_continuous lemma tendsto_log_one_zero : tendsto log (𝓝 1) (𝓝 0) := begin rw tendsto_nhds_nhds, assume ε ε0, let δ := min (exp ε - 1) (1 - exp (-ε)), have : 0 < δ, refine lt_min (sub_pos_of_lt (by rwa one_lt_exp_iff)) (sub_pos_of_lt _), by { rw exp_lt_one_iff, linarith }, use [δ, this], assume x h, cases le_total 1 x with hx hx, { have h : x < exp ε, rw [dist_eq, abs_of_nonneg (sub_nonneg_of_le hx)] at h, linarith [(min_le_left _ _ : δ ≤ exp ε - 1)], calc abs (log x - 0) = abs (log x) : by simp ... = log x : abs_of_nonneg $ log_nonneg hx ... < ε : by { rwa [← exp_lt_exp, exp_log], linarith }}, { have h : exp (-ε) < x, rw [dist_eq, abs_of_nonpos (sub_nonpos_of_le hx)] at h, linarith [(min_le_right _ _ : δ ≤ 1 - exp (-ε))], have : 0 < x := lt_trans (exp_pos _) h, calc abs (log x - 0) = abs (log x) : by simp ... = -log x : abs_of_nonpos $ log_nonpos hx ... < ε : by { rw [neg_lt, ← exp_lt_exp, exp_log], assumption' } } end lemma continuous_log' : continuous (λx : {x:ℝ // 0 < x}, log x.val) := continuous_iff_continuous_at.2 $ λ x, begin rw continuous_at, let f₁ := λ h:{h:ℝ // 0 < h}, log (x.1 * h.1), let f₂ := λ y:{y:ℝ // 0 < y}, subtype.mk (x.1 ⁻¹ * y.1) (mul_pos (inv_pos.2 x.2) y.2), have H1 : tendsto f₁ (𝓝 ⟨1, zero_lt_one⟩) (𝓝 (log (x.1*1))), have : f₁ = λ h:{h:ℝ // 0 < h}, log x.1 + log h.1, ext h, rw ← log_mul x.2 h.2, simp only [this, log_mul x.2 zero_lt_one, log_one], exact tendsto_const_nhds.add (tendsto.comp tendsto_log_one_zero continuous_at_subtype_val), have H2 : tendsto f₂ (𝓝 x) (𝓝 ⟨x.1⁻¹ * x.1, mul_pos (inv_pos.2 x.2) x.2⟩), rw tendsto_subtype_rng, exact tendsto_const_nhds.mul continuous_at_subtype_val, suffices h : tendsto (f₁ ∘ f₂) (𝓝 x) (𝓝 (log x.1)), begin convert h, ext y, have : x.val * (x.val⁻¹ * y.val) = y.val, rw [← mul_assoc, mul_inv_cancel (ne_of_gt x.2), one_mul], show log (y.val) = log (x.val * (x.val⁻¹ * y.val)), rw this end, exact tendsto.comp (by rwa mul_one at H1) (by { simp only [inv_mul_cancel (ne_of_gt x.2)] at H2, assumption }) end lemma continuous_at_log (hx : 0 < x) : continuous_at log x := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_log' _ hx) (mem_nhds_sets (is_open_lt' _) hx) /-- Three forms of the continuity of `real.log` is provided. For the other two forms, see `real.continuous_log'` and `real.continuous_at_log` -/ lemma continuous_log {α : Type*} [topological_space α] {f : α → ℝ} (h : ∀a, 0 < f a) (hf : continuous f) : continuous (λa, log (f a)) := show continuous ((log ∘ @subtype.val ℝ (λr, 0 < r)) ∘ λa, ⟨f a, h a⟩), from continuous_log'.comp (continuous_subtype_mk _ hf) end prove_log_is_continuous lemma exists_cos_eq_zero : 0 ∈ cos '' set.Icc (1:ℝ) 2 := intermediate_value_Icc' (by norm_num) continuous_cos.continuous_on ⟨le_of_lt cos_two_neg, le_of_lt cos_one_pos⟩ /-- The number π = 3.14159265... Defined here using choice as twice a zero of cos in [1,2], from which one can derive all its properties. For explicit bounds on π, see `data.real.pi`. -/ noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero localized "notation `π` := real.pi" in real @[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 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.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).1.2 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 [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 [sub_eq_add_neg, 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 [sub_eq_add_neg, 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 [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, 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 [sub_eq_add_neg, 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 [sub_eq_add_neg, 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 [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 [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 : set.Icc (-1:ℝ) 1 ⊆ sin '' set.Icc (-(π / 2)) (π / 2) := by convert intermediate_value_Icc (le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos)) continuous_sin.continuous_on; simp only [sin_neg, sin_pi_div_two] 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) : x - x ^ 3 / 4 < sin x := 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 /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (gmultiples (2 * π)) namespace angle instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group _ instance : inhabited angle := ⟨0⟩ instance angle.has_coe : has_coe ℝ angle := ⟨quotient.mk'⟩ instance angle.is_add_group_hom : @is_add_group_hom ℝ angle _ _ (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_smul (x : ℝ) (n : ℕ) : ↑(add_monoid.smul n x : ℝ) = add_monoid.smul n (↑x : angle) := add_monoid_hom.map_smul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp] lemma coe_gsmul (x : ℝ) (n : ℤ) : ↑(gsmul n x : ℝ) = gsmul n (↑x : angle) := add_monoid_hom.map_gsmul ⟨coe, coe_zero, coe_add⟩ _ _ @[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) 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.2 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.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 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 [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 [sub_eq_add_neg, arccos] lemma arccos_le_pi (x : ℝ) : arccos x ≤ π := by unfold arccos; linarith [neg_pi_div_two_le_arcsin x] lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x := by unfold arccos; linarith [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 [sub_eq_add_neg]; 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 [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 [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, 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 open_locale real /-- `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 [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 [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 [sub_eq_add_neg, arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] 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, ← 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 [sub_eq_add_neg, 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 := begin by_cases h : x = 0, { simp only [h, euclidean_domain.zero_div, complex.zero_im, complex.arg_zero, real.tan_zero, complex.zero_re]}, rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg h, div_div_div_cancel_right' _ (mt abs_eq_zero.1 h)] end 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 [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; try {simp [add_left_comm]}; 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 [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.sin_pi_sub, real.arcsin_sin]; simp [sub_eq_add_neg]; 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 [sub_eq_add_neg, 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 [sub_eq_add_neg, 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 [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, 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 [sub_eq_add_neg, 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 /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ 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⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl 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 cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[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_comm, 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 /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log (-x)) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl 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_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] } open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log (-x) * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log (-x) * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := abs_le_of_le_of_neg_le begin cases lt_trichotomy 0 x, { rw abs_of_pos h }, cases h, { simp [h.symm] }, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h], calc exp (log (-x) * y) * cos (y * π) ≤ exp (log (-x) * y) * 1 : mul_le_mul_of_nonneg_left (cos_le_one _) (le_of_lt $ exp_pos _) ... = _ : mul_one _ end begin cases lt_trichotomy 0 x, { rw abs_of_pos h, have : 0 < x^y := rpow_pos_of_pos h _, linarith }, cases h, { simp only [h.symm, abs_zero, rpow_def_of_nonneg], split_ifs, repeat {norm_num}}, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h], calc -(exp (log (-x) * y) * cos (y * π)) = exp (log (-x) * y) * (-cos (y * π)) : by ring ... ≤ exp (log (-x) * y) * 1 : mul_le_mul_of_nonneg_left (neg_le.2 $ neg_one_le_cos _) (le_of_lt $ exp_pos _) ... = exp (log (-x) * y) : mul_one _ 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 open_locale real variables {x y z : ℝ} @[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_pos hx, 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_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos hx1), 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 one_lt_rpow (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma rpow_lt_one (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow (le_of_lt hx) hx1 hz } 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] lemma rpow_nat_inv_pow_nat {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, inv_mul_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2] }, (continuous_exp.comp $ (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul (continuous_cos.comp $ (continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_lt' (0:ℝ)) is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_gt' (0:ℝ)) is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_prod is_open_univ (is_open_lt' (0:ℝ)), ext, finish }) hy) lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x } variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end lemma continuous_sqrt : continuous sqrt := by rw sqrt_eq_rpow; exact continuous_rpow_of_pos (λa, by norm_num) continuous_id continuous_const end sqrt section exp /-- The real exponential function tends to +infinity at +infinity -/ lemma tendsto_exp_at_top : tendsto exp at_top at_top := begin have A : tendsto (λx:ℝ, x + 1) at_top at_top := tendsto_at_top_add_const_right at_top 1 tendsto_id, have B : ∀ᶠ x in at_top, x + 1 ≤ exp x, { have : ∀ᶠ (x : ℝ) in at_top, 0 ≤ x := mem_at_top 0, filter_upwards [this], exact λx hx, add_one_le_exp_of_nonneg hx }, exact tendsto_at_top_mono' at_top B A end /-- The real exponential function tends to 0 at -infinity or, equivalently, `exp(-x)` tends to `0` at +infinity -/ lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_at_top)).congr (λx, (exp_neg x).symm) /-- The function `exp(x)/x^n` tends to +infinity at +infinity, for any natural number `n` -/ lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top := begin have n_pos : (0 : ℝ) < n + 1 := nat.cast_add_one_pos n, have n_ne_zero : (n : ℝ) + 1 ≠ 0 := ne_of_gt n_pos, have A : ∀x:ℝ, 0 < x → exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n, { assume x hx, let y := x / (n+1), have y_pos : 0 < y := div_pos hx n_pos, have : exp (x / (n+1)) ≤ (n+1)^n * (exp x / x^n), from calc exp y = exp y * 1 : by simp ... ≤ exp y * (exp y / y)^n : begin apply mul_le_mul_of_nonneg_left (one_le_pow_of_one_le _ n) (le_of_lt (exp_pos _)), apply one_le_div_of_le _ y_pos, apply le_trans _ (add_one_le_exp_of_nonneg (le_of_lt y_pos)), exact le_add_of_le_of_nonneg (le_refl _) (zero_le_one) end ... = exp y * exp (n * y) / y^n : by rw [div_pow, exp_nat_mul, mul_div_assoc] ... = exp ((n + 1) * y) / y^n : by rw [← exp_add, add_mul, one_mul, add_comm] ... = exp x / (x / (n+1))^n : by { dsimp [y], rw mul_div_cancel' _ n_ne_zero } ... = (n+1)^n * (exp x / x^n) : by rw [← mul_div_assoc, div_pow, div_div_eq_mul_div, mul_comm], rwa div_le_iff' (pow_pos n_pos n) }, have B : ∀ᶠ x in at_top, exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n := mem_at_top_sets.2 ⟨1, λx hx, A _ (lt_of_lt_of_le zero_lt_one hx)⟩, have C : tendsto (λx, exp (x / (n+1)) / (n+1)^n) at_top at_top := tendsto_at_top_div (pow_pos n_pos n) (tendsto_exp_at_top.comp (tendsto_at_top_div (nat.cast_add_one_pos n) tendsto_id)), exact tendsto_at_top_mono' at_top B C end /-- The function `x^n * exp(-x)` tends to `0` at +infinity, for any natural number `n`. -/ lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_div_pow_at_top n)).congr $ λx, by rw [function.comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg] end exp end real lemma has_deriv_at.rexp {f : ℝ → ℝ} {f' x : ℝ} (hf : has_deriv_at f f' x) : has_deriv_at (real.exp ∘ f) (real.exp (f x) * f') x := (real.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.rexp {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (real.exp ∘ f) (real.exp (f x) * f') s x := (real.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : nnreal` and `y : ℝ ` as the restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def rpow (x : nnreal) (y : ℝ) : nnreal := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow nnreal ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : nnreal) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, move_cast] lemma coe_rpow (x : nnreal) (y : ℝ) : ((x ^ y : nnreal) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : nnreal) : x ^ (0 : ℝ) = 1 := by { rw ← nnreal.coe_eq, exact real.rpow_zero _ } @[simp] lemma rpow_eq_zero_iff {x : nnreal} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := begin rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero], exact real.rpow_eq_zero_iff_of_nonneg x.2 end @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : nnreal) ^ x = 0 := by { rw ← nnreal.coe_eq, exact real.zero_rpow h } @[simp] lemma rpow_one (x : nnreal) : x ^ (1 : ℝ) = x := by { rw ← nnreal.coe_eq, exact real.rpow_one _ } @[simp] lemma one_rpow (x : ℝ) : (1 : nnreal) ^ x = 1 := by { rw ← nnreal.coe_eq, exact real.one_rpow _ } lemma rpow_add {x : nnreal} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z := by { rw ← nnreal.coe_eq, exact real.rpow_add _ _ hx } lemma rpow_mul (x : nnreal) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by { rw ← nnreal.coe_eq, exact real.rpow_mul x.2 y z } lemma rpow_neg (x : nnreal) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by { rw ← nnreal.coe_eq, exact real.rpow_neg x.2 _ } @[simp] lemma rpow_nat_cast (x : nnreal) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by { rw [← nnreal.coe_eq, coe_pow], exact real.rpow_nat_cast (x : ℝ) n } lemma mul_rpow {x y : nnreal} {z : ℝ} : (x*y)^z = x^z * y^z := by { rw ← nnreal.coe_eq, exact real.mul_rpow x.2 y.2 } lemma one_le_rpow {x : nnreal} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma rpow_le_rpow {x y : nnreal} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := real.rpow_le_rpow x.2 h₁ h₂ lemma rpow_lt_rpow {x y : nnreal} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_of_exponent_lt {x : nnreal} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z := real.rpow_lt_rpow_of_exponent_lt hx hyz lemma rpow_le_rpow_of_exponent_le {x : nnreal} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_le hx hyz lemma rpow_lt_rpow_of_exponent_gt {x : nnreal} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz lemma rpow_le_rpow_of_exponent_ge {x : nnreal} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz lemma rpow_le_one {x : nnreal} {e : ℝ} (he : 0 ≤ e) (hx2 : x ≤ 1) : x^e ≤ 1 := real.rpow_le_one he x.2 hx2 lemma one_lt_rpow {x : nnreal} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma rpow_lt_one {x : nnreal} {z : ℝ} (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma pow_nat_rpow_nat_inv (x : nnreal) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : nnreal) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : nnreal} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:nnreal×ℝ, p.1^p.2) (x, y) := begin have : (λp:nnreal×ℝ, p.1^p.2) = nnreal.of_real ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:nnreal × ℝ, (p.1.1, p.2)), { ext p, rw [← nnreal.coe_eq, coe_rpow, coe_of_real _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine continuous_of_real.continuous_at.comp (continuous_at.comp _ _), { apply real.continuous_at_rpow, simp at h, rw ← (nnreal.coe_eq_zero x) at h, exact h }, { exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at } end end nnreal lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → nnreal} {v : α → ℝ} {x : nnreal} {y : ℝ} (hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) := tendsto.comp (nnreal.continuous_at_rpow h) (tendsto.prod_mk_nhds hx hy)
b66aa70c4f34ecfaf69aaf9d4bc5d97675efd2dd
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Server/Rpc/Basic.lean
482c266e8b1fcf668d69b4b38429be541fb59dd3
[ "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
4,746
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Data.Json /-! Allows LSP clients to make Remote Procedure Calls to the server. The single use case for these is to allow the infoview UI to refer to and manipulate heavy-weight objects residing on the server. It would be inefficient to serialize these into JSON and send over. For example, the client can format an `Expr` without transporting the whole `Environment`. All RPC requests are relative to an open file and an RPC session for that file. The client must first connect to the session using `$/lean/rpc/connect`. -/ namespace Lean.Lsp /-- An object which RPC clients can refer to without marshalling. -/ structure RpcRef where /- NOTE(WN): It is important for this to be a single-field structure in order to deserialize as an `Object` on the JS side. -/ p : USize deriving BEq, Hashable, FromJson, ToJson instance : ToString RpcRef where toString r := toString r.p end Lean.Lsp namespace Lean.Server structure RpcObjectStore : Type where /-- Objects that are being kept alive for the RPC client, together with their type names, mapped to by their RPC reference. Note that we may currently have multiple references to the same object. It is only disposed of once all of those are gone. This simplifies the client a bit as it can drop every reference received separately. -/ aliveRefs : PersistentHashMap Lsp.RpcRef Dynamic := {} /-- Value to use for the next `RpcRef`. It is monotonically increasing to avoid any possible bugs resulting from its reuse. -/ nextRef : USize := 0 def rpcStoreRef (any : Dynamic) : StateM RpcObjectStore Lsp.RpcRef := do let st ← get set { st with aliveRefs := st.aliveRefs.insert ⟨st.nextRef⟩ any nextRef := st.nextRef + 1 } return ⟨st.nextRef⟩ def rpcGetRef (r : Lsp.RpcRef) : ReaderT RpcObjectStore Id (Option Dynamic) := return (← read).aliveRefs.find? r def rpcReleaseRef (r : Lsp.RpcRef) : StateM RpcObjectStore Bool := do let st ← get if st.aliveRefs.contains r then set { st with aliveRefs := st.aliveRefs.erase r } return true else return false /-- `RpcEncodable α` means that `α` can be serialized in the RPC system of the Lean server. This is required when `α` contains fields which should be serialized as an RPC reference instead of being sent in full. The type wrapper `WithRpcRef` is used for these fields which should be sent as a reference. - Any type with `FromJson` and `ToJson` instance is automatically `RpcEncodable`. - If a type has an `Dynamic` instance, then `WithRpcRef` can be used for its references. - `deriving RpcEncodable` acts like `FromJson`/`ToJson` but marshalls any `WithRpcRef` fields as `Lsp.RpcRef`s. -/ -- TODO(WN): for Lean.js, compile `WithRpcRef` to "opaque reference" on the client class RpcEncodable (α : Type) where rpcEncode : α → StateM RpcObjectStore Json rpcDecode : Json → ExceptT String (ReaderT RpcObjectStore Id) α export RpcEncodable (rpcEncode rpcDecode) instance : Nonempty (RpcEncodable α) := ⟨{ rpcEncode := default, rpcDecode := default }⟩ instance [FromJson α] [ToJson α] : RpcEncodable α where rpcEncode a := return toJson a rpcDecode j := ofExcept (fromJson? j) instance [RpcEncodable α] : RpcEncodable (Option α) where rpcEncode v := toJson <$> v.mapM rpcEncode rpcDecode j := do Option.mapM rpcDecode (← fromJson? j) -- TODO(WN): instance [RpcEncodable α β] [Traversable t] : RpcEncodable (t α) (t β) instance [RpcEncodable α] : RpcEncodable (Array α) where rpcEncode a := toJson <$> a.mapM rpcEncode rpcDecode b := do Array.mapM rpcDecode (← fromJson? b) instance [RpcEncodable α] [RpcEncodable β] : RpcEncodable (α × β) where rpcEncode := fun (a, b) => return toJson (← rpcEncode a, ← rpcEncode b) rpcDecode j := do let (a, b) ← fromJson? j return (← rpcDecode a, ← rpcDecode b) /-- Marks fields to encode as opaque references in LSP packets. -/ structure WithRpcRef (α : Type u) where val : α deriving Inhabited instance [TypeName α] : RpcEncodable (WithRpcRef α) := { rpcEncode, rpcDecode } where -- separate definitions to prevent inlining rpcEncode r := toJson <$> rpcStoreRef (.mk r.val) rpcDecode j := do let r ← fromJson? j match (← rpcGetRef r) with | none => throw s!"RPC reference '{r}' is not valid" | some any => if let some obj := any.get? α then return ⟨obj⟩ else throw s!"RPC call type mismatch in reference '{r}'\nexpected '{TypeName.typeName α}', got '{any.typeName}'" end Lean.Server
2a5b401abb380da113d2f60536a09aa8ef371353
80746c6dba6a866de5431094bf9f8f841b043d77
/src/algebra/module.lean
3cb9995e4ba16ba7a122df099e5eaa33409bb084
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
12,153
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro Modules over a ring. -/ import algebra.ring algebra.big_operators open function universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) infixr ` • `:73 := has_scalar.smul /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `α` and an additive monoid of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class semimodule (α : Type u) (β : Type v) [semiring α] [add_comm_monoid β] extends has_scalar α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : α) (x : β), (r * s) • x = r • s • x) (one_smul : ∀x : β, (1 : α) • x = x) (zero_smul : ∀x : β, (0 : α) • x = 0) (smul_zero {} : ∀(r : α), r • (0 : β) = 0) section semimodule variables [R:semiring α] [add_comm_monoid β] [semimodule α β] (r s : α) (x y : β) include R theorem smul_add : r • (x + y) = r • x + r • y := semimodule.smul_add r x y theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x theorem mul_smul : (r * s) • x = r • s • x := semimodule.mul_smul r s x @[simp] theorem smul_zero : r • (0 : β) = 0 := semimodule.smul_zero r variables (α) @[simp] theorem one_smul : (1 : α) • x = x := semimodule.one_smul α x @[simp] theorem zero_smul : (0 : α) • x = 0 := semimodule.zero_smul α x lemma smul_smul : r • s • x = (r * s) • x := (mul_smul _ _ _).symm instance smul.is_add_monoid_hom {r : α} : is_add_monoid_hom (λ x : β, r • x) := by refine_struct {..}; simp [smul_add] end semimodule /-- A module is a generalization of vector spaces to a scalar ring. It consists of a scalar ring `α` and an additive group of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class module (α : Type u) (β : Type v) [ring α] [add_comm_group β] extends semimodule α β structure module.core (α β) [ring α] [add_comm_group β] extends has_scalar α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : α) (x : β), (r * s) • x = r • s • x) (one_smul : ∀x : β, (1 : α) • x = x) def module.of_core {α β} [ring α] [add_comm_group β] (M : module.core α β) : module α β := by letI := M.to_has_scalar; exact { zero_smul := λ x, have (0 : α) • x + (0 : α) • x = (0 : α) • x + 0, by rw ← M.add_smul; simp, add_left_cancel this, smul_zero := λ r, have r • (0:β) + r • 0 = r • 0 + 0, by rw ← M.smul_add; simp, add_left_cancel this, ..M } section module variables [ring α] [add_comm_group β] [module α β] (r s : α) (x y : β) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (α) theorem neg_one_smul (x : β) : (-1 : α) • x = -x := by simp variables {α} @[simp] theorem smul_neg : r • (-x) = -(r • x) := by rw [← neg_one_smul α, ← mul_smul, mul_neg_one, neg_smul] theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y := by simp [smul_add]; rw smul_neg theorem sub_smul (r s : α) (y : β) : (r - s) • y = r • y - s • y := by simp [add_smul] end module instance semiring.to_semimodule [r : semiring α] : semimodule α α := { smul := (*), smul_add := mul_add, add_smul := add_mul, mul_smul := mul_assoc, one_smul := one_mul, zero_smul := zero_mul, smul_zero := mul_zero, ..r } @[simp] lemma smul_eq_mul [semiring α] {a a' : α} : a • a' = a * a' := rfl instance ring.to_module [r : ring α] : module α α := { ..semiring.to_semimodule } class is_linear_map (α : Type u) {β : Type v} {γ : Type w} [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] (f : β → γ) : Prop := (add : ∀x y, f (x + y) = f x + f y) (smul : ∀(c : α) x, f (c • x) = c • f x) structure linear_map (α : Type u) (β : Type v) (γ : Type w) [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] := (to_fun : β → γ) (add : ∀x y, to_fun (x + y) = to_fun x + to_fun y) (smul : ∀(c : α) x, to_fun (c • x) = c • to_fun x) infixr ` →ₗ `:25 := linear_map _ notation β ` →ₗ[`:25 α `] ` γ := linear_map α β γ namespace linear_map variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] variables (f g : β →ₗ[α] γ) include α instance : has_coe_to_fun (β →ₗ[α] γ) := ⟨_, to_fun⟩ theorem is_linear : is_linear_map α f := {..f} @[extensionality] theorem ext {f g : β →ₗ[α] γ} (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H theorem ext_iff {f g : β →ₗ[α] γ} : f = g ↔ ∀ x, f x = g x := ⟨by rintro rfl; simp, ext⟩ @[simp] lemma map_add (x y : β) : f (x + y) = f x + f y := f.add x y @[simp] lemma map_smul (c : α) (x : β) : f (c • x) = c • f x := f.smul c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul α, map_smul f 0 0, zero_smul] instance : is_add_group_hom f := ⟨map_add f⟩ @[simp] lemma map_neg (x : β) : f (- x) = - f x := by rw [← neg_one_smul α, map_smul, neg_one_smul] @[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y := by simp [map_neg, map_add] @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → β} : f (t.sum g) = t.sum (λi, f (g i)) := (finset.sum_hom f).symm def comp (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) : β →ₗ[α] δ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) (x : β) : f.comp g x = f (g x) := rfl def id : β →ₗ[α] β := ⟨id, by simp, by simp⟩ @[simp] lemma id_apply (x : β) : @id α β _ _ _ x = x := rfl end linear_map namespace is_linear_map variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] include α def mk' (f : β → γ) (H : is_linear_map α f) : β →ₗ γ := {to_fun := f, ..H} @[simp] theorem mk'_apply {f : β → γ} (H : is_linear_map α f) (x : β) : mk' f H x = f x := rfl end is_linear_map /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (α : Type u) (β : Type v) [ring α] [add_comm_group β] [module α β] : Type v := (carrier : set β) (zero : (0:β) ∈ carrier) (add : ∀ {x y}, x ∈ carrier → y ∈ carrier → x + y ∈ carrier) (smul : ∀ (c:α) {x}, x ∈ carrier → c • x ∈ carrier) namespace submodule variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] variables (p p' : submodule α β) variables {r : α} {x y : β} instance : has_coe (submodule α β) (set β) := ⟨submodule.carrier⟩ instance : has_mem β (submodule α β) := ⟨λ x p, x ∈ (p : set β)⟩ @[simp] theorem mem_coe : x ∈ (p : set β) ↔ x ∈ p := iff.rfl theorem ext' {s t : submodule α β} (h : (s : set β) = t) : s = t := by cases s; cases t; congr' protected theorem ext'_iff {s t : submodule α β} : (s : set β) = t ↔ s = t := ⟨ext', λ h, h ▸ rfl⟩ @[extensionality] theorem ext {s t : submodule α β} (h : ∀ x, x ∈ s ↔ x ∈ t) : s = t := ext' $ set.ext h @[simp] lemma zero_mem : (0 : β) ∈ p := p.zero lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add h₁ h₂ lemma smul_mem (r : α) (h : x ∈ p) : r • x ∈ p := p.smul r h lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul α; exact p.smul_mem _ hx lemma sub_mem (hx : x ∈ p) (hy : y ∈ p) : x - y ∈ p := p.add_mem hx (p.neg_mem hy) lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := ⟨λ h, by simpa using neg_mem p h, neg_mem p⟩ lemma add_mem_iff_left (h₁ : y ∈ p) : x + y ∈ p ↔ x ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, λ h₂, add_mem _ h₂ h₁⟩ lemma add_mem_iff_right (h₁ : x ∈ p) : x + y ∈ p ↔ y ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, add_mem _ h₁⟩ lemma sum_mem {ι : Type w} [decidable_eq ι] {t : finset ι} {f : ι → β} : (∀c∈t, f c ∈ p) → t.sum f ∈ p := finset.induction_on t (by simp [p.zero_mem]) (by simp [p.add_mem] {contextual := tt}) instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ instance : has_scalar α p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩ @[simp] lemma coe_add (x y : p) : (↑(x + y) : β) = ↑x + ↑y := rfl @[simp] lemma coe_zero : ((0 : p) : β) = 0 := rfl @[simp] lemma coe_neg (x : p) : ((-x : p) : β) = -x := rfl @[simp] lemma coe_smul (r : α) (x : p) : ((r • x : p) : β) = r • ↑x := rfl instance : add_comm_group p := by refine {add := (+), zero := 0, neg := has_neg.neg, ..}; { intros, apply set_coe.ext, simp } lemma coe_sub (x y : p) : (↑(x - y) : β) = ↑x - ↑y := by simp instance : module α p := by refine {smul := (•), ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } protected def subtype : p →ₗ[α] β := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl end submodule @[reducible] def ideal (α : Type u) [comm_ring α] := submodule α α namespace ideal variables [comm_ring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem _ lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left h end ideal /-- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like `ℝ^n`, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ class vector_space (α : Type u) (β : Type v) [discrete_field α] [add_comm_group β] extends module α β /-- Subspace of a vector space. Defined to equal `submodule`. -/ @[reducible] def subspace (α : Type u) (β : Type v) [discrete_field α] [add_comm_group β] [vector_space α β] : Type v := submodule α β instance subspace.vector_space {α β} {f : discrete_field α} [add_comm_group β] [vector_space α β] (p : subspace α β) : vector_space α p := {..submodule.module p} namespace submodule variables {R:discrete_field α} [add_comm_group β] [add_comm_group γ] variables [vector_space α β] [vector_space α γ] variables (p p' : submodule α β) variables {r : α} {x y : β} include R theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p := ⟨λ h, by simpa [smul_smul, inv_mul_cancel r0] using p.smul_mem (r⁻¹) h, p.smul_mem r⟩ end submodule
54ff19ea8a8814a78f2ecb6bba4ac82ec5d744c8
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/order/filter/basic.lean
2a226c16b14e8ba5c3ad5f75179c01cb7d795171
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
101,271
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad -/ import order.zorn import order.copy import data.set.finite import tactic.monotonicity /-! # Theory of filters on sets ## Main definitions * `filter` : filters on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `prod` : operations on filters; * `tendsto` : limit with respect to filters; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `ne_bot f` : an utility class stating that `f` is a non-trivial filter. Filters on a type `X` are sets of sets of `X` satisfying three conditions. They are mostly used to abstract two related kinds of ideas: * *limits*, including finite or infinite limits of sequences, finite or infinite limits of functions at a point or at infinity, etc... * *things happening eventually*, including things happening for large enough `n : ℕ`, or near enough a point `x`, or for close enough pairs of points, or things happening almost everywhere in the sense of measure theory. Dually, filters can also express the idea of *things happening often*: for arbitrarily large `n`, or at a point in any neighborhood of given a point etc... In this file, we define the type `filter X` of filters on `X`, and endow it with a complete lattice structure. This structure is lifted from the lattice structure on `set (set X)` using the Galois insertion which maps a filter to its elements in one direction, and an arbitrary set of sets to the smallest filter containing it in the other direction. We also prove `filter` is a monadic functor, with a push-forward operation `filter.map` and a pull-back operation `filter.comap` that form a Galois connections for the order on filters. Finally we describe a product operation `filter X → filter Y → filter (X × Y)`. The examples of filters appearing in the description of the two motivating ideas are: * `(at_top : filter ℕ)` : made of sets of `ℕ` containing `{n | n ≥ N}` for some `N` * `𝓝 x` : made of neighborhoods of `x` in a topological space (defined in topology.basic) * `𝓤 X` : made of entourages of a uniform space (those space are generalizations of metric spaces defined in topology.uniform_space.basic) * `μ.ae` : made of sets whose complement has zero measure with respect to `μ` (defined in `measure_theory.measure_space`) The general notion of limit of a map with respect to filters on the source and target types is `filter.tendsto`. It is defined in terms of the order and the push-forward operation. The predicate "happening eventually" is `filter.eventually`, and "happening often" is `filter.frequently`, whose definitions are immediate after `filter` is defined (but they come rather late in this file in order to immediately relate them to the lattice structure). For instance, anticipating on topology.basic, the statement: "if a sequence `u` converges to some `x` and `u n` belongs to a set `M` for `n` large enough then `x` is in the closure of `M`" is formalized as: `tendsto u at_top (𝓝 x) → (∀ᶠ n in at_top, u n ∈ M) → x ∈ closure M`, which is a special case of `mem_closure_of_tendsto` from topology.basic. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`; * `f =ᶠ[l] g` : `∀ᶠ x in l, f x = g x`; * `f ≤ᶠ[l] g` : `∀ᶠ x in l, f x ≤ g x`; * `f ×ᶠ g` : `filter.prod f g`, localized in `filter`; * `𝓟 s` : `principal s`, localized in `filter`. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] Important note: Bourbaki requires that a filter on `X` cannot contain all sets of `X`, which we do *not* require. This gives `filter X` better formal properties, in particular a bottom element `⊥` for its lattice structure, at the cost of including the assumption `[ne_bot f]` in a number of lemmas and definitions. -/ open set universes u v w x y open_locale classical /-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`, is upwards-closed, and is stable under intersection. We do not forbid this collection to be all sets of `α`. -/ structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} instance inhabited_mem : inhabited {s : set α // s ∈ f} := ⟨⟨univ, f.univ_sets⟩⟩ lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by rw [filter_eq_iff, ext_iff] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 lemma univ_mem_sets : univ ∈ f := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets lemma univ_mem_sets' (h : ∀ a, a ∈ s) : s ∈ f := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)), λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩ lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (∀i∈is, s i ∈ f) → (⋂i∈is, s i) ∈ f := finite.induction_on hf (assume hs, by simp only [univ_mem_sets, mem_empty_eq, Inter_neg, Inter_univ, not_false_iff]) (assume i is _ hf hi hs, have h₁ : s i ∈ f, from hs i (by simp), have h₂ : (⋂x∈is, s x) ∈ f, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true], by simp [inter_mem_sets h₁ h₂]) lemma sInter_mem_sets_of_finite {s : set (set α)} (hfin : finite s) (h_in : ∀ U ∈ s, U ∈ f) : ⋂₀ s ∈ f := by { rw sInter_eq_bInter, exact Inter_mem_sets hfin h_in } lemma Inter_mem_sets_of_fintype {β : Type v} {s : β → set α} [fintype β] (h : ∀i, s i ∈ f) : (⋂i, s i) ∈ f := by simpa using Inter_mem_sets finite_univ (λi hi, h i) lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e), eapplyc `filter.univ_mem_sets', match e' with | some e := interactive.exact e | none := skip end end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := assume x y hx hy, subset.trans hx hy, inter_sets := assume x y, subset_inter } localized "notation `𝓟` := filter.principal" in filter instance : inhabited (filter α) := ⟨𝓟 ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ 𝓟 t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ 𝓟 s := subset.refl _ end principal open_locale filter section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [univ_mem_sets, mem_set_of_eq]; exact univ_mem_sets, sets_of_superset := assume x y hx xy, mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy, inter_sets := assume x y hx hy, mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ } @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := assume x y, generate_sets.superset, inter_sets := assume s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (assume h u hu, h $ generate_sets.basic $ hu) (assume h u hu, hu.rec_on h univ_mem_sets (assume x y _ hxy hx, mem_sets_of_superset hx hxy) (assume x y _ _ hx hy, inter_mem_sets hx hy)) lemma mem_generate_iff (s : set $ set α) {U : set α} : U ∈ generate s ↔ ∃ t ⊆ s, finite t ∧ ⋂₀ t ⊆ U := begin split ; intro h, { induction h with V V_in V W V_in hVW hV V W V_in W_in hV hW, { use {V}, simp [V_in] }, { use ∅, simp [subset.refl, univ] }, { rcases hV with ⟨t, hts, htfin, hinter⟩, exact ⟨t, hts, htfin, subset.trans hinter hVW⟩ }, { rcases hV with ⟨t, hts, htfin, htinter⟩, rcases hW with ⟨z, hzs, hzfin, hzinter⟩, refine ⟨t ∪ z, union_subset hts hzs, htfin.union hzfin, _⟩, rw sInter_union, exact inter_subset_inter htinter hzinter } }, { rcases h with ⟨t, ts, tfin, h⟩, apply generate_sets.superset _ h, revert ts, apply finite.induction_on tfin, { intro h, rw sInter_empty, exact generate_sets.univ }, { intros V r hV rfin hinter h, cases insert_subset.mp h with V_in r_sub, rw [insert_eq V r, sInter_union], apply generate_sets.inter _ (hinter r_sub), rw sInter_singleton, exact generate_sets.basic V_in } }, end /-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly `s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/ protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s), sets_of_superset := assume x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := assume x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ assume u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /-- Galois insertion from sets of sets into filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := assume s f, sets_iff_generate, le_l_u := assume f u h, generate_sets.basic h, choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), a ∩ b ⊆ s }, univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩, sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩, ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd, calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩ @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃t₁∈f, ∃t₂∈g, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩ lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht) instance : has_top (filter α) := ⟨{ sets := {s | ∀x, x ∈ s}, univ_sets := assume x, mem_univ x, sets_of_superset := assume x y hx hxy a, hxy (hx a), inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀x, x ∈ s) := iff.rfl @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_sets_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.has_top).1 (top_unique $ assume s hs, by have := univ_mem_sets ; finish) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right)) (assume s ⟨a, ha, b, hb, hs⟩, show s ∈ complete_lattice.inf f g, from mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ 𝓟) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice /-- A filter is `ne_bot` if it is not equal to `⊥`, or equivalently the empty set does not belong to the filter. Bourbaki include this assumption in the definition of a filter but we prefer to have a `complete_lattice` structure on filter, so we use a typeclass argument in lemmas instead. -/ @[class] def ne_bot (f : filter α) := f ≠ ⊥ lemma ne_bot.ne {f : filter α} (hf : ne_bot f) : f ≠ ⊥ := hf @[simp] lemma not_ne_bot {α : Type*} {f : filter α} : ¬ f.ne_bot ↔ f = ⊥ := not_not lemma ne_bot.mono {f g : filter α} (hf : ne_bot f) (hg : f ≤ g) : ne_bot g := ne_bot_of_le_ne_bot hf hg lemma ne_bot_of_le {f g : filter α} [hf : ne_bot f] (hg : f ≤ g) : ne_bot g := hf.mono hg lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl lemma union_mem_sup {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∪ t ∈ f ⊔ g := ⟨mem_sets_of_superset hs (subset_union_left s t), mem_sets_of_superset ht (subset_union_right s t)⟩ @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀i, x ∈ f i) := by simp only [supr_sets_eq, iff_self, mem_Inter] lemma infi_eq_generate (s : ι → filter α) : infi s = generate (⋃ i, (s i).sets) := show generate _ = generate _, from congr_arg _ supr_range lemma mem_infi_iff {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : {i | i ∈ I} → set α, (∀ i, V i ∈ s i) ∧ (⋂ i, V i) ⊆ U := begin rw [infi_eq_generate, mem_generate_iff], split, { rintro ⟨t, tsub, tfin, tinter⟩, rcases eq_finite_Union_of_finite_subset_Union tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩, rw sInter_Union at tinter, let V := λ i, ⋂₀ σ i, have V_in : ∀ i, V i ∈ s i, { rintro ⟨i, i_in⟩, apply sInter_mem_sets_of_finite (σfin _), apply σsub }, exact ⟨I, Ifin, V, V_in, tinter⟩ }, { rintro ⟨I, Ifin, V, V_in, h⟩, refine ⟨range V, _, _, h⟩, { rintro _ ⟨i, rfl⟩, rw mem_Union, use [i, V_in i] }, { haveI : fintype {i : ι | i ∈ I} := finite.fintype Ifin, exact finite_range _ } }, end @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ 𝓟 s ↔ s ∈ f := show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : 𝓟 s ≤ 𝓟 t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal_sets] @[mono] lemma monotone_principal : monotone (𝓟 : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : 𝓟 s = 𝓟 t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (𝓟 s) = Sup s := rfl @[simp] lemma principal_univ : 𝓟 (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true] @[simp] lemma principal_empty : 𝓟 (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ /-! ### Lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma nonempty_of_mem_sets {f : filter α} [hf : ne_bot f] {s : set α} (hs : s ∈ f) : s.nonempty := s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_in_sets_eq_bot.mp hf)) id lemma ne_bot.nonempty_of_mem {f : filter α} (hf : ne_bot f) {s : set α} (hs : s ∈ f) : s.nonempty := @nonempty_of_mem_sets α f hf s hs lemma nonempty_of_ne_bot (f : filter α) [ne_bot f] : nonempty α := nonempty_of_exists $ nonempty_of_mem_sets (univ_mem_sets : univ ∈ f) lemma filter_eq_bot_of_not_nonempty (f : filter α) (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩) lemma forall_sets_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ ne_bot f := ⟨λ h hf, empty_not_nonempty (h ∅ $ hf.symm ▸ mem_bot_sets), @nonempty_of_mem_sets _ _⟩ lemma mem_sets_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ 𝓟 sᶜ = ⊥) : s ∈ f := have ∅ ∈ f ⊓ 𝓟 sᶜ, from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : sᶜ ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩ lemma inf_ne_bot_iff {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {U V}, U ∈ f → V ∈ g → set.nonempty (U ∩ V) := begin rw ← forall_sets_nonempty_iff_ne_bot, simp_rw mem_inf_sets, split ; intro h, { intros U V U_in V_in, exact h (U ∩ V) ⟨U, U_in, V, V_in, subset.refl _⟩ }, { rintros S ⟨U, U_in, V, V_in, hUV⟩, cases h U_in V_in with a ha, use [a, hUV ha] } end lemma inf_principal_ne_bot_iff {f : filter α} {s : set α} : ne_bot (f ⊓ 𝓟 s) ↔ ∀ U ∈ f, (U ∩ s).nonempty := begin rw inf_ne_bot_iff, apply forall_congr, intros U, split, { intros h U_in, exact h U_in (mem_principal_self s) }, { intros h V U_in V_in, rw mem_principal_sets at V_in, cases h U_in with x hx, exact ⟨x, hx.1, V_in hx.2⟩ }, end lemma inf_eq_bot_iff {f g : filter α} : f ⊓ g = ⊥ ↔ ∃ U V, (U ∈ f) ∧ (V ∈ g) ∧ U ∩ V = ∅ := begin rw ← not_iff_not, apply inf_ne_bot_iff.trans, simp only [not_exists, not_and, ← ne.def, ne_empty_iff_nonempty] end protected lemma disjoint_iff {f g : filter α} : disjoint f g ↔ ∃ U V, (U ∈ f) ∧ (V ∈ g) ∧ U ∩ V = ∅ := disjoint_iff.trans inf_eq_bot_iff lemma eq_Inf_of_mem_sets_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_sets_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_sets_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_sets_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_sets_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) [ne : nonempty ι] : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], assume x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_sets_iff_exists_mem (λ s, by simp only [mem_Union]), congr_arg filter.sets this.symm lemma mem_infi {f : ι → filter α} (h : directed (≥) f) [nonempty ι] (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [infi_sets_eq h, mem_Union] lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := by haveI := ne.to_subtype; calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by rw [infi_subtype]; refl ... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq h.directed_coe ... = (⨆ t ∈ s, (f t).sets) : by rw [supr_subtype]; refl lemma mem_binfi {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i∈s, f i) ↔ ∃ i ∈ s, t ∈ f i := by simp only [binfi_sets_eq h ne, mem_bUnion_iff] lemma infi_sets_eq_finite {ι : Type*} (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset ι, (⨅i∈t, f i).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h), end lemma infi_sets_eq_finite' (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) := by rw [← infi_sets_eq_finite, ← equiv.plift.surjective.infi_comp]; refl lemma mem_infi_finite {ι : Type*} {f : ι → filter α} (s) : s ∈ infi f ↔ s ∈ ⋃t:finset ι, (⨅i∈t, f i).sets := set.ext_iff.1 (infi_sets_eq_finite f) s lemma mem_infi_finite' {f : ι → filter α} (s) : s ∈ infi f ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets := set.ext_iff.1 (infi_sets_eq_finite' f) s @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, mem_sup_sets, iff_self, mem_set_of_eq] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, iff_self, mem_Inter, mem_set_of_eq] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin assume x y z s, simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp], intros hs t₁ ht₁ t₂ ht₂ hts, exact ⟨s ∪ t₁, x.sets_of_superset hs $ subset_union_left _ _, y.sets_of_superset ht₁ $ subset_union_right _ _, s ∪ t₂, x.sets_of_superset hs $ subset_union_left _ _, z.sets_of_superset ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.complete_lattice } /- the complementary version with ⨆i, f ⊓ g i does not hold! -/ lemma infi_sup_left {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ assume i, sup_le_sup_left (infi_le _ _) _), rintros t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite'] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_right_of_le le_top }, { rintros ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma infi_sup_right {f : filter α} {g : ι → filter α} : (⨅ x, g x ⊔ f) = infi g ⊔ f := by simp [sup_comm, ← infi_sup_left] lemma binfi_sup_right (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (f i ⊔ g)) = (⨅ i (h : p i), f i) ⊔ g := by rw [infi_subtype', infi_sup_right, infi_subtype'] lemma binfi_sup_left (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (g ⊔ f i)) = g ⊔ (⨅ i (h : p i), f i) := by rw [infi_subtype', infi_sup_left, infi_subtype'] lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅a∈s, p a) ≤ t), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top_sets, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { intros t₁ ht₁ t₂ p hp ht₂ ht, existsi function.update p a t₁, have : ∀a'∈s, function.update p a t₁ a' = p a', from assume a' ha', have a' ≠ a, from assume h, has $ h ▸ ha', function.update_noteq this _ _, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht }, assume p hpa hp ht, exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /-- If `f : ι → filter α` is directed, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := begin intro h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃i, ∅ ∈ f i, from (mem_infi hd ∅).1 he, exact hb i (empty_in_sets_eq_bot.1 hi) end /-- If `f : ι → filter α` is directed, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} [hn : nonempty α] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := if hι : nonempty ι then @infi_ne_bot_of_directed' _ _ _ hι hd hb else assume h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x) lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) : ne_bot (infi f) ↔ ∀i, ne_bot (f i) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed' hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} [nonempty α] (hd : directed (≥) f) : ne_bot (infi f) ↔ (∀i, ne_bot (f i)) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [mem_infi_finite'] at hs, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { assume s hs, rwa [mem_top_sets.1 hs] }, { rintros ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_sets] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, exact upw hs (ins hs₁ (ih hs₂)) } end /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : 𝓟 s ⊓ 𝓟 t = 𝓟 (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : 𝓟 s ⊔ 𝓟 t = 𝓟 (s ∪ t) := filter_eq $ set.ext $ by simp only [union_subset_iff, union_subset_iff, mem_sup_sets, forall_const, iff_self, mem_principal_sets] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, 𝓟 (s x)) = 𝓟 (⋃i, s i) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, mem_principal_sets, mem_Inter]; exact (@supr_le_iff (set α) _ _ _ _).symm @[simp] lemma principal_eq_bot_iff {s : set α} : 𝓟 s = ⊥ ↔ s = ∅ := empty_in_sets_eq_bot.symm.trans $ mem_principal_sets.trans subset_empty_iff lemma principal_ne_bot_iff {s : set α} : ne_bot (𝓟 s) ↔ s.nonempty := (not_congr principal_eq_bot_iff).trans ne_empty_iff_nonempty lemma is_compl_principal (s : set α) : is_compl (𝓟 s) (𝓟 sᶜ) := ⟨by simp only [inf_principal, inter_compl_self, principal_empty, le_refl], by simp only [sup_principal, union_compl_self, principal_univ, le_refl]⟩ lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : sᶜ ∈ f) : f ⊓ 𝓟 s = ⊥ := empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩ theorem mem_inf_principal {f : filter α} {s t : set α} : s ∈ f ⊓ 𝓟 t ↔ {x | x ∈ t → x ∈ s} ∈ f := begin simp only [← le_principal_iff, (is_compl_principal s).le_left_iff, disjoint, inf_assoc, inf_principal, imp_iff_not_or], rw [← disjoint, ← (is_compl_principal (t ∩ sᶜ)).le_right_iff, compl_inter, compl_compl], refl end lemma diff_mem_inf_principal_compl {f : filter α} {s : set α} (hs : s ∈ f) (t : set α) : s \ t ∈ f ⊓ 𝓟 tᶜ := begin rw mem_inf_principal, filter_upwards [hs], intros a has hat, exact ⟨has, hat⟩ end lemma mem_iff_inf_principal_compl {f : filter α} {V : set α} : V ∈ f ↔ f ⊓ 𝓟 Vᶜ = ⊥ := begin rw inf_eq_bot_iff, split, { intro h, use [V, Vᶜ], simp [h, subset.refl] }, { rintros ⟨U, W, U_in, W_in, UW⟩, rw [mem_principal_sets, compl_subset_comm] at W_in, apply mem_sets_of_superset U_in, intros x x_in, apply W_in, intro H, have : x ∈ U ∩ W := ⟨x_in, H⟩, rwa UW at this }, end lemma le_iff_forall_inf_principal_compl {f g : filter α} : f ≤ g ↔ ∀ V ∈ g, f ⊓ 𝓟 Vᶜ = ⊥ := begin change (∀ V ∈ g, V ∈ f) ↔ _, simp_rw [mem_iff_inf_principal_compl], end lemma principal_le_iff {s : set α} {f : filter α} : 𝓟 s ≤ f ↔ ∀ V ∈ f, s ⊆ V := begin change (∀ V, V ∈ f → V ∈ _) ↔ _, simp_rw mem_principal_sets, end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅i∈s, 𝓟 (f i)) = 𝓟 (⋂i∈s, f i) := begin ext t, simp [mem_infi_sets_finset], split, { rintros ⟨p, hp, ht⟩, calc (⋂ (i : ι) (H : i ∈ s), f i) ≤ (⋂ (i : ι) (H : i ∈ s), p i) : infi_le_infi (λi, infi_le_infi (λhi, mem_principal_sets.1 (hp i hi))) ... ≤ t : ht }, { assume h, exact ⟨f, λi hi, subset.refl _, h⟩ } end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅i, 𝓟 (f i)) = 𝓟 (⋂i, f i) := by simpa using infi_principal_finset finset.univ f end lattice @[mono] lemma join_mono {f₁ f₂ : filter (filter α)} (h : f₁ ≤ f₂) : join f₁ ≤ join f₂ := λ s hs, h hs /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r lemma eventually_iff {f : filter α} {P : α → Prop} : (∀ᶠ x in f, P x) ↔ {x | P x} ∈ f := iff.rfl protected lemma ext' {f₁ f₂ : filter α} (h : ∀ p : α → Prop, (∀ᶠ x in f₁, p x) ↔ (∀ᶠ x in f₂, p x)) : f₁ = f₂ := filter.ext h lemma eventually.filter_mono {f₁ f₂ : filter α} (h : f₁ ≤ f₂) {p : α → Prop} (hp : ∀ᶠ x in f₂, p x) : ∀ᶠ x in f₁, p x := h hp lemma eventually_of_mem {f : filter α} {P : α → Prop} {U : set α} (hU : U ∈ f) (h : ∀ x ∈ U, P x) : ∀ᶠ x in f, P x := mem_sets_of_superset hU h protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem_sets @[simp] lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem_sets lemma eventually_of_forall {p : α → Prop} {f : filter α} (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem_sets' hp @[simp] lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_in_sets_eq_bot @[simp] lemma eventually_const {f : filter α} [ne_bot f] {p : Prop} : (∀ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simp [h]) (λ h, by simpa [h]) lemma eventually_iff_exists_mem {p : α → Prop} {f : filter α} : (∀ᶠ x in f, p x) ↔ ∃ v ∈ f, ∀ y ∈ v, p y := exists_sets_subset_iff.symm lemma eventually.exists_mem {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) : ∃ v ∈ f, ∀ y ∈ v, p y := eventually_iff_exists_mem.1 hp lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_sets hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (eventually_of_forall hq) @[simp] lemma eventually_and {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := ⟨λ h, ⟨h.mono $ λ _, and.left, h.mono $ λ _, and.right⟩, λ h, h.1.and h.2⟩ lemma eventually.congr {f : filter α} {p q : α → Prop} (h' : ∀ᶠ x in f, p x) (h : ∀ᶠ x in f, p x ↔ q x) : ∀ᶠ x in f, q x := h'.mp (h.mono $ λ x hx, hx.mp) lemma eventually_congr {f : filter α} {p q : α → Prop} (h : ∀ᶠ x in f, p x ↔ q x) : (∀ᶠ x in f, p x) ↔ (∀ᶠ x in f, q x) := ⟨λ hp, hp.congr h, λ hq, hq.congr $ by simpa only [iff.comm] using h⟩ @[simp] lemma eventually_or_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p ∨ q x) ↔ (p ∨ ∀ᶠ x in f, q x) := classical.by_cases (λ h : p, by simp [h]) (λ h, by simp [h]) @[simp] lemma eventually_or_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x ∨ q) ↔ ((∀ᶠ x in f, p x) ∨ q) := by simp only [or_comm _ q, eventually_or_distrib_left] @[simp] lemma eventually_imp_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p → q x) ↔ (p → ∀ᶠ x in f, q x) := by simp only [imp_iff_not_or, eventually_or_distrib_left] @[simp] lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩ @[simp] lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) := iff.rfl lemma eventually_sup {p : α → Prop} {f g : filter α} : (∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) := iff.rfl @[simp] lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} : (∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) := iff.rfl @[simp] lemma eventually_supr {p : α → Prop} {fs : β → filter α} : (∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) := mem_supr_sets @[simp] lemma eventually_principal {a : set α} {p : α → Prop} : (∀ᶠ x in 𝓟 a, p x) ↔ (∀ x ∈ a, p x) := iff.rfl theorem eventually_inf_principal {f : filter α} {p : α → Prop} {s : set α} : (∀ᶠ x in f ⊓ 𝓟 s, p x) ↔ ∀ᶠ x in f, x ∈ s → p x := mem_inf_principal /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := begin assume h', have := h.and h', simp only [and_not_self, eventually_false_iff_eq_bot] at this, contradiction end lemma frequently_of_forall {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ x, p x) : ∃ᶠ x in f, p x := eventually.frequently (eventually_of_forall h) lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, assume x hpq hq hp, exact hpq ⟨hp, hq⟩ end lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} [ne_bot f] (hp : ∀ᶠ x in f, p x) : ∃ x, p x := hp.frequently.exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨assume hp q hq, (hp.and_eventually hq).exists, assume H hp, by simpa only [and_not_self, exists_false] using H hp⟩ lemma frequently_iff {f : filter α} {P : α → Prop} : (∃ᶠ x in f, P x) ↔ ∀ {U}, U ∈ f → ∃ x ∈ U, P x := begin rw frequently_iff_forall_eventually_exists_and, split ; intro h, { intros U U_in, simpa [exists_prop, and_comm] using h U_in }, { intros H H', simpa [and_comm] using h H' }, end @[simp] lemma not_eventually {p : α → Prop} {f : filter α} : (¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) := by simp [filter.frequently] @[simp] lemma not_frequently {p : α → Prop} {f : filter α} : (¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) := by simp only [filter.frequently, not_not] @[simp] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ ne_bot f := by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot, ne_bot] @[simp] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp @[simp] lemma frequently_const {f : filter α} [ne_bot f] {p : Prop} : (∃ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simpa [h]) (λ h, by simp [h]) @[simp] lemma frequently_or_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x ∨ q x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in f, q x) := by simp only [filter.frequently, ← not_and_distrib, not_or_distrib, eventually_and] lemma frequently_or_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∨ q x) ↔ (p ∨ ∃ᶠ x in f, q x) := by simp lemma frequently_or_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∨ q) ↔ (∃ᶠ x in f, p x) ∨ q := by simp @[simp] lemma frequently_imp_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x → q x) ↔ ((∀ᶠ x in f, p x) → ∃ᶠ x in f, q x) := by simp [imp_iff_not_or, not_eventually, frequently_or_distrib] lemma frequently_imp_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p → q x) ↔ (p → ∃ᶠ x in f, q x) := by simp lemma frequently_imp_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x → q) ↔ ((∀ᶠ x in f, p x) → q) := by simp @[simp] lemma eventually_imp_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x → q) ↔ ((∃ᶠ x in f, p x) → q) := by simp only [imp_iff_not_or, eventually_or_distrib_right, not_frequently] @[simp] lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp @[simp] lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) := by simp [filter.frequently] lemma inf_ne_bot_iff_frequently_left {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in f, p x) → ∃ᶠ x in g, p x := begin rw filter.inf_ne_bot_iff, split ; intro h, { intros U U_in H, rcases h U_in H with ⟨x, hx, hx'⟩, exact hx' hx}, { intros U V U_in V_in, classical, by_contra H, exact h U_in (mem_sets_of_superset V_in $ λ v v_in v_in', H ⟨v, v_in', v_in⟩) } end lemma inf_ne_bot_iff_frequently_right {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in g, p x) → ∃ᶠ x in f, p x := by { rw inf_comm, exact filter.inf_ne_bot_iff_frequently_left } @[simp] lemma frequently_principal {a : set α} {p : α → Prop} : (∃ᶠ x in 𝓟 a, p x) ↔ (∃ x ∈ a, p x) := by simp [filter.frequently, not_forall] lemma frequently_sup {p : α → Prop} {f g : filter α} : (∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) := by simp only [filter.frequently, eventually_sup, not_and_distrib] @[simp] lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} : (∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) := by simp [filter.frequently, -not_eventually, not_forall] @[simp] lemma frequently_supr {p : α → Prop} {fs : β → filter α} : (∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) := by simp [filter.frequently, -not_eventually, not_forall] /-! ### Relation “eventually equal” -/ /-- Two functions `f` and `g` are *eventually equal* along a filter `l` if the set of `x` such that `f x = g x` belongs to `l`. -/ def eventually_eq (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x = g x notation f ` =ᶠ[`:50 l:50 `] `:0 g:50 := eventually_eq l f g lemma eventually_eq.eventually {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∀ᶠ x in l, f x = g x := h lemma eventually_eq.rw {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) (p : α → β → Prop) (hf : ∀ᶠ x in l, p x (f x)) : ∀ᶠ x in l, p x (g x) := hf.congr $ h.mono $ λ x hx, hx ▸ iff.rfl lemma eventually_eq_set {s t : set α} {l : filter α} : s =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ s ↔ x ∈ t := eventually_congr $ eventually_of_forall $ λ x, ⟨eq.to_iff, iff.to_eq⟩ alias eventually_eq_set ↔ filter.eventually_eq.mem_iff filter.eventually.set_eq lemma eventually_eq.exists_mem {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∃ s ∈ l, eq_on f g s := h.exists_mem lemma eventually_eq_of_mem {l : filter α} {f g : α → β} {s : set α} (hs : s ∈ l) (h : eq_on f g s) : f =ᶠ[l] g := eventually_of_mem hs h lemma eventually_eq_iff_exists_mem {l : filter α} {f g : α → β} : (f =ᶠ[l] g) ↔ ∃ s ∈ l, eq_on f g s := eventually_iff_exists_mem lemma eventually_eq.filter_mono {l l' : filter α} {f g : α → β} (h₁ : f =ᶠ[l] g) (h₂ : l' ≤ l) : f =ᶠ[l'] g := h₂ h₁ @[refl] lemma eventually_eq.refl (l : filter α) (f : α → β) : f =ᶠ[l] f := eventually_of_forall $ λ x, rfl @[symm] lemma eventually_eq.symm {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) : g =ᶠ[l] f := H.mono $ λ _, eq.symm @[trans] lemma eventually_eq.trans {f g h : α → β} {l : filter α} (H₁ : f =ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f =ᶠ[l] h := H₂.rw (λ x y, f x = y) H₁ lemma eventually_eq.prod_mk {l} {f f' : α → β} (hf : f =ᶠ[l] f') {g g' : α → γ} (hg : g =ᶠ[l] g') : (λ x, (f x, g x)) =ᶠ[l] (λ x, (f' x, g' x)) := hf.mp $ hg.mono $ by { intros, simp only * } lemma eventually_eq.fun_comp {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) (h : β → γ) : (h ∘ f) =ᶠ[l] (h ∘ g) := H.mono $ λ x hx, congr_arg h hx lemma eventually_eq.comp₂ {δ} {f f' : α → β} {g g' : α → γ} {l} (Hf : f =ᶠ[l] f') (h : β → γ → δ) (Hg : g =ᶠ[l] g') : (λ x, h (f x) (g x)) =ᶠ[l] (λ x, h (f' x) (g' x)) := (Hf.prod_mk Hg).fun_comp (function.uncurry h) @[to_additive] lemma eventually_eq.mul [has_mul β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x * f' x) =ᶠ[l] (λ x, g x * g' x)) := h.comp₂ (*) h' @[to_additive] lemma eventually_eq.inv [has_inv β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : ((λ x, (f x)⁻¹) =ᶠ[l] (λ x, (g x)⁻¹)) := h.fun_comp has_inv.inv lemma eventually_eq.div [group_with_zero β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := h.mul h'.inv lemma eventually_eq.sub [add_group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x - f' x) =ᶠ[l] (λ x, g x - g' x)) := h.add h'.neg lemma eventually_eq.inter {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∩ s' : set α) =ᶠ[l] (t ∩ t' : set α) := h.comp₂ (∧) h' lemma eventually_eq.union {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∪ s' : set α) =ᶠ[l] (t ∪ t' : set α) := h.comp₂ (∨) h' lemma eventually_eq.compl {s t : set α} {l : filter α} (h : s =ᶠ[l] t) : (sᶜ : set α) =ᶠ[l] (tᶜ : set α) := h.fun_comp not lemma eventually_eq.diff {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s \ s' : set α) =ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma eventually_eq_empty {s : set α} {l : filter α} : s =ᶠ[l] (∅ : set α) ↔ ∀ᶠ x in l, x ∉ s := eventually_eq_set.trans $ by simp @[simp] lemma eventually_eq_principal {s : set α} {f g : α → β} : f =ᶠ[𝓟 s] g ↔ eq_on f g s := iff.rfl lemma eventually_eq_inf_principal_iff {F : filter α} {s : set α} {f g : α → β} : (f =ᶠ[F ⊓ 𝓟 s] g) ↔ ∀ᶠ x in F, x ∈ s → f x = g x := eventually_inf_principal section has_le variables [has_le β] {l : filter α} /-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/ def eventually_le (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x ≤ g x notation f ` ≤ᶠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g lemma eventually_le.congr {f f' g g' : α → β} (H : f ≤ᶠ[l] g) (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f' ≤ᶠ[l] g' := H.mp $ hg.mp $ hf.mono $ λ x hf hg H, by rwa [hf, hg] at H lemma eventually_le_congr {f f' g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f ≤ᶠ[l] g ↔ f' ≤ᶠ[l] g' := ⟨λ H, H.congr hf hg, λ H, H.congr hf.symm hg.symm⟩ end has_le section preorder variables [preorder β] {l : filter α} {f g h : α → β} lemma eventually_eq.le (h : f =ᶠ[l] g) : f ≤ᶠ[l] g := h.mono $ λ x, le_of_eq @[refl] lemma eventually_le.refl (l : filter α) (f : α → β) : f ≤ᶠ[l] f := (eventually_eq.refl l f).le @[trans] lemma eventually_le.trans (H₁ : f ≤ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₂.mp $ H₁.mono $ λ x, le_trans @[trans] lemma eventually_eq.trans_le (H₁ : f =ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₁.le.trans H₂ @[trans] lemma eventually_le.trans_eq (H₁ : f ≤ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f ≤ᶠ[l] h := H₁.trans H₂.le end preorder lemma eventually_le.antisymm [partial_order β] {l : filter α} {f g : α → β} (h₁ : f ≤ᶠ[l] g) (h₂ : g ≤ᶠ[l] f) : f =ᶠ[l] g := h₂.mp $ h₁.mono $ λ x, le_antisymm lemma eventually_le_antisymm_iff [partial_order β] {l : filter α} {f g : α → β} : f =ᶠ[l] g ↔ f ≤ᶠ[l] g ∧ g ≤ᶠ[l] f := by simp only [eventually_eq, eventually_le, le_antisymm_iff, eventually_and] lemma join_le {f : filter (filter α)} {l : filter α} (h : ∀ᶠ m in f, m ≤ l) : join f ≤ l := λ s hs, h.mono $ λ m hm, hm hs /-! ### Push-forwards, pull-backs, and the monad structure -/ section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem_sets, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st, inter_sets := assume s t hs ht, inter_mem_sets hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (𝓟 s) = 𝓟 (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma eventually_map {P : β → Prop} : (∀ᶠ b in map m f, P b) ↔ ∀ᶠ a in f, P (m a) := iff.rfl @[simp] lemma frequently_map {P : β → Prop} : (∃ᶠ b in map m f, P b) ↔ ∃ᶠ a in f, P (m a) := iff.rfl @[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma range_mem_map : range m ∈ map m f := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, m '' s ⊆ t) := iff.intro (assume ht, ⟨set.preimage m t, ht, image_preimage_subset _ _⟩) (assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht) @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f /-- If functions `m₁` and `m₂` are eventually equal at a filter `f`, then they map this filter to the same filter. -/ lemma map_congr {m₁ m₂ : α → β} {f : filter α} (h : m₁ =ᶠ[f] m₂) : map m₁ f = map m₂ f := filter.ext' $ λ p, by { simp only [eventually_map], exact eventually_congr (h.mono $ λ x hx, hx ▸ iff.rfl) } end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } @[simp] lemma eventually_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∀ᶠ a in comap φ f, P a) ↔ ∀ᶠ b in f, ∀ a, φ a = b → P a := begin split ; intro h, { rcases h with ⟨t, t_in, ht⟩, apply mem_sets_of_superset t_in, rintros y y_in _ rfl, apply ht y_in }, { exact ⟨_, h, λ _ x_in, x_in _ rfl⟩ } end @[simp] lemma frequently_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∃ᶠ a in comap φ f, P a) ↔ ∃ᶠ b in f, ∃ a, φ a = b ∧ P a := begin classical, erw [← not_iff_not, not_not, not_not, filter.eventually_comap], simp only [not_exists, not_and], end end comap /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃u∈ f, ∃t∈ g, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩, assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁, assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `𝓟 {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl @[simp] lemma eventually_pure {a : α} {p : α → Prop} : (∀ᶠ x in pure a, p x) ↔ p a := iff.rfl @[simp] lemma principal_singleton (a : α) : 𝓟 {a} = pure a := filter.ext $ λ s, by simp only [mem_pure_sets, mem_principal_sets, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen /-- The monad structure on filters. -/ protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β, pure_bind, bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map, mem_join_sets, mem_set_of_eq, function.comp, mem_pure_sets] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /- map and comap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap_sets : s ∈ comap m g ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.refl _⟩ lemma comap_id : comap id f = f := le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst) lemma comap_const_of_not_mem {x : α} {f : filter α} {V : set α} (hV : V ∈ f) (hx : x ∉ V) : comap (λ y : α, x) f = ⊥ := begin ext W, suffices : ∃ t ∈ f, (λ (y : α), x) ⁻¹' t ⊆ W, by simpa, use [V, hV], simp [preimage_const_of_not_mem hx], end lemma comap_const_of_mem {x : α} {f : filter α} (h : ∀ V ∈ f, x ∈ V) : comap (λ y : α, x) f = ⊤ := begin ext W, suffices : (∃ (t : set α), t ∈ f.sets ∧ (λ (y : α), x) ⁻¹' t ⊆ W) ↔ W = univ, by simpa, split, { rintros ⟨V, V_in, hW⟩, simpa [preimage_const_of_mem (h V V_in), univ_subset_iff] using hW }, { rintro rfl, use univ, simp [univ_mem_sets] }, end lemma comap_comap {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩) @[simp] theorem comap_principal {t : set β} : comap m (𝓟 t) = 𝓟 (m ⁻¹' t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b, assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ @[simp] theorem comap_pure {b : β} : comap m (pure b) = 𝓟 (m ⁻¹' {b}) := by rw [← principal_singleton, comap_principal] lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := assume f g, map_le_iff_le_comap @[mono] lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l @[mono] lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by rw [comap_top]; exact le_top lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ assume s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆i, comap m (f i)) := le_antisymm (assume s hs, have ∀i, ∃t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], assume i, exact (ht i).2 end⟩) (supr_le $ assume i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) ((@comap_mono _ _ m).le_map_sup _ _) lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := le_antisymm map_comap_le (assume t' ⟨t, ht, sub⟩, by filter_upwards [ht, hf]; rintros x hxt ⟨y, rfl⟩; exact sub hxt) lemma image_mem_sets {f : filter α} {c : β → α} (h : range c ∈ f) {W : set β} (W_in : W ∈ comap c f) : c '' W ∈ f := begin rw ← map_comap h, exact image_mem_map W_in end lemma image_coe_mem_sets {f : filter α} {U : set α} (h : U ∈ f) {W : set U} (W_in : W ∈ comap (coe : U → α) f) : coe '' W ∈ f := image_mem_sets (by simp [h]) W_in lemma comap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : comap m (map m f) = f := have ∀s, preimage m (image m s) = s, from assume s, preimage_image_eq s h, le_antisymm (assume s hs, ⟨ image m s, f.sets_of_superset hs $ by simp only [this, subset.refl], by simp only [this, subset.refl]⟩) le_comap_map lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)] assume a has ⟨b, ⟨hbs, hb⟩, h⟩, have b = a, from hm _ hbs _ has h, this ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this theorem le_map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : l ≤ map f (comap f l) := assume s ⟨t, tl, ht⟩, have t ∩ u ⊆ s, from assume x ⟨xt, xu⟩, exists.elim (hf x xu) $ λ a faeq, by { rw ←faeq, apply ht, change f a ∈ t, rw faeq, exact xt }, mem_sets_of_superset (inter_mem_sets tl ul) this theorem map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective' ul hf) theorem le_map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : l ≤ map f (comap f l) := le_map_comap_of_surjective' univ_mem_sets (λ y _, hf y) theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective hf l) lemma subtype_coe_map_comap (s : set α) (f : filter α) : map (coe : s → α) (comap (coe : s → α) f) = f ⊓ 𝓟 s := begin apply le_antisymm, { rw [map_le_iff_le_comap, comap_inf, comap_principal], have : (coe : s → α) ⁻¹' s = univ, by { ext x, simp }, rw [this, principal_univ], simp [le_refl _] }, { intros V V_in, rcases V_in with ⟨W, W_in, H⟩, rw mem_inf_sets, use [W, W_in, s, mem_principal_self s], erw [← image_subset_iff, subtype.image_preimage_coe] at H, exact H } end lemma subtype_coe_map_comap_prod (s : set α) (f : filter (α × α)) : map (coe : s × s → α × α) (comap (coe : s × s → α × α) f) = f ⊓ 𝓟 (s.prod s) := let φ (x : s × s) : s.prod s := ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩ in begin rw show (coe : s × s → α × α) = coe ∘ φ, by ext x; cases x; refl, rw [← filter.map_map, ← filter.comap_comap], rw map_comap_of_surjective, exact subtype_coe_map_comap _ _, exact λ ⟨⟨a, b⟩, ⟨ha, hb⟩⟩, ⟨⟨⟨a, ha⟩, ⟨b, hb⟩⟩, rfl⟩ end lemma comap_ne_bot_iff {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin rw ← forall_sets_nonempty_iff_ne_bot, exact ⟨λ h t t_in, h (m ⁻¹' t) ⟨t, t_in, subset.refl _⟩, λ h s ⟨u, u_in, hu⟩, let ⟨x, hx⟩ := h u u_in in ⟨x, hu hx⟩⟩, end lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀t∈ f, ∃a, m a ∈ t) : ne_bot (comap m f) := comap_ne_bot_iff.mpr hm lemma ne_bot.comap_of_range_mem {f : filter β} {m : α → β} (hf : ne_bot f) (hm : range m ∈ f) : ne_bot (comap m f) := comap_ne_bot $ assume t ht, let ⟨_, ha, a, rfl⟩ := hf.nonempty_of_mem (inter_mem_sets ht hm) in ⟨a, ha⟩ lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f ⊓ 𝓟 s) := begin refine compl_compl s ▸ mt mem_sets_of_eq_bot _, rintros ⟨t, ht, hts⟩, rcases hf.nonempty_of_mem (inter_mem_sets hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma ne_bot.comap_of_surj {f : filter β} {m : α → β} (hf : ne_bot f) (hm : function.surjective m) : ne_bot (comap m f) := hf.comap_of_range_mem $ univ_mem_sets' hm lemma ne_bot.comap_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f) := hf.comap_of_range_mem $ mem_sets_of_superset hs (image_subset_range _ _) @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot_iff (f : α → β) {F : filter α} : ne_bot (map f F) ↔ ne_bot F := not_congr map_eq_bot_iff lemma ne_bot.map (hf : ne_bot f) (m : α → β) : ne_bot (map m f) := (map_ne_bot_iff m).2 hf instance map_ne_bot [hf : ne_bot f] : ne_bot (f.map m) := hf.map m lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀(comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter, iff_self, mem_Inter, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) [nonempty ι] : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ infi f), have ∃i, preimage m s ∈ f i, by simp only [infi_sets_eq hf, mem_Union] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ 𝓟 s, from infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption, by simp only [filter.le_principal_iff] at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := begin haveI := nonempty_subtype.2 ne, simp only [infi_subtype'], exact map_infi_eq h.directed_coe end lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm map_inf_le (assume s hs, _), simp only [map, mem_inf_sets, exists_prop, mem_map, mem_preimage, mem_inf_sets] at hs ⊢, rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩, refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩, { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { rw [image_inter_on], { refine image_subset_iff.2 _, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _ hxy, h hxy) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀s∈ f, m '' s ∈ g) : g ≤ f.map m := assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _ protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) : map f (F ⊓ comap f G) = map f F ⊓ G := begin apply le_antisymm, { calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le ... ≤ map f F ⊓ G : inf_le_inf_left (map f F) map_comap_le }, { rintros U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩, rw ← image_subset_iff at h, use [f '' V, image_mem_map V_in, Z, Z_in], refine subset.trans _ h, have : f '' (V ∩ f ⁻¹' Z) ⊆ f '' (V ∩ W), from image_subset _ (inter_subset_inter_right _ ‹_›), rwa image_inter_preimage at this } end protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) : map f (comap f G ⊓ F) = G ⊓ map f F := by simp only [filter.push_pull, inf_comm] section applicative lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_injective : function.injective (pure : α → filter α) := assume a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl instance pure_ne_bot {α : Type u} {a : α} : ne_bot (pure a) := mt empty_in_sets_eq_bot.2 $ not_mem_empty a @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure_sets, λ h s hs, mem_sets_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀x∈u, ∀y∈t, m x y ∈ s) := iff.intro (assume ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, assume a, hts _⟩) (assume ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, assume f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀t ∈ f, ∀u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $ assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha @[mono] lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq_sets _ hs, exact singleton_mem_pure_sets }, { refine sets_of_superset (map g f) (image_mem_map ht) _, rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq_sets hs singleton_mem_pure_sets }, { refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)), rw ← set.seq_seq, exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) }, { rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht), rw set.seq_seq, exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw ← set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu }, { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := assume α f, map_id, comp_map := assume α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := assume α β, pure_seq_eq_map, map_pure := assume α β, map_pure, seq_pure := assume α β, seq_pure, seq_assoc := assume α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨assume α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /- bind equations -/ section bind @[simp] lemma eventually_bind {f : filter α} {m : α → filter β} {p : β → Prop} : (∀ᶠ y in bind f m, p y) ↔ ∀ᶠ x in f, ∀ᶠ y in m x, p y := iff.rfl @[simp] lemma eventually_eq_bind {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ =ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ =ᶠ[m x] g₂ := iff.rfl @[simp] lemma eventually_le_bind [has_le γ] {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ ≤ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ ≤ᶠ[m x] g₂ := iff.rfl lemma mem_bind_sets' {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ {a | s ∈ m a} ∈ f := iff.rfl @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : iff.rfl ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.rfl lemma bind_le {f : filter α} {g : α → filter β} {l : filter β} (h : ∀ᶠ x in f, g x ≤ l) : f.bind g ≤ l := join_le $ eventually_map.2 h @[mono] lemma bind_mono {f₁ f₂ : filter α} {g₁ g₂ : α → filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ᶠ[f₁] g₂) : bind f₁ g₁ ≤ bind f₂ g₂ := begin refine le_trans (λ s hs, _) (join_mono $ map_mono hf), simp only [mem_join_sets, mem_bind_sets', mem_map] at hs ⊢, filter_upwards [hg, hs], exact λ x hx hs, hx hs end lemma bind_inf_principal {f : filter α} {g : α → filter β} {s : set β} : f.bind (λ x, g x ⊓ 𝓟 s) = (f.bind g) ⊓ 𝓟 s := filter.ext $ λ s, by simp only [mem_bind_sets, mem_inf_principal] lemma sup_bind {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma principal_bind {s : set α} {f : α → filter β} : (bind (𝓟 s) f) = (⨆x ∈ s, f x) := show join (map f (𝓟 s)) = (⨆x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind section list_traverse /- This is a separate section in order to open `list`, but mostly because of universe equality requirements in `traverse` -/ open list lemma sequence_mono : ∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_refl _ | (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) variables {α' β' γ' : Type u} {f : β' → filter α'} {s : γ' → set α'} lemma mem_traverse_sets : ∀(fs : list β') (us : list γ'), forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _ | (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs) lemma mem_traverse_sets_iff (fs : list β') (t : set (list α')) : t ∈ traverse f fs ↔ (∃us:list (set α'), forall₂ (λb (s : set α'), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure_sets, imp_self, forall₂_nil_left_iff, exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { assume ht, rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } }, { rintros ⟨us, hus, hs⟩, exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs } end end list_traverse /-! ### Limits -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ ⦃p : β → Prop⦄, (∀ᶠ y in l₂, p y) → ∀ᶠ x in l₁, p (f x) := iff.rfl lemma tendsto.eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∀ᶠ y in l₂, p y) : ∀ᶠ x in l₁, p (f x) := hf h lemma tendsto.frequently {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∃ᶠ x in l₁, p (f x)) : ∃ᶠ y in l₂, p y := mt hf.eventually h @[simp] lemma tendsto_bot {f : α → β} {l : filter β} : tendsto f ⊥ l := by simp [tendsto] lemma tendsto_of_not_nonempty {f : α → β} {la : filter α} {lb : filter β} (h : ¬nonempty α) : tendsto f la lb := by simp only [filter_eq_bot_of_not_nonempty la h, tendsto_bot] lemma eventually_eq_of_left_inv_of_right_inv {f : α → β} {g₁ g₂ : β → α} {fa : filter α} {fb : filter β} (hleft : ∀ᶠ x in fa, g₁ (f x) = x) (hright : ∀ᶠ y in fb, f (g₂ y) = y) (htendsto : tendsto g₂ fb fa) : g₁ =ᶠ[fb] g₂ := (htendsto.eventually hleft).mp $ hright.mono $ λ y hr hl, (congr_arg g₁ hr.symm).trans hl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap alias tendsto_iff_comap ↔ filter.tendsto.le_comap _ lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_congr hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem_sets' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto.mono_left {f : α → β} {x y : filter α} {z : filter β} (hx : tendsto f x z) (h : y ≤ x) : tendsto f y z := le_trans (map_mono h) hx lemma tendsto.mono_right {f : α → β} {x : filter α} {y z : filter β} (hy : tendsto f x y) (hz : y ≤ z) : tendsto f x z := le_trans hy hz lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) [hx : ne_bot x] : ne_bot y := (hx.map _).mono h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by rw [tendsto, map_map]; refl lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, tendsto_comap.comp h, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by rw [tendsto, ← map_compose]; simp only [(∘), map_comap h, tendsto] lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ), rw [comap_comap, eq, comap_id], exact le_refl _ end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_refl _ end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ @[simp] lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp only [tendsto, iff_self, le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) (hi : tendsto f (x i) y) : tendsto f (⨅i, x i) y := hi.mono_left $ infi_le _ _ lemma tendsto_sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f (x₁ ⊔ x₂) y ↔ tendsto f x₁ y ∧ tendsto f x₂ y := by simp only [tendsto, map_sup, sup_le_iff] lemma tendsto.sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f x₁ y → tendsto f x₂ y → tendsto f (x₁ ⊔ x₂) y := λ h₁ h₂, tendsto_sup.mpr ⟨ h₁, h₂ ⟩ @[simp] lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} : tendsto f l (𝓟 s) ↔ ∀ᶠ a in l, f a ∈ s := by simp only [tendsto, le_principal_iff, mem_map, filter.eventually] @[simp] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (𝓟 s) (𝓟 t) ↔ ∀a∈s, f a ∈ t := by simp only [tendsto_principal, eventually_principal] @[simp] lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ ∀ᶠ x in a, f x = b := by simp only [tendsto, le_pure_iff, mem_map, mem_singleton_iff, filter.eventually] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λx, b) a (pure b) := tendsto_pure.2 $ univ_mem_sets' $ λ _, rfl lemma pure_le_iff {a : α} {l : filter α} : pure a ≤ l ↔ ∀ s ∈ l, a ∈ s := iff.rfl lemma tendsto_pure_left {f : α → β} {a : α} {l : filter β} : tendsto f (pure a) l ↔ ∀ s ∈ l, f a ∈ s := iff.rfl /-- If two filters are disjoint, then a function cannot tend to both of them along a non-trivial filter. -/ lemma tendsto.not_tendsto {f : α → β} {a : filter α} {b₁ b₂ : filter β} (hf : tendsto f a b₁) [ne_bot a] (hb : disjoint b₁ b₂) : ¬ tendsto f a b₂ := λ hf', (tendsto_inf.2 ⟨hf, hf'⟩).ne_bot hb.eq_bot lemma tendsto_if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [decidable_pred p] (h₀ : tendsto f (l₁ ⊓ 𝓟 p) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin revert h₀ h₁, simp only [tendsto_def, mem_inf_principal], intros h₀ h₁ s hs, apply mem_sets_of_superset (inter_mem_sets (h₀ s hs) (h₁ s hs)), rintros x ⟨hp₀, hp₁⟩, simp only [mem_preimage], by_cases h : p x, { rw if_pos h, exact hp₀ h }, rw if_neg h, exact hp₁ h end /-! ### Products of filters -/ section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd localized "infix ` ×ᶠ `:60 := filter.prod" in filter lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ f ×ᶠ g := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f ×ᶠ g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩, ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩, exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩, ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩ end lemma comap_prod (f : α → β × γ) (b : filter β) (c : filter γ) : comap f (b ×ᶠ c) = (comap (prod.fst ∘ f) b) ⊓ (comap (prod.snd ∘ f) c) := by erw [comap_inf, filter.comap_comap, filter.comap_comap] lemma eventually_prod_iff {p : α × β → Prop} {f : filter α} {g : filter β} : (∀ᶠ x in f ×ᶠ g, p x) ↔ ∃ (pa : α → Prop) (ha : ∀ᶠ x in f, pa x) (pb : β → Prop) (hb : ∀ᶠ y in g, pb y), ∀ {x}, pa x → ∀ {y}, pb y → p (x, y) := by simpa only [set.prod_subset_iff] using @mem_prod_iff α β p f g lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (f ×ᶠ g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (f ×ᶠ g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (g ×ᶠ h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma eventually.prod_inl {la : filter α} {p : α → Prop} (h : ∀ᶠ x in la, p x) (lb : filter β) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).1 := tendsto_fst.eventually h lemma eventually.prod_inr {lb : filter β} {p : β → Prop} (h : ∀ᶠ x in lb, p x) (la : filter α) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).2 := tendsto_snd.eventually h lemma eventually.prod_mk {la : filter α} {pa : α → Prop} (ha : ∀ᶠ x in la, pa x) {lb : filter β} {pb : β → Prop} (hb : ∀ᶠ y in lb, pb y) : ∀ᶠ p in la ×ᶠ lb, pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl lb).and (hb.prod_inr la) lemma eventually.curry {la : filter α} {lb : filter β} {p : α × β → Prop} (h : ∀ᶠ x in la ×ᶠ lb, p x) : ∀ᶠ x in la, ∀ᶠ y in lb, p (x, y) := begin rcases eventually_prod_iff.1 h with ⟨pa, ha, pb, hb, h⟩, exact ha.mono (λ a ha, hb.mono $ λ b hb, h ha hb) end lemma prod_infi_left [nonempty ι] {f : ι → filter α} {g : filter β}: (⨅i, f i) ×ᶠ g = (⨅i, (f i) ×ᶠ g) := by rw [filter.prod, comap_infi, infi_inf]; simp only [filter.prod, eq_self_iff_true] lemma prod_infi_right [nonempty ι] {f : filter α} {g : ι → filter β} : f ×ᶠ (⨅i, g i) = (⨅i, f ×ᶠ (g i)) := by rw [filter.prod, comap_infi, inf_infi]; simp only [filter.prod, eq_self_iff_true] @[mono] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ ×ᶠ g₁ ≤ f₂ ×ᶠ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : (comap m₁ f₁) ×ᶠ (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := by simp only [filter.prod, comap_comap, eq_self_iff_true, comap_inf] lemma prod_comm' : f ×ᶠ g = comap (prod.swap) (g ×ᶠ f) := by simp only [filter.prod, comap_comap, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : f ×ᶠ g = map (λp:β×α, (p.2, p.1)) (g ×ᶠ f) := by rw [prod_comm', ← map_swap_eq_comap_swap]; refl lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : (map m₁ f₁) ×ᶠ (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := le_antisymm (assume s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp (le_refl _) tendsto_fst).prod_mk (tendsto.comp (le_refl _) tendsto_snd)) lemma tendsto.prod_map {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a ×ᶠ b) (c ×ᶠ d) := begin erw [tendsto, ← prod_map_map_eq], exact filter.prod_mono hf hg, end lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f ×ᶠ g) = (f.map (λa b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], assume s, split, exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f ×ᶠ g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : (f₁ ×ᶠ g₁) ⊓ (f₂ ×ᶠ g₂) = (f₁ ⊓ f₂) ×ᶠ (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, inf_left_comm] @[simp] lemma prod_bot {f : filter α} : f ×ᶠ (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : (⊥ : filter α) ×ᶠ g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : (𝓟 s) ×ᶠ (𝓟 t) = 𝓟 (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma prod_pure_pure {a : α} {b : β} : (pure a) ×ᶠ (pure b) = pure (a, b) := by simp only [← principal_singleton, prod_principal_principal, singleton_prod_singleton] lemma prod_eq_bot {f : filter α} {g : filter β} : f ×ᶠ g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { assume h, rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) }, { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } }, { rintros (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : ne_bot (f ×ᶠ g) ↔ (ne_bot f ∧ ne_bot g) := (not_congr prod_eq_bot).trans not_or_distrib lemma ne_bot.prod {f : filter α} {g : filter β} (hf : ne_bot f) (hg : ne_bot g) : ne_bot (f ×ᶠ g) := prod_ne_bot.2 ⟨hf, hg⟩ instance prod_ne_bot' {f : filter α} {g : filter β} [hf : ne_bot f] [hg : ne_bot g] : ne_bot (f ×ᶠ g) := hf.prod hg lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (x ×ᶠ y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod end filter open_locale filter lemma set.eq_on.eventually_eq {α β} {s : set α} {f g : α → β} (h : eq_on f g s) : f =ᶠ[𝓟 s] g := h
1d88ea4d38b212529aa019b25f3c35f7d7929b1a
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.39.lean
1cc753e6265a0cf5ad812b36925fabd58a4b530a
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
184
lean
/- page 90 -/ import standard inductive tree (A : Type) : Type := | node : A → forest A → tree A with forest : Type := | nil : forest A | cons : tree A → forest A → forest A
a70ce9fb7b39fa99f1d742e58763e5fb0dd718f0
82e44445c70db0f03e30d7be725775f122d72f3e
/src/group_theory/specific_groups/dihedral.lean
5652d4a7f161550e766a63ec5b653c289f0fc995
[ "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
5,553
lean
/- Copyright (c) 2020 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import data.fintype.card import data.zmod.basic import group_theory.order_of_element /-! # Dihedral Groups We define the dihedral groups `dihedral_group n`, with elements `r i` and `sr i` for `i : zmod n`. For `n ≠ 0`, `dihedral_group n` represents the symmetry group of the regular `n`-gon. `r i` represents the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon. `dihedral_group 0` corresponds to the infinite dihedral group. -/ /-- For `n ≠ 0`, `dihedral_group n` represents the symmetry group of the regular `n`-gon. `r i` represents the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon. `dihedral_group 0` corresponds to the infinite dihedral group. -/ @[derive decidable_eq] inductive dihedral_group (n : ℕ) : Type | r : zmod n → dihedral_group | sr : zmod n → dihedral_group namespace dihedral_group variables {n : ℕ} /-- Multiplication of the dihedral group. -/ private def mul : dihedral_group n → dihedral_group n → dihedral_group n | (r i) (r j) := r (i + j) | (r i) (sr j) := sr (j - i) | (sr i) (r j) := sr (i + j) | (sr i) (sr j) := r (j - i) /-- The identity `1` is the rotation by `0`. -/ private def one : dihedral_group n := r 0 instance : inhabited (dihedral_group n) := ⟨one⟩ /-- The inverse of a an element of the dihedral group. -/ private def inv : dihedral_group n → dihedral_group n | (r i) := r (-i) | (sr i) := sr i /-- The group structure on `dihedral_group n`. -/ instance : group (dihedral_group n) := { mul := mul, mul_assoc := begin rintros (a | a) (b | b) (c | c); simp only [mul]; ring, end, one := one, one_mul := begin rintros (a | a), exact congr_arg r (zero_add a), exact congr_arg sr (sub_zero a), end, mul_one := begin rintros (a | a), exact congr_arg r (add_zero a), exact congr_arg sr (add_zero a), end, inv := inv, mul_left_inv := begin rintros (a | a), exact congr_arg r (neg_add_self a), exact congr_arg r (sub_self a), end } @[simp] lemma r_mul_r (i j : zmod n) : r i * r j = r (i + j) := rfl @[simp] lemma r_mul_sr (i j : zmod n) : r i * sr j = sr (j - i) := rfl @[simp] lemma sr_mul_r (i j : zmod n) : sr i * r j = sr (i + j) := rfl @[simp] lemma sr_mul_sr (i j : zmod n) : sr i * sr j = r (j - i) := rfl lemma one_def : (1 : dihedral_group n) = r 0 := rfl private def fintype_helper : (zmod n ⊕ zmod n) ≃ dihedral_group n := { inv_fun := λ i, match i with | (r j) := sum.inl j | (sr j) := sum.inr j end, to_fun := λ i, match i with | (sum.inl j) := r j | (sum.inr j) := sr j end, left_inv := by rintro (x | x); refl, right_inv := by rintro (x | x); refl } /-- If `0 < n`, then `dihedral_group n` is a finite group. -/ instance [fact (0 < n)] : fintype (dihedral_group n) := fintype.of_equiv _ fintype_helper instance : nontrivial (dihedral_group n) := ⟨⟨r 0, sr 0, dec_trivial⟩⟩ /-- If `0 < n`, then `dihedral_group n` has `2n` elements. -/ lemma card [fact (0 < n)] : fintype.card (dihedral_group n) = 2 * n := by rw [← fintype.card_eq.mpr ⟨fintype_helper⟩, fintype.card_sum, zmod.card, two_mul] @[simp] lemma r_one_pow (k : ℕ) : (r 1 : dihedral_group n) ^ k = r k := begin induction k with k IH, { refl }, { rw [pow_succ, IH, r_mul_r], congr' 1, norm_cast, rw nat.one_add } end @[simp] lemma r_one_pow_n : (r (1 : zmod n))^n = 1 := begin cases n, { rw pow_zero }, { rw [r_one_pow, one_def], congr' 1, exact zmod.nat_cast_self _, } end @[simp] lemma sr_mul_self (i : zmod n) : sr i * sr i = 1 := by rw [sr_mul_sr, sub_self, one_def] /-- If `0 < n`, then `sr i` has order 2. -/ @[simp] lemma order_of_sr (i : zmod n) : order_of (sr i) = 2 := begin rw order_of_eq_prime _ _, { exact ⟨nat.prime_two⟩ }, rw [sq, sr_mul_self], dec_trivial, end /-- If `0 < n`, then `r 1` has order `n`. -/ @[simp] lemma order_of_r_one : order_of (r 1 : dihedral_group n) = n := begin by_cases hnpos : 0 < n, { haveI : fact (0 < n) := ⟨hnpos⟩, cases lt_or_eq_of_le (nat.le_of_dvd hnpos (order_of_dvd_of_pow_eq_one (@r_one_pow_n n))) with h h, { have h1 : (r 1 : dihedral_group n)^(order_of (r 1)) = 1, { exact pow_order_of_eq_one _ }, rw r_one_pow at h1, injection h1 with h2, rw [← zmod.val_eq_zero, zmod.val_nat_cast, nat.mod_eq_of_lt h] at h2, apply absurd h2.symm, apply ne_of_lt, exact absurd h2.symm (ne_of_lt (order_of_pos _)) }, { exact h } }, { simp only [not_lt, nonpos_iff_eq_zero] at hnpos, rw hnpos, apply order_of_eq_zero, rw is_of_fin_order_iff_pow_eq_one, push_neg, intros m hm, rw [r_one_pow, one_def], by_contradiction, rw not_not at h, have h' : (m : zmod 0) = 0, { exact r.inj h, }, have h'' : m = 0, { simp only [int.coe_nat_eq_zero, int.nat_cast_eq_coe_nat] at h', exact h', }, rw h'' at hm, apply nat.lt_irrefl, exact hm }, end /-- If `0 < n`, then `i : zmod n` has order `n / gcd n i`. -/ lemma order_of_r [fact (0 < n)] (i : zmod n) : order_of (r i) = n / nat.gcd n i.val := begin conv_lhs { rw ←zmod.nat_cast_zmod_val i }, rw [←r_one_pow, order_of_pow, order_of_r_one] end end dihedral_group
0daf7539117c685dde69150e0ed214dbffef9ebf
0dbd5f7001f62ee8d54ed48bada66bfeaf55e550
/src/ent/gcd.lean
6f34eb44b4d5e4254943e51b0001ab345d16522b
[]
no_license
rwbarton/lean-elementary-number-theory
667203b08501792eef48217759539f6c1e2da25a
fabef0737fd2486e3f24f9e04652db4c182d5425
refs/heads/master
1,670,605,651,029
1,599,565,470,000
1,599,565,470,000
293,792,043
2
0
null
null
null
null
UTF-8
Lean
false
false
5,910
lean
import data.nat.modeq import ent.modeq import ent.parity open nat namespace gcd theorem gcd_row_op (a b k : ℕ) : gcd a b = gcd a (a * k + b) := have mods : b ≡ a * k + b [MOD a] := modeq.modeq_of_rep.symm, calc gcd a b = gcd (b % a) a : by rw gcd_rec ... = gcd ((a * k + b) % a) a : begin unfold modeq at mods, rw mods end ... = gcd a (a * k + b) : by rw ←gcd_rec lemma sum_difference_sum {a c : ℕ} (H : a ≤ c) : (c - a) + (c + a) = 2 * c := calc (c - a) + (c + a) = (c - a) + (a + c) : by rw add_comm a c ... = ((c - a) + a) + c : by rw add_assoc ... = (a + (c - a)) + c : by rw add_comm (c - a) a ... = c + c : by rw add_sub_of_le H ... = 2 * c : by rw two_mul lemma sum_difference_difference {a c : ℕ} (H : a ≤ c) : (c + a) - (c - a) = 2 * a := calc (c + a) - (c - a) = (a + c) - (c - a) : by rw add_comm c a ... = a + (c - (c - a)) : by rw nat.add_sub_assoc (sub_le c a) a ... = a + a : by rw nat.sub_sub_self H ... = 2 * a : by rw two_mul lemma sum_difference_of_coprime (a c : ℕ) (H : a ≤ c) : coprime a c → gcd (c - a) (c + a) ∣ 2 := begin intros ac, let g := gcd (c - a) (c + a), cases gcd_dvd (c - a) (c + a) with gminus gplus, have g2c : g ∣ 2 * c := by rw ←sum_difference_sum H; apply dvd_add; assumption, have : c - a ≤ c + a := trans (nat.sub_le c a) (le_add_right c a), have g2a : g ∣ 2 * a := by rw ←sum_difference_difference H; apply nat.dvd_sub this; assumption, have g2ac : g ∣ gcd (2 * a) (2 * c) := dvd_gcd g2a g2c, rw [gcd_mul_left 2 a c, ac.gcd_eq_one] at g2ac, exact g2ac end lemma sum_difference_of_coprime_odd (a c : ℕ) (H : a ≤ c) : coprime a c → odd a → odd c → gcd (c - a) (c + a) = 2 := begin intros ac oa oc, apply nat.dvd_antisymm, { exact sum_difference_of_coprime a c H ac }, { exact dvd_gcd (even_iff_two_dvd.mp (odd_minus_odd_is_even H oa oc)) (even_iff_two_dvd.mp (odd_plus_odd_is_even oc oa)) } end lemma coprime_iff_squares_coprime {x y : ℕ} : coprime (x^2) (y^2) ↔ coprime x y := iff.intro (λ H, coprime.coprime_dvd_left self_divides_square (coprime.coprime_dvd_right self_divides_square H)) (coprime.pow 2 2) end gcd lemma coprime_square_product {x y z : ℕ} : x * y = z^2 → coprime x y → ∃ x1 y1, x = x1^2 ∧ y = y1^2 := begin intros, rw nat.pow_two at a, cases eq_zero_or_pos x with xzero xpos, { -- x = 0 have y1 : y = 1 := begin simp [xzero, coprime, gcd_zero_left] at a_1, exact a_1 end, existsi [0, 1], split, { rw xzero, refl }, { rw y1, refl } }, -- x > 0 have H : x ∣ z * z := begin rw ←a, apply dvd_mul_right end, cases exists_eq_prod_and_dvd_and_dvd H with x1 H1, cases H1 with x2, cases H1_h, cases H1_h_right, existsi [x1, (z/x1)], let y1 := z / x1, let y2 := z / x2, have xyz1 : x1 * y1 = z := begin show x1 * (z / x1) = z, apply nat.mul_div_cancel', exact H1_h_right_left end, have xyz2 : x2 * y2 = z := begin show x2 * (z / x2) = z, apply nat.mul_div_cancel', exact H1_h_right_right end, have y1y2 : y = y1 * y2 := begin show y = (z / x1) * (z / x2), rw [←nat.mul_left_inj xpos, a, H1_h_left], have res : z * z = x1 * x2 * (z / x1 * (z / x2)) := calc z * z = (x1 * (z / x1)) * z : by rw nat.mul_div_cancel' H1_h_right_left ... = (x1 * (z / x1)) * (x2 * (z / x2)) : by rw nat.mul_div_cancel' H1_h_right_right ... = x1 * ((z / x1) * (x2 * (z / x2))) : by rw mul_assoc ... = x1 * (((z / x1) * x2) * (z / x2)) : by rw mul_assoc ... = x1 * ((x2 * (z / x1)) * (z / x2)) : by rw mul_comm (z / x1) x2 ... = x1 * (x2 * ((z / x1) * (z / x2))) : by rw mul_assoc ... = (x1 * x2) * ((z / x1) * (z / x2)) : by rw mul_assoc, exact res end, have xeq : x1 = x2 := begin rw [H1_h_left, y1y2] at a_1, have cx1y2 : gcd x1 y2 = 1 := a_1.coprime_mul_right.coprime_mul_left_right, have cx2y1 : gcd x2 y1 = 1 := a_1.coprime_mul_left.coprime_mul_right_right, have g2 : gcd x z = x2 := begin rw [H1_h_left, ←xyz2, mul_comm x2 y2], calc gcd (x1 * x2) (y2 * x2) = gcd x1 y2 * x2 : by rw gcd_mul_right ... = 1 * x2 : by rw cx1y2 ... = x2 : by simp end, have g1 : gcd x z = x1 := begin rw [H1_h_left, ←xyz1], calc gcd (x1 * x2) (x1 * y1) = x1 * gcd x2 y1 : by rw gcd_mul_left ... = x1 * 1 : by rw cx2y1 ... = x1 : by simp end, exact (symm g1).trans g2 end, split, { rw [nat.pow_two], rwa ←xeq at H1_h_left }, { have yeq : y1 = y2 := begin show z / x1 = z / x2, rw xeq end, rw [nat.pow_two], calc y = y1 * y2 : y1y2 ... = y1 * y1 : by rw yeq ... = (z / x1) * (z / x1) : by simp } end /- x y = z^2, x _|_ y x = z1 z2 y = (z / z1) (z / z2) If p divides z2 more times than z1 then p will also divide z / z1 at least once, and then z / z1 and z2 will not be relatively prime. gcd(z2, z/z1) = 1 => gcd(z1 z2, z) = z1 gcd(z1, z/z2) = 1 => gcd(z1 z2, z) = z2 -/
4d115e223963c7e2c22a659c38f543eafeedece5
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/complex/isometry.lean
88de13fee8aa5353e54a430caef0294d41a914fe
[ "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
6,721
lean
/- Copyright (c) 2021 François Sunatori. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: François Sunatori -/ import analysis.complex.circle import linear_algebra.determinant import linear_algebra.general_linear_group /-! # Isometries of the Complex Plane The lemma `linear_isometry_complex` states the classification of isometries in the complex plane. Specifically, isometries with rotations but without translation. The proof involves: 1. creating a linear isometry `g` with two fixed points, `g(0) = 0`, `g(1) = 1` 2. applying `linear_isometry_complex_aux` to `g` The proof of `linear_isometry_complex_aux` is separated in the following parts: 1. show that the real parts match up: `linear_isometry.re_apply_eq_re` 2. show that I maps to either I or -I 3. every z is a linear combination of a + b * I ## References * [Isometries of the Complex Plane](http://helmut.knaust.info/mediawiki/images/b/b5/Iso.pdf) -/ noncomputable theory open complex open_locale complex_conjugate local notation (name := complex.abs) `|` x `|` := complex.abs x /-- An element of the unit circle defines a `linear_isometry_equiv` from `ℂ` to itself, by rotation. -/ def rotation : circle →* (ℂ ≃ₗᵢ[ℝ] ℂ) := { to_fun := λ a, { norm_map' := λ x, show |a * x| = |x|, by rw [complex.abs_mul, abs_coe_circle, one_mul], ..distrib_mul_action.to_linear_equiv ℝ ℂ a }, map_one' := linear_isometry_equiv.ext $ one_smul _, map_mul' := λ _ _, linear_isometry_equiv.ext $ mul_smul _ _ } @[simp] lemma rotation_apply (a : circle) (z : ℂ) : rotation a z = a * z := rfl @[simp] lemma rotation_symm (a : circle) : (rotation a).symm = rotation a⁻¹ := linear_isometry_equiv.ext $ λ x, rfl @[simp] lemma rotation_trans (a b : circle) : (rotation a).trans (rotation b) = rotation (b * a) := by { ext1, simp } lemma rotation_ne_conj_lie (a : circle) : rotation a ≠ conj_lie := begin intro h, have h1 : rotation a 1 = conj 1 := linear_isometry_equiv.congr_fun h 1, have hI : rotation a I = conj I := linear_isometry_equiv.congr_fun h I, rw [rotation_apply, ring_hom.map_one, mul_one] at h1, rw [rotation_apply, conj_I, ← neg_one_mul, mul_left_inj' I_ne_zero, h1, eq_neg_self_iff] at hI, exact one_ne_zero hI, end /-- Takes an element of `ℂ ≃ₗᵢ[ℝ] ℂ` and checks if it is a rotation, returns an element of the unit circle. -/ @[simps] def rotation_of (e : ℂ ≃ₗᵢ[ℝ] ℂ) : circle := ⟨(e 1) / complex.abs (e 1), by simp⟩ @[simp] lemma rotation_of_rotation (a : circle) : rotation_of (rotation a) = a := subtype.ext $ by simp lemma rotation_injective : function.injective rotation := function.left_inverse.injective rotation_of_rotation lemma linear_isometry.re_apply_eq_re_of_add_conj_eq (f : ℂ →ₗᵢ[ℝ] ℂ) (h₃ : ∀ z, z + conj z = f z + conj (f z)) (z : ℂ) : (f z).re = z.re := by simpa [ext_iff, add_re, add_im, conj_re, conj_im, ←two_mul, (show (2 : ℝ) ≠ 0, by simp [two_ne_zero'])] using (h₃ z).symm lemma linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re {f : ℂ →ₗᵢ[ℝ] ℂ} (h₂ : ∀ z, (f z).re = z.re) (z : ℂ) : (f z).im = z.im ∨ (f z).im = -z.im := begin have h₁ := f.norm_map z, simp only [complex.abs, norm_eq_abs] at h₁, rwa [real.sqrt_inj (norm_sq_nonneg _) (norm_sq_nonneg _), norm_sq_apply (f z), norm_sq_apply z, h₂, add_left_cancel_iff, mul_self_eq_mul_self_iff] at h₁, end lemma linear_isometry.im_apply_eq_im {f : ℂ →ₗᵢ[ℝ] ℂ} (h : f 1 = 1) (z : ℂ) : z + conj z = f z + conj (f z) := begin have : ∥f z - 1∥ = ∥z - 1∥ := by rw [← f.norm_map (z - 1), f.map_sub, h], apply_fun λ x, x ^ 2 at this, simp only [norm_eq_abs, ←norm_sq_eq_abs] at this, rw [←of_real_inj, ←mul_conj, ←mul_conj] at this, rw [ring_hom.map_sub, ring_hom.map_sub] at this, simp only [sub_mul, mul_sub, one_mul, mul_one] at this, rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs, linear_isometry.norm_map] at this, rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs] at this, simp only [sub_sub, sub_right_inj, mul_one, of_real_pow, ring_hom.map_one, norm_eq_abs] at this, simp only [add_sub, sub_left_inj] at this, rw [add_comm, ←this, add_comm], end lemma linear_isometry.re_apply_eq_re {f : ℂ →ₗᵢ[ℝ] ℂ} (h : f 1 = 1) (z : ℂ) : (f z).re = z.re := begin apply linear_isometry.re_apply_eq_re_of_add_conj_eq, intro z, apply linear_isometry.im_apply_eq_im h, end lemma linear_isometry_complex_aux {f : ℂ ≃ₗᵢ[ℝ] ℂ} (h : f 1 = 1) : f = linear_isometry_equiv.refl ℝ ℂ ∨ f = conj_lie := begin have h0 : f I = I ∨ f I = -I, { have : |f I| = 1 := by simpa using f.norm_map complex.I, simp only [ext_iff, ←and_or_distrib_left, neg_re, I_re, neg_im, neg_zero], split, { rw ←I_re, exact @linear_isometry.re_apply_eq_re f.to_linear_isometry h I, }, { apply @linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re f.to_linear_isometry, intro z, rw @linear_isometry.re_apply_eq_re f.to_linear_isometry h } }, refine h0.imp (λ h' : f I = I, _) (λ h' : f I = -I, _); { apply linear_isometry_equiv.to_linear_equiv_injective, apply complex.basis_one_I.ext', intros i, fin_cases i; simp [h, h'] } end lemma linear_isometry_complex (f : ℂ ≃ₗᵢ[ℝ] ℂ) : ∃ a : circle, f = rotation a ∨ f = conj_lie.trans (rotation a) := begin let a : circle := ⟨f 1, by simpa using f.norm_map 1⟩, use a, have : (f.trans (rotation a).symm) 1 = 1, { simpa using rotation_apply a⁻¹ (f 1) }, refine (linear_isometry_complex_aux this).imp (λ h₁, _) (λ h₂, _), { simpa using eq_mul_of_inv_mul_eq h₁ }, { exact eq_mul_of_inv_mul_eq h₂ } end /-- The matrix representation of `rotation a` is equal to the conformal matrix `!![re a, -im a; im a, re a]`. -/ lemma to_matrix_rotation (a : circle) : linear_map.to_matrix basis_one_I basis_one_I (rotation a).to_linear_equiv = matrix.plane_conformal_matrix (re a) (im a) (by simp [pow_two, ←norm_sq_apply]) := begin ext i j, simp [linear_map.to_matrix_apply], fin_cases i; fin_cases j; simp end /-- The determinant of `rotation` (as a linear map) is equal to `1`. -/ @[simp] lemma det_rotation (a : circle) : ((rotation a).to_linear_equiv : ℂ →ₗ[ℝ] ℂ).det = 1 := begin rw [←linear_map.det_to_matrix basis_one_I, to_matrix_rotation, matrix.det_fin_two], simp [←norm_sq_apply] end /-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/ @[simp] lemma linear_equiv_det_rotation (a : circle) : (rotation a).to_linear_equiv.det = 1 := by rw [←units.eq_iff, linear_equiv.coe_det, det_rotation, units.coe_one]
eae30c4d9b28dc1b8a3a6df0ffca9120ded81e4c
ec5a7ae10c533e1b1f4b0bc7713e91ecf829a3eb
/ijcar16/examples/cc11.lean
2da291986c455716c4171e3ce5caf81d4679859b
[ "MIT" ]
permissive
leanprover/leanprover.github.io
cf248934af7c7e9aeff17cf8df3c12c5e7e73f1a
071a20d2e059a2c3733e004c681d3949cac3c07a
refs/heads/master
1,692,621,047,417
1,691,396,994,000
1,691,396,994,000
19,366,263
18
27
MIT
1,693,989,071,000
1,399,006,345,000
Lean
UTF-8
Lean
false
false
1,162
lean
/- Example/test file for the congruence closure procedure described in the paper: "Congruence Closure for Intensional Type Theory" Daniel Selsam and Leonardo de Moura The tactic `by blast` has been configured in this file to use just the congruence closure procedure using the command set_option blast.strategy "cc" -/ import data.list set_option blast.strategy "cc" /- Our congurence closure procedure handles symmetric relations automatically. -/ example (a b : nat) : (a = b) ↔ (b = a) := by blast example (a b : nat) : (a = b) = (b = a) := by blast example (a b : nat) : (a = b) == (b = a) := by blast open perm example (a b : list nat) : (a ~ b) ↔ (b ~ a) := by blast example (a b : list nat) : (a ~ b) = (b ~ a) := by blast example (a b : list nat) : (a ~ b) == (b ~ a) := by blast example (p : Prop) (a b : nat) : a = b → b ≠ a → p := by blast example (a b : Prop) : (a ↔ b) → ((b ↔ a) ↔ (a ↔ b)) := by blast example (a b c : nat) : b = c → (a = b ↔ c = a) := by blast example (a b c : list nat) : b ~ c → (a ~ b ↔ c ~ a) := by blast example (a b c : list nat) : b ~ c → ((a ~ b) = (c ~ a)) := by blast
b4f9d492777f9be640b7f9047b2569f9b689b770
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/list/forall2.lean
4eea34cfad2d6babdb710e7731a83cfbbcc319b7
[ "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
14,099
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl -/ import data.list.infix /-! # Double universal quantification on a list This file provides an API for `list.forall₂` (definition in `data.list.defs`). `forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length, and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`, then `R a b` is satisfied. -/ open nat function namespace list variables {α β γ δ : Type*} {R S : α → β → Prop} {P : γ → δ → Prop} {Rₐ : α → α → Prop} open relator mk_iff_of_inductive_prop list.forall₂ list.forall₂_iff @[simp] theorem forall₂_cons {a b l₁ l₂} : forall₂ R (a :: l₁) (b :: l₂) ↔ R a b ∧ forall₂ R l₁ l₂ := ⟨λ h, by cases h with h₁ h₂; split; assumption, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩ theorem forall₂.imp (H : ∀ a b, R a b → S a b) {l₁ l₂} (h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ := by induction h; constructor; solve_by_elim lemma forall₂.mp {Q : α → β → Prop} (h : ∀ a b, Q a b → R a b → S a b) : ∀ {l₁ l₂}, forall₂ Q l₁ l₂ → forall₂ R l₁ l₂ → forall₂ S l₁ l₂ | [] [] forall₂.nil forall₂.nil := forall₂.nil | (a :: l₁) (b :: l₂) (forall₂.cons hr hrs) (forall₂.cons hq hqs) := forall₂.cons (h a b hr hq) (forall₂.mp hrs hqs) lemma forall₂.flip : ∀ {a b}, forall₂ (flip R) b a → forall₂ R a b | _ _ forall₂.nil := forall₂.nil | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ h₂.flip @[simp] lemma forall₂_same : ∀ {l : list α}, forall₂ Rₐ l l ↔ ∀ x ∈ l, Rₐ x x | [] := by simp | (a :: l) := by simp [@forall₂_same l] lemma forall₂_refl [is_refl α Rₐ] (l : list α) : forall₂ Rₐ l l := forall₂_same.2 $ λ a h, refl _ @[simp] lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) := begin funext a b, apply propext, split, { intro h, induction h, {refl}, simp only [*]; split; refl }, { rintro rfl, exact forall₂_refl _ } end @[simp, priority 900] lemma forall₂_nil_left_iff {l} : forall₂ R nil l ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ @[simp, priority 900] lemma forall₂_nil_right_iff {l} : forall₂ R l nil ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ lemma forall₂_cons_left_iff {a l u} : forall₂ R (a :: l) u ↔ (∃b u', R a b ∧ forall₂ R l u' ∧ u = b :: u') := iff.intro (λ h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (λ h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_cons_right_iff {b l u} : forall₂ R u (b :: l) ↔ (∃a u', R a b ∧ forall₂ R u' l ∧ u = a :: u') := iff.intro (λ h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (λ h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_and_left {p : α → Prop} : ∀ l u, forall₂ (λa b, p a ∧ R a b) l u ↔ (∀ a∈l, p a) ∧ forall₂ R l u | [] u := by simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _), imp_true_iff, true_and] | (a :: l) u := by simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons, and_assoc, and_comm, and.left_comm, exists_and_distrib_left.symm] @[simp] lemma forall₂_map_left_iff {f : γ → α} : ∀ {l u}, forall₂ R (map f l) u ↔ forall₂ (λc b, R (f c) b) l u | [] _ := by simp only [map, forall₂_nil_left_iff] | (a :: l) _ := by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff] @[simp] lemma forall₂_map_right_iff {f : γ → β} : ∀ {l u}, forall₂ R l (map f u) ↔ forall₂ (λa c, R a (f c)) l u | _ [] := by simp only [map, forall₂_nil_right_iff] | _ (b :: u) := by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff] lemma left_unique_forall₂' (hr : left_unique R) : ∀ {a b c}, forall₂ R a c → forall₂ R b c → a = b | a₀ nil a₁ forall₂.nil forall₂.nil := rfl | (a₀ :: l₀) (b :: l) (a₁ :: l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ left_unique_forall₂' h₀ h₁ ▸ rfl lemma _root_.relator.left_unique.forall₂ (hr : left_unique R) : left_unique (forall₂ R) := @left_unique_forall₂' _ _ _ hr lemma right_unique_forall₂' (hr : right_unique R) : ∀ {a b c}, forall₂ R a b → forall₂ R a c → b = c | nil a₀ a₁ forall₂.nil forall₂.nil := rfl | (b :: l) (a₀ :: l₀) (a₁ :: l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ right_unique_forall₂' h₀ h₁ ▸ rfl lemma _root_.relator.right_unique.forall₂ (hr : right_unique R) : right_unique (forall₂ R) := @right_unique_forall₂' _ _ _ hr lemma _root_.relator.bi_unique.forall₂ (hr : bi_unique R) : bi_unique (forall₂ R) := ⟨hr.left.forall₂, hr.right.forall₂⟩ theorem forall₂.length_eq : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂ | _ _ forall₂.nil := rfl | _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂.length_eq h₂) theorem forall₂.nth_le : ∀ {x : list α} {y : list β} (h : forall₂ R x y) ⦃i : ℕ⦄ (hx : i < x.length) (hy : i < y.length), R (x.nth_le i hx) (y.nth_le i hy) | (a₁ :: l₁) (a₂ :: l₂) (forall₂.cons ha hl) 0 hx hy := ha | (a₁ :: l₁) (a₂ :: l₂) (forall₂.cons ha hl) (succ i) hx hy := hl.nth_le _ _ lemma forall₂_of_length_eq_of_nth_le : ∀ {x : list α} {y : list β}, x.length = y.length → (∀ i h₁ h₂, R (x.nth_le i h₁) (y.nth_le i h₂)) → forall₂ R x y | [] [] hl h := forall₂.nil | (a₁ :: l₁) (a₂ :: l₂) hl h := forall₂.cons (h 0 (nat.zero_lt_succ _) (nat.zero_lt_succ _)) (forall₂_of_length_eq_of_nth_le (succ.inj hl) ( λ i h₁ h₂, h i.succ (succ_lt_succ h₁) (succ_lt_succ h₂))) theorem forall₂_iff_nth_le {l₁ : list α} {l₂ : list β} : forall₂ R l₁ l₂ ↔ l₁.length = l₂.length ∧ ∀ i h₁ h₂, R (l₁.nth_le i h₁) (l₂.nth_le i h₂) := ⟨λ h, ⟨h.length_eq, h.nth_le⟩, and.rec forall₂_of_length_eq_of_nth_le⟩ theorem forall₂_zip : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b | _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁ | _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃ theorem forall₂_iff_zip {l₁ l₂} : forall₂ R l₁ l₂ ↔ length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b := ⟨λ h, ⟨forall₂.length_eq h, @forall₂_zip _ _ _ _ _ h⟩, λ h, begin cases h with h₁ h₂, induction l₁ with a l₁ IH generalizing l₂, { cases length_eq_zero.1 h₁.symm, constructor }, { cases l₂ with b l₂; injection h₁ with h₁, exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) } end⟩ theorem forall₂_take : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂) | 0 _ _ _ := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_take n] theorem forall₂_drop : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂) | 0 _ _ h := by simp only [drop, h] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, drop] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_drop n] theorem forall₂_take_append (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.take (length l₁) l) l₁ := have h': forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)), from forall₂_take (length l₁) h, by rwa [take_left] at h' theorem forall₂_drop_append (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.drop (length l₁) l) l₂ := have h': forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)), from forall₂_drop (length l₁) h, by rwa [drop_left] at h' lemma rel_mem (hr : bi_unique R) : (R ⇒ forall₂ R ⇒ iff) (∈) (∈) | a b h [] [] forall₂.nil := by simp only [not_mem_nil] | a b h (a' :: as) (b' :: bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂) lemma rel_map : ((R ⇒ P) ⇒ forall₂ R ⇒ forall₂ P) map map | f g h [] [] forall₂.nil := forall₂.nil | f g h (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂) lemma rel_append : (forall₂ R ⇒ forall₂ R ⇒ forall₂ R) append append | [] [] h l₁ l₂ hl := hl | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl) lemma rel_reverse : (forall₂ R ⇒ forall₂ R) reverse reverse | [] [] forall₂.nil := forall₂.nil | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := begin simp only [reverse_cons], exact rel_append (rel_reverse h₂) (forall₂.cons h₁ forall₂.nil) end @[simp] lemma forall₂_reverse_iff {l₁ l₂} : forall₂ R (reverse l₁) (reverse l₂) ↔ forall₂ R l₁ l₂ := iff.intro (λ h, by { rw [← reverse_reverse l₁, ← reverse_reverse l₂], exact rel_reverse h }) (λ h, rel_reverse h) lemma rel_join : (forall₂ (forall₂ R) ⇒ forall₂ R) join join | [] [] forall₂.nil := forall₂.nil | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂) lemma rel_bind : (forall₂ R ⇒ (R ⇒ forall₂ P) ⇒ forall₂ P) list.bind list.bind := λ a b h₁ f g h₂, rel_join (rel_map @h₂ h₁) lemma rel_foldl : ((P ⇒ R ⇒ P) ⇒ P ⇒ forall₂ R ⇒ P) foldl foldl | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs lemma rel_foldr : ((R ⇒ P ⇒ P) ⇒ P ⇒ forall₂ R ⇒ P) foldr foldr | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs) lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q] (hpq : (R ⇒ (↔)) p q) : (forall₂ R ⇒ forall₂ R) (filter p) (filter q) | _ _ forall₂.nil := forall₂.nil | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := begin by_cases p a, { have : q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_pos _ h, filter_cons_of_pos _ this, forall₂_cons, h₁, rel_filter h₂, and_true], }, { have : ¬ q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_neg _ h, filter_cons_of_neg _ this, rel_filter h₂], }, end lemma rel_filter_map : ((R ⇒ option.rel P) ⇒ forall₂ R ⇒ forall₂ P) filter_map filter_map | f g hfg _ _ forall₂.nil := forall₂.nil | f g hfg (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := by rw [filter_map_cons, filter_map_cons]; from match f a, g b, hfg h₁ with | _, _, option.rel.none := rel_filter_map @hfg h₂ | _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂) end @[to_additive] lemma rel_prod [monoid α] [monoid β] (h : R 1 1) (hf : (R ⇒ R ⇒ R) (*) (*)) : (forall₂ R ⇒ R) prod prod := rel_foldl hf h /-- Given a relation `R`, `sublist_forall₂ r l₁ l₂` indicates that there is a sublist of `l₂` such that `forall₂ r l₁ l₂`. -/ inductive sublist_forall₂ (R : α → β → Prop) : list α → list β → Prop | nil {l} : sublist_forall₂ [] l | cons {a₁ a₂ l₁ l₂} : R a₁ a₂ → sublist_forall₂ l₁ l₂ → sublist_forall₂ (a₁ :: l₁) (a₂ :: l₂) | cons_right {a l₁ l₂} : sublist_forall₂ l₁ l₂ → sublist_forall₂ l₁ (a :: l₂) lemma sublist_forall₂_iff {l₁ : list α} {l₂ : list β} : sublist_forall₂ R l₁ l₂ ↔ ∃ l, forall₂ R l₁ l ∧ l <+ l₂ := begin split; intro h, { induction h with _ a b l1 l2 rab rll ih b l1 l2 hl ih, { exact ⟨nil, forall₂.nil, nil_sublist _⟩ }, { obtain ⟨l, hl1, hl2⟩ := ih, refine ⟨b :: l, forall₂.cons rab hl1, hl2.cons_cons b⟩ }, { obtain ⟨l, hl1, hl2⟩ := ih, exact ⟨l, hl1, hl2.trans (sublist.cons _ _ _ (sublist.refl _))⟩ } }, { obtain ⟨l, hl1, hl2⟩ := h, revert l₁, induction hl2 with _ _ _ _ ih _ _ _ _ ih; intros l₁ hl1, { rw [forall₂_nil_right_iff.1 hl1], exact sublist_forall₂.nil }, { exact sublist_forall₂.cons_right (ih hl1) }, { cases hl1 with _ _ _ _ hr hl _, exact sublist_forall₂.cons hr (ih hl) } } end instance sublist_forall₂.is_refl [is_refl α Rₐ] : is_refl (list α) (sublist_forall₂ Rₐ) := ⟨λ l, sublist_forall₂_iff.2 ⟨l, forall₂_refl l, sublist.refl l⟩⟩ instance sublist_forall₂.is_trans [is_trans α Rₐ] : is_trans (list α) (sublist_forall₂ Rₐ) := ⟨λ a b c, begin revert a b, induction c with _ _ ih, { rintros _ _ h1 (_ | _ | _), exact h1 }, { rintros a b h1 h2, cases h2 with _ _ _ _ _ hbc tbc _ _ y1 btc, { cases h1, exact sublist_forall₂.nil }, { cases h1 with _ _ _ _ _ hab tab _ _ _ atb, { exact sublist_forall₂.nil }, { exact sublist_forall₂.cons (trans hab hbc) (ih _ _ tab tbc) }, { exact sublist_forall₂.cons_right (ih _ _ atb tbc) } }, { exact sublist_forall₂.cons_right (ih _ _ h1 btc), } } end⟩ lemma sublist.sublist_forall₂ {l₁ l₂ : list α} (h : l₁ <+ l₂) [is_refl α Rₐ] : sublist_forall₂ Rₐ l₁ l₂ := sublist_forall₂_iff.2 ⟨l₁, forall₂_refl l₁, h⟩ lemma tail_sublist_forall₂_self [is_refl α Rₐ] (l : list α) : sublist_forall₂ Rₐ l.tail l := l.tail_sublist.sublist_forall₂ end list
f9e49091cf6ccca1a3960e95075671de55125a50
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/fingerprint.lean
b7ace0832b16d107e30766979731512cc8e8999c
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
759
lean
open tactic meta def nat.to_expr (n : nat) : tactic expr := to_expr (quote n) run_cmd attribute.fingerprint `reducible >>= trace definition ex0 : nat := by attribute.fingerprint `reducible >>= nat.to_expr >>= exact attribute [reducible] definition f : nat := 10 run_cmd attribute.fingerprint `reducible >>= trace definition ex1 : nat := by attribute.fingerprint `reducible >>= nat.to_expr >>= exact #eval ex1 definition g : nat := 20 run_cmd attribute.fingerprint `reducible >>= trace definition ex2 : nat := by attribute.fingerprint `reducible >>= nat.to_expr >>= exact #eval ex2 example : ex1 = ex2 := rfl definition h : nat := 20 definition ex3 : nat := by attribute.fingerprint `reducible >>= nat.to_expr >>= exact example : ex1 = ex3 := rfl
b0f2bc9945b4e27d288577030eb485d6031f492a
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/category_theory/yoneda.lean
369c2270d358b16076ec520860da5e02aa7db62e
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,584
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.hom_functor /-! # The Yoneda embedding The Yoneda embedding as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`, along with an instance that it is `fully_faithful`. Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`. ## References * [Stacks: Opposite Categories and the Yoneda Lemma](https://stacks.math.columbia.edu/tag/001L) -/ namespace category_theory open opposite universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v₁} C] /-- The Yoneda embedding, as a functor from `C` into presheaves on `C`. See https://stacks.math.columbia.edu/tag/001O. -/ @[simps] def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop Y ⟶ X, map := λ Y Y' f g, f.unop ≫ g, 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 g, g ≫ f } } /-- The co-Yoneda embedding, as a functor from `Cᵒᵖ` into co-presheaves on `C`. -/ @[simps] def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop X ⟶ Y, map := λ Y Y' f g, g ≫ f, map_comp' := λ _ _ _ f g, begin ext1, dsimp, erw [category.assoc] end, map_id' := λ Y, begin ext1, dsimp, erw [category.comp_id] end }, map := λ X X' f, { app := λ Y g, f.unop ≫ g }, map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end, map_id' := λ X, begin ext, dsimp, erw [category.id_comp] end } namespace yoneda lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) : ((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f.unop).app (op Y) (𝟙 Y) := by obviously @[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y) {Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) := (functor_to_types.naturality _ _ α f.op h).symm /-- The Yoneda embedding is full. See https://stacks.math.columbia.edu/tag/001P. -/ instance yoneda_full : full (@yoneda C _) := { preimage := λ X Y f, (f.app (op X)) (𝟙 X) } /-- The Yoneda embedding is faithful. See https://stacks.math.columbia.edu/tag/001P. -/ instance yoneda_faithful : faithful (@yoneda C _) := { map_injective' := λ X Y f g p, begin injection p with h, convert (congr_fun (congr_fun h (op X)) (𝟙 X)); dsimp; simp, end } /-- Extensionality via Yoneda. The typical usage would be ``` -- Goal is `X ≅ Y` apply yoneda.ext, -- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these functions are inverses and natural in `Z`. ``` -/ def ext (X Y : C) (p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X)) (h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f) (n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y := @preimage_iso _ _ _ _ yoneda _ _ _ _ (nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy)) /-- If `yoneda.map f` is an isomorphism, so was `f`. -/ def is_iso {X Y : C} (f : X ⟶ Y) [is_iso (yoneda.map f)] : is_iso f := is_iso_of_fully_faithful yoneda f end yoneda namespace coyoneda @[simp] lemma naturality {X Y : Cᵒᵖ} (α : coyoneda.obj X ⟶ coyoneda.obj Y) {Z Z' : C} (f : Z' ⟶ Z) (h : unop X ⟶ Z') : (α.app Z' h) ≫ f = α.app Z (h ≫ f) := begin erw [functor_to_types.naturality], refl end instance coyoneda_full : full (@coyoneda C _) := { preimage := λ X Y f, ((f.app (unop X)) (𝟙 _)).op } instance coyoneda_faithful : faithful (@coyoneda C _) := { map_injective' := λ X Y f g p, begin injection p with h, have t := (congr_fun (congr_fun h (unop X)) (𝟙 _)), simpa using congr_arg has_hom.hom.op t, end } /-- If `coyoneda.map f` is an isomorphism, so was `f`. -/ def is_iso {X Y : Cᵒᵖ} (f : X ⟶ Y) [is_iso (coyoneda.map f)] : is_iso f := is_iso_of_fully_faithful coyoneda f end coyoneda /-- A presheaf `F` is representable if there is object `X` so `F ≅ yoneda.obj X`. See https://stacks.math.columbia.edu/tag/001Q. -/ -- TODO should we make this a Prop, merely asserting existence of such an object? class representable (F : Cᵒᵖ ⥤ Type v₁) := (X : C) (w : yoneda.obj X ≅ F) end category_theory namespace category_theory -- For the rest of the file, we are using product categories, -- so need to restrict to the case morphisms are in 'Type', not 'Sort'. universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation open opposite variables (C : Type u₁) [category.{v₁} C] -- We need to help typeclass inference with some awkward universe levels here. instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) := category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) := category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁) open yoneda /-- The "Yoneda evaluation" functor, which sends `X : Cᵒᵖ` and `F : Cᵒᵖ ⥤ Type` to `F.obj X`, functorially in both `X` and `F`. -/ def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁} @[simp] lemma yoneda_evaluation_map_down (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) : ((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl /-- The "Yoneda pairing" functor, which sends `X : Cᵒᵖ` and `F : Cᵒᵖ ⥤ Type` to `yoneda.op.obj X ⟶ F`, functorially in both `X` and `F`. -/ def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := functor.prod yoneda.op (𝟭 (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁) @[simp] lemma yoneda_pairing_map (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) : (yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl /-- The Yoneda lemma asserts that that the Yoneda pairing `(X : Cᵒᵖ, F : Cᵒᵖ ⥤ Type) ↦ (yoneda.obj (unop X) ⟶ F)` is naturally isomorphic to the evaluation `(X, F) ↦ F.obj X`. See https://stacks.math.columbia.edu/tag/001P. -/ def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C := { hom := { app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))), naturality' := begin intros X Y f, ext, dsimp, erw [category.id_comp, ←functor_to_types.naturality], simp only [category.comp_id, yoneda_obj_map], end }, inv := { app := λ F x, { app := λ X a, (F.2.map a.op) x.down, naturality' := begin intros X Y f, ext, dsimp, rw [functor_to_types.map_comp_apply] end }, naturality' := begin intros X Y f, ext, dsimp, rw [←functor_to_types.naturality, functor_to_types.map_comp_apply] end }, hom_inv_id' := begin ext, dsimp, erw [←functor_to_types.naturality, obj_map_id], simp only [yoneda_map_app, has_hom.hom.unop_op], erw [category.id_comp], end, inv_hom_id' := begin ext, dsimp, rw [functor_to_types.map_id_apply] end }. variables {C} /-- The isomorphism between `yoneda.obj X ⟶ F` and `F.obj (op X)` (we need to insert a `ulift` to get the universes right!) given by the Yoneda lemma. -/ @[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) : (yoneda.obj X ⟶ F) ≅ ulift.{u₁} (F.obj (op X)) := (yoneda_lemma C).app (op X, F) /-- We have a type-level equivalence between natural transformations from the yoneda embedding and elements of `F.obj X`, without any universe switching. -/ def yoneda_equiv {X : C} {F : Cᵒᵖ ⥤ Type v₁} : (yoneda.obj X ⟶ F) ≃ F.obj (op X) := (yoneda_sections X F).to_equiv.trans equiv.ulift lemma yoneda_equiv_naturality {X Y : C} {F : Cᵒᵖ ⥤ Type v₁} (f : yoneda.obj X ⟶ F) (g : Y ⟶ X) : F.map g.op (yoneda_equiv f) = yoneda_equiv (yoneda.map g ≫ f) := begin change (f.app (op X) ≫ F.map g.op) (𝟙 X) = f.app (op Y) (𝟙 Y ≫ g), rw ← f.naturality, dsimp, simp, end @[simp] lemma yoneda_equiv_apply {X : C} {F : Cᵒᵖ ⥤ Type v₁} (f : yoneda.obj X ⟶ F) : yoneda_equiv f = f.app (op X) (𝟙 X) := rfl @[simp] lemma yoneda_equiv_symm_app_apply {X : C} {F : Cᵒᵖ ⥤ Type v₁} (x : F.obj (op X)) (Y : Cᵒᵖ) (f : Y.unop ⟶ X) : (yoneda_equiv.symm x).app Y f = F.map f.op x := rfl /-- When `C` is a small category, we can restate the isomorphism from `yoneda_sections` without having to change universes. -/ def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) : (yoneda.obj X ⟶ F) ≅ F.obj (op X) := yoneda_sections X F ≪≫ ulift_trivial _ @[simp] lemma yoneda_sections_small_hom {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) (f : yoneda.obj X ⟶ F) : (yoneda_sections_small X F).hom f = f.app _ (𝟙 _) := rfl @[simp] lemma yoneda_sections_small_inv_app_apply {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) (t : F.obj (op X)) (Y : Cᵒᵖ) (f : Y.unop ⟶ X) : ((yoneda_sections_small X F).inv t).app Y f = F.map f.op t := rfl end category_theory
70a16e0a1b5a2e38fa8d7851d22dd500b22cabf8
618003631150032a5676f229d13a079ac875ff77
/src/topology/bounded_continuous_function.lean
fe1eae39ba7db50357b3231eef6ab6a6f3eaac40
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
28,996
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Mario Carneiro, Yury Kudryashov, Heather Macbeth -/ import analysis.normed_space.basic /-! # Bounded continuous functions The type of bounded continuous functions taking values in a metric space, with the uniform distance. -/ noncomputable theory open_locale topological_space classical open set filter metric universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- The type of bounded continuous functions from a topological space to a metric space -/ def bounded_continuous_function (α : Type u) (β : Type v) [topological_space α] [metric_space β] : Type (max u v) := {f : α → β // continuous f ∧ ∃C, ∀x y:α, dist (f x) (f y) ≤ C} local infixr ` →ᵇ `:25 := bounded_continuous_function namespace bounded_continuous_function section basics variables [topological_space α] [metric_space β] [metric_space γ] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance : has_coe_to_fun (α →ᵇ β) := ⟨_, subtype.val⟩ lemma bounded_range : bounded (range f) := bounded_range_iff.2 f.2.2 /-- If a function is continuous on a compact space, it is automatically bounded, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_compact [compact_space α] (f : α → β) (hf : continuous f) : α →ᵇ β := ⟨f, hf, bounded_range_iff.1 $ bounded_of_compact $ compact_range hf⟩ /-- If a function is bounded on a discrete space, it is automatically continuous, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_discrete [discrete_topology α] (f : α → β) (hf : ∃C, ∀x y, dist (f x) (f y) ≤ C) : α →ᵇ β := ⟨f, continuous_of_discrete_topology, hf⟩ /-- The uniform distance between two bounded continuous functions -/ instance : has_dist (α →ᵇ β) := ⟨λf g, Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C}⟩ lemma dist_eq : dist f g = Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C} := rfl lemma dist_set_exists : ∃ C, 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C := begin refine if h : nonempty α then _ else ⟨0, le_refl _, λ x, h.elim ⟨x⟩⟩, cases h with x, rcases f.2 with ⟨_, Cf, hCf⟩, /- hCf : ∀ (x y : α), dist (f.val x) (f.val y) ≤ Cf -/ rcases g.2 with ⟨_, Cg, hCg⟩, /- hCg : ∀ (x y : α), dist (g.val x) (g.val y) ≤ Cg -/ let C := max 0 (dist (f x) (g x) + (Cf + Cg)), exact ⟨C, le_max_left _ _, λ y, calc dist (f y) (g y) ≤ dist (f x) (g x) + (dist (f x) (f y) + dist (g x) (g y)) : dist_triangle4_left _ _ _ _ ... ≤ dist (f x) (g x) + (Cf + Cg) : add_le_add_left (add_le_add (hCf _ _) (hCg _ _)) _ ... ≤ C : le_max_right _ _⟩ end /-- The pointwise distance is controlled by the distance between functions, by definition -/ lemma dist_coe_le_dist (x : α) : dist (f x) (g x) ≤ dist f g := le_cInf dist_set_exists $ λb hb, hb.2 x @[ext] lemma ext (H : ∀x, f x = g x) : f = g := subtype.eq $ funext H lemma ext_iff : f = g ↔ ∀ x, f x = g x := ⟨λ h, λ x, h ▸ rfl, ext⟩ /- This lemma will be needed in the proof of the metric space instance, but it will become useless afterwards as it will be superceded by the general result that the distance is nonnegative is metric spaces. -/ private lemma dist_nonneg' : 0 ≤ dist f g := le_cInf dist_set_exists (λ C, and.left) /-- The distance between two functions is controlled by the supremum of the pointwise distances -/ lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C := ⟨λ h x, le_trans (dist_coe_le_dist x) h, λ H, cInf_le ⟨0, λ C, and.left⟩ ⟨C0, H⟩⟩ /-- On an empty space, bounded continuous functions are at distance 0 -/ lemma dist_zero_of_empty (e : ¬ nonempty α) : dist f g = 0 := le_antisymm ((dist_le (le_refl _)).2 $ λ x, e.elim ⟨x⟩) dist_nonneg' /-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/ instance : metric_space (α →ᵇ β) := { dist_self := λ f, le_antisymm ((dist_le (le_refl _)).2 $ λ x, by simp) dist_nonneg', eq_of_dist_eq_zero := λ f g hfg, by ext x; exact eq_of_dist_eq_zero (le_antisymm (hfg ▸ dist_coe_le_dist _) dist_nonneg), dist_comm := λ f g, by simp [dist_eq, dist_comm], dist_triangle := λ f g h, (dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ λ x, le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) } variable (α) /-- Constant as a continuous bounded function. -/ def const (b : β) : α →ᵇ β := ⟨λx, b, continuous_const, 0, by simp [le_refl]⟩ variable {α} @[simp] lemma coe_const (b : β) : ⇑(const α b) = function.const α b := rfl lemma const_apply (a : α) (b : β) : (const α b : α → β) a = b := rfl /-- If the target space is inhabited, so is the space of bounded continuous functions -/ instance [inhabited β] : inhabited (α →ᵇ β) := ⟨const α (default β)⟩ /-- The evaluation map is continuous, as a joint function of `u` and `x` -/ theorem continuous_eval : continuous (λ p : (α →ᵇ β) × α, p.1 p.2) := continuous_iff'.2 $ λ ⟨f, x⟩ ε ε0, /- use the continuity of `f` to find a neighborhood of `x` where it varies at most by ε/2 -/ have Hs : _ := continuous_iff'.1 f.2.1 x (ε/2) (half_pos ε0), mem_sets_of_superset (prod_mem_nhds_sets (ball_mem_nhds _ (half_pos ε0)) Hs) $ λ ⟨g, y⟩ ⟨hg, hy⟩, calc dist (g y) (f x) ≤ dist (g y) (f y) + dist (f y) (f x) : dist_triangle _ _ _ ... < ε/2 + ε/2 : add_lt_add (lt_of_le_of_lt (dist_coe_le_dist _) hg) hy ... = ε : add_halves _ /-- In particular, when `x` is fixed, `f → f x` is continuous -/ theorem continuous_evalx {x : α} : continuous (λ f : α →ᵇ β, f x) := continuous_eval.comp (continuous_id.prod_mk continuous_const) /-- When `f` is fixed, `x → f x` is also continuous, by definition -/ theorem continuous_evalf {f : α →ᵇ β} : continuous f := f.2.1 /-- Bounded continuous functions taking values in a complete space form a complete space. -/ instance [complete_space β] : complete_space (α →ᵇ β) := complete_of_cauchy_seq_tendsto $ λ (f : ℕ → α →ᵇ β) (hf : cauchy_seq f), begin /- We have to show that `f n` converges to a bounded continuous function. For this, we prove pointwise convergence to define the limit, then check it is a continuous bounded function, and then check the norm convergence. -/ rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, have f_bdd := λx n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm), have fx_cau : ∀x, cauchy_seq (λn, f n x) := λx, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩, choose F hF using λx, cauchy_seq_tendsto_of_complete (fx_cau x), /- F : α → β, hF : ∀ (x : α), tendsto (λ (n : ℕ), f n x) at_top (𝓝 (F x)) `F` is the desired limit function. Check that it is uniformly approximated by `f N` -/ have fF_bdd : ∀x N, dist (f N x) (F x) ≤ b N := λ x N, le_of_tendsto (by simp) (tendsto_const_nhds.dist (hF x)) (filter.eventually_at_top.2 ⟨N, λn hn, f_bdd x N n N (le_refl N) hn⟩), refine ⟨⟨F, _, _⟩, _⟩, { /- Check that `F` is continuous, as a uniform limit of continuous functions -/ have : tendsto_uniformly (λn x, f n x) F at_top, { refine metric.tendsto_uniformly_iff.2 (λ ε ε0, _), refine ((tendsto_order.1 b_lim).2 ε ε0).mono (λ n hn x, _), rw dist_comm, exact lt_of_le_of_lt (fF_bdd x n) hn }, exact this.continuous (λN, (f N).2.1) at_top_ne_bot }, { /- Check that `F` is bounded -/ rcases (f 0).2.2 with ⟨C, hC⟩, exact ⟨C + (b 0 + b 0), λ x y, calc dist (F x) (F y) ≤ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) : dist_triangle4_left _ _ _ _ ... ≤ C + (b 0 + b 0) : add_le_add (hC x y) (add_le_add (fF_bdd x 0) (fF_bdd y 0))⟩ }, { /- Check that `F` is close to `f N` in distance terms -/ refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (λ _, dist_nonneg) _ b_lim), exact λ N, (dist_le (b0 _)).2 (λx, fF_bdd x N) } end /-- Composition (in the target) of a bounded continuous function with a Lipschitz map again gives a bounded continuous function -/ def comp (G : β → γ) {C : nnreal} (H : lipschitz_with C G) (f : α →ᵇ β) : α →ᵇ γ := ⟨λx, G (f x), H.continuous.comp f.2.1, let ⟨D, hD⟩ := f.2.2 in ⟨max C 0 * D, λ x y, calc dist (G (f x)) (G (f y)) ≤ C * dist (f x) (f y) : H.dist_le_mul _ _ ... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg ... ≤ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩ /-- The composition operator (in the target) with a Lipschitz map is Lipschitz -/ lemma lipschitz_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : lipschitz_with C (comp G H : (α →ᵇ β) → α →ᵇ γ) := lipschitz_with.of_dist_le_mul $ λ f g, (dist_le (mul_nonneg C.2 dist_nonneg)).2 $ λ x, calc dist (G (f x)) (G (g x)) ≤ C * dist (f x) (g x) : H.dist_le_mul _ _ ... ≤ C * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) C.2 /-- The composition operator (in the target) with a Lipschitz map is uniformly continuous -/ lemma uniform_continuous_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : uniform_continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).uniform_continuous /-- The composition operator (in the target) with a Lipschitz map is continuous -/ lemma continuous_comp {G : β → γ} {C : nnreal} (H : lipschitz_with C G) : continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).continuous /-- Restriction (in the target) of a bounded continuous function taking values in a subset -/ def cod_restrict (s : set β) (f : α →ᵇ β) (H : ∀x, f x ∈ s) : α →ᵇ s := ⟨s.cod_restrict f H, continuous_subtype_mk _ f.2.1, f.2.2⟩ end basics section arzela_ascoli variables [topological_space α] [compact_space α] [metric_space β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} /- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing a common modulus of continuity and taking values in a compact set forms a compact subset for the topology of uniform convergence. In this section, we prove this theorem and several useful variations around it. -/ /-- First version, with pointwise equicontinuity and range in a compact space -/ theorem arzela_ascoli₁ [compact_space β] (A : set (α →ᵇ β)) (closed : is_closed A) (H : ∀ (x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact A := begin refine compact_of_totally_bounded_is_closed _ closed, refine totally_bounded_of_finite_discretization (λ ε ε0, _), rcases dense ε0 with ⟨ε₁, ε₁0, εε₁⟩, let ε₂ := ε₁/2/2, /- We have to find a finite discretization of `u`, i.e., finite information that is sufficient to reconstruct `u` up to ε. This information will be provided by the values of `u` on a sufficiently dense set tα, slightly translated to fit in a finite ε₂-dense set tβ in the image. Such sets exist by compactness of the source and range. Then, to check that these data determine the function up to ε, one uses the control on the modulus of continuity to extend the closeness on tα to closeness everywhere. -/ have ε₂0 : ε₂ > 0 := half_pos (half_pos ε₁0), have : ∀x:α, ∃U, x ∈ U ∧ is_open U ∧ ∀ (y z ∈ U) {f : α →ᵇ β}, f ∈ A → dist (f y) (f z) < ε₂ := λ x, let ⟨U, nhdsU, hU⟩ := H x _ ε₂0, ⟨V, VU, openV, xV⟩ := mem_nhds_sets_iff.1 nhdsU in ⟨V, xV, openV, λy z hy hz f hf, hU y z (VU hy) (VU hz) f hf⟩, choose U hU using this, /- For all x, the set hU x is an open set containing x on which the elements of A fluctuate by at most ε₂. We extract finitely many of these sets that cover the whole space, by compactness -/ rcases compact_univ.elim_finite_subcover_image (λx _, (hU x).2.1) (λx hx, mem_bUnion (mem_univ _) (hU x).1) with ⟨tα, _, ⟨_⟩, htα⟩, /- tα : set α, htα : univ ⊆ ⋃x ∈ tα, U x -/ rcases @finite_cover_balls_of_compact β _ _ compact_univ _ ε₂0 with ⟨tβ, _, ⟨_⟩, htβ⟩, resetI, /- tβ : set β, htβ : univ ⊆ ⋃y ∈ tβ, ball y ε₂ -/ /- Associate to every point `y` in the space a nearby point `F y` in tβ -/ choose F hF using λy, show ∃z∈tβ, dist y z < ε₂, by simpa using htβ (mem_univ y), /- F : β → β, hF : ∀ (y : β), F y ∈ tβ ∧ dist y (F y) < ε₂ -/ /- Associate to every function a discrete approximation, mapping each point in `tα` to a point in `tβ` close to its true image by the function. -/ refine ⟨tα → tβ, by apply_instance, λ f a, ⟨F (f a), (hF (f a)).1⟩, _⟩, rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g, /- If two functions have the same approximation, then they are within distance ε -/ refine lt_of_le_of_lt ((dist_le $ le_of_lt ε₁0).2 (λ x, _)) εε₁, obtain ⟨x', x'tα, hx'⟩ : ∃x' ∈ tα, x ∈ U x' := mem_bUnion_iff.1 (htα (mem_univ x)), refine calc dist (f x) (g x) ≤ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _ ... ≤ ε₂ + ε₂ + ε₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _) ... = ε₁ : by rw [add_halves, add_halves], { exact (hU x').2.2 _ _ hx' ((hU x').1) hf }, { exact (hU x').2.2 _ _ hx' ((hU x').1) hg }, { have F_f_g : F (f x') = F (g x') := (congr_arg (λ f:tα → tβ, (f ⟨x', x'tα⟩ : β)) f_eq_g : _), calc dist (f x') (g x') ≤ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _ ... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g ... < ε₂ + ε₂ : add_lt_add (hF (f x')).2 (hF (g x')).2 ... = ε₁/2 : add_halves _ } end /-- Second version, with pointwise equicontinuity and range in a compact subset -/ theorem arzela_ascoli₂ (s : set β) (hs : compact s) (A : set (α →ᵇ β)) (closed : is_closed A) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact A := /- This version is deduced from the previous one by restricting to the compact type in the target, using compactness there and then lifting everything to the original space. -/ begin have M : lipschitz_with 1 coe := lipschitz_with.subtype_coe s, let F : (α →ᵇ s) → α →ᵇ β := comp coe M, refine compact_of_is_closed_subset ((_ : compact (F ⁻¹' A)).image (continuous_comp M)) closed (λ f hf, _), { haveI : compact_space s := compact_iff_compact_space.1 hs, refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed) (λ x ε ε0, bex.imp_right (λ U U_nhds hU y z hy hz f hf, _) (H x ε ε0)), calc dist (f y) (f z) = dist (F f y) (F f z) : rfl ... < ε : hU y z hy hz (F f) hf }, { let g := cod_restrict s f (λx, in_s f x hf), rw [show f = F g, by ext; refl] at hf ⊢, exact ⟨g, hf, rfl⟩ } end /-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but without closedness. The closure is then compact -/ theorem arzela_ascoli (s : set β) (hs : compact s) (A : set (α →ᵇ β)) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact (closure A) := /- This version is deduced from the previous one by checking that the closure of A, in addition to being closed, still satisfies the properties of compact range and equicontinuity -/ arzela_ascoli₂ s hs (closure A) is_closed_closure (λ f x hf, (mem_of_closed' (closed_of_compact _ hs)).2 $ λ ε ε0, let ⟨g, gA, dist_fg⟩ := metric.mem_closure_iff.1 hf ε ε0 in ⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩) (λ x ε ε0, show ∃ U ∈ 𝓝 x, ∀ y z ∈ U, ∀ (f : α →ᵇ β), f ∈ closure A → dist (f y) (f z) < ε, begin refine bex.imp_right (λ U U_set hU y z hy hz f hf, _) (H x (ε/2) (half_pos ε0)), rcases metric.mem_closure_iff.1 hf (ε/2/2) (half_pos (half_pos ε0)) with ⟨g, gA, dist_fg⟩, replace dist_fg := λ x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg, calc dist (f y) (f z) ≤ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) : dist_triangle4_right _ _ _ _ ... < ε/2/2 + ε/2/2 + ε/2 : add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y z hy hz g gA) ... = ε : by rw [add_halves, add_halves] end) /- To apply the previous theorems, one needs to check the equicontinuity. An important instance is when the source space is a metric space, and there is a fixed modulus of continuity for all the functions in the set A -/ lemma equicontinuous_of_continuity_modulus {α : Type u} [metric_space α] (b : ℝ → ℝ) (b_lim : tendsto b (𝓝 0) (𝓝 0)) (A : set (α →ᵇ β)) (H : ∀(x y:α) (f : α →ᵇ β), f ∈ A → dist (f x) (f y) ≤ b (dist x y)) (x:α) (ε : ℝ) (ε0 : ε > 0) : ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε := begin rcases tendsto_nhds_nhds.1 b_lim ε ε0 with ⟨δ, δ0, hδ⟩, refine ⟨ball x (δ/2), ball_mem_nhds x (half_pos δ0), λ y z hy hz f hf, _⟩, have : dist y z < δ := calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... < δ/2 + δ/2 : add_lt_add hy hz ... = δ : add_halves _, calc dist (f y) (f z) ≤ b (dist y z) : H y z f hf ... ≤ abs (b (dist y z)) : le_abs_self _ ... = dist (b (dist y z)) 0 : by simp [real.dist_eq] ... < ε : hδ (by simpa [real.dist_eq] using this), end end arzela_ascoli section normed_group /- In this section, if β is a normed group, then we show that the space of bounded continuous functions from α to β inherits a normed group structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space α] [normed_group β] variables (f g : α →ᵇ β) {x : α} {C : ℝ} instance : has_zero (α →ᵇ β) := ⟨const α 0⟩ @[simp] lemma coe_zero : (0 : α →ᵇ β) x = 0 := rfl instance : has_norm (α →ᵇ β) := ⟨λu, dist u 0⟩ lemma norm_def : ∥f∥ = dist f 0 := rfl /-- The norm of a bounded continuous function is the supremum of `∥f x∥`. We use `Inf` to ensure that the definition works if `α` has no elements. -/ lemma norm_eq (f : α →ᵇ β) : ∥f∥ = Inf {C : ℝ | 0 ≤ C ∧ ∀ (x : α), ∥f x∥ ≤ C} := by simp [norm_def, bounded_continuous_function.dist_eq] lemma norm_coe_le_norm (x : α) : ∥f x∥ ≤ ∥f∥ := calc ∥f x∥ = dist (f x) ((0 : α →ᵇ β) x) : by simp [dist_zero_right] ... ≤ ∥f∥ : dist_coe_le_dist _ lemma dist_le_two_norm' {f : γ → β} {C : ℝ} (hC : ∀ x, ∥f x∥ ≤ C) (x y : γ) : dist (f x) (f y) ≤ 2 * C := calc dist (f x) (f y) ≤ ∥f x∥ + ∥f y∥ : dist_le_norm_add_norm _ _ ... ≤ C + C : add_le_add (hC x) (hC y) ... = 2 * C : (two_mul _).symm /-- Distance between the images of any two points is at most twice the norm of the function. -/ lemma dist_le_two_norm (x y : α) : dist (f x) (f y) ≤ 2 * ∥f∥ := dist_le_two_norm' f.norm_coe_le_norm x y variable {f} /-- The norm of a function is controlled by the supremum of the pointwise norms -/ lemma norm_le (C0 : (0 : ℝ) ≤ C) : ∥f∥ ≤ C ↔ ∀x:α, ∥f x∥ ≤ C := by simpa only [coe_zero, dist_zero_right] using @dist_le _ _ _ _ f 0 _ C0 variable (f) /-- Norm of `const α b` is less than or equal to `∥b∥`. If `α` is nonempty, then it is equal to `∥b∥`. -/ lemma norm_const_le (b : β) : ∥const α b∥ ≤ ∥b∥ := (norm_le (norm_nonneg b)).2 $ λ x, le_refl _ @[simp] lemma norm_const_eq [h : nonempty α] (b : β) : ∥const α b∥ = ∥b∥ := le_antisymm (norm_const_le b) $ h.elim $ λ x, (const α b).norm_coe_le_norm x /-- Constructing a bounded continuous function from a uniformly bounded continuous function taking values in a normed group. -/ def of_normed_group {α : Type u} {β : Type v} [topological_space α] [normed_group β] (f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) : α →ᵇ β := ⟨λn, f n, ⟨Hf, ⟨_, dist_le_two_norm' H⟩⟩⟩ lemma norm_of_normed_group_le {f : α → β} (hfc : continuous f) {C : ℝ} (hC : 0 ≤ C) (hfC : ∀ x, ∥f x∥ ≤ C) : ∥of_normed_group f hfc C hfC∥ ≤ C := (norm_le hC).2 hfC /-- Constructing a bounded continuous function from a uniformly bounded function on a discrete space, taking values in a normed group -/ def of_normed_group_discrete {α : Type u} {β : Type v} [topological_space α] [discrete_topology α] [normed_group β] (f : α → β) (C : ℝ) (H : ∀x, norm (f x) ≤ C) : α →ᵇ β := of_normed_group f continuous_of_discrete_topology C H /-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/ instance : has_add (α →ᵇ β) := ⟨λf g, of_normed_group (f + g) (f.2.1.add g.2.1) (∥f∥ + ∥g∥) $ λ x, le_trans (norm_add_le _ _) (add_le_add (f.norm_coe_le_norm x) (g.norm_coe_le_norm x))⟩ /-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/ instance : has_neg (α →ᵇ β) := ⟨λf, of_normed_group (-f) f.2.1.neg ∥f∥ $ λ x, trans_rel_right _ (norm_neg _) (f.norm_coe_le_norm x)⟩ @[simp] lemma coe_add : ⇑(f + g) = λ x, f x + g x := rfl lemma add_apply : (f + g) x = f x + g x := rfl @[simp] lemma coe_neg : ⇑(-f) = λ x, - f x := rfl lemma neg_apply : (-f) x = -f x := rfl lemma forall_coe_zero_iff_zero : (∀x, f x = 0) ↔ f = 0 := (@ext_iff _ _ _ _ f 0).symm instance : add_comm_group (α →ᵇ β) := { add_assoc := assume f g h, by ext; simp [add_assoc], zero_add := assume f, by ext; simp, add_zero := assume f, by ext; simp, add_left_neg := assume f, by ext; simp, add_comm := assume f g, by ext; simp [add_comm], ..bounded_continuous_function.has_add, ..bounded_continuous_function.has_neg, ..bounded_continuous_function.has_zero } @[simp] lemma coe_sub : ⇑(f - g) = λ x, f x - g x := rfl lemma sub_apply : (f - g) x = f x - g x := rfl instance : normed_group (α →ᵇ β) := { dist_eq := λ f g, by simp only [norm_eq, dist_eq, dist_eq_norm, sub_apply] } lemma abs_diff_coe_le_dist : ∥f x - g x∥ ≤ dist f g := by { rw dist_eq_norm, exact (f - g).norm_coe_le_norm x } lemma coe_le_coe_add_dist {f g : α →ᵇ ℝ} : f x ≤ g x + dist f g := sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2 end normed_group section normed_space /-! ### Normed space structure In this section, if `β` is a normed space, then we show that the space of bounded continuous functions from `α` to `β` inherits a normed space structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables {𝕜 : Type*} [normed_field 𝕜] variables [topological_space α] [normed_group β] [normed_space 𝕜 β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance : has_scalar 𝕜 (α →ᵇ β) := ⟨λ c f, of_normed_group (c • f) (continuous_const.smul f.2.1) (∥c∥ * ∥f∥) $ λ x, trans_rel_right _ (norm_smul _ _) (mul_le_mul_of_nonneg_left (f.norm_coe_le_norm _) (norm_nonneg _))⟩ @[simp] lemma coe_smul (c : 𝕜) (f : α →ᵇ β) : ⇑(c • f) = λ x, c • (f x) := rfl lemma smul_apply (c : 𝕜) (f : α →ᵇ β) (x : α) : (c • f) x = c • f x := rfl instance : semimodule 𝕜 (α →ᵇ β) := semimodule.of_core $ { smul := (•), smul_add := λ c f g, ext $ λ x, smul_add c (f x) (g x), add_smul := λ c₁ c₂ f, ext $ λ x, add_smul c₁ c₂ (f x), mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul c₁ c₂ (f x), one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) } instance : normed_space 𝕜 (α →ᵇ β) := ⟨λ c f, norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _⟩ end normed_space section normed_ring /-! ### Normed ring structure In this section, if `R` is a normed ring, then we show that the space of bounded continuous functions from `α` to `R` inherits a normed ring structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space α] {R : Type*} [normed_ring R] instance : ring (α →ᵇ R) := { one := const α 1, mul := λ f g, of_normed_group (f * g) (f.2.1.mul g.2.1) (∥f∥ * ∥g∥) $ λ x, le_trans (normed_ring.norm_mul (f x) (g x)) $ mul_le_mul (f.norm_coe_le_norm x) (g.norm_coe_le_norm x) (norm_nonneg _) (norm_nonneg _), one_mul := λ f, ext $ λ x, one_mul (f x), mul_one := λ f, ext $ λ x, mul_one (f x), mul_assoc := λ f₁ f₂ f₃, ext $ λ x, mul_assoc _ _ _, left_distrib := λ f₁ f₂ f₃, ext $ λ x, left_distrib _ _ _, right_distrib := λ f₁ f₂ f₃, ext $ λ x, right_distrib _ _ _, .. bounded_continuous_function.add_comm_group } instance : normed_ring (α →ᵇ R) := { norm_mul := λ f g, norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _, .. bounded_continuous_function.normed_group } end normed_ring section normed_algebra /-! ### Normed algebra structure In this section, if `γ` is a normed algebra, then we show that the space of bounded continuous functions from `α` to `γ` inherits a normed algebra structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables {𝕜 : Type*} [normed_field 𝕜] variables [topological_space α] [normed_group β] [normed_space 𝕜 β] variables [normed_ring γ] [normed_algebra 𝕜 γ] variables {f g : α →ᵇ γ} {x : α} {c : 𝕜} /-- `bounded_continuous_function.const` as a `ring_hom`. -/ def C : 𝕜 →+* (α →ᵇ γ) := { to_fun := λ (c : 𝕜), const α ((algebra_map 𝕜 γ) c), map_one' := ext $ λ x, (algebra_map 𝕜 γ).map_one, map_mul' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_mul _ _, map_zero' := ext $ λ x, (algebra_map 𝕜 γ).map_zero, map_add' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_add _ _ } instance : algebra 𝕜 (α →ᵇ γ) := { to_ring_hom := C, commutes' := λ c f, ext $ λ x, algebra.commutes' _ _, smul_def' := λ c f, ext $ λ x, algebra.smul_def' _ _, ..bounded_continuous_function.semimodule, ..bounded_continuous_function.ring } instance [nonempty α] : normed_algebra 𝕜 (α →ᵇ γ) := { norm_algebra_map_eq := λ c, begin calc ∥ (algebra_map 𝕜 (α →ᵇ γ)).to_fun c∥ = ∥(algebra_map 𝕜 γ) c∥ : _ ... = ∥c∥ : norm_algebra_map_eq _ _, apply norm_const_eq ((algebra_map 𝕜 γ) c), assumption, end, ..bounded_continuous_function.algebra } /-! ### Structure as normed module over scalar functions If `β` is a normed `𝕜`-space, then we show that the space of bounded continuous functions from `α` to `β` is naturally a module over the algebra of bounded continuous functions from `α` to `𝕜`. -/ instance has_scalar' : has_scalar (α →ᵇ 𝕜) (α →ᵇ β) := ⟨λ (f : α →ᵇ 𝕜) (g : α →ᵇ β), of_normed_group (λ x, (f x) • (g x)) (continuous.smul f.2.1 g.2.1) (∥f∥ * ∥g∥) (λ x, calc ∥f x • g x∥ ≤ ∥f x∥ * ∥g x∥ : normed_space.norm_smul_le _ _ ... ≤ ∥f∥ * ∥g∥ : mul_le_mul (f.norm_coe_le_norm _) (g.norm_coe_le_norm _) (norm_nonneg _) (norm_nonneg _)) ⟩ instance module' : module (α →ᵇ 𝕜) (α →ᵇ β) := semimodule.of_core $ { smul := (•), smul_add := λ c f₁ f₂, ext $ λ x, smul_add _ _ _, add_smul := λ c₁ c₂ f, ext $ λ x, add_smul _ _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) } lemma norm_smul_le (f : α →ᵇ 𝕜) (g : α →ᵇ β) : ∥f • g∥ ≤ ∥f∥ * ∥g∥ := norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _ /- TODO: When `normed_module` has been added to `normed_space.basic`, the above facts show that the space of bounded continuous functions from `α` to `β` is naturally a normed module over the algebra of bounded continuous functions from `α` to `𝕜`. -/ end normed_algebra end bounded_continuous_function
24b7f2b0a5b00f18e78565d7a06bb2e562b69c70
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/convex/specific_functions_auto.lean
360ab0f35f8fabc0c71200483cd17a55673dae64
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,398
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.calculus.mean_value import Mathlib.data.nat.parity import Mathlib.analysis.special_functions.pow import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Collection of convex functions In this file we prove that the following functions are convex: * `convex_on_exp` : the exponential function is convex on $(-∞, +∞)$; * `convex_on_pow_of_even` : given an even natural number $n$, the function $f(x)=x^n$ is convex on $(-∞, +∞)$; * `convex_on_pow` : for a natural $n$, the function $f(x)=x^n$ is convex on $[0, +∞)$; * `convex_on_fpow` : for an integer $m$, the function $f(x)=x^m$ is convex on $(0, +∞)$. * `convex_on_rpow : ∀ p : ℝ, 1 ≤ p → convex_on (Ici 0) (λ x, x ^ p)` * `concave_on_log_Ioi` and `concave_on_log_Iio`: log is concave on `Ioi 0` and `Iio 0` respectively. -/ /-- `exp` is convex on the whole real line -/ theorem convex_on_exp : convex_on set.univ real.exp := sorry /-- `x^n`, `n : ℕ` is convex on the whole real line whenever `n` is even -/ theorem convex_on_pow_of_even {n : ℕ} (hn : even n) : convex_on set.univ fun (x : ℝ) => x ^ n := sorry /-- `x^n`, `n : ℕ` is convex on `[0, +∞)` for all `n` -/ theorem convex_on_pow (n : ℕ) : convex_on (set.Ici 0) fun (x : ℝ) => x ^ n := sorry theorem finset.prod_nonneg_of_card_nonpos_even {α : Type u_1} {β : Type u_2} [linear_ordered_comm_ring β] {f : α → β} [decidable_pred fun (x : α) => f x ≤ 0] {s : finset α} (h0 : even (finset.card (finset.filter (fun (x : α) => f x ≤ 0) s))) : 0 ≤ finset.prod s fun (x : α) => f x := sorry theorem int_prod_range_nonneg (m : ℤ) (n : ℕ) (hn : even n) : 0 ≤ finset.prod (finset.range n) fun (k : ℕ) => m - ↑k := sorry /-- `x^m`, `m : ℤ` is convex on `(0, +∞)` for all `m` -/ theorem convex_on_fpow (m : ℤ) : convex_on (set.Ioi 0) fun (x : ℝ) => x ^ m := sorry theorem convex_on_rpow {p : ℝ} (hp : 1 ≤ p) : convex_on (set.Ici 0) fun (x : ℝ) => x ^ p := sorry theorem concave_on_log_Ioi : concave_on (set.Ioi 0) real.log := sorry theorem concave_on_log_Iio : concave_on (set.Iio 0) real.log := sorry end Mathlib
192a8883bcdd4e9f0fb73385e6761f280651ed42
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/polynomial/eval.lean
66ed647c6893be1c086766fb49b8518d35f51e25
[ "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
26,440
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.induction import data.polynomial.degree.definitions /-! # Theory of univariate polynomials The main defs here are `eval₂`, `eval`, and `map`. We give several lemmas about their interaction with each other and with module operations. -/ noncomputable theory open finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v w y variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : polynomial R} section variables [semiring S] variables (f : R →+* S) (x : S) /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial R) : S := p.sum (λ e a, f a * x ^ e) lemma eval₂_eq_sum {f : R →+* S} {x : S} : p.eval₂ f x = p.sum (λ e a, f a * x ^ e) := rfl lemma eval₂_congr {R S : Type*} [semiring R] [semiring S] {f g : R →+* S} {s t : S} {φ ψ : polynomial R} : f = g → s = t → φ = ψ → eval₂ f s φ = eval₂ g t ψ := by rintro rfl rfl rfl; refl @[simp] lemma eval₂_at_zero : p.eval₂ f 0 = f (coeff p 0) := by simp only [eval₂_eq_sum, zero_pow_eq, mul_ite, mul_zero, mul_one, sum, not_not, mem_support_iff, sum_ite_eq', ite_eq_left_iff, ring_hom.map_zero, implies_true_iff, eq_self_iff_true] {contextual := tt} @[simp] lemma eval₂_zero : (0 : polynomial R).eval₂ f x = 0 := by simp [eval₂_eq_sum] @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := by simp [eval₂_eq_sum] @[simp] lemma eval₂_X : X.eval₂ f x = x := by simp [eval₂_eq_sum] @[simp] lemma eval₂_monomial {n : ℕ} {r : R} : (monomial n r).eval₂ f x = (f r) * x^n := by simp [eval₂_eq_sum] @[simp] lemma eval₂_X_pow {n : ℕ} : (X^n).eval₂ f x = x^n := begin rw X_pow_eq_monomial, convert eval₂_monomial f x, simp, end @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := by { apply sum_add_index; simp [add_mul] } @[simp] lemma eval₂_one : (1 : polynomial R).eval₂ f x = 1 := by rw [← C_1, eval₂_C, f.map_one] @[simp] lemma eval₂_bit0 : (bit0 p).eval₂ f x = bit0 (p.eval₂ f x) := by rw [bit0, eval₂_add, bit0] @[simp] lemma eval₂_bit1 : (bit1 p).eval₂ f x = bit1 (p.eval₂ f x) := by rw [bit1, eval₂_add, eval₂_bit0, eval₂_one, bit1] @[simp] lemma eval₂_smul (g : R →+* S) (p : polynomial R) (x : S) {s : R} : eval₂ g x (s • p) = g s * eval₂ g x p := begin have A : p.nat_degree < p.nat_degree.succ := nat.lt_succ_self _, have B : (s • p).nat_degree < p.nat_degree.succ := (nat_degree_smul_le _ _).trans_lt A, rw [eval₂_eq_sum, eval₂_eq_sum, sum_over_range' _ _ _ A, sum_over_range' _ _ _ B]; simp [mul_sum, mul_assoc], end @[simp] lemma eval₂_C_X : eval₂ C X p = p := polynomial.induction_on' p (λ p q hp hq, by simp [hp, hq]) (λ n x, by rw [eval₂_monomial, monomial_eq_smul_X, C_mul']) /-- `eval₂_add_monoid_hom (f : R →+* S) (x : S)` is the `add_monoid_hom` from `polynomial R` to `S` obtained by evaluating the pushforward of `p` along `f` at `x`. -/ @[simps] def eval₂_add_monoid_hom : polynomial R →+ S := { to_fun := eval₂ f x, map_zero' := eval₂_zero _ _, map_add' := λ _ _, eval₂_add _ _ } @[simp] lemma eval₂_nat_cast (n : ℕ) : (n : polynomial R).eval₂ f x = n := begin induction n with n ih, { simp only [eval₂_zero, nat.cast_zero] }, { rw [n.cast_succ, eval₂_add, ih, eval₂_one, n.cast_succ] } end variables [semiring T] lemma eval₂_sum (p : polynomial T) (g : ℕ → T → polynomial R) (x : S) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := begin let T : polynomial R →+ S := { to_fun := eval₂ f x, map_zero' := eval₂_zero _ _, map_add' := λ p q, eval₂_add _ _ }, have A : ∀ y, eval₂ f x y = T y := λ y, rfl, simp only [A], rw [sum, T.map_sum, sum] end lemma eval₂_finset_sum (s : finset ι) (g : ι → polynomial R) (x : S) : (∑ i in s, g i).eval₂ f x = ∑ i in s, (g i).eval₂ f x := begin classical, induction s using finset.induction with p hp s hs, simp, rw [sum_insert, eval₂_add, hs, sum_insert]; assumption, end lemma eval₂_to_finsupp_eq_lift_nc {f : R →+* S} {x : S} {p : add_monoid_algebra R ℕ} : eval₂ f x (⟨p⟩ : polynomial R) = lift_nc ↑f (powers_hom S x) p := by { simp only [eval₂_eq_sum, sum, sum_to_finsupp, support, coeff], refl } lemma eval₂_mul_noncomm (hf : ∀ k, commute (f $ q.coeff k) x) : eval₂ f x (p * q) = eval₂ f x p * eval₂ f x q := begin rcases p, rcases q, simp only [coeff] at hf, simp only [mul_to_finsupp, eval₂_to_finsupp_eq_lift_nc], exact lift_nc_mul _ _ p q (λ k n hn, (hf k).pow_right n) end @[simp] lemma eval₂_mul_X : eval₂ f x (p * X) = eval₂ f x p * x := begin refine trans (eval₂_mul_noncomm _ _ $ λ k, _) (by rw eval₂_X), rcases em (k = 1) with (rfl|hk), { simp }, { simp [coeff_X_of_ne_one hk] } end @[simp] lemma eval₂_X_mul : eval₂ f x (X * p) = eval₂ f x p * x := by rw [X_mul, eval₂_mul_X] lemma eval₂_mul_C' (h : commute (f a) x) : eval₂ f x (p * C a) = eval₂ f x p * f a := begin rw [eval₂_mul_noncomm, eval₂_C], intro k, by_cases hk : k = 0, { simp only [hk, h, coeff_C_zero, coeff_C_ne_zero] }, { simp only [coeff_C_ne_zero hk, ring_hom.map_zero, commute.zero_left] } end lemma eval₂_list_prod_noncomm (ps : list (polynomial R)) (hf : ∀ (p ∈ ps) k, commute (f $ coeff p k) x) : eval₂ f x ps.prod = (ps.map (polynomial.eval₂ f x)).prod := begin induction ps using list.reverse_rec_on with ps p ihp, { simp }, { simp only [list.forall_mem_append, list.forall_mem_singleton] at hf, simp [eval₂_mul_noncomm _ _ hf.2, ihp hf.1] } end /-- `eval₂` as a `ring_hom` for noncommutative rings -/ def eval₂_ring_hom' (f : R →+* S) (x : S) (hf : ∀ a, commute (f a) x) : polynomial R →+* S := { to_fun := eval₂ f x, map_add' := λ _ _, eval₂_add _ _, map_zero' := eval₂_zero _ _, map_mul' := λ p q, eval₂_mul_noncomm f x (λ k, hf $ coeff q k), map_one' := eval₂_one _ _ } end /-! We next prove that eval₂ is multiplicative as long as target ring is commutative (even if the source ring is not). -/ section eval₂ variables [comm_semiring S] variables (f : R →+* S) (x : S) @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := eval₂_mul_noncomm _ _ $ λ k, commute.all _ _ lemma eval₂_mul_eq_zero_of_left (q : polynomial R) (hp : p.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_left hp (q.eval₂ f x) end lemma eval₂_mul_eq_zero_of_right (p : polynomial R) (hq : q.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_right (p.eval₂ f x) hq end /-- `eval₂` as a `ring_hom` -/ def eval₂_ring_hom (f : R →+* S) (x : S) : polynomial R →+* S := { map_one' := eval₂_one _ _, map_mul' := λ _ _, eval₂_mul _ _, ..eval₂_add_monoid_hom f x } @[simp] lemma coe_eval₂_ring_hom (f : R →+* S) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := (eval₂_ring_hom _ _).map_pow _ _ lemma eval₂_eq_sum_range : p.eval₂ f x = ∑ i in finset.range (p.nat_degree + 1), f (p.coeff i) * x^i := trans (congr_arg _ p.as_sum_range) (trans (eval₂_finset_sum f _ _ x) (congr_arg _ (by simp))) lemma eval₂_eq_sum_range' (f : R →+* S) {p : polynomial R} {n : ℕ} (hn : p.nat_degree < n) (x : S) : eval₂ f x p = ∑ i in finset.range n, f (p.coeff i) * x ^ i := begin rw [eval₂_eq_sum, p.sum_over_range' _ _ hn], intro i, rw [f.map_zero, zero_mul] end end eval₂ section eval variables {x : R} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : R → polynomial R → R := eval₂ (ring_hom.id _) lemma eval_eq_sum : p.eval x = p.sum (λ e a, a * x ^ e) := rfl lemma eval_eq_finset_sum (p : polynomial R) (x : R) : p.eval x = ∑ i in range (p.nat_degree + 1), p.coeff i * x ^ i := by { rw [eval_eq_sum, sum_over_range], simp } lemma eval_eq_finset_sum' (P : polynomial R) : (λ x, eval x P) = (λ x, ∑ i in range (P.nat_degree + 1), P.coeff i * x ^ i) := begin ext, exact P.eval_eq_finset_sum x end @[simp] lemma eval₂_at_apply {S : Type*} [semiring S] (f : R →+* S) (r : R) : p.eval₂ f (f r) = f (p.eval r) := begin rw [eval₂_eq_sum, eval_eq_sum, sum, sum, f.map_sum], simp only [f.map_mul, f.map_pow], end @[simp] lemma eval₂_at_one {S : Type*} [semiring S] (f : R →+* S) : p.eval₂ f 1 = f (p.eval 1) := begin convert eval₂_at_apply f 1, simp, end @[simp] lemma eval₂_at_nat_cast {S : Type*} [semiring S] (f : R →+* S) (n : ℕ) : p.eval₂ f n = f (p.eval n) := begin convert eval₂_at_apply f n, simp, end @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_nat_cast {n : ℕ} : (n : polynomial R).eval x = n := by simp only [←C_eq_nat_cast, eval_C] @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_monomial {n a} : (monomial n a).eval x = a * x^n := eval₂_monomial _ _ @[simp] lemma eval_zero : (0 : polynomial R).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial R).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_bit0 : (bit0 p).eval x = bit0 (p.eval x) := eval₂_bit0 _ _ @[simp] lemma eval_bit1 : (bit1 p).eval x = bit1 (p.eval x) := eval₂_bit1 _ _ @[simp] lemma eval_smul (p : polynomial R) (x : R) {s : R} : (s • p).eval x = s * p.eval x := eval₂_smul (ring_hom.id _) _ _ @[simp] lemma eval_C_mul : (C a * p).eval x = a * p.eval x := begin apply polynomial.induction_on' p, { intros p q ph qh, simp only [mul_add, eval_add, ph, qh], }, { intros n b, simp [mul_assoc], } end @[simp] lemma eval_nat_cast_mul {n : ℕ} : ((n : polynomial R) * p).eval x = n * p.eval x := by rw [←C_eq_nat_cast, eval_C_mul] @[simp] lemma eval_mul_X : (p * X).eval x = p.eval x * x := begin apply polynomial.induction_on' p, { intros p q ph qh, simp only [add_mul, eval_add, ph, qh], }, { intros n a, simp only [←monomial_one_one_eq_X, monomial_mul_monomial, eval_monomial, mul_one, pow_succ', mul_assoc], } end @[simp] lemma eval_mul_X_pow {k : ℕ} : (p * X^k).eval x = p.eval x * x^k := begin induction k with k ih, { simp, }, { simp [pow_succ', ←mul_assoc, ih], } end lemma eval_sum (p : polynomial R) (f : ℕ → R → polynomial R) (x : R) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval_finset_sum (s : finset ι) (g : ι → polynomial R) (x : R) : (∑ i in s, g i).eval x = ∑ i in s, (g i).eval x := eval₂_finset_sum _ _ _ _ /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial R) (a : R) : Prop := p.eval a = 0 instance [decidable_eq R] : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma coeff_zero_eq_eval_zero (p : polynomial R) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) lemma zero_is_root_of_coeff_zero_eq_zero {p : polynomial R} (hp : p.coeff 0 = 0) : is_root p 0 := by rwa coeff_zero_eq_eval_zero at hp end eval section comp /-- The composition of polynomials as a polynomial. -/ def comp (p q : polynomial R) : polynomial R := p.eval₂ C q lemma comp_eq_sum_left : p.comp q = p.sum (λ e a, C a * q ^ e) := rfl @[simp] lemma comp_X : p.comp X = p := begin simp only [comp, eval₂, ← monomial_eq_C_mul_X], exact sum_monomial_eq _, end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := by simp [comp, (C : R →+* _).map_sum] @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma nat_cast_comp {n : ℕ} : (n : polynomial R).comp p = n := by rw [←C_eq_nat_cast, C_comp] @[simp] lemma comp_zero : p.comp (0 : polynomial R) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : polynomial R) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : polynomial R) p = 1 := by rw [← C_1, C_comp] @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma monomial_comp (n : ℕ) : (monomial n a).comp p = C a * p^n := eval₂_monomial _ _ @[simp] lemma mul_X_comp : (p * X).comp r = p.comp r * r := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq, add_mul], }, { intros n b, simp [pow_succ', mul_assoc], } end @[simp] lemma X_pow_comp {k : ℕ} : (X^k).comp p = p^k := begin induction k with k ih, { simp, }, { simp [pow_succ', mul_X_comp, ih], }, end @[simp] lemma mul_X_pow_comp {k : ℕ} : (p * X^k).comp r = p.comp r * r^k := begin induction k with k ih, { simp, }, { simp [ih, pow_succ', ←mul_assoc, mul_X_comp], }, end @[simp] lemma C_mul_comp : (C a * p).comp r = C a * p.comp r := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq, mul_add], }, { intros n b, simp [mul_assoc], } end @[simp] lemma nat_cast_mul_comp {n : ℕ} : ((n : polynomial R) * p).comp r = n * p.comp r := by rw [←C_eq_nat_cast, C_mul_comp, C_eq_nat_cast] @[simp] lemma mul_comp {R : Type*} [comm_semiring R] (p q r : polynomial R) : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ lemma prod_comp {R : Type*} [comm_semiring R] (s : multiset (polynomial R)) (p : polynomial R) : s.prod.comp p = (s.map (λ q : polynomial R, q.comp p)).prod := (s.prod_hom (monoid_hom.mk (λ q : polynomial R, q.comp p) one_comp (λ q r, mul_comp q r p))).symm @[simp] lemma pow_comp {R : Type*} [comm_semiring R] (p q : polynomial R) (n : ℕ) : (p^n).comp q = (p.comp q)^n := ((monoid_hom.mk (λ r : polynomial R, r.comp q)) one_comp (λ r s, mul_comp r s q)).map_pow p n @[simp] lemma bit0_comp : comp (bit0 p : polynomial R) q = bit0 (p.comp q) := by simp only [bit0, add_comp] @[simp] lemma bit1_comp : comp (bit1 p : polynomial R) q = bit1 (p.comp q) := by simp only [bit1, add_comp, bit0_comp, one_comp] lemma comp_assoc {R : Type*} [comm_semiring R] (φ ψ χ : polynomial R) : (φ.comp ψ).comp χ = φ.comp (ψ.comp χ) := begin apply polynomial.induction_on φ; { intros, simp only [add_comp, mul_comp, C_comp, X_comp, pow_succ', ← mul_assoc, *] at * } end end comp section map variables [semiring S] variables (f : R →+* S) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial R → polynomial S := eval₂ (C.comp f) X @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_monomial {n a} : (monomial n a).map f = monomial n (f a) := begin dsimp only [map], rw [eval₂_monomial, monomial_eq_C_mul_X], refl, end @[simp] lemma map_zero : (0 : polynomial R).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial R).map f = 1 := eval₂_one _ _ @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := by { rw [map, eval₂_mul_noncomm], exact λ k, (commute_X _).symm } @[simp] lemma map_smul (r : R) : (r • p).map f = f r • p.map f := by rw [map, eval₂_smul, ring_hom.comp_apply, C_mul'] /-- `polynomial.map` as a `ring_hom` -/ def map_ring_hom (f : R →+* S) : polynomial R →+* polynomial S := { to_fun := polynomial.map f, map_add' := λ _ _, map_add f, map_zero' := map_zero f, map_mul' := λ _ _, map_mul f, map_one' := map_one f } @[simp] lemma coe_map_ring_hom (f : R →+* S) : ⇑(map_ring_hom f) = map f := rfl @[simp] theorem map_nat_cast (n : ℕ) : (n : polynomial R).map f = n := (map_ring_hom f).map_nat_cast n @[simp] lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum, sum], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, sum, ring_hom.map_sum], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X, f.map_mul], split_ifs; simp [f.map_zero], end lemma map_map [semiring T] (g : S →+* T) (p : polynomial R) : (p.map f).map g = p.map (g.comp f) := ext (by simp [coeff_map]) @[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map] lemma eval₂_eq_eval_map {x : S} : p.eval₂ f x = (p.map f).eval x := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end lemma map_injective (hf : function.injective f) : function.injective (map f) := λ p q h, ext $ λ m, hf $ by rw [← coeff_map f, ← coeff_map f, h] lemma map_surjective (hf : function.surjective f) : function.surjective (map f) := λ p, polynomial.induction_on' p (λ p q hp hq, let ⟨p', hp'⟩ := hp, ⟨q', hq'⟩ := hq in ⟨p' + q', by rw [map_add f, hp', hq']⟩) (λ n s, let ⟨r, hr⟩ := hf s in ⟨monomial n r, by rw [map_monomial f, hr]⟩) lemma degree_map_le (p : polynomial R) : degree (p.map f) ≤ degree p := begin apply (degree_le_iff_coeff_zero _ _).2 (λ m hm, _), rw degree_lt_iff_coeff_zero at hm, simp [hm m (le_refl _)], end lemma nat_degree_map_le (p : polynomial R) : nat_degree (p.map f) ≤ nat_degree p := nat_degree_le_nat_degree (degree_map_le f p) variables {f} lemma map_monic_eq_zero_iff (hp : p.monic) : p.map f = 0 ↔ ∀ x, f x = 0 := ⟨ λ hfp x, calc f x = f x * f p.leading_coeff : by simp [hp] ... = f x * (p.map f).coeff p.nat_degree : by { congr, apply (coeff_map _ _).symm } ... = 0 : by simp [hfp], λ h, ext (λ n, by simp [h]) ⟩ lemma map_monic_ne_zero (hp : p.monic) [nontrivial S] : p.map f ≠ 0 := λ h, f.map_one_ne_zero ((map_monic_eq_zero_iff hp).mp h _) variables (f) @[simp] lemma map_ring_hom_id : map_ring_hom (ring_hom.id R) = ring_hom.id (polynomial R) := ring_hom.ext $ λ x, map_id @[simp] lemma map_ring_hom_comp [semiring T] (f : S →+* T) (g : R →+* S) : (map_ring_hom f).comp (map_ring_hom g) = map_ring_hom (f.comp g) := ring_hom.ext $ map_map g f lemma map_list_prod (L : list (polynomial R)) : L.prod.map f = (L.map $ map f).prod := eq.symm $ list.prod_hom _ (map_ring_hom f).to_monoid_hom @[simp] lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := (map_ring_hom f).map_pow _ _ lemma mem_map_srange {p : polynomial S} : p ∈ (map_ring_hom f).srange ↔ ∀ n, p.coeff n ∈ f.srange := begin split, { rintro ⟨p, rfl⟩ n, rw [coe_map_ring_hom, coeff_map], exact set.mem_range_self _ }, { intro h, rw p.as_sum_range_C_mul_X_pow, refine (map_ring_hom f).srange.sum_mem _, intros i hi, rcases h i with ⟨c, hc⟩, use [C c * X^i], rw [coe_map_ring_hom, map_mul, map_C, hc, map_pow, map_X] } end lemma mem_map_range {R S : Type*} [ring R] [ring S] (f : R →+* S) {p : polynomial S} : p ∈ (map_ring_hom f).range ↔ ∀ n, p.coeff n ∈ f.range := mem_map_srange f lemma eval₂_map [semiring T] (g : S →+* T) (x : T) : (p.map f).eval₂ g x = p.eval₂ (g.comp f) x := begin have A : nat_degree (p.map f) < p.nat_degree.succ := (nat_degree_map_le _ _).trans_lt (nat.lt_succ_self _), conv_lhs { rw [eval₂_eq_sum], }, rw [sum_over_range' _ _ _ A], { simp [coeff_map, eval₂_eq_sum, sum_over_range] }, { simp } end lemma eval_map (x : S) : (p.map f).eval x = p.eval₂ f x := eval₂_map f (ring_hom.id _) x lemma map_sum {ι : Type*} (g : ι → polynomial R) (s : finset ι) : (∑ i in s, g i).map f = ∑ i in s, (g i).map f := (map_ring_hom f).map_sum _ _ lemma map_comp (p q : polynomial R) : map f (p.comp q) = (map f p).comp (map f q) := polynomial.induction_on p (by simp) (by simp {contextual := tt}) (by simp [pow_succ', ← mul_assoc, polynomial.comp] {contextual := tt}) @[simp] lemma eval_zero_map (f : R →+* S) (p : polynomial R) : (p.map f).eval 0 = f (p.eval 0) := by simp [←coeff_zero_eq_eval_zero] @[simp] lemma eval_one_map (f : R →+* S) (p : polynomial R) : (p.map f).eval 1 = f (p.eval 1) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end @[simp] lemma eval_nat_cast_map (f : R →+* S) (p : polynomial R) (n : ℕ) : (p.map f).eval n = f (p.eval n) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end @[simp] lemma eval_int_cast_map {R S : Type*} [ring R] [ring S] (f : R →+* S) (p : polynomial R) (i : ℤ) : (p.map f).eval i = f (p.eval i) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end end map /-! After having set up the basic theory of `eval₂`, `eval`, `comp`, and `map`, we make `eval₂` irreducible. Perhaps we can make the others irreducible too? -/ attribute [irreducible] polynomial.eval₂ section hom_eval₂ -- TODO: Here we need commutativity in both `S` and `T`? variables [comm_semiring S] [comm_semiring T] variables (f : R →+* S) (g : S →+* T) (p) lemma hom_eval₂ (x : S) : g (p.eval₂ f x) = p.eval₂ (g.comp f) (g x) := begin apply polynomial.induction_on p; clear p, { intros a, rw [eval₂_C, eval₂_C], refl, }, { intros p q hp hq, simp only [hp, hq, eval₂_add, g.map_add] }, { intros n a ih, simp only [eval₂_mul, eval₂_C, eval₂_X_pow, g.map_mul, g.map_pow], refl, } end end hom_eval₂ end semiring section comm_semiring section eval variables [comm_semiring R] {p q : polynomial R} {x : R} lemma eval₂_comp [comm_semiring S] (f : R →+* S) {x : S} : eval₂ f x (p.comp q) = eval₂ f (eval₂ f x q) p := by rw [comp, p.as_sum_range]; simp [eval₂_finset_sum, eval₂_pow] @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ /-- `eval r`, regarded as a ring homomorphism from `polynomial R` to `R`. -/ def eval_ring_hom : R → polynomial R →+* R := eval₂_ring_hom (ring_hom.id _) @[simp] lemma coe_eval_ring_hom (r : R) : ((eval_ring_hom r) : polynomial R → R) = eval r := rfl @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ @[simp] lemma eval_comp : (p.comp q).eval x = p.eval (q.eval x) := begin apply polynomial.induction_on' p, { intros r s hr hs, simp [add_comp, hr, hs], }, { intros n a, simp, } end /-- `comp p`, regarded as a ring homomorphism from `polynomial R` to itself. -/ def comp_ring_hom : polynomial R → polynomial R →+* polynomial R := eval₂_ring_hom C lemma eval₂_hom [comm_semiring S] (f : R →+* S) (x : R) : p.eval₂ f (f x) = f (p.eval x) := (ring_hom.comp_id f) ▸ (hom_eval₂ p (ring_hom.id R) f x).symm lemma root_mul_left_of_is_root (p : polynomial R) {q : polynomial R} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial R} (q : polynomial R) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] /-- Polynomial evaluation commutes with finset.prod -/ lemma eval_prod {ι : Type*} (s : finset ι) (p : ι → polynomial R) (x : R) : eval x (∏ j in s, p j) = ∏ j in s, eval x (p j) := begin classical, apply finset.induction_on s, { simp only [finset.prod_empty, eval_one] }, { intros j s hj hpj, have h0 : ∏ i in insert j s, eval x (p i) = (eval x (p j)) * ∏ i in s, eval x (p i), { apply finset.prod_insert hj }, rw [h0, ← hpj, finset.prod_insert hj, eval_mul] }, end end eval section map variables [comm_semiring R] [comm_semiring S] (f : R →+* S) lemma map_multiset_prod (m : multiset (polynomial R)) : m.prod.map f = (m.map $ map f).prod := eq.symm $ multiset.prod_hom _ (map_ring_hom f).to_monoid_hom lemma map_prod {ι : Type*} (g : ι → polynomial R) (s : finset ι) : (∏ i in s, g i).map f = ∏ i in s, (g i).map f := (map_ring_hom f).map_prod _ _ lemma support_map_subset (p : polynomial R) : (map f p).support ⊆ p.support := begin intros x, simp only [mem_support_iff], contrapose!, change p.coeff x = 0 → (map f p).coeff x = 0, rw coeff_map, intro hx, rw hx, exact ring_hom.map_zero f, end end map end comm_semiring section ring variables [ring R] {p q r : polynomial R} lemma C_neg : C (-a) = -C a := ring_hom.map_neg C a lemma C_sub : C (a - b) = C a - C b := ring_hom.map_sub C a b @[simp] lemma map_sub {S} [ring S] (f : R →+* S) : (p - q).map f = p.map f - q.map f := (map_ring_hom f).map_sub p q @[simp] lemma map_neg {S} [ring S] (f : R →+* S) : (-p).map f = -(p.map f) := (map_ring_hom f).map_neg p @[simp] lemma map_int_cast {S} [ring S] (f : R →+* S) (n : ℤ) : map f ↑n = ↑n := (map_ring_hom f).map_int_cast n @[simp] lemma eval_int_cast {n : ℤ} {x : R} : (n : polynomial R).eval x = n := by simp only [←C_eq_int_cast, eval_C] @[simp] lemma eval₂_neg {S} [ring S] (f : R →+* S) {x : S} : (-p).eval₂ f x = -p.eval₂ f x := by rw [eq_neg_iff_add_eq_zero, ←eval₂_add, add_left_neg, eval₂_zero] @[simp] lemma eval₂_sub {S} [ring S] (f : R →+* S) {x : S} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := by rw [sub_eq_add_neg, eval₂_add, eval₂_neg, sub_eq_add_neg] @[simp] lemma eval_neg (p : polynomial R) (x : R) : (-p).eval x = -p.eval x := eval₂_neg _ @[simp] lemma eval_sub (p q : polynomial R) (x : R) : (p - q).eval x = p.eval x - q.eval x := eval₂_sub _ lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero, eq_comm] @[simp] lemma neg_comp : (-p).comp q = -p.comp q := eval₂_neg _ @[simp] lemma sub_comp : (p - q).comp r = p.comp r - q.comp r := eval₂_sub _ @[simp] lemma cast_int_comp (i : ℤ) : comp (i : polynomial R) p = i := by cases i; simp end ring end polynomial
eb7bb9cd0ef2b368bca678441751f04629b103bb
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/measure_theory/function/conditional_expectation/real.lean
6360daf577c2358de9a5f0e5b71b80e9f14d0293
[ "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
15,207
lean
/- Copyright (c) 2022 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Kexing Ying -/ import measure_theory.function.conditional_expectation.indicator /-! # Conditional expectation of real-valued functions This file proves some results regarding the conditional expectation of real-valued functions. ## Main results * `measure_theory.rn_deriv_ae_eq_condexp`: the conditional expectation `μ[f | m]` is equal to the Radon-Nikodym derivative of `fμ` restricted on `m` with respect to `μ` restricted on `m`. * `measure_theory.integrable.uniform_integrable_condexp`: the conditional expectation of a function form a uniformly integrable class. * `measure_theory.condexp_strongly_measurable_mul`: the pull-out property of the conditional expectation. -/ noncomputable theory open topological_space measure_theory.Lp filter continuous_linear_map open_locale nnreal ennreal topological_space big_operators measure_theory namespace measure_theory variables {α : Type*} {m m0 : measurable_space α} {μ : measure α} lemma rn_deriv_ae_eq_condexp {hm : m ≤ m0} [hμm : sigma_finite (μ.trim hm)] {f : α → ℝ} (hf : integrable f μ) : signed_measure.rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm) =ᵐ[μ] μ[f | m] := begin refine ae_eq_condexp_of_forall_set_integral_eq hm hf _ _ _, { exact λ _ _ _, (integrable_of_integrable_trim hm (signed_measure.integrable_rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm))).integrable_on }, { intros s hs hlt, conv_rhs { rw [← hf.with_densityᵥ_trim_eq_integral hm hs, ← signed_measure.with_densityᵥ_rn_deriv_eq ((μ.with_densityᵥ f).trim hm) (μ.trim hm) (hf.with_densityᵥ_trim_absolutely_continuous hm)], }, rw [with_densityᵥ_apply (signed_measure.integrable_rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm)) hs, ← set_integral_trim hm _ hs], exact (signed_measure.measurable_rn_deriv _ _).strongly_measurable }, { exact strongly_measurable.ae_strongly_measurable' (signed_measure.measurable_rn_deriv _ _).strongly_measurable }, end /-- TODO: this should be generalized and proved using Jensen's inequality for the conditional expectation (not in mathlib yet) .-/ lemma snorm_one_condexp_le_snorm (f : α → ℝ) : snorm (μ[f | m]) 1 μ ≤ snorm f 1 μ := begin by_cases hf : integrable f μ, swap, { rw [snorm_congr_ae (condexp_undef hf), snorm_zero], exact zero_le _ }, by_cases hm : m ≤ m0, swap, { rw [condexp_of_not_le hm, snorm_zero], exact zero_le _ }, by_cases hsig : sigma_finite (μ.trim hm), swap, { rw [condexp_of_not_sigma_finite hm hsig, snorm_zero], exact zero_le _ }, calc snorm (μ[f | m]) 1 μ ≤ snorm (μ[|f| | m]) 1 μ : begin refine snorm_mono_ae _, filter_upwards [@condexp_mono _ m m0 _ _ _ _ _ _ _ _ hf hf.abs (@ae_of_all _ m0 _ μ (λ x, le_abs_self (f x) : ∀ x, f x ≤ |f x|)), eventually_le.trans (condexp_neg f).symm.le (@condexp_mono _ m m0 _ _ _ _ _ _ _ _ hf.neg hf.abs (@ae_of_all _ m0 _ μ (λ x, neg_le_abs_self (f x) : ∀ x, -f x ≤ |f x|)))] with x hx₁ hx₂, exact abs_le_abs hx₁ hx₂, end ... = snorm f 1 μ : begin rw [snorm_one_eq_lintegral_nnnorm, snorm_one_eq_lintegral_nnnorm, ← ennreal.to_real_eq_to_real (ne_of_lt integrable_condexp.2) (ne_of_lt hf.2), ← integral_norm_eq_lintegral_nnnorm (strongly_measurable_condexp.mono hm).ae_strongly_measurable, ← integral_norm_eq_lintegral_nnnorm hf.1], simp_rw [real.norm_eq_abs], rw ← @integral_condexp _ _ _ _ _ m m0 μ _ hm hsig hf.abs, refine integral_congr_ae _, have : 0 ≤ᵐ[μ] μ[|f| | m], { rw ← @condexp_zero α ℝ _ _ _ m m0 μ, exact condexp_mono (integrable_zero _ _ _) hf.abs (@ae_of_all _ m0 _ μ (λ x, abs_nonneg (f x) : ∀ x, 0 ≤ |f x|)) }, filter_upwards [this] with x hx, exact abs_eq_self.2 hx end end /-- Given a integrable function `g`, the conditional expectations of `g` with respect to a sequence of sub-σ-algebras is uniformly integrable. -/ lemma integrable.uniform_integrable_condexp {ι : Type*} [is_finite_measure μ] {g : α → ℝ} (hint : integrable g μ) {ℱ : ι → measurable_space α} (hℱ : ∀ i, ℱ i ≤ m0) : uniform_integrable (λ i, μ[g | ℱ i]) 1 μ := begin have hmeas : ∀ n, ∀ C, measurable_set {x | C ≤ ∥μ[g | ℱ n] x∥₊} := λ n C, measurable_set_le measurable_const (strongly_measurable_condexp.mono (hℱ n)).measurable.nnnorm, have hg : mem_ℒp g 1 μ := mem_ℒp_one_iff_integrable.2 hint, refine uniform_integrable_of le_rfl ennreal.one_ne_top (λ n, (strongly_measurable_condexp.mono (hℱ n)).ae_strongly_measurable) (λ ε hε, _), by_cases hne : snorm g 1 μ = 0, { rw snorm_eq_zero_iff hg.1 one_ne_zero at hne, refine ⟨0, λ n, (le_of_eq $ (snorm_eq_zero_iff ((strongly_measurable_condexp.mono (hℱ n)).ae_strongly_measurable.indicator (hmeas n 0)) one_ne_zero).2 _).trans (zero_le _)⟩, filter_upwards [@condexp_congr_ae _ _ _ _ _ (ℱ n) m0 μ _ _ hne] with x hx, simp only [zero_le', set.set_of_true, set.indicator_univ, pi.zero_apply, hx, condexp_zero] }, obtain ⟨δ, hδ, h⟩ := hg.snorm_indicator_le μ le_rfl ennreal.one_ne_top hε, set C : ℝ≥0 := ⟨δ, hδ.le⟩⁻¹ * (snorm g 1 μ).to_nnreal with hC, have hCpos : 0 < C := mul_pos (nnreal.inv_pos.2 hδ) (ennreal.to_nnreal_pos hne hg.snorm_lt_top.ne), have : ∀ n, μ {x : α | C ≤ ∥μ[g | ℱ n] x∥₊} ≤ ennreal.of_real δ, { intro n, have := mul_meas_ge_le_pow_snorm' μ one_ne_zero ennreal.one_ne_top ((@strongly_measurable_condexp _ _ _ _ _ (ℱ n) _ μ g).mono (hℱ n)).ae_strongly_measurable C, rw [ennreal.one_to_real, ennreal.rpow_one, ennreal.rpow_one, mul_comm, ← ennreal.le_div_iff_mul_le (or.inl (ennreal.coe_ne_zero.2 hCpos.ne.symm)) (or.inl ennreal.coe_lt_top.ne)] at this, simp_rw [ennreal.coe_le_coe] at this, refine this.trans _, rw [ennreal.div_le_iff_le_mul (or.inl (ennreal.coe_ne_zero.2 hCpos.ne.symm)) (or.inl ennreal.coe_lt_top.ne), hC, nonneg.inv_mk, ennreal.coe_mul, ennreal.coe_to_nnreal hg.snorm_lt_top.ne, ← mul_assoc, ← ennreal.of_real_eq_coe_nnreal, ← ennreal.of_real_mul hδ.le, mul_inv_cancel hδ.ne.symm, ennreal.of_real_one, one_mul], exact snorm_one_condexp_le_snorm _ }, refine ⟨C, λ n, le_trans _ (h {x : α | C ≤ ∥μ[g | ℱ n] x∥₊} (hmeas n C) (this n))⟩, have hmeasℱ : measurable_set[ℱ n] {x : α | C ≤ ∥μ[g | ℱ n] x∥₊} := @measurable_set_le _ _ _ _ _ (ℱ n) _ _ _ _ _ measurable_const (@measurable.nnnorm _ _ _ _ _ (ℱ n) _ strongly_measurable_condexp.measurable), rw ← snorm_congr_ae (condexp_indicator hint hmeasℱ), exact snorm_one_condexp_le_snorm _, end section pull_out -- TODO: this section could be generalized beyond multiplication, to any bounded bilinear map. /-- Auxiliary lemma for `condexp_measurable_mul`. -/ lemma condexp_strongly_measurable_simple_func_mul (hm : m ≤ m0) (f : @simple_func α m ℝ) {g : α → ℝ} (hg : integrable g μ) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin have : ∀ s c (f : α → ℝ), set.indicator s (function.const α c) * f = s.indicator (c • f), { intros s c f, ext1 x, by_cases hx : x ∈ s, { simp only [hx, pi.mul_apply, set.indicator_of_mem, pi.smul_apply, algebra.id.smul_eq_mul] }, { simp only [hx, pi.mul_apply, set.indicator_of_not_mem, not_false_iff, zero_mul], }, }, refine @simple_func.induction _ _ m _ _ (λ c s hs, _) (λ g₁ g₂ h_disj h_eq₁ h_eq₂, _) f, { simp only [simple_func.const_zero, simple_func.coe_piecewise, simple_func.coe_const, simple_func.coe_zero, set.piecewise_eq_indicator], rw [this, this], refine (condexp_indicator (hg.smul c) hs).trans _, filter_upwards [@condexp_smul α ℝ ℝ _ _ _ _ _ m m0 μ c g] with x hx, classical, simp_rw [set.indicator_apply, hx], }, { have h_add := @simple_func.coe_add _ _ m _ g₁ g₂, calc μ[⇑(g₁ + g₂) * g|m] =ᵐ[μ] μ[(⇑g₁ + ⇑g₂) * g|m] : by { refine condexp_congr_ae (eventually_eq.mul _ eventually_eq.rfl), rw h_add, } ... =ᵐ[μ] μ[⇑g₁ * g|m] + μ[⇑g₂ * g|m] : by { rw add_mul, exact condexp_add (hg.simple_func_mul' hm _) (hg.simple_func_mul' hm _), } ... =ᵐ[μ] ⇑g₁ * μ[g|m] + ⇑g₂ * μ[g|m] : eventually_eq.add h_eq₁ h_eq₂ ... =ᵐ[μ] ⇑(g₁ + g₂) * μ[g|m] : by rw [h_add, add_mul], }, end lemma condexp_strongly_measurable_mul_of_bound (hm : m ≤ m0) [is_finite_measure μ] {f g : α → ℝ} (hf : strongly_measurable[m] f) (hg : integrable g μ) (c : ℝ) (hf_bound : ∀ᵐ x ∂μ, ∥f x∥ ≤ c) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin let fs := hf.approx_bounded c, have hfs_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, fs n x) at_top (𝓝 (f x)), from hf.tendsto_approx_bounded_ae hf_bound, by_cases hμ : μ = 0, { simp only [hμ, ae_zero], }, haveI : μ.ae.ne_bot, by simp only [hμ, ae_ne_bot, ne.def, not_false_iff], have hc : 0 ≤ c, { have h_exists : ∃ x, ∥f x∥ ≤ c := eventually.exists hf_bound, exact (norm_nonneg _).trans h_exists.some_spec, }, have hfs_bound : ∀ n x, ∥fs n x∥ ≤ c := hf.norm_approx_bounded_le hc, have hn_eq : ∀ n, μ[fs n * g | m] =ᵐ[μ] fs n * μ[g | m], from λ n, condexp_strongly_measurable_simple_func_mul hm _ hg, have : μ[f * μ[g|m]|m] = f * μ[g|m], { refine condexp_of_strongly_measurable hm (hf.mul strongly_measurable_condexp) _, exact integrable_condexp.bdd_mul' ((hf.mono hm).ae_strongly_measurable) hf_bound, }, rw ← this, refine tendsto_condexp_unique (λ n x, fs n x * g x) (λ n x, fs n x * μ[g|m] x) (f * g) (f * μ[g|m]) _ _ _ _ (λ x, c * ∥g x∥) _ (λ x, c * ∥μ[g|m] x∥) _ _ _ _, { exact λ n, hg.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, { exact λ n, integrable_condexp.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, { filter_upwards [hfs_tendsto] with x hx, rw pi.mul_apply, exact tendsto.mul hx tendsto_const_nhds, }, { filter_upwards [hfs_tendsto] with x hx, rw pi.mul_apply, exact tendsto.mul hx tendsto_const_nhds, }, { exact hg.norm.const_mul c, }, { exact integrable_condexp.norm.const_mul c, }, { refine λ n, eventually_of_forall (λ x, _), exact (norm_mul_le _ _).trans (mul_le_mul_of_nonneg_right (hfs_bound n x) (norm_nonneg _)), }, { refine λ n, eventually_of_forall (λ x, _), exact (norm_mul_le _ _).trans (mul_le_mul_of_nonneg_right (hfs_bound n x) (norm_nonneg _)), }, { intros n, simp_rw ← pi.mul_apply, refine (condexp_strongly_measurable_simple_func_mul hm _ hg).trans _, rw condexp_of_strongly_measurable hm ((simple_func.strongly_measurable _).mul strongly_measurable_condexp) _, { apply_instance, }, { apply_instance, }, exact integrable_condexp.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, end lemma condexp_strongly_measurable_mul_of_bound₀ (hm : m ≤ m0) [is_finite_measure μ] {f g : α → ℝ} (hf : ae_strongly_measurable' m f μ) (hg : integrable g μ) (c : ℝ) (hf_bound : ∀ᵐ x ∂μ, ∥f x∥ ≤ c) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin have : μ[f * g | m] =ᵐ[μ] μ[hf.mk f * g | m], from condexp_congr_ae (eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl), refine this.trans _, have : f * μ[g | m] =ᵐ[μ] hf.mk f * μ[g | m] := eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, refine eventually_eq.trans _ this.symm, refine condexp_strongly_measurable_mul_of_bound hm hf.strongly_measurable_mk hg c _, filter_upwards [hf_bound, hf.ae_eq_mk] with x hxc hx_eq, rw ← hx_eq, exact hxc, end /-- Pull-out property of the conditional expectation. -/ lemma condexp_strongly_measurable_mul {f g : α → ℝ} (hf : strongly_measurable[m] f) (hfg : integrable (f * g) μ) (hg : integrable g μ) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin by_cases hm : m ≤ m0, swap, { simp_rw condexp_of_not_le hm, rw mul_zero, }, by_cases hμm : sigma_finite (μ.trim hm), swap, { simp_rw condexp_of_not_sigma_finite hm hμm, rw mul_zero, }, haveI : sigma_finite (μ.trim hm) := hμm, obtain ⟨sets, sets_prop, h_univ⟩ := hf.exists_spanning_measurable_set_norm_le hm μ, simp_rw forall_and_distrib at sets_prop, obtain ⟨h_meas, h_finite, h_norm⟩ := sets_prop, suffices : ∀ n, ∀ᵐ x ∂μ, x ∈ sets n → μ[f * g|m] x = f x * μ[g|m] x, { rw ← ae_all_iff at this, filter_upwards [this] with x hx, rw pi.mul_apply, obtain ⟨i, hi⟩ : ∃ i, x ∈ sets i, { have h_mem : x ∈ ⋃ i, sets i, { rw h_univ, exact set.mem_univ _, }, simpa using h_mem, }, exact hx i hi, }, refine λ n, ae_imp_of_ae_restrict _, suffices : (μ.restrict (sets n))[f * g | m] =ᵐ[μ.restrict (sets n)] f * (μ.restrict (sets n))[g | m], { simp_rw ← pi.mul_apply, refine (condexp_restrict_ae_eq_restrict hm (h_meas n) hfg).symm.trans _, exact this.trans (eventually_eq.rfl.mul (condexp_restrict_ae_eq_restrict hm (h_meas n) hg)), }, suffices : (μ.restrict (sets n))[((sets n).indicator f) * g | m] =ᵐ[μ.restrict (sets n)] ((sets n).indicator f) * (μ.restrict (sets n))[g | m], { refine eventually_eq.trans _ (this.trans _), { exact condexp_congr_ae ((indicator_ae_eq_restrict (hm _ (h_meas n))).symm.mul eventually_eq.rfl), }, { exact (indicator_ae_eq_restrict (hm _ (h_meas n))).mul eventually_eq.rfl, }, }, haveI : is_finite_measure (μ.restrict (sets n)), { constructor, rw measure.restrict_apply_univ, exact h_finite n, }, refine condexp_strongly_measurable_mul_of_bound hm (hf.indicator (h_meas n)) hg.integrable_on n _, refine eventually_of_forall (λ x, _), by_cases hxs : x ∈ sets n, { simp only [hxs, set.indicator_of_mem], exact h_norm n x hxs, }, { simp only [hxs, set.indicator_of_not_mem, not_false_iff, _root_.norm_zero, nat.cast_nonneg], }, end /-- Pull-out property of the conditional expectation. -/ lemma condexp_strongly_measurable_mul₀ {f g : α → ℝ} (hf : ae_strongly_measurable' m f μ) (hfg : integrable (f * g) μ) (hg : integrable g μ) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin have : μ[f * g | m] =ᵐ[μ] μ[hf.mk f * g | m], from condexp_congr_ae (eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl), refine this.trans _, have : f * μ[g | m] =ᵐ[μ] hf.mk f * μ[g | m] := eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, refine eventually_eq.trans _ this.symm, refine condexp_strongly_measurable_mul hf.strongly_measurable_mk _ hg, refine (integrable_congr _).mp hfg, exact eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, end end pull_out end measure_theory
718438fff3c50dc7c39fc13972e4e667da4d66f6
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Init/Data/Nat.lean
bb3eb12dc109ba0692fbcdb13413edf225d7b386
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
386
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic import Init.Data.Nat.Div import Init.Data.Nat.Gcd import Init.Data.Nat.Bitwise import Init.Data.Nat.Control import Init.Data.Nat.Log2 import Init.Data.Nat.Linear import Init.Data.Nat.SOM
054d31de5e82bd58f8cb9b2a8399b2bc58350221
c0ddb2cf190d518bc0f2f0ee221dd22b1172888f
/mguaypaq/count.lean
a5cb9bd24e9be6f7e963b019b1fea2711a8b9f44
[]
no_license
mguaypaq/haskell-math
3b314552878517806b3151aa36aae422f383fad1
1ce7f3067eb8966fe7e7e4bffdf073b1f815fc04
refs/heads/master
1,607,775,289,122
1,582,435,358,000
1,582,435,358,000
234,125,578
0
0
null
1,579,106,398,000
1,579,106,397,000
null
UTF-8
Lean
false
false
21,798
lean
---------------------------------------------------------------- -- 1. Statement ---------------------------------------------------------------- -- Every nonempty list of distinct strictly positive integers -- has a member at least as large as the length of the list. ---------------------------------------------------------------- -- The proposition that a list has distinct elements. def list.distinct : list nat -> Prop | [] := true | (head :: tail) := (head ∉ tail) ∧ tail.distinct -- The proposition that a list only has positive elements. def list.positive : list nat -> Prop | [] := true | (head :: tail) := (head > 0) ∧ tail.positive -- The theorem statement. def goal : Prop := forall (L : list nat), ¬L.empty ∧ L.distinct ∧ L.positive -> exists (n : nat), (n ∈ L) ∧ (n ≥ L.length) ---------------------------------------------------------------- -- 2. Overview ---------------------------------------------------------------- -- Proof idea: given a subset S of the natural numbers and a -- list L of distinct natural numbers, the number of elements -- of L contained in S is bounded by the size of S. -- Since the set {1, 2, ..., (L.length-1)} has size -- (L.length-1), there must be some element of L which falls -- outside of this range, and this is what we're looking for. -- Structure of this file: -- 1. (Above) A self-contained statement of the theorem. -- 2. (Here) A tiny proof sketch. -- 3. Counting elements in a list with a property. -- 4. Counting and existence of list elements. -- 5. Counting with different subsets. -- 6. Bounded size subsets. -- 7. Ranges. -- 8. Main proof. ---------------------------------------------------------------- -- 3. Counting elements in a list with a property ---------------------------------------------------------------- -- Every fact involving natural numbers and lists that we care -- about in this file (equality, order relation, list length, -- membership testing) is decidable. In a sense this is great, -- because more approaches are viable. But it's not clear from -- the outset which of these approaches will be easier. -- -- For example, how should we represent subsets of the natural -- numbers? -- -- * As Prop-valued predicates? This allows subsets whose -- description is non-computable. -- -- * As bool-valued predicates? This only allows subsets whose -- description is computable. -- -- * As a few custom types, for the few subsets we care about, -- like consecutive ranges of natural numbers? -- -- My experience so far is that custom types need a lot of glue -- and boilerplate. Also, that bools make it easy to define -- functions, but hard to prove things about them. So, I'm -- defining subsets as Prop-valued predicates. -- -- This is one of the ways provided by the core library, -- incidentally: example : (set nat) = (nat -> Prop) := rfl -- Next, how should we talk about counting elements of a list -- which belong to a given subset of the natural numbers? -- -- * Using a function which takes a predicate and a list and -- returns the count, as a natural number? -- -- * Using a Prop which takes a predicate, a list, a count, and -- states that the count is correct? -- -- The function approach can work, because it can also take as -- an extra parameter a proof that the given predicate is -- decidable, even if it's a Prop-valued predicate. But again, -- my experience is that functions are easy to define but hard -- to use in proofs. So, I'm using a Prop for stating counts. -- -- The order of arguments (subset, count, list) is a bit weird, -- but it happened to make some of pattern matching easier. inductive count (S : set nat) : nat -> (list nat) -> Prop -- The empty list has 0 elements in the subset S. | nil {} : (count 0 []) -- The case when the head of the list is in S. | cons_true : forall {head tail c}, (head ∈ S) -> (count c tail) -> (count (c+1) (head :: tail)) -- The case when the head of the list is not in S. | cons_false : forall {head tail c}, (head ∉ S) -> (count c tail) -> (count c (head :: tail)) -- Given a subset S and a list L, the count is not guaranteed to -- exist, because the predicate defining S may not be provably -- true or false on an element of L. -- But if the count does exist, it's unique. lemma count_unique {S : set nat} : forall {c₁ c₂ : nat} {L : list nat}, (count S c₁ L) -> (count S c₂ L) -> (c₁ = c₂) -- Case 1: the empty list always has a count of 0. | 0 0 [] count.nil count.nil := (eq.refl 0) -- Case 2: the head of the list is in S. | (c₁+1) (c₂+1) (head :: tail) (count.cons_true _ tail_count₁) (count.cons_true _ tail_count₂) := (congr_arg nat.succ (count_unique tail_count₁ tail_count₂)) -- Case 3: the two counts disagree on whether the head of -- the list is in S or not, which is a contradiction. | (c₁+1) c₂ (head :: tail) (count.cons_true head_in_S _) (count.cons_false head_notin_S _) := (absurd head_in_S head_notin_S) -- Case 4: symmetric to case 3, also absurd. | c₁ (c₂+1) (head :: tail) (count.cons_false head_notin_S _) (count.cons_true head_in_S _) := (absurd head_in_S head_notin_S) -- Case 5: the head of the list is not in S. | c₁ c₂ (head :: tail) (count.cons_false _ tail_count₁) (count.cons_false _ tail_count₂) := (count_unique tail_count₁ tail_count₂) -- Cases 6, 7, 8, 9: automatically proved to be impossible. -- For decidable predicates, the count does exist. lemma count_decidable (S : set nat) [decidable_pred S] : forall (L : list nat), exists (c : nat), (count S c L) | [] := ⟨0, count.nil⟩ | (head :: tail) := let ⟨c, tail_count⟩ := (count_decidable tail) in if h : (S head) then ⟨c+1, count.cons_true h tail_count⟩ else ⟨c, count.cons_false h tail_count⟩ ---------------------------------------------------------------- -- 4. Counting and existence of list elements ---------------------------------------------------------------- -- Here are four lemmas that relate the counting of elements in -- a list, and the existence of elements) in the list. They -- provide the glue needed to connect the theorem statement at -- the top of the file with the machinery used in the proof. -- If the count is zero, then no element of the list is in the -- subset. (This lemma is not actually used, but it just fits in -- with the rest of the section.) lemma count_zero {S : set nat} : forall {L : list nat}, (count S 0 L) -> (forall (n : nat), (n ∈ L) -> (n ∈ S) -> false) | [] _ _ n_in_L _ := (list.not_mem_nil _ n_in_L) | (head :: tail) (count.cons_false head_notin_S tail_count) n n_in_L n_in_S := (or.elim (list.eq_or_mem_of_mem_cons n_in_L) -- Derive a contradiction from (n = head). (fun n_eq_head, head_notin_S (eq.rec n_in_S n_eq_head)) -- Derive a contradiction from (n ∈ tail). (fun n_in_tail, count_zero tail_count n n_in_tail n_in_S)) -- If the count is positive, then some element of the list is in -- the subset. (The conclusion is written in just the right form -- for the theorem statement at the top of the file.) lemma count_positive {S : set nat} {c : nat} : forall {L : list nat}, (count S (c+1) L) -> (exists (n : nat), (n ∈ L) ∧ (n ∈ S)) -- The n we're looking for is the head. | (head :: tail) (count.cons_true head_in_S _) := ⟨head, list.mem_cons_self _ _, head_in_S⟩ -- The n we're looking for is in the tail. | (head :: tail) (count.cons_false _ tail_count) := -- We have to re-wrap the recursive result for the tail -- so that it applies to (head :: tail). (@exists_imp_exists _ (fun n, (n ∈ tail) ∧ (n ∈ S)) (fun n, (n ∈ (head :: tail)) ∧ (n ∈ S)) (fun n, and_implies (list.mem_cons_of_mem _) id) -- The recursive result. (count_positive tail_count)) -- The previous two lemmas are about going from a counting fact -- to an existence fact; the following three lemmas go the other -- way, from a (non-)existence fact to a counting fact. -- A non-element of the list has a count of 0. lemma count_notin {n : nat} : forall {L : list nat}, (n ∉ L) -> (count (eq n) 0 L) | [] _ := count.nil | (head :: tail) n_notin_L := (count.cons_false -- Composition because of negation. (n_notin_L ∘ or.inl) (count_notin (n_notin_L ∘ or.inr))) -- An element of a list of distinct elements has a count of 1. lemma count_distinct {n : nat} : forall {L : list nat}, L.distinct -> (n ∈ L) -> (count (eq n) 1 L) | [] _ n_in_L := -- An absurd case, since n ∉ []. false.elim (list.not_mem_nil _ n_in_L) -- Pattern matching on the shape of L, and also on the proof -- of (n ∈ L), which can be either (n = head)... | (head :: tail) ⟨head_notin_tail, _⟩ (or.inl n_eq_head) := (count.cons_true n_eq_head (count_notin (eq.rec head_notin_tail n_eq_head.symm))) -- ...or (n ∈ tail). | (head :: tail) ⟨head_notin_tail, tail_distinct⟩ (or.inr n_in_tail) := (count.cons_false (fun n_eq_head, head_notin_tail (eq.rec n_in_tail n_eq_head)) (count_distinct tail_distinct n_in_tail)) -- Because equality of natural numbers is decidable, the -- condition (n ∈ L) is decidable, so we can package the -- previous two lemmas into one: the count of any number in a -- list with distinct elements is at most 1. lemma count_distinct_le (n : nat) {L : list nat} : L.distinct -> exists (c : nat), (count (eq n) c L) ∧ (c ≤ 1) := fun L_distinct, if h : (n ∈ L) then ⟨1, count_distinct L_distinct h, nat.le_refl _⟩ else ⟨0, count_notin h, nat.zero_le _⟩ ---------------------------------------------------------------- -- 5. Counting with different subsets ---------------------------------------------------------------- -- In the definition of "count" above, the subset predicate is -- fixed, and the count is defined recursively on the list. -- Another way of counting elements is to keep the list fixed, -- but decompose the subset as a union of other subsets. This -- section provides lemmas to deal with this. -- The empty set always has a count of zero. (This is included -- here because the empty set is the empty union.) lemma count_empty_set : forall {L : list nat}, (count ∅ 0 L) | [] := count.nil | (head :: tail) := (count.cons_false id count_empty_set) -- For two subsets and a fixed list, the count of the union -- is bounded by the sum of the counts. -- -- This is used twice later: -- -- * To split up the count of elements in L that are ≥L.length -- from those that are <L.length; and -- -- * To decompose the count of elements in {1, 2, 3, ..., m} -- into the count for each of the singletons {1}, {2}, -- {3}, ..., {m}. -- -- The proof idea is trivial, but the proof is very long, -- because 4 of the 5 cases are almost-but-not-quite the same, -- and I didn't figure out a simple way to factor out the -- commonalities. Possibly I should have used tactics and/or -- I have the wrong abstractions above. lemma count_union {S₁ S₂ : set nat} : forall {c₁ c₂ : nat} {L : list nat}, (count S₁ c₁ L) -> (count S₂ c₂ L) -> exists (c : nat), (count (S₁ ∪ S₂) c L) ∧ (c ≤ c₁ + c₂) | c₁ c₂ [] count.nil count.nil := ⟨0, count.nil, nat.zero_le 0⟩ | (c₁+1) (c₂+1) (head :: tail) (count.cons_true head_in_S₁ tail_count₁) (count.cons_true head_in_S₂ tail_count₂) := let ⟨c, tail_count, c_le_sum⟩ := (count_union tail_count₁ tail_count₂) in ⟨c+1, (count.cons_true (or.inl head_in_S₁) tail_count), -- The "simp" tactic is used here to rewrite sums of -- natural numbers using commutativity and -- associativity, because that's just too tedious. by {simp, exact (nat.succ_le_succ (nat.le_succ_of_le c_le_sum))}⟩ | (c₁+1) c₂ (head :: tail) (count.cons_true head_in_S₁ tail_count₁) (count.cons_false head_notin_S₂ tail_count₂) := let ⟨c, tail_count, c_le_sum⟩ := (count_union tail_count₁ tail_count₂) in ⟨c+1, (count.cons_true (or.inl head_in_S₁) tail_count), -- Another use to the "simp" tactic to avoid tedium. by {simp, exact (nat.succ_le_succ c_le_sum)}⟩ | c₁ (c₂+1) (head :: tail) (count.cons_false head_notin_S₁ tail_count₁) (count.cons_true head_in_S₂ tail_count₂) := let ⟨c, tail_count, c_le_sum⟩ := (count_union tail_count₁ tail_count₂) in ⟨c+1, (count.cons_true (or.inr head_in_S₂) tail_count), -- No need for "simp" in this case, luckily. (nat.succ_le_succ c_le_sum)⟩ | c₁ c₂ (head :: tail) (count.cons_false head_notin_S₁ tail_count₁) (count.cons_false head_notin_S₂ tail_count₂) := let ⟨c, tail_count, c_le_sum⟩ := (count_union tail_count₁ tail_count₂) in ⟨c, (count.cons_false (or.rec head_notin_S₁ head_notin_S₂) tail_count), c_le_sum⟩ ---------------------------------------------------------------- -- 6. Bounded size subsets ---------------------------------------------------------------- -- This section is about subsets of the natural numbers formed -- inductively by taking the empty set, and adding elements to -- the subset one by one. Note that we don't check whether the -- added element is already in the subset, so we only obtain an -- upper bound on the size of the subset. -- An inductive upper bound for the size of a subset. inductive bounded : (set nat) -> nat -> Type | nil : (bounded ∅ 0) | cons : forall head tail s, (bounded tail s) -> (bounded (tail ∪ (eq head)) (s+1)) -- A version of the pigeonhole principle, for these inductively -- constructed subsets of the natural numbers: a list of -- distinct natural numbers cannot contain more elements in the -- subset than the size bound of the subset. -- This lemma also states that the count is computable for -- subsets defined this way. lemma count_bounded {L : list nat} (h : L.distinct) : forall {S : set nat} {s : nat}, (bounded S s) -> exists (c : nat), (count S c L) ∧ (c ≤ s) | _ _ bounded.nil := ⟨0, count_empty_set, nat.zero_le 0⟩ | _ _ (bounded.cons head tail s tail_bounded) := let ⟨c₁, tail_count, c₁_le_s⟩ := (count_bounded tail_bounded), ⟨c₂, head_count, c₂_le_1⟩ := (count_distinct_le head h), ⟨c, L_count, c_le_sum⟩ := (count_union tail_count head_count) in ⟨c, L_count, (@nat.le_trans c (c₁ + c₂) (s+1) c_le_sum (add_le_add c₁_le_s c₂_le_1))⟩ ---------------------------------------------------------------- -- 7. Ranges ---------------------------------------------------------------- -- The previous lemmas are written for more general subsets of -- the natural numbers, but we only care about two kinds: -- -- * Subsets of the form {1, 2, 3, ..., m}, which we'll call -- "positive ranges"; and -- -- * Subsets of the form {m+1, m+2, m+3, ...}, which we'll call -- "positive rays". -- -- We need lemmas about the size of positive ranges, and a few -- ways to break down these subsets as unions of other subsets. -- The subset {1, 2, 3, ..., m}. def positive_range (m : nat) : (set nat) := (fun n, (0 < n) ∧ (n ≤ m)) -- When m=0, this is the empty set. lemma positive_range_zero : (positive_range 0) = ∅ := funext (fun n, propext ⟨ -- positive range ⊆ empty set (fun ⟨zero_lt_n, n_le_zero⟩, nat.lt_le_antisymm zero_lt_n n_le_zero), -- empty set ⊆ positive range false.elim⟩) -- When m>0, it's a union of a smaller range and a singleton. lemma positive_range_succ (m : nat) : (positive_range (m+1)) = (positive_range m) ∪ (eq (m+1)) := funext (fun n, propext ⟨ -- bigger range ⊆ union (fun ⟨zero_lt_n, n_le_succ_m⟩, (or.elim (nat.eq_or_lt_of_le n_le_succ_m)) (fun (h : n = m+1), or.inr h.symm) (fun (h : n < m+1), or.inl ⟨zero_lt_n, (nat.le_of_lt_succ h)⟩)), -- union ⊆ bigger range (@or.rec -- condition for the first subset in the union ((0 < n) ∧ (n ≤ m)) -- condition for the second subset in the union (m+1 = n) -- target condition, for the bigger range ((0 < n) ∧ (n ≤ m+1)) -- smaller range ⊆ bigger range (fun ⟨zero_lt_n, n_le_m⟩, ⟨ zero_lt_n, nat.le_succ_of_le n_le_m⟩) -- singleton ⊆ bigger range (fun h, ⟨ eq.rec (nat.zero_lt_succ m) h, nat.le_of_eq h.symm⟩))⟩) -- The subset {1, 2, 3, ..., m} has size m. lemma positive_range_bounded : forall (m : nat), (bounded (positive_range m) m) | 0 := (eq.rec (bounded.nil) positive_range_zero.symm) | (m+1) := (eq.rec (bounded.cons _ _ _ (positive_range_bounded m)) (positive_range_succ m).symm) -- The infinite subset {m+1, m+2, m+3, ...}. def positive_ray (m : nat) : (set nat) := (fun n, m < n) -- The predicate in the definition of positive_ray is decidable, -- so the lemma count_decidable can be used. The following -- declaration records this fact in a way that the automated -- typeclass search can find. instance {m : nat} : (decidable_pred (positive_ray m)) := -- In fact, Lean already knows that this predicate is -- decidable, but written in a different way. We have to -- explicitly write the type in the right way to convince it. (fun n, (infer_instance : decidable (m < n))) -- The subset {1, 2, 3, ...} of all positive natural numbers is -- the union of the positive range {1, 2, 3, ..., m} and the -- positive ray {m+1, m+2, m+3, ...}. lemma positive_split (m : nat) : (positive_ray 0) = (positive_range m) ∪ (positive_ray m) := funext (fun n, propext ⟨ -- positive ⊆ union (fun (zero_lt_n : 0 < n), or.elim (nat.lt_or_ge m n) (fun (m_lt_n : m < n), or.inr m_lt_n) (fun (n_le_m : n ≤ m), or.inl ⟨zero_lt_n, n_le_m⟩)), -- union ⊆ positive (@or.rec ((0 < n) ∧ (n ≤ m)) (m < n) (0 < n) -- range ⊆ positive and.left -- ray ⊆ positive (nat.lt_of_le_of_lt (nat.zero_le m)))⟩) ---------------------------------------------------------------- -- 8. Main proof ---------------------------------------------------------------- -- In a list of positive integers, the number of elements which -- are positive is the length of the list. This is a trivial -- statement, but it's written as a separate lemma because the -- proof is by induction on the list. lemma positive_count : forall {L : list nat}, L.positive -> (count (positive_ray 0) (L.length) L) | [] _ := count.nil | (head :: tail) ⟨head_positive, tail_positive⟩ := (count.cons_true head_positive (positive_count tail_positive)) -- The proof is split in two cases so that, in the main case, -- we are dealing with a list which is nonempty-by-construction, -- rather than just nonempty-by-proposition. theorem proof : goal -- The empty list case. -- (false.elim) works on Prop's, but (list.empty) is a bool, -- so there's some glue involved in this case. | [] ⟨L_nonempty, _, _⟩ := (false.elim (L_nonempty (eq.refl tt))) -- The nonempty list case. | (head :: tail) ⟨_, L_distinct, L_positive⟩ := let -- The tail has length (L.length-1). m := tail.length, -- The number of list elements in {1, 2, ..., m}. -- This number is at most m. ⟨c₁, low_count, c₁_le_m⟩ := (count_bounded L_distinct (positive_range_bounded m)), -- The number of list elements that are ≥ (L.length). -- This will be at least 1. ⟨c₂, high_count⟩ := (count_decidable (positive_ray m) (head :: tail)), -- The sum of the two numbers above is at least -- (L.length). ⟨c, split_count, c_le_sum⟩ := (count_union low_count high_count) in have h_ineq : ((m+1) ≤ (m + c₂)), from (calc -- We computed (L.length) in two ways, so the two answers -- are equal. m+1 = c : (count_unique (positive_count L_positive) (eq.rec split_count (positive_split m).symm)) ... ≤ c₁ + c₂ : c_le_sum ... ≤ m + c₂ : (nat.add_le_add_right c₁_le_m c₂)), -- It's a bit annoying to get the predecessor of a natural -- number, because the core library defines (0.pred = 0). have h_eq : (c₂.pred + 1 = c₂), from (nat.succ_pred_eq_of_pos (nat.le_of_add_le_add_left h_ineq)), -- Now that we know the count of elements in L which are -- ≥ (L.length) is positive, rewrite the conclusion in the -- same way as the original theorem statement. (count_positive (@eq.rec _ c₂ _ high_count _ h_eq.symm))
ffa0888957809805103110a3b4f725edfe1cec30
e6b8240a90527fd55d42d0ec6649253d5d0bd414
/src/order/filter/lift.lean
6ce8e7e2e85bf4cc7a3cc3ffb412ab9705a7570b
[ "Apache-2.0" ]
permissive
mattearnshaw/mathlib
ac90f9fb8168aa642223bea3ffd0286b0cfde44f
d8dc1445cf8a8c74f8df60b9f7a1f5cf10946666
refs/heads/master
1,606,308,351,137
1,576,594,130,000
1,576,594,130,000
228,666,195
0
0
Apache-2.0
1,576,603,094,000
1,576,603,093,000
null
UTF-8
Lean
false
false
18,021
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 Lift filters along filter and set functions. -/ import order.filter.basic open lattice set open_locale classical namespace filter variables {α : Type*} {β : Type*} {γ : Type*} {ι : Sort*} section lift /-- A variant on `bind` using a function `g` taking a set instead of a member of `α`. This is essentially a push-forward along a function mapping each set to a filter. -/ protected def lift (f : filter α) (g : set α → filter β) := ⨅s ∈ f.sets, g s variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β} lemma lift_sets_eq (hg : monotone g) : (f.lift g).sets = (⋃t∈f.sets, (g t).sets) := binfi_sets_eq (assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht, hg $ inter_subset_left s t, hg $ inter_subset_right s t⟩) ⟨univ, univ_mem_sets⟩ lemma mem_lift_iff (hg : monotone g) {s : set β} : s ∈ f.lift g ↔ s ∈ ⋃t∈f.sets, (g t).sets := show s ∈ (f.lift g).sets ↔ _, by rw lift_sets_eq hg lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f.sets) (hs : s ∈ (g t).sets) : s ∈ (f.lift g).sets := le_principal_iff.mp $ show f.lift g ≤ principal s, from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs lemma mem_lift_sets (hg : monotone g) {s : set β} : s ∈ (f.lift g).sets ↔ (∃t∈f.sets, s ∈ (g t).sets) := by rw [lift_sets_eq hg]; simp only [mem_Union] lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α} (hs : s ∈ f.sets) (hg : g s ≤ h) : f.lift g ≤ h := infi_le_of_le s $ infi_le_of_le hs $ hg lemma le_lift {f : filter α} {g : set α → filter β} {h : filter β} (hh : ∀s∈f.sets, h ≤ g s) : h ≤ f.lift g := le_infi $ assume s, le_infi $ assume hs, hh s hs lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.lift g₁ ≤ f₂.lift g₂ := infi_le_infi $ assume s, infi_le_infi2 $ assume hs, ⟨hf hs, hg s⟩ lemma lift_mono' (hg : ∀s∈f.sets, g₁ s ≤ g₂ s) : f.lift g₁ ≤ f.lift g₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, hg s hs lemma map_lift_eq {m : β → γ} (hg : monotone g) : map m (f.lift g) = f.lift (map m ∘ g) := have monotone (map m ∘ g), from monotone_map.comp hg, filter_eq $ set.ext $ by simp only [mem_lift_sets, hg, @mem_lift_sets _ _ f _ this, exists_prop, forall_const, mem_map, iff_self, function.comp_app] lemma comap_lift_eq {m : γ → β} (hg : monotone g) : comap m (f.lift g) = f.lift (comap m ∘ g) := have monotone (comap m ∘ g), from monotone_comap.comp hg, filter_eq $ set.ext begin simp only [hg, @mem_lift_sets _ _ f _ this, comap, mem_lift_sets, mem_set_of_eq, exists_prop, function.comp_apply], exact λ s, ⟨λ ⟨b, ⟨a, ha, hb⟩, hs⟩, ⟨a, ha, b, hb, hs⟩, λ ⟨a, ha, b, hb, hs⟩, ⟨b, ⟨a, ha, hb⟩, hs⟩⟩ end theorem comap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) : (comap m f).lift g = f.lift (g ∘ preimage m) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, infi_le_of_le (preimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩) (le_infi $ assume s, le_infi $ assume ⟨s', hs', (h_sub : preimage m s' ⊆ s)⟩, infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub) lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) : (map m f).lift g = f.lift (g ∘ image m) := le_antisymm (infi_le_infi2 $ assume s, ⟨image m s, infi_le_infi2 $ assume hs, ⟨ f.sets_of_superset hs $ assume a h, mem_image_of_mem _ h, le_refl _⟩⟩) (infi_le_infi2 $ assume t, ⟨preimage m t, infi_le_infi2 $ assume ht, ⟨ht, hg $ assume x, assume h : x ∈ m '' preimage m t, let ⟨y, hy, h_eq⟩ := h in show x ∈ t, from h_eq ▸ hy⟩⟩) lemma lift_comm {g : filter β} {h : set α → set β → filter γ} : f.lift (λs, g.lift (h s)) = g.lift (λt, f.lift (λs, h s t)) := le_antisymm (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) lemma lift_assoc {h : set β → filter γ} (hg : monotone g) : (f.lift g).lift h = f.lift (λs, (g s).lift h) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le _ $ (mem_lift_sets hg).mpr ⟨_, hs, ht⟩) (le_infi $ assume t, le_infi $ assume ht, let ⟨s, hs, h'⟩ := (mem_lift_sets hg).mp ht in infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h') lemma lift_lift_same_le_lift {g : set α → set α → filter β} : f.lift (λs, f.lift (g s)) ≤ f.lift (λs, g s s) := le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le _ hs lemma lift_lift_same_eq_lift {g : set α → set α → filter β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) : f.lift (λs, f.lift (g s)) = f.lift (λs, g s s) := le_antisymm lift_lift_same_le_lift (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le (s ∩ t) $ infi_le_of_le (inter_mem_sets hs ht) $ calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _) ... ≤ g s t : hg₁ s (inter_subset_right _ _)) lemma lift_principal {s : set α} (hg : monotone g) : (principal s).lift g = g s := le_antisymm (infi_le_of_le s $ infi_le _ $ subset.refl _) (le_infi $ assume t, le_infi $ assume hi, hg hi) theorem monotone_lift [preorder γ] {f : γ → filter α} {g : γ → set α → filter β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift (g c)) := assume a b h, lift_mono (hf h) (hg h) lemma lift_neq_bot_iff (hm : monotone g) : (f.lift g ≠ ⊥) ↔ (∀s∈f.sets, g s ≠ ⊥) := classical.by_cases (assume hn : nonempty β, calc f.lift g ≠ ⊥ ↔ (⨅s : { s // s ∈ f.sets}, g s.val) ≠ ⊥ : by simp only [filter.lift, infi_subtype, iff_self, ne.def] ... ↔ (∀s:{ s // s ∈ f.sets}, g s.val ≠ ⊥) : infi_neq_bot_iff_of_directed hn (assume ⟨a, ha⟩ ⟨b, hb⟩, ⟨⟨a ∩ b, inter_mem_sets ha hb⟩, hm $ inter_subset_left _ _, hm $ inter_subset_right _ _⟩) ... ↔ (∀s∈f.sets, g s ≠ ⊥) : ⟨assume h s hs, h ⟨s, hs⟩, assume h ⟨s, hs⟩, h s hs⟩) (assume hn : ¬ nonempty β, have h₁ : f.lift g = ⊥, from filter_eq_bot_of_not_nonempty hn, have h₂ : ∀s, g s = ⊥, from assume s, filter_eq_bot_of_not_nonempty hn, calc (f.lift g ≠ ⊥) ↔ false : by simp only [h₁, iff_self, eq_self_iff_true, not_true, ne.def] ... ↔ (∀s∈f.sets, false) : ⟨false.elim, assume h, h univ univ_mem_sets⟩ ... ↔ (∀s∈f.sets, g s ≠ ⊥) : by simp only [h₂, iff_self, eq_self_iff_true, not_true, ne.def]) @[simp] lemma lift_const {f : filter α} {g : filter β} : f.lift (λx, g) = g := le_antisymm (lift_le univ_mem_sets $ le_refl g) (le_lift $ assume s hs, le_refl g) @[simp] lemma lift_inf {f : filter α} {g h : set α → filter β} : f.lift (λx, g x ⊓ h x) = f.lift g ⊓ f.lift h := by simp only [filter.lift, infi_inf_eq, eq_self_iff_true] @[simp] lemma lift_principal2 {f : filter α} : f.lift principal = f := le_antisymm (assume s hs, mem_lift hs (mem_principal_self s)) (le_infi $ assume s, le_infi $ assume hs, by simp only [hs, le_principal_iff]) lemma lift_infi {f : ι → filter α} {g : set α → filter β} (hι : nonempty ι) (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f).lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, have g_mono : monotone g, from assume s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h, have ∀t∈(infi f).sets, (⨅ (i : ι), filter.lift (f i) g) ≤ g t, from assume t ht, infi_sets_induct ht (let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem_sets) (assume i s₁ s₂ hs₁ hs₂, @hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂) (assume s₁ s₂ hs₁ hs₂, le_trans hs₂ $ g_mono hs₁), begin simp only [mem_lift_iff g_mono, mem_Union, exists_imp_distrib], exact assume t ht hs, this t ht hs end) end lift section lift' /-- Specialize `lift` to functions `set α → set β`. This can be viewed as a generalization of `map`. This is essentially a push-forward along a function mapping each set to a set. -/ protected def lift' (f : filter α) (h : set α → set β) := f.lift (principal ∘ h) variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β} lemma mem_lift' {t : set α} (ht : t ∈ f.sets) : h t ∈ (f.lift' h).sets := le_principal_iff.mp $ show f.lift' h ≤ principal (h t), from infi_le_of_le t $ infi_le_of_le ht $ le_refl _ lemma mem_lift'_sets (hh : monotone h) {s : set β} : s ∈ (f.lift' h).sets ↔ (∃t∈f.sets, h t ⊆ s) := have monotone (principal ∘ h), from assume a b h, principal_mono.mpr $ hh h, by simp only [filter.lift', @mem_lift_sets α β f _ this, exists_prop, iff_self, mem_principal_sets, function.comp_app] lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α} (hs : s ∈ f.sets) (hg : principal (g s) ≤ h) : f.lift' g ≤ h := lift_le hs hg lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁.lift' h₁ ≤ f₂.lift' h₂ := lift_mono hf $ assume s, principal_mono.mpr $ hh s lemma lift'_mono' (hh : ∀s∈f.sets, h₁ s ⊆ h₂ s) : f.lift' h₁ ≤ f.lift' h₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, principal_mono.mpr $ hh s hs lemma lift'_cong (hh : ∀s∈f.sets, h₁ s = h₂ s) : f.lift' h₁ = f.lift' h₂ := le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs) (lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm) lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f.lift' h) = f.lift' (image m ∘ h) := calc map m (f.lift' h) = f.lift (map m ∘ principal ∘ h) : map_lift_eq $ monotone_principal.comp hh ... = f.lift' (image m ∘ h) : by simp only [(∘), filter.lift', map_principal, eq_self_iff_true] lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) : (map m f).lift' g = f.lift' (g ∘ image m) := map_lift_eq2 $ monotone_principal.comp hg theorem comap_lift'_eq {m : γ → β} (hh : monotone h) : comap m (f.lift' h) = f.lift' (preimage m ∘ h) := calc comap m (f.lift' h) = f.lift (comap m ∘ principal ∘ h) : comap_lift_eq $ monotone_principal.comp hh ... = f.lift' (preimage m ∘ h) : by simp only [(∘), filter.lift', comap_principal, eq_self_iff_true] theorem comap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) : (comap m f).lift' g = f.lift' (g ∘ preimage m) := comap_lift_eq2 $ monotone_principal.comp hg lemma lift'_principal {s : set α} (hh : monotone h) : (principal s).lift' h = principal (h s) := lift_principal $ monotone_principal.comp hh lemma principal_le_lift' {t : set β} (hh : ∀s∈f.sets, t ⊆ h s) : principal t ≤ f.lift' h := le_infi $ assume s, le_infi $ assume hs, principal_mono.mpr (hh s hs) theorem monotone_lift' [preorder γ] {f : γ → filter α} {g : γ → set α → set β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift' (g c)) := assume a b h, lift'_mono (hf h) (hg h) lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift h = f.lift (λs, h (g s)) := calc (f.lift' g).lift h = f.lift (λs, (principal (g s)).lift h) : lift_assoc (monotone_principal.comp hg) ... = f.lift (λs, h (g s)) : by simp only [lift_principal, hh, eq_self_iff_true] lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift' h = f.lift' (λs, h (g s)) := lift_lift'_assoc hg (monotone_principal.comp hh) lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ} (hg : monotone g) : (f.lift g).lift' h = f.lift (λs, (g s).lift' h) := lift_assoc hg lemma lift_lift'_same_le_lift' {g : set α → set α → set β} : f.lift (λs, f.lift' (g s)) ≤ f.lift' (λs, g s s) := lift_lift_same_le_lift lemma lift_lift'_same_eq_lift' {g : set α → set α → set β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) : f.lift (λs, f.lift' (g s)) = f.lift' (λs, g s s) := lift_lift_same_eq_lift (assume s, monotone_principal.comp (hg₁ s)) (assume t, monotone_principal.comp (hg₂ t)) lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} : f.lift' h ⊓ principal s = f.lift' (λt, h t ∩ s) := le_antisymm (le_infi $ assume t, le_infi $ assume ht, calc filter.lift' f h ⊓ principal s ≤ principal (h t) ⊓ principal s : inf_le_inf (infi_le_of_le t $ infi_le _ ht) (le_refl _) ... = _ : by simp only [principal_eq_iff_eq, inf_principal, eq_self_iff_true, function.comp_app]) (le_inf (le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le_of_le ht $ by simp only [le_principal_iff, inter_subset_left, mem_principal_sets, function.comp_app]; exact inter_subset_right _ _) (infi_le_of_le univ $ infi_le_of_le univ_mem_sets $ by simp only [le_principal_iff, inter_subset_right, mem_principal_sets, function.comp_app]; exact inter_subset_left _ _)) lemma lift'_neq_bot_iff (hh : monotone h) : (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, h s ≠ ∅) := calc (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, principal (h s) ≠ ⊥) : lift_neq_bot_iff (monotone_principal.comp hh) ... ↔ (∀s∈f.sets, h s ≠ ∅) : by simp only [principal_eq_bot_iff, iff_self, ne.def, principal_eq_bot_iff] @[simp] lemma lift'_id {f : filter α} : f.lift' id = f := lift_principal2 lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β} (h_le : ∀s∈f.sets, h s ∈ g.sets) : g ≤ f.lift' h := le_infi $ assume s, le_infi $ assume hs, by simp only [h_le, le_principal_iff, function.comp_app]; exact h_le s hs lemma lift_infi' {f : ι → filter α} {g : set α → filter β} (hι : nonempty ι) (hf : directed (≥) f) (hg : monotone g) : (infi f).lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, begin rw mem_lift_iff hg, simp only [mem_Union, exists_imp_distrib, infi_sets_eq hf hι], exact assume t i ht hs, mem_infi_sets i $ mem_lift ht hs end) lemma lift'_infi {f : ι → filter α} {g : set α → set β} (hι : nonempty ι) (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f).lift' g = (⨅i, (f i).lift' g) := lift_infi hι $ by simp only [principal_eq_iff_eq, inf_principal, function.comp_app]; apply assume s t, hg theorem comap_eq_lift' {f : filter β} {m : α → β} : comap m f = f.lift' (preimage m) := filter_eq $ set.ext $ by simp only [mem_lift'_sets, monotone_preimage, comap, exists_prop, forall_const, iff_self, mem_set_of_eq] end lift' section prod variables {f : filter α} lemma prod_def {f : filter α} {g : filter β} : f.prod g = (f.lift $ λs, g.lift' $ set.prod s) := have ∀(s:set α) (t : set β), principal (set.prod s t) = (principal s).comap prod.fst ⊓ (principal t).comap prod.snd, by simp only [principal_eq_iff_eq, comap_principal, inf_principal]; intros; refl, begin simp only [filter.lift', function.comp, this, -comap_principal, lift_inf, lift_const, lift_inf], rw [← comap_lift_eq monotone_principal, ← comap_lift_eq monotone_principal], simp only [filter.prod, lift_principal2, eq_self_iff_true] end lemma prod_same_eq : filter.prod f f = f.lift' (λt, set.prod t t) := by rw [prod_def]; from lift_lift'_same_eq_lift' (assume s, set.monotone_prod monotone_const monotone_id) (assume t, set.monotone_prod monotone_id monotone_const) lemma mem_prod_same_iff {s : set (α×α)} : s ∈ (filter.prod f f).sets ↔ (∃t∈f.sets, set.prod t t ⊆ s) := by rw [prod_same_eq, mem_lift'_sets]; exact set.monotone_prod monotone_id monotone_id lemma tendsto_prod_self_iff {f : α × α → β} {x : filter α} {y : filter β} : filter.tendsto f (filter.prod x x) y ↔ ∀ W ∈ y.sets, ∃ U ∈ x.sets, ∀ (x x' : α), x ∈ U → x' ∈ U → f (x, x') ∈ W := by simp only [tendsto_def, mem_prod_same_iff, prod_sub_preimage_iff, exists_prop, iff_self] variables {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} lemma prod_lift_lift {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : filter.prod (f₁.lift g₁) (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, filter.prod (g₁ s) (g₂ t))) := begin simp only [prod_def], rw [lift_assoc], apply congr_arg, funext x, rw [lift_comm], apply congr_arg, funext y, rw [lift'_lift_assoc], exact hg₂, exact hg₁ end lemma prod_lift'_lift' {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : filter.prod (f₁.lift' g₁) (f₂.lift' g₂) = f₁.lift (λs, f₂.lift' (λt, set.prod (g₁ s) (g₂ t))) := begin rw [prod_def, lift_lift'_assoc], apply congr_arg, funext x, rw [lift'_lift'_assoc], exact hg₂, exact set.monotone_prod monotone_const monotone_id, exact hg₁, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, set.monotone_prod monotone_id monotone_const) end end prod end filter
010bf65cc6f232e5364830848d972b787697b3b6
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/monoidal/internal/Module.lean
5ad24ea1bd31900fc619cbf0f7830955819ea0ea
[ "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
5,062
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Module.monoidal import algebra.category.Algebra.basic import category_theory.monoidal.internal /-! # `Mon_ (Module R) ≌ Algebra R` The category of internal monoid objects in `Module R` is equivalent to the category of "native" bundled `R`-algebras. Moreover, this equivalence is compatible with the forgetful functors to `Module R`. -/ universes v u open category_theory open linear_map open_locale tensor_product namespace Module variables {R : Type u} [comm_ring R] namespace Mon_Module_equivalence_Algebra @[simps] instance (A : Mon_ (Module.{u} R)) : ring A.X := { one := A.one (1 : R), mul := λ x y, A.mul (x ⊗ₜ y), one_mul := λ x, by { convert lcongr_fun A.one_mul ((1 : R) ⊗ₜ x), simp, }, mul_one := λ x, by { convert lcongr_fun A.mul_one (x ⊗ₜ (1 : R)), simp, }, mul_assoc := λ x y z, by convert lcongr_fun A.mul_assoc ((x ⊗ₜ y) ⊗ₜ z), left_distrib := λ x y z, begin convert A.mul.map_add (x ⊗ₜ y) (x ⊗ₜ z), rw ←tensor_product.tmul_add, refl, end, right_distrib := λ x y z, begin convert A.mul.map_add (x ⊗ₜ z) (y ⊗ₜ z), rw ←tensor_product.add_tmul, refl, end, ..(by apply_instance : add_comm_group A.X) } instance (A : Mon_ (Module.{u} R)) : algebra R A.X := { map_zero' := A.one.map_zero, map_one' := rfl, map_mul' := λ x y, begin have h := lcongr_fun A.one_mul.symm (x ⊗ₜ (A.one y)), rwa [monoidal_category.left_unitor_hom_apply, ←A.one.map_smul] at h, end, commutes' := λ r a, begin dsimp, have h₁ := lcongr_fun A.one_mul (r ⊗ₜ a), have h₂ := lcongr_fun A.mul_one (a ⊗ₜ r), exact h₁.trans h₂.symm, end, smul_def' := λ r a, by { convert (lcongr_fun A.one_mul (r ⊗ₜ a)).symm, simp, }, ..A.one } @[simp] lemma algebra_map (A : Mon_ (Module.{u} R)) (r : R) : algebra_map R A.X r = A.one r := rfl /-- Converting a monoid object in `Module R` to a bundled algebra. -/ @[simps] def functor : Mon_ (Module.{u} R) ⥤ Algebra R := { obj := λ A, Algebra.of R A.X, map := λ A B f, { to_fun := f.hom, map_one' := lcongr_fun f.one_hom (1 : R), map_mul' := λ x y, lcongr_fun f.mul_hom (x ⊗ₜ y), commutes' := λ r, lcongr_fun f.one_hom r, ..(f.hom.to_add_monoid_hom) }, }. /-- Converting a bundled algebra to a monoid object in `Module R`. -/ @[simps] def inverse_obj (A : Algebra.{u} R) : Mon_ (Module.{u} R) := { X := Module.of R A, one := algebra.linear_map R A, mul := algebra.lmul' R A, one_mul' := begin ext x, dsimp, rw [algebra.lmul'_apply, monoidal_category.left_unitor_hom_apply, algebra.smul_def], refl, end, mul_one' := begin ext x, dsimp, rw [algebra.lmul'_apply, monoidal_category.right_unitor_hom_apply, ←algebra.commutes, algebra.smul_def], refl, end, mul_assoc' := begin ext xy z, dsimp, apply tensor_product.induction_on xy, { simp only [linear_map.map_zero, tensor_product.zero_tmul], }, { intros x y, dsimp, simp [mul_assoc], }, { intros x y hx hy, dsimp, simp [tensor_product.add_tmul, hx, hy], }, end } /-- Converting a bundled algebra to a monoid object in `Module R`. -/ @[simps] def inverse : Algebra.{u} R ⥤ Mon_ (Module.{u} R) := { obj := inverse_obj, map := λ A B f, { hom := f.to_linear_map, }, }. end Mon_Module_equivalence_Algebra open Mon_Module_equivalence_Algebra /-- The category of internal monoid objects in `Module R` is equivalent to the category of "native" bundled `R`-algebras. -/ def Mon_Module_equivalence_Algebra : Mon_ (Module.{u} R) ≌ Algebra R := { functor := functor, inverse := inverse, unit_iso := nat_iso.of_components (λ A, { hom := { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r a, rfl, } }, inv := { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r a, rfl, } } }) (by tidy), counit_iso := nat_iso.of_components (λ A, { hom := { to_fun := id, map_zero' := rfl, map_add' := λ x y, rfl, map_one' := (algebra_map R A).map_one, map_mul' := λ x y, algebra.lmul'_apply, commutes' := λ r, rfl, }, inv := { to_fun := id, map_zero' := rfl, map_add' := λ x y, rfl, map_one' := (algebra_map R A).map_one.symm, map_mul' := λ x y, algebra.lmul'_apply.symm, commutes' := λ r, rfl } }) (by tidy), }. /-- The equivalence `Mon_ (Module R) ≌ Algebra R` is naturally compatible with the forgetful functors to `Module R`. -/ def Mon_Module_equivalence_Algebra_forget : Mon_Module_equivalence_Algebra.functor ⋙ forget₂ (Algebra.{u} R) (Module.{u} R) ≅ Mon_.forget := nat_iso.of_components (λ A, { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ c x, rfl }, inv := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ c x, rfl }, }) (by tidy) end Module
d70a9bef57aa2eb11c7ba646ea265d28e0ef3e23
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Meta/KAbstract.lean
5a2a07ec963dea159a6dd1f9ca3a1a8a66613c46
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,749
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Lean.Data.Occurrences import Lean.HeadIndex import Lean.Meta.Basic namespace Lean.Meta def kabstract (e : Expr) (p : Expr) (occs : Occurrences := Occurrences.all) : MetaM Expr := do let e ← instantiateMVars e if p.isFVar && occs == Occurrences.all then return e.abstract #[p] -- Easy case else let pHeadIdx := p.toHeadIndex let pNumArgs := p.headNumArgs let rec visit (e : Expr) (offset : Nat) : StateRefT Nat MetaM Expr := do let visitChildren : Unit → StateRefT Nat MetaM Expr := fun _ => do match e with | Expr.app f a _ => return e.updateApp! (← visit f offset) (← visit a offset) | Expr.mdata _ b _ => return e.updateMData! (← visit b offset) | Expr.proj _ _ b _ => return e.updateProj! (← visit b offset) | Expr.letE _ t v b _ => return e.updateLet! (← visit t offset) (← visit v offset) (← visit b (offset+1)) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit d offset) (← visit b (offset+1)) | Expr.forallE _ d b _ => return e.updateForallE! (← visit d offset) (← visit b (offset+1)) | e => return e if e.hasLooseBVars then visitChildren () else if e.toHeadIndex != pHeadIdx || e.headNumArgs != pNumArgs then visitChildren () else if (← isDefEq e p) then let i ← get set (i+1) if occs.contains i then pure (mkBVar offset) else visitChildren () else visitChildren () visit e 0 |>.run' 1 end Lean.Meta
ace73588e11dff614adfefd143285c07415ec3b4
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/int/gcd.lean
dd3d280fb4565b416b248290b726219a4355c4b9
[ "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
24,426
lean
/- Copyright (c) 2018 Guy Leroy. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sangwoo Jo (aka Jason), Guy Leroy, Johannes Hölzl, Mario Carneiro -/ import data.nat.prime /-! # Extended GCD and divisibility over ℤ ## Main definitions * Given `x y : ℕ`, `xgcd x y` computes the pair of integers `(a, b)` such that `gcd x y = x * a + y * b`. `gcd_a x y` and `gcd_b x y` are defined to be `a` and `b`, respectively. ## Main statements * `gcd_eq_gcd_ab`: Bézout's lemma, given `x y : ℕ`, `gcd x y = x * gcd_a x y + y * gcd_b x y`. ## Tags Bézout's lemma, Bezout's lemma -/ /-! ### Extended Euclidean algorithm -/ namespace nat /-- Helper function for the extended GCD algorithm (`nat.xgcd`). -/ def xgcd_aux : ℕ → ℤ → ℤ → ℕ → ℤ → ℤ → ℕ × ℤ × ℤ | 0 s t r' s' t' := (r', s', t') | r@(succ _) s t r' s' t' := have r' % r < r, from mod_lt _ $ succ_pos _, let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t @[simp] theorem xgcd_zero_left {s t r' s' t'} : xgcd_aux 0 s t r' s' t' = (r', s', t') := by simp [xgcd_aux] theorem xgcd_aux_rec {r s t r' s' t'} (h : 0 < r) : xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t := by cases r; [exact absurd h (lt_irrefl _), {simp only [xgcd_aux], refl}] /-- Use the extended GCD algorithm to generate the `a` and `b` values satisfying `gcd x y = x * a + y * b`. -/ def xgcd (x y : ℕ) : ℤ × ℤ := (xgcd_aux x 1 0 y 0 1).2 /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_a (x y : ℕ) : ℤ := (xgcd x y).1 /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_b (x y : ℕ) : ℤ := (xgcd x y).2 @[simp] theorem gcd_a_zero_left {s : ℕ} : gcd_a 0 s = 0 := by { unfold gcd_a, rw [xgcd, xgcd_zero_left] } @[simp] theorem gcd_b_zero_left {s : ℕ} : gcd_b 0 s = 1 := by { unfold gcd_b, rw [xgcd, xgcd_zero_left] } @[simp] theorem gcd_a_zero_right {s : ℕ} (h : s ≠ 0) : gcd_a s 0 = 1 := begin unfold gcd_a xgcd, induction s, { exact absurd rfl h, }, { simp [xgcd_aux], } end @[simp] theorem gcd_b_zero_right {s : ℕ} (h : s ≠ 0) : gcd_b s 0 = 0 := begin unfold gcd_b xgcd, induction s, { exact absurd rfl h, }, { simp [xgcd_aux], } end @[simp] theorem xgcd_aux_fst (x y) : ∀ s t s' t', (xgcd_aux x s t y s' t').1 = gcd x y := gcd.induction x y (by simp) (λ x y h IH s t s' t', by simp [xgcd_aux_rec, h, IH]; rw ← gcd_rec) theorem xgcd_aux_val (x y) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) := by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1]; cases xgcd_aux x 1 0 y 0 1; refl theorem xgcd_val (x y) : xgcd x y = (gcd_a x y, gcd_b x y) := by unfold gcd_a gcd_b; cases xgcd x y; refl section parameters (x y : ℕ) private def P : ℕ × ℤ × ℤ → Prop | (r, s, t) := (r : ℤ) = x * s + y * t theorem xgcd_aux_P {r r'} : ∀ {s t s' t'}, P (r, s, t) → P (r', s', t') → P (xgcd_aux r s t r' s' t') := gcd.induction r r' (by simp) $ λ a b h IH s t s' t' p p', begin rw [xgcd_aux_rec h], refine IH _ p, dsimp [P] at *, rw [int.mod_def], generalize : (b / a : ℤ) = k, rw [p, p'], simp [mul_add, mul_comm, mul_left_comm, add_comm, add_left_comm, sub_eq_neg_add, mul_assoc] end /-- **Bézout's lemma**: given `x y : ℕ`, `gcd x y = x * a + y * b`, where `a = gcd_a x y` and `b = gcd_b x y` are computed by the extended Euclidean algorithm. -/ theorem gcd_eq_gcd_ab : (gcd x y : ℤ) = x * gcd_a x y + y * gcd_b x y := by have := @xgcd_aux_P x y x y 1 0 0 1 (by simp [P]) (by simp [P]); rwa [xgcd_aux_val, xgcd_val] at this end lemma exists_mul_mod_eq_gcd {k n : ℕ} (hk : gcd n k < k) : ∃ m, n * m % k = gcd n k := begin have hk' := int.coe_nat_ne_zero.mpr (ne_of_gt (lt_of_le_of_lt (zero_le (gcd n k)) hk)), have key := congr_arg (λ m, int.nat_mod m k) (gcd_eq_gcd_ab n k), simp_rw int.nat_mod at key, rw [int.add_mul_mod_self_left, ←int.coe_nat_mod, int.to_nat_coe_nat, mod_eq_of_lt hk] at key, refine ⟨(n.gcd_a k % k).to_nat, eq.trans (int.coe_nat_inj _) key.symm⟩, rw [int.coe_nat_mod, int.coe_nat_mul, int.to_nat_of_nonneg (int.mod_nonneg _ hk'), int.to_nat_of_nonneg (int.mod_nonneg _ hk'), int.mul_mod, int.mod_mod, ←int.mul_mod], end lemma exists_mul_mod_eq_one_of_coprime {k n : ℕ} (hkn : coprime n k) (hk : 1 < k) : ∃ m, n * m % k = 1 := Exists.cases_on (exists_mul_mod_eq_gcd (lt_of_le_of_lt (le_of_eq hkn) hk)) (λ m hm, ⟨m, hm.trans hkn⟩) end nat /-! ### Divisibility over ℤ -/ namespace int protected lemma coe_nat_gcd (m n : ℕ) : int.gcd ↑m ↑n = nat.gcd m n := rfl /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_a : ℤ → ℤ → ℤ | (of_nat m) n := m.gcd_a n.nat_abs | -[1+ m] n := -m.succ.gcd_a n.nat_abs /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_b : ℤ → ℤ → ℤ | m (of_nat n) := m.nat_abs.gcd_b n | m -[1+ n] := -m.nat_abs.gcd_b n.succ /-- **Bézout's lemma** -/ theorem gcd_eq_gcd_ab : ∀ x y : ℤ, (gcd x y : ℤ) = x * gcd_a x y + y * gcd_b x y | (m : ℕ) (n : ℕ) := nat.gcd_eq_gcd_ab _ _ | (m : ℕ) -[1+ n] := show (_ : ℤ) = _ + -(n+1) * -_, by rw neg_mul_neg; apply nat.gcd_eq_gcd_ab | -[1+ m] (n : ℕ) := show (_ : ℤ) = -(m+1) * -_ + _ , by rw neg_mul_neg; apply nat.gcd_eq_gcd_ab | -[1+ m] -[1+ n] := show (_ : ℤ) = -(m+1) * -_ + -(n+1) * -_, by { rw [neg_mul_neg, neg_mul_neg], apply nat.gcd_eq_gcd_ab } theorem nat_abs_div (a b : ℤ) (H : b ∣ a) : nat_abs (a / b) = (nat_abs a) / (nat_abs b) := begin cases (nat.eq_zero_or_pos (nat_abs b)), {rw eq_zero_of_nat_abs_eq_zero h, simp [int.div_zero]}, calc nat_abs (a / b) = nat_abs (a / b) * 1 : by rw mul_one ... = nat_abs (a / b) * (nat_abs b / nat_abs b) : by rw nat.div_self h ... = nat_abs (a / b) * nat_abs b / nat_abs b : by rw (nat.mul_div_assoc _ (dvd_refl _)) ... = nat_abs (a / b * b) / nat_abs b : by rw (nat_abs_mul (a / b) b) ... = nat_abs a / nat_abs b : by rw int.div_mul_cancel H, end theorem nat_abs_dvd_abs_iff {i j : ℤ} : i.nat_abs ∣ j.nat_abs ↔ i ∣ j := ⟨assume (H : i.nat_abs ∣ j.nat_abs), dvd_nat_abs.mp (nat_abs_dvd.mp (coe_nat_dvd.mpr H)), assume H : (i ∣ j), coe_nat_dvd.mp (dvd_nat_abs.mpr (nat_abs_dvd.mpr H))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : nat.prime p) {m n : ℤ} {k l : ℕ} (hpm : ↑(p ^ k) ∣ m) (hpn : ↑(p ^ l) ∣ n) (hpmn : ↑(p ^ (k+l+1)) ∣ m*n) : ↑(p ^ (k+1)) ∣ m ∨ ↑(p ^ (l+1)) ∣ n := have hpm' : p ^ k ∣ m.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpm, have hpn' : p ^ l ∣ n.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpn, have hpmn' : (p ^ (k+l+1)) ∣ m.nat_abs*n.nat_abs, by rw ←int.nat_abs_mul; apply (int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpmn), let hsd := nat.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hpm' hpn' hpmn' in hsd.elim (λ hsd1, or.inl begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd1 end) (λ hsd2, or.inr begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd2 end) theorem dvd_of_mul_dvd_mul_left {i j k : ℤ} (k_non_zero : k ≠ 0) (H : k * i ∣ k * j) : i ∣ j := dvd.elim H (λl H1, by rw mul_assoc at H1; exact ⟨_, mul_left_cancel' k_non_zero H1⟩) theorem dvd_of_mul_dvd_mul_right {i j k : ℤ} (k_non_zero : k ≠ 0) (H : i * k ∣ j * k) : i ∣ j := by rw [mul_comm i k, mul_comm j k] at H; exact dvd_of_mul_dvd_mul_left k_non_zero H lemma prime.dvd_nat_abs_of_coe_dvd_sq {p : ℕ} (hp : p.prime) (k : ℤ) (h : ↑p ∣ k ^ 2) : p ∣ k.nat_abs := begin apply @nat.prime.dvd_of_dvd_pow _ _ 2 hp, rwa [sq, ← nat_abs_mul, ← coe_nat_dvd_left, ← sq] end /-- ℤ specific version of least common multiple. -/ def lcm (i j : ℤ) : ℕ := nat.lcm (nat_abs i) (nat_abs j) theorem lcm_def (i j : ℤ) : lcm i j = nat.lcm (nat_abs i) (nat_abs j) := rfl protected lemma coe_nat_lcm (m n : ℕ) : int.lcm ↑m ↑n = nat.lcm m n := rfl theorem gcd_dvd_left (i j : ℤ) : (gcd i j : ℤ) ∣ i := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_left _ _ theorem gcd_dvd_right (i j : ℤ) : (gcd i j : ℤ) ∣ j := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_right _ _ theorem dvd_gcd {i j k : ℤ} (h1 : k ∣ i) (h2 : k ∣ j) : k ∣ gcd i j := nat_abs_dvd.1 $ coe_nat_dvd.2 $ nat.dvd_gcd (nat_abs_dvd_abs_iff.2 h1) (nat_abs_dvd_abs_iff.2 h2) theorem gcd_mul_lcm (i j : ℤ) : gcd i j * lcm i j = nat_abs (i * j) := by rw [int.gcd, int.lcm, nat.gcd_mul_lcm, nat_abs_mul] theorem gcd_comm (i j : ℤ) : gcd i j = gcd j i := nat.gcd_comm _ _ theorem gcd_assoc (i j k : ℤ) : gcd (gcd i j) k = gcd i (gcd j k) := nat.gcd_assoc _ _ _ @[simp] theorem gcd_self (i : ℤ) : gcd i i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_left (i : ℤ) : gcd 0 i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_right (i : ℤ) : gcd i 0 = nat_abs i := by simp [gcd] @[simp] theorem gcd_one_left (i : ℤ) : gcd 1 i = 1 := nat.gcd_one_left _ @[simp] theorem gcd_one_right (i : ℤ) : gcd i 1 = 1 := nat.gcd_one_right _ theorem gcd_mul_left (i j k : ℤ) : gcd (i * j) (i * k) = nat_abs i * gcd j k := by { rw [int.gcd, int.gcd, nat_abs_mul, nat_abs_mul], apply nat.gcd_mul_left } theorem gcd_mul_right (i j k : ℤ) : gcd (i * j) (k * j) = gcd i k * nat_abs j := by { rw [int.gcd, int.gcd, nat_abs_mul, nat_abs_mul], apply nat.gcd_mul_right } theorem gcd_pos_of_non_zero_left {i : ℤ} (j : ℤ) (i_non_zero : i ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_left (nat_abs j) (nat_abs_pos_of_ne_zero i_non_zero) theorem gcd_pos_of_non_zero_right (i : ℤ) {j : ℤ} (j_non_zero : j ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_right (nat_abs i) (nat_abs_pos_of_ne_zero j_non_zero) theorem gcd_eq_zero_iff {i j : ℤ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := begin rw int.gcd, split, { intro h, exact ⟨nat_abs_eq_zero.mp (nat.eq_zero_of_gcd_eq_zero_left h), nat_abs_eq_zero.mp (nat.eq_zero_of_gcd_eq_zero_right h)⟩ }, { intro h, rw [nat_abs_eq_zero.mpr h.left, nat_abs_eq_zero.mpr h.right], apply nat.gcd_zero_left } end theorem gcd_div {i j k : ℤ} (H1 : k ∣ i) (H2 : k ∣ j) : gcd (i / k) (j / k) = gcd i j / nat_abs k := by rw [gcd, nat_abs_div i k H1, nat_abs_div j k H2]; exact nat.gcd_div (nat_abs_dvd_abs_iff.mpr H1) (nat_abs_dvd_abs_iff.mpr H2) theorem gcd_div_gcd_div_gcd {i j : ℤ} (H : 0 < gcd i j) : gcd (i / gcd i j) (j / gcd i j) = 1 := begin rw [gcd_div (gcd_dvd_left i j) (gcd_dvd_right i j)], rw [nat_abs_of_nat, nat.div_self H] end theorem gcd_dvd_gcd_of_dvd_left {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd i j ∣ gcd k j := int.coe_nat_dvd.1 $ dvd_gcd (dvd.trans (gcd_dvd_left i j) H) (gcd_dvd_right i j) theorem gcd_dvd_gcd_of_dvd_right {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd j i ∣ gcd j k := int.coe_nat_dvd.1 $ dvd_gcd (gcd_dvd_left j i) (dvd.trans (gcd_dvd_right j i) H) theorem gcd_dvd_gcd_mul_left (i j k : ℤ) : gcd i j ∣ gcd (k * i) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (i j k : ℤ) : gcd i j ∣ gcd (i * k) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (i j k : ℤ) : gcd i j ∣ gcd i (k * j) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (i j k : ℤ) : gcd i j ∣ gcd i (j * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {i j : ℤ} (H : i ∣ j) : gcd i j = nat_abs i := nat.dvd_antisymm (by unfold gcd; exact nat.gcd_dvd_left _ _) (by unfold gcd; exact nat.dvd_gcd (dvd_refl _) (nat_abs_dvd_abs_iff.mpr H)) theorem gcd_eq_right {i j : ℤ} (H : j ∣ i) : gcd i j = nat_abs j := by rw [gcd_comm, gcd_eq_left H] theorem ne_zero_of_gcd {x y : ℤ} (hc : gcd x y ≠ 0) : x ≠ 0 ∨ y ≠ 0 := begin contrapose! hc, rw [hc.left, hc.right, gcd_zero_right, nat_abs_zero] end theorem exists_gcd_one {m n : ℤ} (H : 0 < gcd m n) : ∃ (m' n' : ℤ), gcd m' n' = 1 ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, gcd_div_gcd_div_gcd H, (int.div_mul_cancel (gcd_dvd_left m n)).symm, (int.div_mul_cancel (gcd_dvd_right m n)).symm⟩ theorem exists_gcd_one' {m n : ℤ} (H : 0 < gcd m n) : ∃ (g : ℕ) (m' n' : ℤ), 0 < g ∧ gcd m' n' = 1 ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_gcd_one H in ⟨_, m', n', H, h⟩ theorem pow_dvd_pow_iff {m n : ℤ} {k : ℕ} (k0 : 0 < k) : m ^ k ∣ n ^ k ↔ m ∣ n := begin refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩, apply int.nat_abs_dvd_abs_iff.mp, apply (nat.pow_dvd_pow_iff k0).mp, rw [← int.nat_abs_pow, ← int.nat_abs_pow], exact int.nat_abs_dvd_abs_iff.mpr h end /-! ### lcm -/ theorem lcm_comm (i j : ℤ) : lcm i j = lcm j i := by { rw [int.lcm, int.lcm], exact nat.lcm_comm _ _ } theorem lcm_assoc (i j k : ℤ) : lcm (lcm i j) k = lcm i (lcm j k) := by { rw [int.lcm, int.lcm, int.lcm, int.lcm, nat_abs_of_nat, nat_abs_of_nat], apply nat.lcm_assoc } @[simp] theorem lcm_zero_left (i : ℤ) : lcm 0 i = 0 := by { rw [int.lcm], apply nat.lcm_zero_left } @[simp] theorem lcm_zero_right (i : ℤ) : lcm i 0 = 0 := by { rw [int.lcm], apply nat.lcm_zero_right } @[simp] theorem lcm_one_left (i : ℤ) : lcm 1 i = nat_abs i := by { rw int.lcm, apply nat.lcm_one_left } @[simp] theorem lcm_one_right (i : ℤ) : lcm i 1 = nat_abs i := by { rw int.lcm, apply nat.lcm_one_right } @[simp] theorem lcm_self (i : ℤ) : lcm i i = nat_abs i := by { rw int.lcm, apply nat.lcm_self } theorem dvd_lcm_left (i j : ℤ) : i ∣ lcm i j := by { rw int.lcm, apply coe_nat_dvd_right.mpr, apply nat.dvd_lcm_left } theorem dvd_lcm_right (i j : ℤ) : j ∣ lcm i j := by { rw int.lcm, apply coe_nat_dvd_right.mpr, apply nat.dvd_lcm_right } theorem lcm_dvd {i j k : ℤ} : i ∣ k → j ∣ k → (lcm i j : ℤ) ∣ k := begin rw int.lcm, intros hi hj, exact coe_nat_dvd_left.mpr (nat.lcm_dvd (nat_abs_dvd_abs_iff.mpr hi) (nat_abs_dvd_abs_iff.mpr hj)) end end int lemma pow_gcd_eq_one {M : Type*} [monoid M] (x : M) {m n : ℕ} (hm : x ^ m = 1) (hn : x ^ n = 1) : x ^ m.gcd n = 1 := begin cases m, { simp only [hn, nat.gcd_zero_left] }, obtain ⟨x, rfl⟩ : is_unit x, { apply is_unit_of_pow_eq_one _ _ hm m.succ_pos }, simp only [← units.coe_pow] at *, rw [← units.coe_one, ← gpow_coe_nat, ← units.ext_iff] at *, simp only [nat.gcd_eq_gcd_ab, gpow_add, gpow_mul, hm, hn, one_gpow, one_mul] end lemma gcd_nsmul_eq_zero {M : Type*} [add_monoid M] (x : M) {m n : ℕ} (hm : m • x = 0) (hn : n • x = 0) : (m.gcd n) • x = 0 := begin apply multiplicative.of_add.injective, rw [of_add_nsmul, of_add_zero, pow_gcd_eq_one]; rwa [←of_add_nsmul, ←of_add_zero, equiv.apply_eq_iff_eq] end /-! ### GCD prover -/ namespace tactic namespace norm_num open norm_num lemma int_gcd_helper' {d : ℕ} {x y a b : ℤ} (h₁ : (d:ℤ) ∣ x) (h₂ : (d:ℤ) ∣ y) (h₃ : x * a + y * b = d) : int.gcd x y = d := begin refine nat.dvd_antisymm _ (int.coe_nat_dvd.1 (int.dvd_gcd h₁ h₂)), rw [← int.coe_nat_dvd, ← h₃], apply dvd_add, { exact dvd_mul_of_dvd_left (int.gcd_dvd_left _ _) _ }, { exact dvd_mul_of_dvd_left (int.gcd_dvd_right _ _) _ } end lemma nat_gcd_helper_dvd_left (x y a : ℕ) (h : x * a = y) : nat.gcd x y = x := nat.gcd_eq_left ⟨a, h.symm⟩ lemma nat_gcd_helper_dvd_right (x y a : ℕ) (h : y * a = x) : nat.gcd x y = y := nat.gcd_eq_right ⟨a, h.symm⟩ lemma nat_gcd_helper_2 (d x y a b u v tx ty : ℕ) (hu : d * u = x) (hv : d * v = y) (hx : x * a = tx) (hy : y * b = ty) (h : ty + d = tx) : nat.gcd x y = d := begin rw ← int.coe_nat_gcd, apply @int_gcd_helper' _ _ _ a (-b) (int.coe_nat_dvd.2 ⟨_, hu.symm⟩) (int.coe_nat_dvd.2 ⟨_, hv.symm⟩), rw [mul_neg_eq_neg_mul_symm, ← sub_eq_add_neg, sub_eq_iff_eq_add'], norm_cast, rw [hx, hy, h] end lemma nat_gcd_helper_1 (d x y a b u v tx ty : ℕ) (hu : d * u = x) (hv : d * v = y) (hx : x * a = tx) (hy : y * b = ty) (h : tx + d = ty) : nat.gcd x y = d := (nat.gcd_comm _ _).trans $ nat_gcd_helper_2 _ _ _ _ _ _ _ _ _ hv hu hy hx h lemma nat_lcm_helper (x y d m n : ℕ) (hd : nat.gcd x y = d) (d0 : 0 < d) (xy : x * y = n) (dm : d * m = n) : nat.lcm x y = m := (nat.mul_right_inj d0).1 $ by rw [dm, ← xy, ← hd, nat.gcd_mul_lcm] lemma nat_coprime_helper_zero_left (x : ℕ) (h : 1 < x) : ¬ nat.coprime 0 x := mt (nat.coprime_zero_left _).1 $ ne_of_gt h lemma nat_coprime_helper_zero_right (x : ℕ) (h : 1 < x) : ¬ nat.coprime x 0 := mt (nat.coprime_zero_right _).1 $ ne_of_gt h lemma nat_coprime_helper_1 (x y a b tx ty : ℕ) (hx : x * a = tx) (hy : y * b = ty) (h : tx + 1 = ty) : nat.coprime x y := nat_gcd_helper_1 _ _ _ _ _ _ _ _ _ (one_mul _) (one_mul _) hx hy h lemma nat_coprime_helper_2 (x y a b tx ty : ℕ) (hx : x * a = tx) (hy : y * b = ty) (h : ty + 1 = tx) : nat.coprime x y := nat_gcd_helper_2 _ _ _ _ _ _ _ _ _ (one_mul _) (one_mul _) hx hy h lemma nat_not_coprime_helper (d x y u v : ℕ) (hu : d * u = x) (hv : d * v = y) (h : 1 < d) : ¬ nat.coprime x y := nat.not_coprime_of_dvd_of_dvd h ⟨_, hu.symm⟩ ⟨_, hv.symm⟩ lemma int_gcd_helper (x y : ℤ) (nx ny d : ℕ) (hx : (nx:ℤ) = x) (hy : (ny:ℤ) = y) (h : nat.gcd nx ny = d) : int.gcd x y = d := by rwa [← hx, ← hy, int.coe_nat_gcd] lemma int_gcd_helper_neg_left (x y : ℤ) (d : ℕ) (h : int.gcd x y = d) : int.gcd (-x) y = d := by rw int.gcd at h ⊢; rwa int.nat_abs_neg lemma int_gcd_helper_neg_right (x y : ℤ) (d : ℕ) (h : int.gcd x y = d) : int.gcd x (-y) = d := by rw int.gcd at h ⊢; rwa int.nat_abs_neg lemma int_lcm_helper (x y : ℤ) (nx ny d : ℕ) (hx : (nx:ℤ) = x) (hy : (ny:ℤ) = y) (h : nat.lcm nx ny = d) : int.lcm x y = d := by rwa [← hx, ← hy, int.coe_nat_lcm] lemma int_lcm_helper_neg_left (x y : ℤ) (d : ℕ) (h : int.lcm x y = d) : int.lcm (-x) y = d := by rw int.lcm at h ⊢; rwa int.nat_abs_neg lemma int_lcm_helper_neg_right (x y : ℤ) (d : ℕ) (h : int.lcm x y = d) : int.lcm x (-y) = d := by rw int.lcm at h ⊢; rwa int.nat_abs_neg /-- Evaluates the `nat.gcd` function. -/ meta def prove_gcd_nat (c : instance_cache) (ex ey : expr) : tactic (instance_cache × expr × expr) := do x ← ex.to_nat, y ← ey.to_nat, match x, y with | 0, _ := pure (c, ey, `(nat.gcd_zero_left).mk_app [ey]) | _, 0 := pure (c, ex, `(nat.gcd_zero_right).mk_app [ex]) | 1, _ := pure (c, `(1:ℕ), `(nat.gcd_one_left).mk_app [ey]) | _, 1 := pure (c, `(1:ℕ), `(nat.gcd_one_right).mk_app [ex]) | _, _ := do let (d, a, b) := nat.xgcd_aux x 1 0 y 0 1, if d = x then do (c, ea) ← c.of_nat (y / x), (c, _, p) ← prove_mul_nat c ex ea, pure (c, ex, `(nat_gcd_helper_dvd_left).mk_app [ex, ey, ea, p]) else if d = y then do (c, ea) ← c.of_nat (x / y), (c, _, p) ← prove_mul_nat c ey ea, pure (c, ey, `(nat_gcd_helper_dvd_right).mk_app [ex, ey, ea, p]) else do (c, ed) ← c.of_nat d, (c, ea) ← c.of_nat a.nat_abs, (c, eb) ← c.of_nat b.nat_abs, (c, eu) ← c.of_nat (x / d), (c, ev) ← c.of_nat (y / d), (c, _, pu) ← prove_mul_nat c ed eu, (c, _, pv) ← prove_mul_nat c ed ev, (c, etx, px) ← prove_mul_nat c ex ea, (c, ety, py) ← prove_mul_nat c ey eb, (c, p) ← if a ≥ 0 then prove_add_nat c ety ed etx else prove_add_nat c etx ed ety, let pf : expr := if a ≥ 0 then `(nat_gcd_helper_2) else `(nat_gcd_helper_1), pure (c, ed, pf.mk_app [ed, ex, ey, ea, eb, eu, ev, etx, ety, pu, pv, px, py, p]) end /-- Evaluates the `nat.lcm` function. -/ meta def prove_lcm_nat (c : instance_cache) (ex ey : expr) : tactic (instance_cache × expr × expr) := do x ← ex.to_nat, y ← ey.to_nat, match x, y with | 0, _ := pure (c, `(0:ℕ), `(nat.lcm_zero_left).mk_app [ey]) | _, 0 := pure (c, `(0:ℕ), `(nat.lcm_zero_right).mk_app [ex]) | 1, _ := pure (c, ey, `(nat.lcm_one_left).mk_app [ey]) | _, 1 := pure (c, ex, `(nat.lcm_one_right).mk_app [ex]) | _, _ := do (c, ed, pd) ← prove_gcd_nat c ex ey, (c, p0) ← prove_pos c ed, (c, en, xy) ← prove_mul_nat c ex ey, d ← ed.to_nat, (c, em) ← c.of_nat ((x * y) / d), (c, _, dm) ← prove_mul_nat c ed em, pure (c, em, `(nat_lcm_helper).mk_app [ex, ey, ed, em, en, pd, p0, xy, dm]) end /-- Evaluates the `int.gcd` function. -/ meta def prove_gcd_int (zc nc : instance_cache) : expr → expr → tactic (instance_cache × instance_cache × expr × expr) | x y := match match_neg x with | some x := do (zc, nc, d, p) ← prove_gcd_int x y, pure (zc, nc, d, `(int_gcd_helper_neg_left).mk_app [x, y, d, p]) | none := match match_neg y with | some y := do (zc, nc, d, p) ← prove_gcd_int x y, pure (zc, nc, d, `(int_gcd_helper_neg_right).mk_app [x, y, d, p]) | none := do (zc, nc, nx, px) ← prove_nat_uncast zc nc x, (zc, nc, ny, py) ← prove_nat_uncast zc nc y, (nc, d, p) ← prove_gcd_nat nc nx ny, pure (zc, nc, d, `(int_gcd_helper).mk_app [x, y, nx, ny, d, px, py, p]) end end /-- Evaluates the `int.lcm` function. -/ meta def prove_lcm_int (zc nc : instance_cache) : expr → expr → tactic (instance_cache × instance_cache × expr × expr) | x y := match match_neg x with | some x := do (zc, nc, d, p) ← prove_lcm_int x y, pure (zc, nc, d, `(int_lcm_helper_neg_left).mk_app [x, y, d, p]) | none := match match_neg y with | some y := do (zc, nc, d, p) ← prove_lcm_int x y, pure (zc, nc, d, `(int_lcm_helper_neg_right).mk_app [x, y, d, p]) | none := do (zc, nc, nx, px) ← prove_nat_uncast zc nc x, (zc, nc, ny, py) ← prove_nat_uncast zc nc y, (nc, d, p) ← prove_lcm_nat nc nx ny, pure (zc, nc, d, `(int_lcm_helper).mk_app [x, y, nx, ny, d, px, py, p]) end end /-- Evaluates the `nat.coprime` function. -/ meta def prove_coprime_nat (c : instance_cache) (ex ey : expr) : tactic (instance_cache × (expr ⊕ expr)) := do x ← ex.to_nat, y ← ey.to_nat, match x, y with | 1, _ := pure (c, sum.inl $ `(nat.coprime_one_left).mk_app [ey]) | _, 1 := pure (c, sum.inl $ `(nat.coprime_one_right).mk_app [ex]) | 0, 0 := pure (c, sum.inr `(nat.not_coprime_zero_zero)) | 0, _ := do c ← mk_instance_cache `(ℕ), (c, p) ← prove_lt_nat c `(1) ey, pure (c, sum.inr $ `(nat_coprime_helper_zero_left).mk_app [ey, p]) | _, 0 := do c ← mk_instance_cache `(ℕ), (c, p) ← prove_lt_nat c `(1) ex, pure (c, sum.inr $ `(nat_coprime_helper_zero_right).mk_app [ex, p]) | _, _ := do c ← mk_instance_cache `(ℕ), let (d, a, b) := nat.xgcd_aux x 1 0 y 0 1, if d = 1 then do (c, ea) ← c.of_nat a.nat_abs, (c, eb) ← c.of_nat b.nat_abs, (c, etx, px) ← prove_mul_nat c ex ea, (c, ety, py) ← prove_mul_nat c ey eb, (c, p) ← if a ≥ 0 then prove_add_nat c ety `(1) etx else prove_add_nat c etx `(1) ety, let pf : expr := if a ≥ 0 then `(nat_coprime_helper_2) else `(nat_coprime_helper_1), pure (c, sum.inl $ pf.mk_app [ex, ey, ea, eb, etx, ety, px, py, p]) else do (c, ed) ← c.of_nat d, (c, eu) ← c.of_nat (x / d), (c, ev) ← c.of_nat (y / d), (c, _, pu) ← prove_mul_nat c ed eu, (c, _, pv) ← prove_mul_nat c ed ev, (c, p) ← prove_lt_nat c `(1) ed, pure (c, sum.inr $ `(nat_not_coprime_helper).mk_app [ed, ex, ey, eu, ev, pu, pv, p]) end /-- Evaluates the `gcd`, `lcm`, and `coprime` functions. -/ @[norm_num] meta def eval_gcd : expr → tactic (expr × expr) | `(nat.gcd %%ex %%ey) := do c ← mk_instance_cache `(ℕ), prod.snd <$> prove_gcd_nat c ex ey | `(nat.lcm %%ex %%ey) := do c ← mk_instance_cache `(ℕ), prod.snd <$> prove_lcm_nat c ex ey | `(nat.coprime %%ex %%ey) := do c ← mk_instance_cache `(ℕ), prove_coprime_nat c ex ey >>= sum.elim true_intro false_intro ∘ prod.snd | `(int.gcd %%ex %%ey) := do zc ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), (prod.snd ∘ prod.snd) <$> prove_gcd_int zc nc ex ey | `(int.lcm %%ex %%ey) := do zc ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), (prod.snd ∘ prod.snd) <$> prove_lcm_int zc nc ex ey | _ := failed end norm_num end tactic
ac32cf0cfc1c28f749471a8694bff4be0db60932
626e312b5c1cb2d88fca108f5933076012633192
/src/ring_theory/principal_ideal_domain.lean
8ceac8b4786147adc47904047ac8a1ed9ad9be8e
[ "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
10,147
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Morenikeji Neri -/ import ring_theory.unique_factorization_domain /-! # Principal ideal rings and principal ideal domains A principal ideal ring (PIR) is a ring in which all left ideals are principal. A principal ideal domain (PID) is an integral domain which is a principal ideal ring. # Main definitions Note that for principal ideal domains, one should use `[integral_domain R] [is_principal_ideal_ring R]`. There is no explicit definition of a PID. Theorems about PID's are in the `principal_ideal_ring` namespace. - `is_principal_ideal_ring`: a predicate on rings, saying that every left ideal is principal. - `generator`: a generator of a principal ideal (or more generally submodule) - `to_unique_factorization_monoid`: a PID is a unique factorization domain # Main results - `to_maximal_ideal`: a non-zero prime ideal in a PID is maximal. - `euclidean_domain.to_principal_ideal_domain` : a Euclidean domain is a PID. -/ universes u v variables {R : Type u} {M : Type v} open set function open submodule open_locale classical section variables [ring R] [add_comm_group M] [module R M] /-- An `R`-submodule of `M` is principal if it is generated by one element. -/ class submodule.is_principal (S : submodule R M) : Prop := (principal [] : ∃ a, S = span R {a}) instance bot_is_principal : (⊥ : submodule R M).is_principal := ⟨⟨0, by simp⟩⟩ instance top_is_principal : (⊤ : submodule R R).is_principal := ⟨⟨1, ideal.span_singleton_one.symm⟩⟩ variables (R) /-- A ring is a principal ideal ring if all (left) ideals are principal. -/ class is_principal_ideal_ring (R : Type u) [ring R] : Prop := (principal : ∀ (S : ideal R), S.is_principal) attribute [instance] is_principal_ideal_ring.principal @[priority 100] instance division_ring.is_principal_ideal_ring (K : Type u) [division_ring K] : is_principal_ideal_ring K := { principal := λ S, by rcases ideal.eq_bot_or_top S with (rfl|rfl); apply_instance } end namespace submodule.is_principal variables [add_comm_group M] section ring variables [ring R] [module R M] /-- `generator I`, if `I` is a principal submodule, is an `x ∈ M` such that `span R {x} = I` -/ noncomputable def generator (S : submodule R M) [S.is_principal] : M := classical.some (principal S) lemma span_singleton_generator (S : submodule R M) [S.is_principal] : span R {generator S} = S := eq.symm (classical.some_spec (principal S)) @[simp] lemma generator_mem (S : submodule R M) [S.is_principal] : generator S ∈ S := by { conv_rhs { rw ← span_singleton_generator S }, exact subset_span (mem_singleton _) } lemma mem_iff_eq_smul_generator (S : submodule R M) [S.is_principal] {x : M} : x ∈ S ↔ ∃ s : R, x = s • generator S := by simp_rw [@eq_comm _ x, ← mem_span_singleton, span_singleton_generator] lemma eq_bot_iff_generator_eq_zero (S : submodule R M) [S.is_principal] : S = ⊥ ↔ generator S = 0 := by rw [← @span_singleton_eq_bot R M, span_singleton_generator] end ring section comm_ring variables [comm_ring R] [module R M] lemma mem_iff_generator_dvd (S : ideal R) [S.is_principal] {x : R} : x ∈ S ↔ generator S ∣ x := (mem_iff_eq_smul_generator S).trans (exists_congr (λ a, by simp only [mul_comm, smul_eq_mul])) lemma prime_generator_of_is_prime (S : ideal R) [submodule.is_principal S] [is_prime : S.is_prime] (ne_bot : S ≠ ⊥) : prime (generator S) := ⟨λ h, ne_bot ((eq_bot_iff_generator_eq_zero S).2 h), λ h, is_prime.ne_top (S.eq_top_of_is_unit_mem (generator_mem S) h), by simpa only [← mem_iff_generator_dvd S] using is_prime.2⟩ end comm_ring end submodule.is_principal namespace is_prime open submodule.is_principal ideal -- TODO -- for a non-ID one could perhaps prove that if p < q are prime then q maximal; -- 0 isn't prime in a non-ID PIR but the Krull dimension is still <= 1. -- The below result follows from this, but we could also use the below result to -- prove this (quotient out by p). lemma to_maximal_ideal [integral_domain R] [is_principal_ideal_ring R] {S : ideal R} [hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S := is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin assume T x hST hxS hxT, cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz, cases hpi.mem_or_mem (show generator T * z ∈ S, from hz ▸ generator_mem S), { have hTS : T ≤ S, rwa [← span_singleton_generator T, submodule.span_le, singleton_subset_iff], exact (hxS $ hTS hxT).elim }, cases (mem_iff_generator_dvd _).1 h with y hy, have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS, rw [← mul_one (generator S), hy, mul_left_comm, mul_right_inj' this] at hz, exact hz.symm ▸ T.mul_mem_right _ (generator_mem T) end⟩ end is_prime section open euclidean_domain variable [euclidean_domain R] lemma mod_mem_iff {S : ideal R} {x y : R} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := ⟨λ hxy, div_add_mod x y ▸ S.add_mem (S.mul_mem_right _ hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ S.sub_mem hx (S.mul_mem_right _ hy)⟩ @[priority 100] -- see Note [lower instance priority] instance euclidean_domain.to_principal_ideal_domain : is_principal_ideal_ring R := { principal := λ S, by exactI ⟨if h : {x : R | x ∈ S ∧ x ≠ 0}.nonempty then have wf : well_founded (euclidean_domain.r : R → R → Prop) := euclidean_domain.r_well_founded, have hmin : well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ∈ S ∧ well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ≠ 0, from well_founded.min_mem wf {x : R | x ∈ S ∧ x ≠ 0} h, ⟨well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h, submodule.ext $ λ x, ⟨λ hx, div_add_mod x (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ▸ (ideal.mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $ have (x % (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ∉ {x : R | x ∈ S ∧ x ≠ 0}), from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2), have x % well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h = 0, by finish [(mod_mem_iff hmin.1).2 hx], by simp *), λ hx, let ⟨y, hy⟩ := ideal.mem_span_singleton.1 hx in hy.symm ▸ S.mul_mem_right _ hmin.1⟩⟩ else ⟨0, submodule.ext $ λ a, by rw [← @submodule.bot_coe R R _ _ _, span_eq, submodule.mem_bot]; exact ⟨λ haS, by_contradiction $ λ ha0, h ⟨a, ⟨haS, ha0⟩⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩⟩ } end lemma is_field.is_principal_ideal_ring {R : Type*} [integral_domain R] (h : is_field R) : is_principal_ideal_ring R := @euclidean_domain.to_principal_ideal_domain R (@field.to_euclidean_domain R (h.to_field R)) namespace principal_ideal_ring open is_principal_ideal_ring @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring [ring R] [is_principal_ideal_ring R] : is_noetherian_ring R := is_noetherian_ring_iff.2 ⟨assume s : ideal R, begin rcases (is_principal_ideal_ring.principal s).principal with ⟨a, rfl⟩, rw [← finset.coe_singleton], exact ⟨{a}, set_like.coe_injective rfl⟩ end⟩ lemma is_maximal_of_irreducible [comm_ring R] [is_principal_ideal_ring R] {p : R} (hp : irreducible p) : ideal.is_maximal (span R ({p} : set R)) := ⟨⟨mt ideal.span_singleton_eq_top.1 hp.1, λ I hI, begin rcases principal I with ⟨a, rfl⟩, erw ideal.span_singleton_eq_top, unfreezingI { rcases ideal.span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩ }, refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)), erw [ideal.span_singleton_le_span_singleton, is_unit.mul_right_dvd hb] end⟩⟩ variables [integral_domain R] [is_principal_ideal_ring R] lemma irreducible_iff_prime {p : R} : irreducible p ↔ prime p := ⟨λ hp, (ideal.span_singleton_prime hp.ne_zero).1 $ (is_maximal_of_irreducible hp).is_prime, prime.irreducible⟩ lemma associates_irreducible_iff_prime : ∀{p : associates R}, irreducible p ↔ prime p := associates.irreducible_iff_prime_iff.1 (λ _, irreducible_iff_prime) section open_locale classical /-- `factors a` is a multiset of irreducible elements whose product is `a`, up to units -/ noncomputable def factors (a : R) : multiset R := if h : a = 0 then ∅ else classical.some (wf_dvd_monoid.exists_factors a h) lemma factors_spec (a : R) (h : a ≠ 0) : (∀b∈factors a, irreducible b) ∧ associated (factors a).prod a := begin unfold factors, rw [dif_neg h], exact classical.some_spec (wf_dvd_monoid.exists_factors a h) end lemma ne_zero_of_mem_factors {R : Type v} [integral_domain R] [is_principal_ideal_ring R] {a b : R} (ha : a ≠ 0) (hb : b ∈ factors a) : b ≠ 0 := irreducible.ne_zero ((factors_spec a ha).1 b hb) lemma mem_submonoid_of_factors_subset_of_units_subset (s : submonoid R) {a : R} (ha : a ≠ 0) (hfac : ∀ b ∈ factors a, b ∈ s) (hunit : ∀ c : units R, (c : R) ∈ s) : a ∈ s := begin rcases ((factors_spec a ha).2) with ⟨c, hc⟩, rw [← hc], exact submonoid.mul_mem _ (submonoid.multiset_prod_mem _ _ hfac) (hunit _), end /-- If a `ring_hom` maps all units and all factors of an element `a` into a submonoid `s`, then it also maps `a` into that submonoid. -/ lemma ring_hom_mem_submonoid_of_factors_subset_of_units_subset {R S : Type*} [integral_domain R] [is_principal_ideal_ring R] [semiring S] (f : R →+* S) (s : submonoid S) (a : R) (ha : a ≠ 0) (h : ∀ b ∈ factors a, f b ∈ s) (hf: ∀ c : units R, f c ∈ s) : f a ∈ s := mem_submonoid_of_factors_subset_of_units_subset (s.comap f.to_monoid_hom) ha h hf /-- A principal ideal domain has unique factorization -/ @[priority 100] -- see Note [lower instance priority] instance to_unique_factorization_monoid : unique_factorization_monoid R := { irreducible_iff_prime := λ _, principal_ideal_ring.irreducible_iff_prime .. (is_noetherian_ring.wf_dvd_monoid : wf_dvd_monoid R) } end end principal_ideal_ring
bfed402ca770083d5429194c30300e517af83665
159fed64bfae88f3b6a6166836d6278f953bcbf9
/Structure/AbstractPiSigma.lean
e6704d7d03e072b44867d2181c8e9b7a4df346d6
[ "MIT" ]
permissive
SReichelt/lean4-experiments
3e56830c8b2fbe3814eda071c48e3c8810d254a8
ff55357a01a34a91bf670d712637480089085ee4
refs/heads/main
1,683,977,454,907
1,622,991,121,000
1,622,991,121,000
340,765,677
2
0
null
null
null
null
UTF-8
Lean
false
false
31,052
lean
-- An abstract formalization of "isomorphism is equality up to relabeling" -- ------------------------------------------------------------------------- -- -- See `README.md` for more info. -- -- As a prerequisite for `AbstractBuildingBlocks.lean`, here we define generalized versions of Π and Σ -- expressions, where all involved types are replaced by structures and all dependencies are functors. import Structure.Basic import Structure.Forgetfulness import Structure.UniverseFunctor import Structure.FunctorStructure open Morphisms open HasStructure open Structure open Pi open StructureFunctor open Forgetfulness open SetoidStructureFunctor set_option autoBoundImplicitLocal false -- TODO: Can we avoid this? set_option maxHeartbeats 200000 universes u v namespace PiSigma -- First, we define a "structure dependency" that holds the information contained in a Π or Σ type: -- A structure (representing the type on the left-hand side) and a functor that returns a structure -- (representing the dependent type on the right-hand side). structure StructureDependency where (S : Structure) (F : UniverseFunctor S) namespace StructureDependency def constDep (S T : Structure) : StructureDependency := ⟨S, constFun T⟩ structure StructureDependencyEquiv (C D : StructureDependency) where (e : C.S ≃ D.S) -- TODO: Why does `≃` not work here? There is some strange type class resolution issue with the `universeFunctor` argument at play. (η : FunctorEquiv C.F (D.F ⊙ e.toFun)) namespace StructureDependencyEquiv def invFunEquiv {C D : StructureDependency} (φ : StructureDependencyEquiv C D) : FunctorEquiv (C.F ⊙ φ.e.invFun) D.F := let e₁ := FunctorEquiv.trans (compFun.congrArg_left (F := φ.e.invFun) φ.η) (compFun.congrArg_right (G := D.F) φ.e.isInv.rightInv); FunctorEquiv.trans e₁ (idFun.rightId D.F) def refl (C : StructureDependency) : StructureDependencyEquiv C C := ⟨StructureEquiv.refl C.S, FunctorEquiv.symm (idFun.rightId C.F)⟩ def symm {C D : StructureDependency} (φ : StructureDependencyEquiv C D) : StructureDependencyEquiv D C := ⟨StructureEquiv.symm φ.e, FunctorEquiv.symm (invFunEquiv φ)⟩ def trans {C D E : StructureDependency} (φ : StructureDependencyEquiv C D) (ψ : StructureDependencyEquiv D E) : StructureDependencyEquiv C E := ⟨StructureEquiv.trans φ.e ψ.e, FunctorEquiv.trans φ.η (compFun.congrArg_left (F := φ.e.toFun) ψ.η)⟩ def StructureDependencyEquivEquiv {C D : StructureDependency} (φ ψ : StructureDependencyEquiv C D) := Σ' ζ : φ.e ≃ ψ.e, compFun.congrArg_right (G := D.F) ζ.toFunEquiv • φ.η ≈ ψ.η namespace StructureDependencyEquivEquiv variable {C D : StructureDependency} def refl (φ : StructureDependencyEquiv C D) : StructureDependencyEquivEquiv φ φ := ⟨StructureEquiv.EquivEquiv.refl φ.e, leftCancelId (compFun.congrArg_right.respectsId φ.e.toFun)⟩ def symm {φ ψ : StructureDependencyEquiv C D} (ζ : StructureDependencyEquivEquiv φ ψ) : StructureDependencyEquivEquiv ψ φ := ⟨StructureEquiv.EquivEquiv.symm ζ.fst, let h₁ := (leftMulInv (h := functorHasStructure) φ.η ψ.η (compFun.congrArg_right ζ.fst.toFunEquiv)).mp ζ.snd; let h₂ := compFun.congrArg_right.respectsInv ζ.fst.toFunEquiv; comp_subst_left h₂ (Setoid.symm h₁)⟩ def trans {φ ψ χ : StructureDependencyEquiv C D} (ζ : StructureDependencyEquivEquiv φ ψ) (ξ : StructureDependencyEquivEquiv ψ χ) : StructureDependencyEquivEquiv φ χ := ⟨StructureEquiv.EquivEquiv.trans ζ.fst ξ.fst, let h₁ := applyAssoc_left (comp_subst_right ζ.snd ξ.snd); let h₂ := compFun.congrArg_right.respectsComp ζ.fst.toFunEquiv ξ.fst.toFunEquiv; comp_subst_left h₂ h₁⟩ def StructureDependencyEquivEquivEquiv {φ ψ : StructureDependencyEquiv C D} (ζ ξ : StructureDependencyEquivEquiv φ ψ) := ζ.fst ≈ ξ.fst namespace StructureDependencyEquivEquivEquiv variable {φ ψ : StructureDependencyEquiv C D} theorem refl (ζ : StructureDependencyEquivEquiv φ ψ) : StructureDependencyEquivEquivEquiv ζ ζ := Setoid.refl ζ.fst theorem symm {ζ ξ : StructureDependencyEquivEquiv φ ψ} (h : StructureDependencyEquivEquivEquiv ζ ξ) : StructureDependencyEquivEquivEquiv ξ ζ := Setoid.symm h theorem trans {ζ ξ σ : StructureDependencyEquivEquiv φ ψ} (h : StructureDependencyEquivEquivEquiv ζ ξ) (i : StructureDependencyEquivEquivEquiv ξ σ) : StructureDependencyEquivEquivEquiv ζ σ := Setoid.trans h i instance structureDependencyEquivEquivSetoid : Setoid (StructureDependencyEquivEquiv φ ψ) := ⟨StructureDependencyEquivEquivEquiv, ⟨refl, symm, trans⟩⟩ end StructureDependencyEquivEquivEquiv def structureDependencyEquivEquiv (φ ψ : StructureDependencyEquiv C D) : BundledSetoid := ⟨StructureDependencyEquivEquiv φ ψ⟩ -- TODO: Is there a less annoying way to do this? def comp_congrArg {φ ψ χ : StructureDependencyEquiv C D} {ζ₁ ζ₂ : StructureDependencyEquivEquiv φ ψ} {ξ₁ ξ₂ : StructureDependencyEquivEquiv ψ χ} (hζ : StructureDependencyEquivEquivEquiv ζ₁ ζ₂) (hξ : StructureDependencyEquivEquivEquiv ξ₁ ξ₂) : StructureDependencyEquivEquivEquiv (trans ζ₁ ξ₁) (trans ζ₂ ξ₂) := HasStructure.comp_congrArg hζ hξ instance structureDependencyEquivEquivHasIso : HasIsomorphisms (@structureDependencyEquivEquiv C D) := { refl := refl, symm := symm, trans := trans, comp_congrArg := comp_congrArg, inv_congrArg := sorry, assoc := λ ζ ξ σ => sorry, leftId := λ ζ => sorry, rightId := λ ζ => sorry, leftInv := λ ζ => sorry, rightInv := λ ζ => sorry, invInv := λ ζ => sorry, compInv := λ ζ ξ => sorry, idInv := λ φ => sorry } end StructureDependencyEquivEquiv instance structureDependencyEquivHasStructure (C D : StructureDependency) : HasStructure (StructureDependencyEquiv C D) := ⟨StructureDependencyEquivEquiv.structureDependencyEquivEquiv⟩ def structureDependencyEquivStructure (C D : StructureDependency) : Structure := ⟨StructureDependencyEquiv C D⟩ instance structureDependencyEquivSetoid (C D : StructureDependency) : Setoid (StructureDependencyEquiv C D) := structureToSetoid (structureDependencyEquivStructure C D) def structureDependencyEquiv (C D : StructureDependency) : BundledSetoid := ⟨StructureDependencyEquiv C D⟩ instance structureDependencyEquivHasIso : HasIsomorphisms structureDependencyEquiv := { refl := refl, symm := symm, trans := trans, comp_congrArg := λ hφ hψ => sorry, inv_congrArg := λ hφ => sorry, assoc := λ φ ψ χ => sorry, leftId := λ φ => sorry, rightId := λ φ => sorry, leftInv := λ φ => sorry, rightInv := λ φ => sorry, invInv := λ φ => sorry, compInv := λ φ ψ => sorry, idInv := λ C => sorry } end StructureDependencyEquiv instance structureDependencyHasStructure : HasStructure StructureDependency := ⟨StructureDependencyEquiv.structureDependencyEquiv⟩ def structureDependencyStructure : Structure := ⟨StructureDependency⟩ namespace structureDependencyStructure -- We can construct a functor into `StructureDependency` by giving essentially a functor yielding `S` and -- a Π expression yielding `F`. structure StructureDependencyFunctorDesc where (FS : UniverseStructureFunctor) (FF (S : Structure) : UniverseFunctor (FS.map S)) (mapEquiv {S T : Structure} (e : S ≃ T) : FunctorEquiv (FF S) (FF T ⊙ (FS.mapEquiv e).toFun)) (respectsEquivEquiv {S T : Structure} {e₁ e₂ : S ≃ T} (η : e₁ ≃ e₂) : compFun.congrArg_right (G := FF T) (FS.respectsEquiv η).toFunEquiv • mapEquiv e₁ ≈ mapEquiv e₂) variable (D : StructureDependencyFunctorDesc) def structureDependency (S : Structure) : StructureDependency := ⟨D.FS S, D.FF S⟩ def mkFunctor_equiv {S T : Structure} (e : S ≃ T) : structureDependency D S ≃ structureDependency D T := ⟨D.FS.mapEquiv e, D.mapEquiv e⟩ def mkFunctor_respectsEquiv {S T : Structure} {e₁ e₂ : S ≃ T} (η : e₁ ≃ e₂) : StructureDependencyEquiv.StructureDependencyEquivEquiv (mkFunctor_equiv D e₁) (mkFunctor_equiv D e₂) := ⟨D.FS.respectsEquiv η, D.respectsEquivEquiv η⟩ def mkFunctor_respectsComp {S T U : Structure} (e : S ≃ T) (f : T ≃ U) : StructureDependencyEquiv.StructureDependencyEquivEquiv (mkFunctor_equiv D (f • e)) (mkFunctor_equiv D f • mkFunctor_equiv D e) := ⟨D.FS.respectsComp e f, sorry⟩ def mkFunctor : StructureFunctor universeStructure structureDependencyStructure := { map := structureDependency D, functor := { mapEquiv := mkFunctor_equiv D, isFunctor := { respectsEquiv := λ ⟨η⟩ => ⟨mkFunctor_respectsEquiv D η⟩, respectsComp := λ e f => ⟨mkFunctor_respectsComp D e f⟩, respectsId := sorry, respectsInv := sorry } } } end structureDependencyStructure def setoidMap (C : StructureDependency) := setoidStructure ∘ C.F.map end StructureDependency open StructureDependency -- A structure that represents a functorial version of the type `∀ a : C.S, C.F a`. -- -- Since `C.F` is a functor, `e : a ≃ b` induces an `e' : C.F a ≃ C.F b`. We then require an -- `F : PiExpr C` to produce an instance equivalence between `F a : C.F a` and `F b : C.F b`. -- As a special case, if `C.F` is constant, this ensures that `F` is a functor. -- -- Since equivalence of equivalences in `C.S` is just a proposition, we cannot meaningfully compare two -- results of `mapEquiv` even if the inputs are equivalent: For `h : e₁ ≈ e₂`, we would need something -- along the lines of `mapEquiv e₁ ≈[respectsSetoid C.F h] mapEquiv e₂`, but such an expression only makes -- sense with an object inside the brackets, not with a proof. -- Therefore, we include a setoid truncation in `mapEquiv` so that its result is just a proof. structure PiExpr (C : StructureDependency) where (map : Pi (setoidMap C)) (mapEquiv {a b : C.S} (e : a ≃ b) : map a ≈[congrArg C.F e] map b) namespace PiExpr instance (C : StructureDependency) : CoeFun (PiExpr C) (λ _ => ∀ a : C.S, C.F a) := ⟨PiExpr.map⟩ def congrArg {C : StructureDependency} (F : PiExpr C) {a b : C.S} (e : a ≃ b) : F a ≈[congrArg C.F e] F b := F.mapEquiv e def PiEquiv {C : StructureDependency} (F G : PiExpr C) := Pi.PiEquiv.MappedPiEquiv PiExpr.map F G namespace PiEquiv variable {C : StructureDependency} def refl (F : PiExpr C) : PiEquiv F F := Pi.PiEquiv.MappedPiEquiv.refl F def symm {F G : PiExpr C} (η : PiEquiv F G) : PiEquiv G F := Pi.PiEquiv.MappedPiEquiv.symm η def trans {F G H : PiExpr C} (η : PiEquiv F G) (θ : PiEquiv G H) : PiEquiv F H := Pi.PiEquiv.MappedPiEquiv.trans η θ def piEquiv : RelationWithSetoid (PiExpr C) := Pi.PiEquiv.MappedPiEquiv.mappedPiEquiv (m := PiExpr.map) instance piEquivHasIso : HasIsomorphisms (@piEquiv C) := Pi.PiEquiv.MappedPiEquiv.mappedPiEquivHasIso end PiEquiv instance piHasStructure (C : StructureDependency) : HasStructure (PiExpr C) := ⟨PiEquiv.piEquiv⟩ def piStructure (C : StructureDependency) : Structure := ⟨PiExpr C⟩ def idPi {S : Structure} : PiExpr (StructureDependency.constDep S S) := { map := id, mapEquiv := structureSetoidEquiv S } def compFunPi {S : Structure} {C : StructureDependency} (F : StructureFunctor S C.S) (G : PiExpr C) : PiExpr ⟨S, C.F ⊙ F⟩ := { map := λ a => G (F a), mapEquiv := λ e => congrArg G (StructureFunctor.congrArg F e) } def constPiToFun {S T : Structure} (F : PiExpr (StructureDependency.constDep S T)) : StructureFunctor S (setoidStructure T) := makeToSetoidStructureFunctor F.map F.mapEquiv def funToConstPi {S T : Structure} (F : StructureFunctor S (setoidStructure T)) : PiExpr (StructureDependency.constDep S T) := { map := F.map, mapEquiv := F.functor.mapEquiv } def transportPi {C D : StructureDependency} (φ : StructureDependencyEquiv C D) : PiExpr C → PiExpr D := let θ := StructureDependencyEquiv.invFunEquiv φ; λ G => { map := λ a => (θ.ext a).toFun (G (φ.e.invFun a)), mapEquiv := λ {a b} e => let ⟨n⟩ := θ.nat e; let ⟨m⟩ := congrArg G (StructureFunctor.congrArg φ.e.invFun e); ⟨HasTrans.trans (n.toFunEquiv.ext (G (φ.e.invFun a))) (StructureFunctor.congrArg (θ.ext b).toFun m)⟩ } def dependentApplicationFunctor {S T : Structure} {F : UniverseFunctor S} (G : PiExpr ⟨S, functorStructure.incomingFunctorFunctor T ⊙ F⟩) (x : PiExpr ⟨S, F⟩) : SetoidStructureFunctor S T := makeSetoidStructureFunctor (λ a => (G a).map (x a)) (λ {a b} ⟨e⟩ => let ⟨h₁⟩ := congrArg G e; let ⟨h₂⟩ := congrArg x e; let h₃ := StructureFunctor.congr h₁ h₂; let h₄ := StructureFunctor.congrArg (G a) ((StructureFunctor.congrArg F e).isInv.leftInv.ext (x a)); ⟨HasTrans.trans (HasSymm.symm h₄) h₃⟩) namespace piStructure instance (C : StructureDependency) : CoeFun (IsType.type (piStructure C)) (λ _ => ∀ a : C.S, C.F a) := ⟨PiExpr.map⟩ -- An independent `PiExpr` is the same as a functor (to a setoid structure). section constDep variable (S T : Structure) @[reducible] def constDepPi := piStructure (StructureDependency.constDep S T) @[reducible] def constDepFun := functorStructure S (setoidStructure T) def constDepToFun : StructureFunctor (constDepPi S T) (constDepFun S T) := { map := constPiToFun, functor := { mapEquiv := λ η => makeToSetoidStructureFunctorEquiv' η, isFunctor := { respectsEquiv := id, respectsComp := λ η θ => Setoid.refl (θ • η), respectsId := λ F => Setoid.refl (id__ F), respectsInv := λ η => Setoid.refl η⁻¹ } } } def constDepInvFun : StructureFunctor (constDepFun S T) (constDepPi S T) := { map := funToConstPi, functor := { mapEquiv := λ η => η.ext, isFunctor := { respectsEquiv := id, respectsComp := λ η θ => Setoid.refl (θ • η), respectsId := λ F => Setoid.refl (id__ F), respectsInv := λ η => Setoid.refl η⁻¹ } } } def constDepEquiv : StructureEquiv (constDepPi S T) (constDepFun S T) := { toFun := constDepToFun S T, invFun := constDepInvFun S T, isInv := { leftInv := { ext := λ F a => HasRefl.refl (F a), nat := λ _ _ => proofIrrel _ _ }, rightInv := { ext := λ F => makeToSetoidStructureFunctorEquiv' (λ a => HasRefl.refl (F a)), nat := λ _ _ => proofIrrel _ _ }, lrCompat := λ _ _ => proofIrrel _ _, rlCompat := λ _ _ => proofIrrel _ _ } } end constDep -- If we fix the argument, we obtain a functor from `piStructure` to the result type. def projFunctor (C : StructureDependency) (a : C.S) : StructureFunctor (piStructure C) (setoidStructure (C.F a)) := { map := λ F => F a, functor := { mapEquiv := λ η => η a, isFunctor := { respectsEquiv := λ h => h a, respectsComp := λ η θ => Setoid.refl (θ a • η a), respectsId := λ F => Setoid.refl (id_ (F a)), respectsInv := λ η => Setoid.refl (η a)⁻¹ } } } -- `piStructure` itself can be viewed as a dependent structure, depending on an instance of -- `StructureDependency`. -- TODO: Why does `C ≃ D` not work? def piStructureFunctor_toFun {C D : StructureDependency} (φ : StructureDependencyEquiv C D) : StructureFunctor (piStructure C) (piStructure D) := let θ := StructureDependencyEquiv.invFunEquiv φ; { map := transportPi φ, functor := { mapEquiv := λ η a => StructureFunctor.congrArg (setoidFunctor (θ.ext a).toFun) (η (φ.e.invFun a)), isFunctor := { respectsEquiv := λ _ _ => proofIrrel _ _, respectsComp := λ _ _ _ => proofIrrel _ _, respectsId := λ _ _ => proofIrrel _ _, respectsInv := λ _ _ => proofIrrel _ _ } } } def piStructureFunctor_equiv {C D : StructureDependency} (φ : StructureDependencyEquiv C D) : piStructure C ≃ piStructure D := { toFun := piStructureFunctor_toFun φ, invFun := piStructureFunctor_toFun (StructureDependencyEquiv.symm φ), isInv := sorry } def piStructureFunctor : UniverseFunctor structureDependencyStructure := { map := piStructure, functor := { mapEquiv := piStructureFunctor_equiv, isFunctor := sorry } } def piStructureDependency : StructureDependency := ⟨structureDependencyStructure, piStructureFunctor⟩ def piStructureMkFunctor (D : structureDependencyStructure.StructureDependencyFunctorDesc) : UniverseStructureFunctor := { map := λ S => piStructure (structureDependencyStructure.structureDependency D S), mapEquiv := λ e => piStructureFunctor_equiv (structureDependencyStructure.mkFunctor_equiv D e), respectsEquiv := sorry, respectsComp := sorry, respectsId := sorry, respectsInv := sorry } end piStructure end PiExpr open PiExpr -- A Σ expression of structures. def SigmaExpr (C : StructureDependency) := Σ' a : C.S, IsType.type (setoidMap C a) namespace SigmaExpr -- The equivalence between encoded Σ expressions is actually the generalized version of the example -- in the introduction: A bundled instance of a Lean type class is an instance of the corresponding -- Σ type. If the type class is a functor, we can define two bundled instances to be isomorphic iff -- we have an equivalence `e` between the types such that `congrArg C.F e` maps one -- instance of the type class to the other. def SigmaEquiv {C : StructureDependency} (P Q : SigmaExpr C) := Σ' e : P.fst ≃ Q.fst, P.snd ≈[congrArg C.F e] Q.snd namespace SigmaEquiv variable {C : StructureDependency} def refl (P : SigmaExpr C) : SigmaEquiv P P := let h₁ := SetoidInstanceEquiv.refl (C.F P.fst) P.snd; let h₂ := Setoid.symm (respectsId C.F P.fst); ⟨HasRefl.refl P.fst, SetoidInstanceEquiv.mapEquiv h₂ P.snd P.snd h₁⟩ def symm {P Q : SigmaExpr C} (e : SigmaEquiv P Q) : SigmaEquiv Q P := let h₁ := SetoidInstanceEquiv.symm (congrArg C.F e.fst) P.snd Q.snd e.snd; let h₂ := Setoid.symm (respectsInv C.F e.fst); ⟨HasSymm.symm e.fst, SetoidInstanceEquiv.mapEquiv h₂ Q.snd P.snd h₁⟩ def trans {P Q R : SigmaExpr C} (e : SigmaEquiv P Q) (f : SigmaEquiv Q R) : SigmaEquiv P R := let h₁ := SetoidInstanceEquiv.trans (congrArg C.F e.fst) (congrArg C.F f.fst) P.snd Q.snd R.snd e.snd f.snd; let h₂ := Setoid.symm (respectsComp C.F e.fst f.fst); ⟨HasTrans.trans e.fst f.fst, SetoidInstanceEquiv.mapEquiv h₂ P.snd R.snd h₁⟩ -- No need to compare `e.snd` and `f.snd` because they are proofs. def SigmaEquivEquiv {P Q : SigmaExpr C} (e f : SigmaEquiv P Q) := e.fst ≈ f.fst namespace SigmaEquivEquiv variable {P Q : SigmaExpr C} theorem refl (e : SigmaEquiv P Q) : SigmaEquivEquiv e e := Setoid.refl e.fst theorem symm {e f : SigmaEquiv P Q} (h : SigmaEquivEquiv e f) : SigmaEquivEquiv f e := Setoid.symm h theorem trans {e f g : SigmaEquiv P Q} (h : SigmaEquivEquiv e f) (i : SigmaEquivEquiv f g) : SigmaEquivEquiv e g := Setoid.trans h i instance sigmaEquivSetoid : Setoid (SigmaEquiv P Q) := ⟨SigmaEquivEquiv, ⟨refl, symm, trans⟩⟩ end SigmaEquivEquiv def sigmaEquiv (P Q : SigmaExpr C) : BundledSetoid := ⟨SigmaEquiv P Q⟩ instance sigmaEquivHasIso : HasIsomorphisms (@sigmaEquiv C) := { refl := refl, symm := symm, trans := trans, comp_congrArg := λ he hf => comp_congrArg he hf, inv_congrArg := λ he => inv_congrArg he, assoc := λ e f g => assoc e.fst f.fst g.fst, leftId := λ e => leftId e.fst, rightId := λ e => rightId e.fst, leftInv := λ e => leftInv e.fst, rightInv := λ e => rightInv e.fst, invInv := λ e => invInv e.fst, compInv := λ e f => compInv e.fst f.fst, idInv := λ s => idInv s.fst } end SigmaEquiv instance sigmaHasStructure (C : StructureDependency) : HasStructure (SigmaExpr C) := ⟨SigmaEquiv.sigmaEquiv⟩ def sigmaStructure (C : StructureDependency) : Structure := ⟨SigmaExpr C⟩ def transportSigma {C D : StructureDependency} (φ : StructureDependencyEquiv C D) : SigmaExpr C → SigmaExpr D := λ s => ⟨φ.e.toFun s.fst, (φ.η.ext s.fst).toFun s.snd⟩ namespace sigmaStructure -- Introduction and projections of `sigmaStructure` are functorial. section MkProj variable (C : StructureDependency) def mkSndFunctor : UniverseFunctor C.S := functorStructure.incomingFunctorFunctor (sigmaStructure C) ⊙ C.F def mkDependency : StructureDependency := ⟨C.S, mkSndFunctor C⟩ def mkExprFunctor (a : C.S) : StructureFunctor (C.F a) (sigmaStructure C) := { map := λ b => ⟨a, b⟩, functor := { mapEquiv := λ {b c} e => ⟨id_ a, SetoidInstanceEquiv.mapEquiv (Setoid.symm (respectsId C.F a)) b c ⟨e⟩⟩, isFunctor := { respectsEquiv := λ _ => Setoid.refl _, respectsComp := λ _ _ => Setoid.symm (leftId _), respectsId := λ _ => Setoid.refl (id'' (S := sigmaStructure C)), respectsInv := λ _ => Setoid.symm (idInv _) } } } theorem mkExprCongrArg {a₁ a₂ : C.S} (e : a₁ ≃ a₂) : mkExprFunctor C a₁ ≈[congrArg (mkSndFunctor C) e] mkExprFunctor C a₂ := ⟨{ ext := λ b => ⟨e, ⟨(StructureFunctor.congrArg C.F e).isInv.rightInv.ext b⟩⟩, nat := λ {b c} ε => sorry }⟩ def mkExpr : PiExpr (mkDependency C) := ⟨mkExprFunctor C, mkExprCongrArg C⟩ def mkFunctor {S : Structure} (mkFst : StructureFunctor S C.S) (mkSnd : PiExpr ⟨S, C.F ⊙ mkFst⟩) : SetoidStructureFunctor S (sigmaStructure C) := let F : PiExpr ⟨S, mkSndFunctor C ⊙ mkFst⟩ := compFunPi (C := mkDependency C) mkFst (mkExpr C); dependentApplicationFunctor F mkSnd def projFstFunctor : StructureFunctor (sigmaStructure C) C.S := { map := PSigma.fst, functor := { mapEquiv := PSigma.fst, isFunctor := { respectsEquiv := id, respectsComp := λ e f => Setoid.refl (f • e), respectsId := λ a => Setoid.refl (id__ a), respectsInv := λ e => Setoid.refl e⁻¹ } } } def projSndDependencyFunctor : UniverseFunctor (sigmaStructure C) := C.F ⊙ projFstFunctor C def projSndDependency : StructureDependency := ⟨sigmaStructure C, projSndDependencyFunctor C⟩ def projSndExpr : PiExpr (projSndDependency C) := ⟨PSigma.snd, PSigma.snd⟩ -- TODO: Show that a sigma structure with `constDep` is the same as a binary product. end MkProj -- `sigmaStructure` itself can be viewed as dependent structures, depending on an instance of -- `StructureDependency`. theorem transportSnd {C D : StructureDependency} (φ : StructureDependencyEquiv C D) {s t : SigmaExpr C} (e : SigmaEquiv s t) : (φ.η.ext s.fst).toFun s.snd ≈[congrArg (D.F ⊙ φ.e.toFun) e.fst] (φ.η.ext t.fst).toFun t.snd := let ⟨f⟩ := φ.η.nat e.fst; let h₁ := ⟨f.toFunEquiv.ext s.snd⟩; let h₂ := StructureFunctor.congrArg (setoidFunctor (φ.η.ext t.fst).toFun) e.snd; Setoid.trans h₁ h₂ -- TODO: Why does `C ≃ D` not work? def sigmaStructureFunctor_toFun {C D : StructureDependency} (φ : StructureDependencyEquiv C D) : StructureFunctor (sigmaStructure C) (sigmaStructure D) := { map := transportSigma φ, functor := { mapEquiv := λ {s t} e => ⟨congrArg φ.e.toFun e.fst, transportSnd φ e⟩, isFunctor := { respectsEquiv := λ h => respectsSetoid φ.e.toFun h, respectsComp := λ e f => respectsComp φ.e.toFun e.fst f.fst, respectsId := λ s => respectsId φ.e.toFun s.fst, respectsInv := λ e => respectsInv φ.e.toFun e.fst } } } def sigmaStructureFunctor_equiv {C D : StructureDependency} (φ : StructureDependencyEquiv C D) : sigmaStructure C ≃ sigmaStructure D := { toFun := sigmaStructureFunctor_toFun φ, invFun := sigmaStructureFunctor_toFun (StructureDependencyEquiv.symm φ), isInv := sorry } def sigmaStructureFunctor : UniverseFunctor structureDependencyStructure := { map := sigmaStructure, functor := { mapEquiv := sigmaStructureFunctor_equiv, isFunctor := sorry } } def sigmaStructureDependency : StructureDependency := ⟨structureDependencyStructure, sigmaStructureFunctor⟩ end sigmaStructure end SigmaExpr open SigmaExpr -- TODO: Define richer Π and Σ structures where the left side is a structure. -- Looks like we need `nestedPiFunctor` to be a `UniverseStructureFunctor` then. Is it possible? -- Analogously to the equivalences in `ProductStructure.lean`, we have equivalences between dependent -- structures. However, since the left side of a dependent structure always requires more data than -- the right side, we need to restrict ourselves to the case that the first variable is a structure, -- the second variable is any instance of any structure, and the third argument is an instance of a -- setoid structure. -- -- TODO: We may be able to give a somewhat general definition of the word "canonical" based on these -- equivalences. namespace PiSigmaEquivalences section InnerPair variable (F : UniverseStructureFunctor) def innerPairStructure := sigmaStructure ⟨universeStructure, UniverseStructureFunctor.universeFunctor F⟩ -- `b ↦ ⟨A, b⟩` def innerPairFunctor (A : Structure) : StructureFunctor (F A) (innerPairStructure F) := sigmaStructure.mkExprFunctor ⟨universeStructure, UniverseStructureFunctor.universeFunctor F⟩ A end InnerPair def NestedDependency := Σ' F : UniverseStructureFunctor, UniverseFunctor (innerPairStructure F) variable (D : NestedDependency) def innerPairDependency : StructureDependency := ⟨innerPairStructure D.fst, D.snd⟩ -- `b ↦ D.snd ⟨A, b⟩` def resultFunctor (A : Structure) : UniverseFunctor (D.fst A) := D.snd ⊙ innerPairFunctor D.fst A -- `A ↦ (b ↦ D.snd ⟨A, b⟩)` def innerDependencyFunctorDesc : structureDependencyStructure.StructureDependencyFunctorDesc := { FS := D.fst, FF := resultFunctor D, mapEquiv := sorry, respectsEquivEquiv := sorry } def innerDependencyFunctor : StructureFunctor universeStructure structureDependencyStructure := StructureDependency.structureDependencyStructure.mkFunctor (innerDependencyFunctorDesc D) -- `(∀ A : Structure, ∀ b : F A, G A b) ≃ (∀ ⟨A, b⟩ : (Σ A : Structure, F A), G A b)` -- (`(λ A b => g A b) ↦ (λ ⟨A, b⟩ => g A b)`) -- `A ↦ ∀ b : D.fst A, D.snd ⟨A, b⟩` def nestedPiFunctor : UniverseFunctor universeStructure := piStructure.piStructureFunctor ⊙ innerDependencyFunctor D def nestedPiDependency : StructureDependency := ⟨universeStructure, nestedPiFunctor D⟩ @[reducible] def piPiCurried := piStructure (nestedPiDependency D) @[reducible] def piPiUncurried := piStructure (innerPairDependency D) def piPiEquivToFun : StructureFunctor (piPiCurried D) (piPiUncurried D) := { map := λ g => ⟨λ ⟨a, b⟩ => (g a).map b, sorry⟩, functor := sorry } def piPiEquivInvFun : StructureFunctor (piPiUncurried D) (piPiCurried D) := { map := λ g => ⟨λ a => ⟨λ b => g ⟨a, b⟩, sorry⟩, sorry⟩, functor := sorry } def piPiEquiv : StructureEquiv (piPiCurried D) (piPiUncurried D) := { toFun := piPiEquivToFun D, invFun := piPiEquivInvFun D, isInv := sorry } -- `(Σ A : Structure, Σ b : F A, G A b) ≃ (Σ ⟨A, b⟩ : (Σ A : Structure, F A), G A b)` -- (`⟨A, ⟨b, c⟩⟩ ↦ ⟨⟨A, b⟩, c⟩`) -- `A ↦ Σ b : D.fst A, D.snd ⟨A, b⟩` def nestedSigmaFunctor : UniverseFunctor universeStructure := sigmaStructure.sigmaStructureFunctor ⊙ innerDependencyFunctor D def nestedSigmaDependency : StructureDependency := ⟨universeStructure, nestedSigmaFunctor D⟩ def sigmaSigmaCurried := sigmaStructure (nestedSigmaDependency D) def sigmaSigmaUncurried := sigmaStructure (innerPairDependency D) def sigmaSigmaEquivToFun : StructureFunctor (sigmaSigmaCurried D) (sigmaSigmaUncurried D) := { map := λ ⟨A, ⟨b, c⟩⟩ => ⟨⟨A, b⟩, c⟩, functor := { mapEquiv := λ ⟨e, he⟩ => sorry, isFunctor := { respectsEquiv := sorry, respectsComp := sorry, respectsId := sorry, respectsInv := sorry } } } def sigmaSigmaEquivInvFun : StructureFunctor (sigmaSigmaUncurried D) (sigmaSigmaCurried D) := { map := λ ⟨⟨A, b⟩, c⟩ => ⟨A, ⟨b, c⟩⟩, functor := { mapEquiv := λ ⟨⟨e, f⟩, g⟩ => sorry, isFunctor := { respectsEquiv := sorry, respectsComp := sorry, respectsId := sorry, respectsInv := sorry } } } def sigmaSigmaEquiv : StructureEquiv (sigmaSigmaCurried D) (sigmaSigmaUncurried D) := { toFun := sigmaSigmaEquivToFun D, invFun := sigmaSigmaEquivInvFun D, isInv := sorry } -- `(∀ A : Structure, Σ b : F A, G A b) ≃ (Σ f : (∀ A : Structure, F A), ∀ A : Structure, G A (f A))` -- (`(λ A => ⟨f A, g A (f A)⟩ ↦ ⟨λ A => f A, λ A => g A (f A)⟩`) -- TODO end PiSigmaEquivalences end PiSigma
e5e16b83ac87c0c9a5149aec3e9b259080749214
4a092885406df4e441e9bb9065d9405dacb94cd8
/src/for_mathlib/filter.lean
d4f77a9e0ba4bdd9dee5459d944af8e4575e7a75
[ "Apache-2.0" ]
permissive
semorrison/lean-perfectoid-spaces
78c1572cedbfae9c3e460d8aaf91de38616904d8
bb4311dff45791170bcb1b6a983e2591bee88a19
refs/heads/master
1,588,841,765,494
1,554,805,620,000
1,554,805,620,000
180,353,546
0
1
null
1,554,809,880,000
1,554,809,880,000
null
UTF-8
Lean
false
false
1,158
lean
import order.filter.basic open filter set variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /- f α → β g ↓ ↓ h γ → δ i -/ variables {f : α → β} {g : α → γ} {h : β → δ} {i : γ → δ} (H : h ∘ f = i ∘ g) include H lemma filter.map_comm (F : filter α) : map h (map f F) = map i (map g F) := by rw [filter.map_map, H, ← filter.map_map] lemma filter.comap_comm (G : filter δ) : comap f (comap h G) = comap g (comap i G) := by rw [filter.comap_comap_comp, H, ← filter.comap_comap_comp] omit H variables (φ : α → β) lemma tendsto_pure (F : filter α) (b : β) : tendsto φ F (pure b) ↔ φ ⁻¹' {b} ∈ F := tendsto_principal variables {G : filter β} {s : set α} {t : set β} {φ} lemma mem_comap_sets_of_inj (h : ∀ a a', φ a = φ a' → a = a') : s ∈ comap φ G ↔ ∃ t ∈ G, s = φ ⁻¹' t := begin rw mem_comap_sets, split ; rintros ⟨t, ht, hts⟩, { use t ∪ φ '' s, split, { simp [mem_sets_of_superset ht] }, { rw [preimage_union, preimage_image_eq _ h], exact (union_eq_self_of_subset_left hts).symm } }, { use [t, ht], rwa hts } end
5c062fb510bd6c6c870e3f780953afcafbfa1d4d
e38e95b38a38a99ecfa1255822e78e4b26f65bb0
/src/certigrad/tfacts.lean
bcfab36a4d81ccaf6f996953a8035c832871260a
[ "Apache-2.0" ]
permissive
ColaDrill/certigrad
fefb1be3670adccd3bed2f3faf57507f156fd501
fe288251f623ac7152e5ce555f1cd9d3a20203c2
refs/heads/master
1,593,297,324,250
1,499,903,753,000
1,499,903,753,000
97,075,797
1
0
null
1,499,916,210,000
1,499,916,210,000
null
UTF-8
Lean
false
false
30,808
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam Miscellaneous facts and theorems about tensors. We view tensors as a field extended component-wise. As such, they form an ordered (but not linearly-ordered) commutative ring. They also have division, except the precondition for cancellation is not `x ≠ 0` but `|x| > 0`, which we simplify to `x > 0`. Note: the axioms are by no means minimal. -/ import .tensor .id .reference .env .dvec -- TODO(dhs): move these elsewhere once #1659 is resolved. attribute [congr] dif_ctx_simp_congr attribute [simp] dif_pos dif_neg namespace certigrad namespace T open list axiom const_scalar : ∀ (α : ℝ), const α [] = α attribute [simp] const_scalar axiom const_mul {shape : S} : Π (α β : ℝ), const (α * β) shape = const α shape * const β shape axiom const_neg {shape : S} : Π (α : ℝ), const (- α) shape = - const α shape axiom const_inv {shape : S} : Π (α : ℝ), const α⁻¹ shape = (const α shape)⁻¹ axiom const_zero {shape : S} : const 0 shape = 0 axiom const_one {shape : S} : const 1 shape = 1 axiom const_bit0 {shape : S} : Π (α : ℝ), const (bit0 α) shape = bit0 (const α shape) axiom const_bit1 {shape : S} : Π (α : ℝ), const (bit1 α) shape = bit1 (const α shape) --attribute [simp] const_mul const_neg const_inv const_zero const_one const_bit0 const_bit1 -- Module structure axiom smul.def (α : ℝ) (shape : S) (x : T shape) : α ⬝ x = const α shape * x axiom smul_neg (α : ℝ) : ∀ {shape : S} (x : T shape), α ⬝ (- x) = - (α ⬝ x) axiom smul_addr (α : ℝ) : ∀ (shape : S) (x y : T shape), α ⬝ (x + y) = α ⬝ x + α ⬝ y axiom smul_addl (α β : ℝ) : ∀ (shape : S) (x : T shape), (α + β) ⬝ x = α ⬝ x + β ⬝ x axiom smul_group (α β : ℝ) : ∀ (shape : S) (x : T shape), (α * β) ⬝ x = α ⬝ (β ⬝ x) axiom smul_flip (α β : ℝ) : ∀ (shape : S) (x : T shape), α ⬝ (β ⬝ x) = β ⬝ (α ⬝ x) axiom one_smul : ∀ (shape : S) (x : T shape), (1 : ℝ) ⬝ x = x axiom smul_zero (α : ℝ) : ∀ (shape : S), α ⬝ (0 : T shape) = 0 axiom zero_smul : ∀ (shape : S) (x : T shape), (0 : ℝ) ⬝ x = 0 axiom smul_mul_scalar_right (α : ℝ) : ∀ (x y : ℝ), α ⬝ (x * y) = x ⬝ (α ⬝ y) axiom smul_mul₁ (α : ℝ) : ∀ {shape : S} (x y : T shape), y * (α ⬝ x) = α ⬝ (x * y) axiom smul_mul₂ (α : ℝ) : ∀ {shape : S} (x y : T shape), (α ⬝ x) * y = α ⬝ (x * y) axiom smul_comm (α β : ℝ) : α ⬝ β = β ⬝ α axiom smul_sum {shape : S} (α : ℝ) (x : T shape) : α ⬝ sum x = sum (α ⬝ x) axiom smul_div {shape : S} (α : ℝ) (x y : T shape) : α ⬝ (x / y) = (α ⬝ x) / y axiom smul_scale : ∀ (α : ℝ) (shape : S) (x : T shape), (α ⬝ 1) * x = α ⬝ x axiom smul_scalar : ∀ (α x : ℝ), (α ⬝ x) = α * x -- sum axiom sum_empty_vec (x : T [0]) : sum x = 0 axiom sum_mat_no_cols {nrows : ℕ} (x : T [nrows, 0]) : sum x = 0 axiom sum_zero : Π {shape : S}, sum (0 : T shape) = 0 axiom sum_add {shape : S} (x y : T shape) : sum (x + y) = sum x + sum y axiom sum_neg {shape : S} (x : T shape) : sum (- x) = - (sum x) axiom sum_smul {shape : S} (α : ℝ) (x : T shape) : sum (α ⬝ x) = α * sum x -- Misc axiom sqrt_mul {shape : S} : ∀ (x y : T shape), sqrt (x * y) = sqrt x * sqrt y axiom sqrt_square {shape : S} : ∀ (x : T shape), sqrt (square x) = x axiom prod_mul {shape : S} : ∀ (x y : T shape), prod (x * y) = prod x * prod y axiom mul_inv_pos {shape : S} : ∀ {x y : T shape}, x > 0 → y > 0 → (x * y)⁻¹ = x⁻¹ * y⁻¹ axiom inv_mul_cancel {shape : S} : ∀ {x : T shape}, x > 0 → (x⁻¹ * x) = 1 axiom mul_inv_cancel {shape : S} : ∀ {x : T shape}, x > 0 → (x * x⁻¹) = 1 axiom div_one {shape : S} : ∀ {x : T shape}, x / 1 = x axiom log_one {shape : S} : log (1 : T shape) = (0 : T shape) axiom log_const {shape : S} (α : ℝ) : log (const α shape) = const (log α) shape axiom exp_inv {shape : S} (x : T shape) : (exp x)⁻¹ = exp (- x) axiom neg_div : ∀ {shape : S} {x y : T shape}, -x / y = -(x / y) axiom log_prod : ∀ {shape : S} {x : T shape}, x > 0 → log (prod x) = sum (log x) axiom log_mul : ∀ {shape : S} {x y : T shape}, x > 0 → y > 0 → log (x * y) = log x + log y axiom log_exp : ∀ {shape : S} {x : T shape}, log (exp x) = x axiom log_sqrt : ∀ {shape : S} {x : T shape}, log (sqrt x) = 2⁻¹ * log x axiom log_inv : ∀ {shape : S} {x : T shape}, log (x⁻¹) = - log x -- Signs axiom nz_of_pos {shape : S} : ∀ {x : T shape}, x > 0 → x ≠ 0 axiom nz_of_div {shape : S} : ∀ {x y : T shape}, x ≠ 0 → y ≠ 0 → x / y ≠ 0 axiom nz_iff {shape : S} : ∀ {x : T shape}, x ≠ 0 ↔ x > 0 ∨ x < 0 axiom nneg_of_pos {shape : S} : ∀ {x : T shape}, x > 0 → x ≥ 0 axiom sqrt_pos {shape : S} : ∀ {x : T shape}, x > 0 → sqrt x > 0 axiom pos_of_sqrt_pos {shape : S} : ∀ {x : T shape}, sqrt x > 0 → x > 0 axiom square_nneg {shape : S} : ∀ {x : T shape}, square x ≥ 0 axiom square_pos_of_pos {shape : S} : ∀ {x : T shape}, 0 < x → 0 < square x axiom square_pos_of_neg {shape : S} : ∀ {x : T shape}, x < 0 → 0 < square x axiom exp_pos {shape : S} : ∀ {x : T shape}, exp x > 0 axiom sigmoid_pos {shape : S} : ∀ {x : T shape}, sigmoid x > 0 axiom sigmoid_lt1 {shape : S} : ∀ {x : T shape}, sigmoid x < 1 axiom lt1_alt {shape : S} : ∀ {x : T shape}, x < 1 → 0 < 1 - x axiom one_plus_pos {shape : S} : ∀ {x : T shape}, x > 0 → 1 + x > 0 axiom one_plus_pos_iff {shape : S} : ∀ {x : T shape}, 0 < 1 + x ↔ (- 1 < x) axiom plus_one_pos {shape : S} : ∀ {x : T shape}, x > 0 → x + 1 > 0 axiom one_pos {shape : S} : (1 : T shape) > 0 axiom neg_of_pos {shape : S} {x : T shape} : x > 0 → - x < 0 axiom const_pos_of_pos {shape : S} {x : ℝ} : x > 0 → const x shape > 0 axiom mul_pos_of_pos_pos {shape : S} {x y : T shape} : x > 0 → y > 0 → x * y > 0 axiom pi_pos {shape : S} : pi shape > 0 axiom inv_pos {shape : S} {x : T shape} : x > 0 → x⁻¹ > 0 axiom div_pos_pos {shape : S} {x y : T shape} : x > 0 → y > 0 → x / y > 0 lemma two_pos {shape : S} : (2 : T shape) > 0 := one_plus_pos one_pos lemma two_pi_pos {shape : S} : 2 * pi shape > 0 := mul_pos_of_pos_pos two_pos pi_pos lemma msigmoid_pos {shape : S} {x : T shape} : 0 < 1 - sigmoid x := lt1_alt sigmoid_lt1 -- div axiom div_mul_cancel {shape : S} : ∀ {x y : T shape}, y > 0 → (x / y) * y = x axiom div_div_eq_div_mul {shape : S} : ∀ (x y z : T shape), (x / y) / z = x / (y * z) axiom div_mul_div {shape : S} : ∀ (x y z w : T shape), (x / y) * (z / w) = (x * z) / (y * w) axiom mul_div_mul {shape : S} : ∀ (x y z : T shape), x * (y / z) = (x / z) * y axiom mul_div_mul_alt {shape : S} : ∀ (x y z : T shape), x * (y / z) = (x * y / z) axiom one_div_inv {shape : S} : ∀ (x : T shape), 1 / x = x⁻¹ axiom div_mul_inv {shape : S} : ∀ (x y : T shape), x / y = x * y⁻¹ axiom div_self {shape : S} : ∀ {x : T shape}, x > 0 → x / x = 1 axiom square_div {shape : S} : ∀ {x y : T shape}, square (x / y) = square x / square y axiom div_add_div_same {shape : S} (x y z : T shape) : x / z + y / z = (x + y) / z lemma div_add_div_same_symm {shape : S} (x y z : T shape) : (x + y) / z = x / z + y / z := by rw div_add_div_same lemma div_sub_div_same {shape : S} (x y z : T shape) : x / z - y / z = (x - y) / z := by simp [T.div_add_div_same_symm, neg_div] lemma div_sub_div_same_symm {shape : S} (x y z : T shape) : (x - y) / z = x / z - y / z := by rw div_sub_div_same lemma div_self_square {shape : S} {x : T shape} (H_pos : x > 0) : x / (x * x)= x⁻¹ := calc x / (x * x) = (x / x) / x : by rw -div_div_eq_div_mul ... = 1 / x : by rw div_self H_pos ... = x⁻¹ : by rw one_div_inv -- integrable axiom is_integrable_const : Π {shape₁ shape₂ : S} (c : T shape₂), is_integrable (λ (x : T shape₁), c) lemma is_integrable_zero {shape₁ shape₂ : S} : is_integrable (λ (x : T shape₁), (0 : T shape₂)) := is_integrable_const (0 : T shape₂) axiom is_integrable_scale : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (α : ℝ), is_integrable f ↔ is_integrable (λ x, α ⬝ f x) axiom is_integrable_neg : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), is_integrable f ↔ is_integrable (λ x, - f x) axiom is_integrable_div : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (y : T shape₂) (Hy : y > 0), is_integrable f ↔ is_integrable (λ x, (f x) / y) axiom is_integrable_add : Π {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂), (is_integrable f ∧ is_integrable g) ↔ is_integrable (λ x, f x + g x) axiom is_integrable_tmulT {ishape oshape fshape : S} (M : T (ishape ++ oshape)) (f : T fshape → T oshape) : is_integrable f ↔ is_integrable (λ x, tmulT M (f x)) axiom is_integrable_sum : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), (is_integrable f) ↔ is_integrable (λ x, sum (f x)) axiom is_integrable_fscale : Π {shape₁ shape₂ : S} (f : T shape₁ → ℝ) (y : T shape₂), is_integrable f ↔ is_integrable (λ x, f x ⬝ y) -- (provable) axiom is_integrable_const_middle : Π {shape₁ shape₂ : S} (pdf : T shape₁ → ℝ) (c : T shape₂), is_integrable (λ (x : T shape₁), pdf x) ↔ is_integrable (λ (x : T shape₁), pdf x ⬝ c) axiom is_integrable_add_middle : Π {shape₁ shape₂ : S} (pdf : T shape₁ → ℝ) (f g : T shape₁ → T shape₂), (is_integrable (λ (x : T shape₁), pdf x ⬝ f x) ∧ is_integrable (λ (x : T shape₁), pdf x ⬝ g x)) ↔ is_integrable (λ (x : T shape₁), pdf x ⬝ (f x + g x)) -- (provable) axiom is_integrable_tmulT_middle {ishape oshape fshape : S} (M : T (ishape ++ oshape)) (pdf : T fshape → ℝ) (f : T fshape → T oshape) : is_integrable (λ (x : T fshape), pdf x ⬝ f x) ↔ is_integrable (λ (x : T fshape), pdf x ⬝ tmulT M (f x)) -- uniformly integrable axiom is_uniformly_integrable_around_binary : Π {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₁ → T shape₂ → T shape₃) (θ : T shape₁), (is_uniformly_integrable_around (λ θ₀ x, f θ₀ θ x) θ ∧ is_uniformly_integrable_around (λ θ₀ x, f θ θ₀ x) θ) ↔ is_uniformly_integrable_around (λ θ₀ x, f θ₀ θ₀ x) θ lemma uint_left {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₁ → T shape₂ → T shape₃) (θ : T shape₁) : is_uniformly_integrable_around (λ θ₀ x, f θ₀ θ₀ x) θ → is_uniformly_integrable_around (λ θ₀ x, f θ₀ θ x) θ := assume H_uint, (iff.mpr (is_uniformly_integrable_around_binary f θ) H_uint)^.left lemma uint_right {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₁ → T shape₂ → T shape₃) (θ : T shape₁) : is_uniformly_integrable_around (λ θ₀ x, f θ₀ θ₀ x) θ → is_uniformly_integrable_around (λ θ₀ x, f θ θ₀ x) θ := assume H_uint, (iff.mpr (is_uniformly_integrable_around_binary f θ) H_uint)^.right -- (provable) axiom is_uniformly_integrable_around_binary_grad : Π {shape₁ shape₂ : S} (f₁ f₂ : T shape₁ → T shape₂ → ℝ) (θ : T shape₁), (∀ x, is_cdifferentiable (λ θ₀, f₁ θ₀ x) θ) → (∀ x, is_cdifferentiable (λ θ₀, f₂ θ₀ x) θ) → (is_uniformly_integrable_around (λ θ₀ x, f₂ θ₀ x ⬝ ∇ (λ θ₁, f₁ θ₁ x) θ₀) θ ∧ is_uniformly_integrable_around (λ θ₀ x, f₁ θ₀ x ⬝ ∇ (λ θ₁, f₂ θ₁ x) θ₀) θ ↔ is_uniformly_integrable_around (λ θ₀ x, ∇ (λ θ₁, f₁ θ₁ x ⬝ f₂ θ₁ x) θ₀) θ) lemma uint_grad_left {shape₁ shape₂ : S} (f₁ f₂ : T shape₁ → T shape₂ → ℝ) (θ : T shape₁) : (∀ x, is_cdifferentiable (λ θ₀, f₁ θ₀ x) θ) → (∀ x, is_cdifferentiable (λ θ₀, f₂ θ₀ x) θ) → is_uniformly_integrable_around (λ θ₀ x, ∇ (λ θ₁, f₁ θ₁ x ⬝ f₂ θ₁ x) θ₀) θ → is_uniformly_integrable_around (λ θ₀ x, f₂ θ₀ x ⬝ ∇ (λ θ₁, f₁ θ₁ x) θ₀) θ := assume H_cdiff₁ H_cdiff₂ H_uint_grad, (iff.mpr (is_uniformly_integrable_around_binary_grad f₁ f₂ θ H_cdiff₁ H_cdiff₂) H_uint_grad)^.left lemma uint_grad_right {shape₁ shape₂ : S} (f₁ f₂ : T shape₁ → T shape₂ → ℝ) (θ : T shape₁) : (∀ x, is_cdifferentiable (λ θ₀, f₁ θ₀ x) θ) → (∀ x, is_cdifferentiable (λ θ₀, f₂ θ₀ x) θ) → is_uniformly_integrable_around (λ θ₀ x, ∇ (λ θ₁, f₁ θ₁ x ⬝ f₂ θ₁ x) θ₀) θ → is_uniformly_integrable_around (λ θ₀ x, f₁ θ₀ x ⬝ ∇ (λ θ₁, f₂ θ₁ x) θ₀) θ := assume H_cdiff₁ H_cdiff₂ H_uint_grad, (iff.mpr (is_uniformly_integrable_around_binary_grad f₁ f₂ θ H_cdiff₁ H_cdiff₂) H_uint_grad)^.right -- integrals axiom integral_scale : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (α : ℝ), ∫ (λ x, α ⬝ f x) = α ⬝ ∫ (λ x, f x) axiom integral_neg : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), ∫ (λ x, - (f x)) = - ∫ (λ x, f x) axiom integral_div : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (y : T shape₂), ∫ (λ x, (f x) / y) = ∫ (λ x, f x) / y axiom integral_add : Π {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂), is_integrable f → is_integrable g → ∫ (λ x, f x + g x) = ∫ (λ x, f x) + ∫ (λ x, g x) axiom integral_fscale : Π {shape₁ shape₂ : S} (f : T shape₁ → ℝ) (y : T shape₂), ∫ (λ x, f x ⬝ y) = ∫ (λ x, f x) ⬝ y axiom integral_pos : ∀ {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), (∀ x, f x > 0) → ∫ (λ x, f x) > 0 axiom integral_nneg : ∀ {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), (∀ x, f x ≥ 0) → ∫ (λ x, f x) ≥ 0 lemma integral_congr {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) (H_fg : ∀ x, f x = g x) : ∫ f = ∫ g := show ∫ (λ x, f x) = ∫ (λ x, g x), by rw (funext H_fg) axiom integral_sum : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), is_integrable f → ∫ (λ x, sum (f x)) = sum (∫ (λ x, f x)) axiom smul_tmulT {ishape oshape : S} (α : ℝ) (M : T (ishape ++ oshape)) (y : T oshape) : α ⬝ (tmulT M y) = tmulT M (α ⬝ y) axiom integral_tmulT {ishape oshape fshape : S} (M : T (ishape ++ oshape)) (f : T fshape → T oshape) : ∫ (λ x, tmulT M (f x)) = tmulT M (∫ f) axiom integral_continuous : ∀ {ishape tshape fshape : S} (f : T ishape → T tshape → T fshape) (θ : T tshape), (∀ x, is_continuous (f x) θ) → is_continuous (λ θ₀, ∫ (λ x₀, f x₀ θ₀)) θ -- D axiom tmulT_scalar {shape : S} : ∀ (x : T (shape ++ [])) (y : ℝ), tmulT x y = y ⬝ (eq.rec_on (append_nil shape) x) axiom D_scalar {shape : S} (f : T shape → ℝ) (θ : T shape) : (eq.rec_on (append_nil shape) (D f θ) : T shape) = ∇ f θ -- dintegral lemma dintegral_pos {oshape : S} : Π {shapes : list S} {f : dvec T shapes → T oshape}, (∀ x, f x > 0) → dintegral (λ x, f x) > 0 | [] f H := by apply H | (shape::shapes) f H := begin dunfold dintegral, apply integral_pos, intro x, apply dintegral_pos, intro xs, apply H, end lemma dintegral_scale {shape : S} (α : ℝ) : Π {shapes : list S} (f : dvec T shapes → T shape), dintegral (λ (xs : dvec T shapes), α ⬝ f xs) = α ⬝ dintegral (λ xs, f xs) | [] f := rfl | (ds::shapes) f := begin dunfold dintegral, simp [λ x, @dintegral_scale shapes (λ v, f (x ::: v))], rw integral_scale, end lemma is_dintegrable_scale {oshape : S} : Π {shapes : list S} (f : dvec T shapes → T oshape) (α : ℝ), is_dintegrable f ↔ is_dintegrable (λ x, α ⬝ f x) | [] f α := begin split, all_goals { intro, exact trivial } end | (shape::shapes) f α := begin dunfold dintegral is_dintegrable, split, { intro Hf, split, { simp only [dintegral_scale], exact iff.mp (is_integrable_scale _ α) Hf^.left }, { intro x, exact iff.mp (is_dintegrable_scale _ _) (Hf^.right x) } }, { intro Hαf, split, { simp only [dintegral_scale] at Hαf, exact iff.mpr (is_integrable_scale _ α) Hαf^.left }, { intro x, exact iff.mpr (is_dintegrable_scale _ _) (Hαf^.right x) } } end lemma dintegral_add {shape : S} : Π {shapes : list S} (f g : dvec T shapes → T shape), is_dintegrable f → is_dintegrable g → dintegral (λ (xs : dvec T shapes), f xs + g xs) = dintegral (λ (xs : dvec T shapes), f xs) + dintegral (λ (xs : dvec T shapes), g xs) | [] f g Hf Hg := rfl | (ds::shapes) f g Hf Hg := begin dunfold dintegral, simp [λ x, @dintegral_add shapes (λ v, f (x ::: v)) (λ v, g (x :::v)) (Hf^.right x) (Hg^.right x)], rw integral_add _ _ Hf^.left Hg^.left end lemma dintegral_div {shape : S} : Π {shapes : list S} (f : dvec T shapes → T shape) (y : T shape), dintegral (λ (xs : dvec T shapes), (f xs) / y) = dintegral (λ (xs : dvec T shapes), f xs) / y | [] f y := rfl | (ds::shapes) f y := begin dunfold dintegral, simp [λ x, @dintegral_div shapes (λ v, f (x ::: v)) y], rw integral_div end lemma dintegral_add_middle {shape : S} : Π {shapes : list S} (pdf : dvec T shapes → ℝ) (f g : dvec T shapes → T shape), is_dintegrable (λ xs, pdf xs ⬝ f xs) → is_dintegrable (λ xs, pdf xs ⬝ g xs) → dintegral (λ (xs : dvec T shapes), pdf xs ⬝ (f xs + g xs)) = dintegral (λ (xs : dvec T shapes), pdf xs ⬝ f xs) + dintegral (λ (xs : dvec T shapes), pdf xs ⬝ g xs) | [] pdf f g Hf Hg := begin dunfold dintegral, apply smul_addr end | (ds::shapes) pdf f g Hf Hg := begin dunfold dintegral, simp [λ x, @dintegral_add_middle shapes (λ v, pdf (x ::: v)) (λ v, f (x ::: v)) (λ v, g (x :::v)) (Hf^.right x) (Hg^.right x)], rw integral_add _ _ Hf^.left Hg^.left end lemma dintegral_neg_middle {shape : S} : Π {shapes : list S} (pdf : dvec T shapes → ℝ) (f : dvec T shapes → T shape), dintegral (λ (xs : dvec T shapes), pdf xs ⬝ - (f xs)) = - dintegral (λ (xs : dvec T shapes), pdf xs ⬝ f xs) | [] pdf f := begin dunfold dintegral, apply smul_neg end | (ds::shapes) pdf f := begin dunfold dintegral, simp [λ x, @dintegral_neg_middle shapes (λ v, pdf (x ::: v)) (λ v, f (x ::: v))], rw integral_neg end lemma dintegral_mul (α : ℝ) : Π {shapes : list S} (f : dvec T shapes → ℝ), dintegral (λ (xs : dvec T shapes), α * f xs) = α * dintegral (λ xs, f xs) := begin intros shapes f, rw -(const_scalar α), simp [λ s x, eq.symm (smul.def α s x)], simp [λ α f, eq.symm (smul_scalar α f)], exact (dintegral_scale α f) end lemma dintegral_scale_middle {shape : S} (α : ℝ) : Π {shapes : list S} (f : dvec T shapes → ℝ) (g : dvec T shapes → T shape), dintegral (λ (xs : dvec T shapes), f xs ⬝ (α ⬝ g xs)) = α ⬝ dintegral (λ xs, f xs ⬝ g xs) | [] f g := begin dunfold dintegral, simp [T.smul.def, mul_comm], end | (ds::shapes) f g := begin dunfold dintegral, simp [λ x, @dintegral_scale_middle shapes (λ v, f (x ::: v)) (λ v, g (x ::: v))], rw integral_scale, end lemma dintegral_mul_middle (α : ℝ) : Π {shapes : list S} (f : dvec T shapes → ℝ) (g : dvec T shapes → ℝ), dintegral (λ (xs : dvec T shapes), f xs ⬝ (α * g xs)) = α * dintegral (λ xs, f xs ⬝ g xs) := begin intros shapes f g, rw -(const_scalar α), simp [λ s x, eq.symm (smul.def α s x)], simp [λ xs, eq.symm (smul_scalar α (g xs))], rw dintegral_scale_middle α f g, simp [smul_scalar] end lemma dintegral_tmulT {shape₁ shape₂ : S} (M : T (shape₁ ++ shape₂)) : Π {shapes : list S} (f : dvec T shapes → T shape₂), dintegral (λ (xs : dvec T shapes), tmulT M (f xs)) = tmulT M (dintegral (λ xs, f xs)) | [] f := rfl | (ds::shapes) f := begin dunfold dintegral, simp [λ x, @dintegral_tmulT shapes (λ v, f (x ::: v))], rw integral_tmulT end lemma dintegral_tmulT_middle {shape₁ shape₂ : S} (M : T (shape₁ ++ shape₂)) : Π {shapes : list S} (f : dvec T shapes → ℝ) (g : dvec T shapes → T shape₂), dintegral (λ (xs : dvec T shapes), f xs ⬝ (tmulT M (g xs))) = tmulT M (dintegral (λ xs, f xs ⬝ g xs)) := begin intros shapes f g, simp [smul_tmulT, dintegral_tmulT] end lemma dintegral_const_middle {yshape : S} : ∀ {shapes : list S} (pdf : dvec T shapes → ℝ) (H_pdf_pos : ∀ x, pdf x > 0) (H_pdf_int1 : dintegral pdf = 1) (y : T yshape), dintegral (λ (xs : dvec T shapes), pdf xs ⬝ y) = y | [] pdf H_pdf_pos H_pdf_int1 y := begin dunfold dintegral, dunfold dintegral at H_pdf_int1, rw H_pdf_int1, rw one_smul end | (shape::shapes) pdf H_pdf_pos H_pdf_int1 y := let pdf' : T shape → dvec T shapes → ℝ := λ x (xs : dvec T shapes), pdf (x ::: xs) / dintegral (λ (xs : dvec T shapes), pdf (x ::: xs)) in have H_dpos : ∀ (x : T shape), dintegral (λ (xs : dvec T shapes), pdf (x ::: xs)) > 0, from λ x, dintegral_pos (λ x, H_pdf_pos _), have H_pdf'_pos : ∀ (x : T shape) (xs : dvec T shapes), pdf' x xs > 0, from assume (x : T shape) (xs : dvec T shapes), have H₁ : pdf (x ::: xs) > 0, by apply H_pdf_pos, T.div_pos_pos H₁ (H_dpos x), have H_pdf'_int1 : ∀ (x : T shape), dintegral (pdf' x) = 1, from assume (x : T shape), begin dsimp, rw T.dintegral_div, exact div_self (H_dpos x) end, have H_inner₁ : ∀ (x : T shape), dintegral (λ (v : dvec T shapes), pdf (x ::: v) ⬝ y) = dintegral (λ (v : dvec T shapes), (pdf' x v * dintegral (λ (vs : dvec T shapes), pdf (x ::: vs))) ⬝ y), from assume (x : T shape), begin dsimp, apply congr_arg, apply funext, intro xs, rw (T.div_mul_cancel (H_dpos _)) end, have H_inner₂ : ∀ x, dintegral (λ (v : dvec T shapes), (pdf' x v * dintegral (λ (vs : dvec T shapes), pdf (x ::: vs))) ⬝ y) = dintegral (λ (vs : dvec T shapes), pdf (x ::: vs)) ⬝ dintegral (λ (v : dvec T shapes), pdf' x v ⬝ y), from assume (x : T shape), begin dsimp, simp [smul_group, dintegral_scale] end, begin dunfold dintegral, simp [H_inner₁, H_inner₂, (λ x, @dintegral_const_middle shapes (pdf' x) (H_pdf'_pos x) (H_pdf'_int1 x)), integral_fscale], change dintegral (λ (vs : dvec T (shape::shapes)), pdf vs) ⬝ y = y, rw [H_pdf_int1, one_smul] end -- btw axioms axiom is_btw_id {shape : S} : is_btw_exp₂ (λ (x : T shape), x) axiom is_btw_const {shape₁ shape₂ : S} (y : T shape₂) : is_btw_exp₂ (λ (x : T shape₁), y) axiom is_btw_sigmoid {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ (λ (x : T shape₁), sigmoid (f x)) axiom is_btw_softplus {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ (λ (x : T shape₁), softplus (f x)) axiom is_btw_sum {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ (λ (x : T shape₁), sum (f x)) axiom is_btw_log_sigmoid {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ (λ (x : T shape₁), log (sigmoid (f x))) axiom is_btw_log_1msigmoid {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ (λ (x : T shape₁), log (1 - sigmoid (f x))) axiom is_btw_gemm {shape : S} {m n p : ℕ} (f : T shape → T [m, n]) (g : T shape → T [n, p]) : is_btw_exp₂ f → is_btw_exp₂ g → is_btw_exp₂ (λ x, gemm (f x) (g x)) axiom is_btw_transpose {shape : S} {m n : ℕ} (f : T shape → T [m, n]) : is_btw_exp₂ f → is_btw_exp₂ (λ x, transpose (f x)) axiom is_btw_neg {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ (λ x, - (f x)) axiom is_btw_inv {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ (λ x, (f x)⁻¹) axiom is_btw_add {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ g → is_btw_exp₂ (λ x, f x + g x) axiom is_btw_mul {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ g → is_btw_exp₂ (λ x, f x * g x) axiom is_btw_sub {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ g → is_btw_exp₂ (λ x, f x - g x) axiom is_btw_div {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ g → is_btw_exp₂ (λ x, f x / g x) axiom is_btw_exp {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_sub_quadratic f → is_btw_exp₂ (λ x, exp (f x)) -- sub quadratic axioms axiom is_sub_quadratic_id {shape : S} : is_sub_quadratic (λ (x : T shape), x) axiom is_sub_quadratic_const {shape₁ shape₂ : S} (y : T shape₂) : is_sub_quadratic (λ (x : T shape₁), y) axiom is_sub_quadratic_gemm {shape : S} {m n p : ℕ} (f : T shape → T [m, n]) (g : T shape → T [n, p]) : is_sub_quadratic f → is_sub_quadratic g → is_sub_quadratic (λ x, gemm (f x) (g x)) axiom is_sub_quadratic_transpose {shape : S} {m n : ℕ} (f : T shape → T [m, n]) : is_sub_quadratic f → is_sub_quadratic (λ x, transpose (f x)) axiom is_sub_quadratic_softplus {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_sub_quadratic f → is_sub_quadratic (λ x, softplus (f x)) axiom is_sub_quadratic_neg {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_sub_quadratic f → is_sub_quadratic (λ x, - (f x)) axiom is_sub_quadratic_mul₁ {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (y : T shape₂) : is_sub_quadratic f → is_sub_quadratic (λ x, y * f x) axiom is_sub_quadratic_mul₂ {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (y : T shape₂) : is_sub_quadratic f → is_sub_quadratic (λ x, f x * y) axiom is_sub_quadratic_add {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_sub_quadratic f → is_sub_quadratic g → is_sub_quadratic (λ x, f x + g x) axiom is_sub_quadratic_sub {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_sub_quadratic f → is_sub_quadratic g → is_sub_quadratic (λ x, f x - g x) -- is_bounded_btw_exp₂_around {shape₁ shape₂ shape₃ : S} (f : Π (x : T shape₁) (θ : T shape₂), T shape₃) (θ : T shape₂) : Prop axiom is_bbtw_of_btw {shape₁ shape₂ shape₃ : S} (f : Π (x : T shape₁), T shape₃) (θ : T shape₂) : is_btw_exp₂ f → is_bounded_btw_exp₂_around (λ x θ₀, f x) θ axiom is_bbtw_id {shape₁ shape₂ : S} (θ : T shape₂) : is_bounded_btw_exp₂_around (λ (x : T shape₁) (θ₀ : T shape₂), θ₀) θ axiom is_bbtw_softplus {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, softplus (f x θ₀)) θ axiom is_bbtw_sum {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, sum (f x θ₀)) θ axiom is_bbtw_log_sigmoid {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, log (sigmoid (f x θ₀))) θ axiom is_bbtw_log_1msigmoid {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, log (1 - sigmoid (f x θ₀))) θ axiom is_bbtw_gemm {shape₁ shape₂ : S} {m n p : ℕ} (f : T shape₁ → T shape₂ → T [m, n]) (g : T shape₁ → T shape₂ → T [n, p]) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around g θ → is_bounded_btw_exp₂_around (λ x θ₀, gemm (f x θ₀) (g x θ₀)) θ axiom is_bbtw_neg {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, - f x θ₀) θ axiom is_bbtw_inv {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, (f x θ₀)⁻¹) θ axiom is_bbtw_add {shape₁ shape₂ shape₃ : S} (f g : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around g θ → is_bounded_btw_exp₂_around (λ x θ₀, f x θ₀ + g x θ₀) θ axiom is_bbtw_sub {shape₁ shape₂ shape₃ : S} (f g : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around g θ → is_bounded_btw_exp₂_around (λ x θ₀, f x θ₀ - g x θ₀) θ axiom is_bbtw_mul {shape₁ shape₂ shape₃ : S} (f g : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around g θ → is_bounded_btw_exp₂_around (λ x θ₀, f x θ₀ * g x θ₀) θ axiom is_bbtw_exp {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_sub_quadratic (λ x, f x θ) → (∀ x, is_sub_quadratic (f x)) → is_bounded_btw_exp₂_around (λ x θ₀, exp (f x θ₀)) θ lemma is_bbtw_bernoulli_neglogpdf {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) (p : T shape₃) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, bernoulli_neglogpdf (sigmoid (f x θ₀)) p) θ := begin intro H, dunfold bernoulli_neglogpdf, apply is_bbtw_neg, apply is_bbtw_sum, apply is_bbtw_add, apply is_bbtw_mul, apply is_bbtw_of_btw, apply is_btw_const, apply is_bbtw_log_sigmoid, exact H, apply is_bbtw_mul, apply is_bbtw_of_btw, apply is_btw_const, apply is_bbtw_log_1msigmoid, exact H end -- misc axiom integral_scale_shift_var {shape fshape : S} (f : T shape → T fshape) (α β : T shape) : ∫ (λ x, f (α * x + β)) = ∫ (λ x, prod α⁻¹ ⬝ f x) @[simp] lemma force_ok {shape : S} (x : T shape) : force x shape = x := by { dunfold force, simp } end T -- helper tactic section tactic open tactic list meta def prove_preconditions_core : tactic unit := first (assumption :: map applyc [`certigrad.T.sqrt_pos, `certigrad.T.square_pos_of_pos, `certigrad.T.exp_pos, `certigrad.T.sigmoid_pos, `certigrad.T.sigmoid_lt1, `certigrad.T.lt1_alt, `certigrad.T.one_plus_pos, `certigrad.T.plus_one_pos, `certigrad.T.one_pos, `certigrad.T.neg_of_pos, `certigrad.T.const_pos_of_pos, `certigrad.T.mul_pos_of_pos_pos, `certigrad.T.pi_pos, `certigrad.T.inv_pos, `certigrad.T.div_pos_pos, `certigrad.T.two_pos, `certigrad.T.two_pi_pos]) meta def prove_preconditions : tactic unit := repeat prove_preconditions_core end tactic end certigrad
68d5c25a83574c432f13e058716ae54d081b80cf
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/zmod/basic_auto.lean
b39831641395c064419c43f1c9ca6d36c573561a
[]
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
17,879
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.int.modeq import Mathlib.algebra.char_p.basic import Mathlib.data.nat.totient import Mathlib.ring_theory.ideal.operations import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. ## Definitions * `zmod n`, which is for integers modulo a nat `n : ℕ` * `val a` is defined as a natural number: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class * `val_min_abs` returns the integer closest to zero in the equivalence class. * A coercion `cast` is defined from `zmod n` into any ring. This is a ring hom if the ring has characteristic dividing `n` -/ namespace fin /-! ## Ring structure on `fin n` We define a commutative ring structure on `fin n`, but we do not register it as instance. Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions to register the ring structure on `zmod n` as type class instance. -/ /-- Negation on `fin n` -/ def has_neg (n : ℕ) : Neg (fin n) := { neg := fun (a : fin n) => { val := int.nat_mod (-↑(subtype.val a)) ↑n, property := sorry } } /-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/ def comm_semigroup (n : ℕ) : comm_semigroup (fin (n + 1)) := comm_semigroup.mk Mul.mul sorry sorry /-- Commutative ring structure on `fin (n+1)`. -/ def comm_ring (n : ℕ) : comm_ring (fin (n + 1)) := comm_ring.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry Neg.neg (ring.sub._default add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry Neg.neg) sorry sorry comm_semigroup.mul sorry 1 fin.one_mul fin.mul_one (left_distrib_aux n) sorry sorry end fin /-- The integers modulo `n : ℕ`. -/ def zmod : ℕ → Type := sorry namespace zmod protected instance fintype (n : ℕ) [fact (0 < n)] : fintype (zmod n) := sorry theorem card (n : ℕ) [fact (0 < n)] : fintype.card (zmod n) = n := nat.cases_on n (fun [_inst_1 : fact (0 < 0)] => False._oldrec (nat.not_lt_zero 0 _inst_1)) (fun (n : ℕ) => fintype.card_fin (n + 1)) _inst_1 protected instance decidable_eq (n : ℕ) : DecidableEq (zmod n) := sorry protected instance has_repr (n : ℕ) : has_repr (zmod n) := sorry protected instance comm_ring (n : ℕ) : comm_ring (zmod n) := sorry protected instance inhabited (n : ℕ) : Inhabited (zmod n) := { default := 0 } /-- `val a` is a natural number defined as: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class See `zmod.val_min_abs` for a variant that takes values in the integers. -/ def val {n : ℕ} : zmod n → ℕ := sorry theorem val_lt {n : ℕ} [fact (0 < n)] (a : zmod n) : val a < n := nat.cases_on n (fun [_inst_1 : fact (0 < 0)] (a : zmod 0) => False._oldrec (nat.not_lt_zero 0 _inst_1)) (fun (n : ℕ) (a : zmod (Nat.succ n)) => fin.is_lt a) _inst_1 a @[simp] theorem val_zero {n : ℕ} : val 0 = 0 := nat.cases_on n (idRhs (val 0 = val 0) rfl) fun (n : ℕ) => idRhs (val 0 = val 0) rfl theorem val_cast_nat {n : ℕ} (a : ℕ) : val ↑a = a % n := sorry protected instance char_p (n : ℕ) : char_p (zmod n) n := sorry @[simp] theorem cast_self (n : ℕ) : ↑n = 0 := char_p.cast_eq_zero (zmod n) n @[simp] theorem cast_self' (n : ℕ) : ↑n + 1 = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (↑n + 1 = 0)) (Eq.symm (nat.cast_add_one n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(n + 1) = 0)) (cast_self (n + 1)))) (Eq.refl 0)) /-- Cast an integer modulo `n` to another semiring. This function is a morphism if the characteristic of `R` divides `n`. See `zmod.cast_hom` for a bundled version. -/ def cast {R : Type u_1} [HasZero R] [HasOne R] [Add R] [Neg R] {n : ℕ} : zmod n → R := sorry -- see Note [coercion into rings] protected instance has_coe_t {R : Type u_1} [HasZero R] [HasOne R] [Add R] [Neg R] (n : ℕ) : has_coe_t (zmod n) R := has_coe_t.mk cast @[simp] theorem cast_zero {n : ℕ} {R : Type u_1} [HasZero R] [HasOne R] [Add R] [Neg R] : ↑0 = 0 := nat.cases_on n (Eq.refl ↑0) fun (n : ℕ) => Eq.refl ↑0 theorem nat_cast_surjective {n : ℕ} [fact (0 < n)] : function.surjective coe := sorry theorem int_cast_surjective {n : ℕ} : function.surjective coe := sorry theorem cast_val {n : ℕ} [fact (0 < n)] (a : zmod n) : ↑(val a) = a := sorry @[simp] theorem cast_id (n : ℕ) (i : zmod n) : ↑i = i := nat.cases_on n (fun (i : zmod 0) => idRhs (↑i = i) (int.cast_id i)) (fun (n : ℕ) (i : zmod (Nat.succ n)) => idRhs (↑(val i) = i) (cast_val i)) i @[simp] theorem nat_cast_val {n : ℕ} {R : Type u_1} [ring R] [fact (0 < n)] (i : zmod n) : ↑(val i) = ↑i := nat.cases_on n (fun [_inst_2 : fact (0 < 0)] (i : zmod 0) => False._oldrec (nat.not_lt_zero 0 _inst_2)) (fun (n : ℕ) (i : zmod (Nat.succ n)) => Eq.refl ↑(val i)) _inst_2 i /-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/ @[simp] theorem cast_one {n : ℕ} {R : Type u_1} [ring R] {m : ℕ} [char_p R m] (h : m ∣ n) : ↑1 = 1 := sorry theorem cast_add {n : ℕ} {R : Type u_1} [ring R] {m : ℕ} [char_p R m] (h : m ∣ n) (a : zmod n) (b : zmod n) : ↑(a + b) = ↑a + ↑b := sorry theorem cast_mul {n : ℕ} {R : Type u_1} [ring R] {m : ℕ} [char_p R m] (h : m ∣ n) (a : zmod n) (b : zmod n) : ↑(a * b) = ↑a * ↑b := sorry /-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`. -/ def cast_hom {n : ℕ} {m : ℕ} (h : m ∣ n) (R : Type u_1) [ring R] [char_p R m] : zmod n →+* R := ring_hom.mk coe (cast_one h) (cast_mul h) sorry (cast_add h) @[simp] theorem cast_hom_apply {n : ℕ} {R : Type u_1} [ring R] {m : ℕ} [char_p R m] {h : m ∣ n} (i : zmod n) : coe_fn (cast_hom h R) i = ↑i := rfl @[simp] theorem cast_sub {n : ℕ} {R : Type u_1} [ring R] {m : ℕ} [char_p R m] (h : m ∣ n) (a : zmod n) (b : zmod n) : ↑(a - b) = ↑a - ↑b := ring_hom.map_sub (cast_hom h R) a b @[simp] theorem cast_neg {n : ℕ} {R : Type u_1} [ring R] {m : ℕ} [char_p R m] (h : m ∣ n) (a : zmod n) : ↑(-a) = -↑a := ring_hom.map_neg (cast_hom h R) a @[simp] theorem cast_pow {n : ℕ} {R : Type u_1} [ring R] {m : ℕ} [char_p R m] (h : m ∣ n) (a : zmod n) (k : ℕ) : ↑(a ^ k) = ↑a ^ k := ring_hom.map_pow (cast_hom h R) a k @[simp] theorem cast_nat_cast {n : ℕ} {R : Type u_1} [ring R] {m : ℕ} [char_p R m] (h : m ∣ n) (k : ℕ) : ↑↑k = ↑k := ring_hom.map_nat_cast (cast_hom h R) k @[simp] theorem cast_int_cast {n : ℕ} {R : Type u_1} [ring R] {m : ℕ} [char_p R m] (h : m ∣ n) (k : ℤ) : ↑↑k = ↑k := ring_hom.map_int_cast (cast_hom h R) k /-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/ @[simp] theorem cast_one' {n : ℕ} {R : Type u_1} [ring R] [char_p R n] : ↑1 = 1 := cast_one (dvd_refl n) @[simp] theorem cast_add' {n : ℕ} {R : Type u_1} [ring R] [char_p R n] (a : zmod n) (b : zmod n) : ↑(a + b) = ↑a + ↑b := cast_add (dvd_refl n) a b @[simp] theorem cast_mul' {n : ℕ} {R : Type u_1} [ring R] [char_p R n] (a : zmod n) (b : zmod n) : ↑(a * b) = ↑a * ↑b := cast_mul (dvd_refl n) a b @[simp] theorem cast_sub' {n : ℕ} {R : Type u_1} [ring R] [char_p R n] (a : zmod n) (b : zmod n) : ↑(a - b) = ↑a - ↑b := cast_sub (dvd_refl n) a b @[simp] theorem cast_pow' {n : ℕ} {R : Type u_1} [ring R] [char_p R n] (a : zmod n) (k : ℕ) : ↑(a ^ k) = ↑a ^ k := cast_pow (dvd_refl n) a k @[simp] theorem cast_nat_cast' {n : ℕ} {R : Type u_1} [ring R] [char_p R n] (k : ℕ) : ↑↑k = ↑k := cast_nat_cast (dvd_refl n) k @[simp] theorem cast_int_cast' {n : ℕ} {R : Type u_1} [ring R] [char_p R n] (k : ℤ) : ↑↑k = ↑k := cast_int_cast (dvd_refl n) k protected instance algebra {n : ℕ} (R : Type u_1) [comm_ring R] [char_p R n] : algebra (zmod n) R := ring_hom.to_algebra (cast_hom (dvd_refl n) R) theorem cast_hom_injective {n : ℕ} (R : Type u_1) [ring R] [char_p R n] : function.injective ⇑(cast_hom (dvd_refl n) R) := sorry theorem cast_hom_bijective {n : ℕ} (R : Type u_1) [ring R] [char_p R n] [fintype R] (h : fintype.card R = n) : function.bijective ⇑(cast_hom (dvd_refl n) R) := sorry /-- The unique ring isomorphism between `zmod n` and a ring `R` of characteristic `n` and cardinality `n`. -/ def ring_equiv {n : ℕ} (R : Type u_1) [ring R] [char_p R n] [fintype R] (h : fintype.card R = n) : zmod n ≃+* R := ring_equiv.of_bijective (cast_hom (dvd_refl n) R) (cast_hom_bijective R h) theorem int_coe_eq_int_coe_iff (a : ℤ) (b : ℤ) (c : ℕ) : ↑a = ↑b ↔ int.modeq (↑c) a b := char_p.int_coe_eq_int_coe_iff (zmod c) c a b theorem nat_coe_eq_nat_coe_iff (a : ℕ) (b : ℕ) (c : ℕ) : ↑a = ↑b ↔ nat.modeq c a b := sorry theorem int_coe_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : ↑a = 0 ↔ ↑b ∣ a := sorry theorem nat_coe_zmod_eq_zero_iff_dvd (a : ℕ) (b : ℕ) : ↑a = 0 ↔ b ∣ a := sorry @[simp] theorem cast_mod_int (a : ℤ) (b : ℕ) : ↑(a % ↑b) = ↑a := eq.mpr (id (Eq._oldrec (Eq.refl (↑(a % ↑b) = ↑a)) (propext (int_coe_eq_int_coe_iff (a % ↑b) a b)))) (int.modeq.mod_modeq a ↑b) @[simp] theorem coe_to_nat (p : ℕ) {z : ℤ} (h : 0 ≤ z) : ↑(int.to_nat z) = ↑z := sorry theorem val_injective (n : ℕ) [fact (0 < n)] : function.injective val := nat.cases_on n (fun [_inst_1 : fact (0 < 0)] => id fun (a₁ : zmod 0) => False._oldrec (nat.not_lt_zero 0 _inst_1)) (fun (n : ℕ) => id fun (a b : zmod (Nat.succ n)) (h : val a = val b) => fin.ext h) _inst_1 theorem val_one_eq_one_mod (n : ℕ) : val 1 = 1 % n := eq.mpr (id (Eq._oldrec (Eq.refl (val 1 = 1 % n)) (Eq.symm nat.cast_one))) (eq.mpr (id (Eq._oldrec (Eq.refl (val ↑1 = 1 % n)) (val_cast_nat 1))) (Eq.refl (1 % n))) theorem val_one (n : ℕ) [fact (1 < n)] : val 1 = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (val 1 = 1)) (val_one_eq_one_mod n))) (nat.mod_eq_of_lt _inst_1) theorem val_add {n : ℕ} [fact (0 < n)] (a : zmod n) (b : zmod n) : val (a + b) = (val a + val b) % n := nat.cases_on n (fun [_inst_1 : fact (0 < 0)] (a b : zmod 0) => False._oldrec (nat.not_lt_zero 0 _inst_1)) (fun (n : ℕ) (a b : zmod (Nat.succ n)) => fin.val_add a b) _inst_1 a b theorem val_mul {n : ℕ} (a : zmod n) (b : zmod n) : val (a * b) = val a * val b % n := sorry protected instance nontrivial (n : ℕ) [fact (1 < n)] : nontrivial (zmod n) := nontrivial.mk (Exists.intro 0 (Exists.intro 1 fun (h : 0 = 1) => zero_ne_one (Eq.trans (Eq.trans (eq.mpr (id (Eq._oldrec (Eq.refl (0 = val 0)) val_zero)) (Eq.refl 0)) (congr_arg val h)) (val_one n)))) /-- The inversion on `zmod n`. It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`. In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/ def inv (n : ℕ) : zmod n → zmod n := sorry protected instance has_inv (n : ℕ) : has_inv (zmod n) := has_inv.mk (inv n) theorem inv_zero (n : ℕ) : 0⁻¹ = 0 := sorry theorem mul_inv_eq_gcd {n : ℕ} (a : zmod n) : a * (a⁻¹) = ↑(nat.gcd (val a) n) := sorry @[simp] theorem cast_mod_nat (n : ℕ) (a : ℕ) : ↑(a % n) = ↑a := sorry theorem eq_iff_modeq_nat (n : ℕ) {a : ℕ} {b : ℕ} : ↑a = ↑b ↔ nat.modeq n a b := sorry theorem coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : nat.coprime x n) : ↑x * (↑x⁻¹) = 1 := sorry /-- `unit_of_coprime` makes an element of `units (zmod n)` given a natural number `x` and a proof that `x` is coprime to `n` -/ def unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : units (zmod n) := units.mk (↑x) (↑x⁻¹) (coe_mul_inv_eq_one x h) sorry @[simp] theorem cast_unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : ↑(unit_of_coprime x h) = ↑x := rfl theorem val_coe_unit_coprime {n : ℕ} (u : units (zmod n)) : nat.coprime (val ↑u) n := sorry @[simp] theorem inv_coe_unit {n : ℕ} (u : units (zmod n)) : ↑u⁻¹ = ↑(u⁻¹) := sorry theorem mul_inv_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a * (a⁻¹) = 1 := sorry theorem inv_mul_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a⁻¹ * a = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * a = 1)) (mul_comm (a⁻¹) a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (a⁻¹) = 1)) (mul_inv_of_unit a h))) (Eq.refl 1)) /-- Equivalence between the units of `zmod n` and the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/ def units_equiv_coprime {n : ℕ} [fact (0 < n)] : units (zmod n) ≃ Subtype fun (x : zmod n) => nat.coprime (val x) n := equiv.mk (fun (x : units (zmod n)) => { val := ↑x, property := val_coe_unit_coprime x }) (fun (x : Subtype fun (x : zmod n) => nat.coprime (val x) n) => unit_of_coprime (val (subtype.val x)) sorry) sorry sorry @[simp] theorem card_units_eq_totient (n : ℕ) [fact (0 < n)] : fintype.card (units (zmod n)) = nat.totient n := sorry protected instance subsingleton_units : subsingleton (units (zmod (bit0 1))) := subsingleton.intro fun (x y : units (zmod (bit0 1))) => units.cases_on x fun (x xi : zmod (bit0 1)) (x_val_inv : x * xi = 1) (x_inv_val : xi * x = 1) => units.cases_on y fun (y yi : zmod (bit0 1)) (y_val_inv : y * yi = 1) (y_inv_val : yi * y = 1) => of_as_true trivial x y xi yi x_val_inv x_inv_val y_val_inv y_inv_val theorem le_div_two_iff_lt_neg (n : ℕ) [hn : fact (n % bit0 1 = 1)] {x : zmod n} (hx0 : x ≠ 0) : val x ≤ n / bit0 1 ↔ n / bit0 1 < val (-x) := sorry theorem ne_neg_self (n : ℕ) [hn : fact (n % bit0 1 = 1)] {a : zmod n} (ha : a ≠ 0) : a ≠ -a := sorry theorem neg_one_ne_one {n : ℕ} [fact (bit0 1 < n)] : -1 ≠ 1 := char_p.neg_one_ne_one (zmod n) n @[simp] theorem neg_eq_self_mod_two (a : zmod (bit0 1)) : -a = a := of_as_true trivial @[simp] theorem nat_abs_mod_two (a : ℤ) : ↑(int.nat_abs a) = ↑a := sorry @[simp] theorem val_eq_zero {n : ℕ} (a : zmod n) : val a = 0 ↔ a = 0 := sorry theorem val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : val ↑a = a := eq.mpr (id (Eq._oldrec (Eq.refl (val ↑a = a)) (val_cast_nat a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a % n = a)) (nat.mod_eq_of_lt h))) (Eq.refl a)) theorem neg_val' {n : ℕ} [fact (0 < n)] (a : zmod n) : val (-a) = (n - val a) % n := sorry theorem neg_val {n : ℕ} [fact (0 < n)] (a : zmod n) : val (-a) = ite (a = 0) 0 (n - val a) := sorry /-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`, The result will be in the interval `(-n/2, n/2]`. -/ def val_min_abs {n : ℕ} : zmod n → ℤ := sorry @[simp] theorem val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl theorem val_min_abs_def_pos {n : ℕ} [fact (0 < n)] (x : zmod n) : val_min_abs x = ite (val x ≤ n / bit0 1) (↑(val x)) (↑(val x) - ↑n) := nat.cases_on n (fun [_inst_1 : fact (0 < 0)] (x : zmod 0) => False._oldrec (nat.not_lt_zero 0 _inst_1)) (fun (n : ℕ) (x : zmod (Nat.succ n)) => Eq.refl (val_min_abs x)) _inst_1 x @[simp] theorem coe_val_min_abs {n : ℕ} (x : zmod n) : ↑(val_min_abs x) = x := sorry theorem nat_abs_val_min_abs_le {n : ℕ} [fact (0 < n)] (x : zmod n) : int.nat_abs (val_min_abs x) ≤ n / bit0 1 := sorry @[simp] theorem val_min_abs_zero (n : ℕ) : val_min_abs 0 = 0 := sorry @[simp] theorem val_min_abs_eq_zero {n : ℕ} (x : zmod n) : val_min_abs x = 0 ↔ x = 0 := sorry theorem cast_nat_abs_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : ↑(int.nat_abs (val_min_abs a)) = ite (val a ≤ n / bit0 1) a (-a) := sorry @[simp] theorem nat_abs_val_min_abs_neg {n : ℕ} (a : zmod n) : int.nat_abs (val_min_abs (-a)) = int.nat_abs (val_min_abs a) := sorry theorem val_eq_ite_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : ↑(val a) = val_min_abs a + ite (val a ≤ n / bit0 1) 0 ↑n := sorry theorem prime_ne_zero (p : ℕ) (q : ℕ) [hp : fact (nat.prime p)] [hq : fact (nat.prime q)] (hpq : p ≠ q) : ↑q ≠ 0 := sorry end zmod namespace zmod /-- Field structure on `zmod p` if `p` is prime. -/ protected instance field (p : ℕ) [fact (nat.prime p)] : field (zmod p) := field.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry has_inv.inv sorry (mul_inv_cancel_aux p) (inv_zero p) end zmod theorem ring_hom.ext_zmod {n : ℕ} {R : Type u_1} [semiring R] (f : zmod n →+* R) (g : zmod n →+* R) : f = g := sorry namespace zmod protected instance subsingleton_ring_hom {n : ℕ} {R : Type u_1} [semiring R] : subsingleton (zmod n →+* R) := subsingleton.intro ring_hom.ext_zmod protected instance subsingleton_ring_equiv {n : ℕ} {R : Type u_1} [semiring R] : subsingleton (zmod n ≃+* R) := subsingleton.intro fun (f g : zmod n ≃+* R) => eq.mpr (id (Eq._oldrec (Eq.refl (f = g)) (propext (ring_equiv.coe_ring_hom_inj_iff f g)))) (ring_hom.ext_zmod ↑f ↑g) theorem ring_hom_surjective {n : ℕ} {R : Type u_1} [ring R] (f : R →+* zmod n) : function.surjective ⇑f := sorry theorem ring_hom_eq_of_ker_eq {n : ℕ} {R : Type u_1} [comm_ring R] (f : R →+* zmod n) (g : R →+* zmod n) (h : ring_hom.ker f = ring_hom.ker g) : f = g := sorry end Mathlib
a104a84241287e9a86dcc2a5f8d5c39d176ff9f6
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/calculus/specific_functions.lean
1dd2f676a78735bb005931ba152dea02e55810f2
[ "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
18,869
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.iterated_deriv import analysis.inner_product_space.euclidean_dist /-! # Infinitely smooth bump function In this file we construct several infinitely smooth functions with properties that an analytic function cannot have: * `exp_neg_inv_glue` is equal to zero for `x ≤ 0` and is strictly positive otherwise; it is given by `x ↦ exp (-1/x)` for `x > 0`; * `real.smooth_transition` is equal to zero for `x ≤ 0` and is equal to one for `x ≥ 1`; it is given by `exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x))`; * `f : times_cont_diff_bump_of_inner c`, where `c` is a point in an inner product space, is a bundled smooth function such that - `f` is equal to `1` in `metric.closed_ball c f.r`; - `support f = metric.ball c f.R`; - `0 ≤ f x ≤ 1` for all `x`. The structure `times_cont_diff_bump_of_inner` contains the data required to construct the function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`. * `f : times_cont_diff_bump c`, where `c` is a point in a finite dimensional real vector space, is a bundled smooth function such that - `f` is equal to `1` in `euclidean.closed_ball c f.r`; - `support f = euclidean.ball c f.R`; - `0 ≤ f x ≤ 1` for all `x`. The structure `times_cont_diff_bump` contains the data required to construct the function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`. -/ noncomputable theory open_locale classical topological_space open polynomial real filter set function /-- `exp_neg_inv_glue` is the real function given by `x ↦ exp (-1/x)` for `x > 0` and `0` for `x ≤ 0`. It is a basic building block to construct smooth partitions of unity. Its main property is that it vanishes for `x ≤ 0`, it is positive for `x > 0`, and the junction between the two behaviors is flat enough to retain smoothness. The fact that this function is `C^∞` is proved in `exp_neg_inv_glue.smooth`. -/ def exp_neg_inv_glue (x : ℝ) : ℝ := if x ≤ 0 then 0 else exp (-x⁻¹) namespace exp_neg_inv_glue /-- Our goal is to prove that `exp_neg_inv_glue` is `C^∞`. For this, we compute its successive derivatives for `x > 0`. The `n`-th derivative is of the form `P_aux n (x) exp(-1/x) / x^(2 n)`, where `P_aux n` is computed inductively. -/ noncomputable def P_aux : ℕ → polynomial ℝ | 0 := 1 | (n+1) := X^2 * (P_aux n).derivative + (1 - C ↑(2 * n) * X) * (P_aux n) /-- Formula for the `n`-th derivative of `exp_neg_inv_glue`, as an auxiliary function `f_aux`. -/ def f_aux (n : ℕ) (x : ℝ) : ℝ := if x ≤ 0 then 0 else (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n) /-- The `0`-th auxiliary function `f_aux 0` coincides with `exp_neg_inv_glue`, by definition. -/ lemma f_aux_zero_eq : f_aux 0 = exp_neg_inv_glue := begin ext x, by_cases h : x ≤ 0, { simp [exp_neg_inv_glue, f_aux, h] }, { simp [h, exp_neg_inv_glue, f_aux, ne_of_gt (not_le.1 h), P_aux] } end /-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n` (given in this statement in unfolded form) is the `n+1`-th auxiliary function, since the polynomial `P_aux (n+1)` was chosen precisely to ensure this. -/ lemma f_aux_deriv (n : ℕ) (x : ℝ) (hx : x ≠ 0) : has_deriv_at (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)) ((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x := begin have A : ∀k:ℕ, 2 * (k + 1) - 1 = 2 * k + 1, { assume k, rw tsub_eq_iff_eq_add_of_le, { ring }, { simp [mul_add] } }, convert (((P_aux n).has_deriv_at x).mul (((has_deriv_at_exp _).comp x (has_deriv_at_inv hx).neg))).div (has_deriv_at_pow (2 * n) x) (pow_ne_zero _ hx) using 1, field_simp [hx, P_aux], -- `ring_exp` can't solve `p ∨ q` goal generated by `mul_eq_mul_right_iff` cases n; simp [nat.succ_eq_add_one, A, -mul_eq_mul_right_iff]; ring_exp end /-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n` is the `n+1`-th auxiliary function. -/ lemma f_aux_deriv_pos (n : ℕ) (x : ℝ) (hx : 0 < x) : has_deriv_at (f_aux n) ((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x := begin apply (f_aux_deriv n x (ne_of_gt hx)).congr_of_eventually_eq, filter_upwards [lt_mem_nhds hx] with _ hy, simp [f_aux, hy.not_le] end /-- To get differentiability at `0` of the auxiliary functions, we need to know that their limit is `0`, to be able to apply general differentiability extension theorems. This limit is checked in this lemma. -/ lemma f_aux_limit (n : ℕ) : tendsto (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)) (𝓝[>] 0) (𝓝 0) := begin have A : tendsto (λx, (P_aux n).eval x) (𝓝[>] 0) (𝓝 ((P_aux n).eval 0)) := (P_aux n).continuous_within_at, have B : tendsto (λx, exp (-x⁻¹) / x^(2 * n)) (𝓝[>] 0) (𝓝 0), { convert (tendsto_pow_mul_exp_neg_at_top_nhds_0 (2 * n)).comp tendsto_inv_zero_at_top, ext x, field_simp }, convert A.mul B; simp [mul_div_assoc] end /-- Deduce from the limiting behavior at `0` of its derivative and general differentiability extension theorems that the auxiliary function `f_aux n` is differentiable at `0`, with derivative `0`. -/ lemma f_aux_deriv_zero (n : ℕ) : has_deriv_at (f_aux n) 0 0 := begin -- we check separately differentiability on the left and on the right have A : has_deriv_within_at (f_aux n) (0 : ℝ) (Iic 0) 0, { apply (has_deriv_at_const (0 : ℝ) (0 : ℝ)).has_deriv_within_at.congr, { assume y hy, simp at hy, simp [f_aux, hy] }, { simp [f_aux, le_refl] } }, have B : has_deriv_within_at (f_aux n) (0 : ℝ) (Ici 0) 0, { have diff : differentiable_on ℝ (f_aux n) (Ioi 0) := λx hx, (f_aux_deriv_pos n x hx).differentiable_at.differentiable_within_at, -- next line is the nontrivial bit of this proof, appealing to differentiability -- extension results. apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff _ self_mem_nhds_within, { refine (f_aux_limit (n+1)).congr' _, apply mem_of_superset self_mem_nhds_within (λx hx, _), simp [(f_aux_deriv_pos n x hx).deriv] }, { have : f_aux n 0 = 0, by simp [f_aux, le_refl], simp only [continuous_within_at, this], refine (f_aux_limit n).congr' _, apply mem_of_superset self_mem_nhds_within (λx hx, _), have : ¬(x ≤ 0), by simpa using hx, simp [f_aux, this] } }, simpa using A.union B, end /-- At every point, the auxiliary function `f_aux n` has a derivative which is equal to `f_aux (n+1)`. -/ lemma f_aux_has_deriv_at (n : ℕ) (x : ℝ) : has_deriv_at (f_aux n) (f_aux (n+1) x) x := begin -- check separately the result for `x < 0`, where it is trivial, for `x > 0`, where it is done -- in `f_aux_deriv_pos`, and for `x = 0`, done in -- `f_aux_deriv_zero`. rcases lt_trichotomy x 0 with hx|hx|hx, { have : f_aux (n+1) x = 0, by simp [f_aux, le_of_lt hx], rw this, apply (has_deriv_at_const x (0 : ℝ)).congr_of_eventually_eq, filter_upwards [gt_mem_nhds hx] with _ hy, simp [f_aux, hy.le] }, { have : f_aux (n + 1) 0 = 0, by simp [f_aux, le_refl], rw [hx, this], exact f_aux_deriv_zero n }, { have : f_aux (n+1) x = (P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n+1)), by simp [f_aux, not_le_of_gt hx], rw this, exact f_aux_deriv_pos n x hx }, end /-- The successive derivatives of the auxiliary function `f_aux 0` are the functions `f_aux n`, by induction. -/ lemma f_aux_iterated_deriv (n : ℕ) : iterated_deriv n (f_aux 0) = f_aux n := begin induction n with n IH, { simp }, { simp [iterated_deriv_succ, IH], ext x, exact (f_aux_has_deriv_at n x).deriv } end /-- The function `exp_neg_inv_glue` is smooth. -/ protected theorem times_cont_diff {n} : times_cont_diff ℝ n exp_neg_inv_glue := begin rw ← f_aux_zero_eq, apply times_cont_diff_of_differentiable_iterated_deriv (λ m hm, _), rw f_aux_iterated_deriv m, exact λ x, (f_aux_has_deriv_at m x).differentiable_at end /-- The function `exp_neg_inv_glue` vanishes on `(-∞, 0]`. -/ lemma zero_of_nonpos {x : ℝ} (hx : x ≤ 0) : exp_neg_inv_glue x = 0 := by simp [exp_neg_inv_glue, hx] /-- The function `exp_neg_inv_glue` is positive on `(0, +∞)`. -/ lemma pos_of_pos {x : ℝ} (hx : 0 < x) : 0 < exp_neg_inv_glue x := by simp [exp_neg_inv_glue, not_le.2 hx, exp_pos] /-- The function exp_neg_inv_glue` is nonnegative. -/ lemma nonneg (x : ℝ) : 0 ≤ exp_neg_inv_glue x := begin cases le_or_gt x 0, { exact ge_of_eq (zero_of_nonpos h) }, { exact le_of_lt (pos_of_pos h) } end end exp_neg_inv_glue /-- An infinitely smooth function `f : ℝ → ℝ` such that `f x = 0` for `x ≤ 0`, `f x = 1` for `1 ≤ x`, and `0 < f x < 1` for `0 < x < 1`. -/ def real.smooth_transition (x : ℝ) : ℝ := exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x)) namespace real namespace smooth_transition variables {x : ℝ} open exp_neg_inv_glue lemma pos_denom (x) : 0 < exp_neg_inv_glue x + exp_neg_inv_glue (1 - x) := ((@zero_lt_one ℝ _ _).lt_or_lt x).elim (λ hx, add_pos_of_pos_of_nonneg (pos_of_pos hx) (nonneg _)) (λ hx, add_pos_of_nonneg_of_pos (nonneg _) (pos_of_pos $ sub_pos.2 hx)) lemma one_of_one_le (h : 1 ≤ x) : smooth_transition x = 1 := (div_eq_one_iff_eq $ (pos_denom x).ne').2 $ by rw [zero_of_nonpos (sub_nonpos.2 h), add_zero] lemma zero_of_nonpos (h : x ≤ 0) : smooth_transition x = 0 := by rw [smooth_transition, zero_of_nonpos h, zero_div] lemma le_one (x : ℝ) : smooth_transition x ≤ 1 := (div_le_one (pos_denom x)).2 $ le_add_of_nonneg_right (nonneg _) lemma nonneg (x : ℝ) : 0 ≤ smooth_transition x := div_nonneg (exp_neg_inv_glue.nonneg _) (pos_denom x).le lemma lt_one_of_lt_one (h : x < 1) : smooth_transition x < 1 := (div_lt_one $ pos_denom x).2 $ lt_add_of_pos_right _ $ pos_of_pos $ sub_pos.2 h lemma pos_of_pos (h : 0 < x) : 0 < smooth_transition x := div_pos (exp_neg_inv_glue.pos_of_pos h) (pos_denom x) protected lemma times_cont_diff {n} : times_cont_diff ℝ n smooth_transition := exp_neg_inv_glue.times_cont_diff.div (exp_neg_inv_glue.times_cont_diff.add $ exp_neg_inv_glue.times_cont_diff.comp $ times_cont_diff_const.sub times_cont_diff_id) $ λ x, (pos_denom x).ne' protected lemma times_cont_diff_at {x n} : times_cont_diff_at ℝ n smooth_transition x := smooth_transition.times_cont_diff.times_cont_diff_at end smooth_transition end real variable {E : Type*} /-- `f : times_cont_diff_bump_of_inner c`, where `c` is a point in an inner product space, is a bundled smooth function such that - `f` is equal to `1` in `metric.closed_ball c f.r`; - `support f = metric.ball c f.R`; - `0 ≤ f x ≤ 1` for all `x`. The structure `times_cont_diff_bump_of_inner` contains the data required to construct the function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`. -/ structure times_cont_diff_bump_of_inner (c : E) := (r R : ℝ) (r_pos : 0 < r) (r_lt_R : r < R) namespace times_cont_diff_bump_of_inner lemma R_pos {c : E} (f : times_cont_diff_bump_of_inner c) : 0 < f.R := f.r_pos.trans f.r_lt_R instance (c : E) : inhabited (times_cont_diff_bump_of_inner c) := ⟨⟨1, 2, zero_lt_one, one_lt_two⟩⟩ variables [inner_product_space ℝ E] {c : E} (f : times_cont_diff_bump_of_inner c) {x : E} /-- The function defined by `f : times_cont_diff_bump_of_inner c`. Use automatic coercion to function instead. -/ def to_fun (f : times_cont_diff_bump_of_inner c) : E → ℝ := λ x, real.smooth_transition ((f.R - dist x c) / (f.R - f.r)) instance : has_coe_to_fun (times_cont_diff_bump_of_inner c) (λ _, E → ℝ) := ⟨to_fun⟩ open real (smooth_transition) real.smooth_transition metric lemma one_of_mem_closed_ball (hx : x ∈ closed_ball c f.r) : f x = 1 := one_of_one_le $ (one_le_div (sub_pos.2 f.r_lt_R)).2 $ sub_le_sub_left hx _ lemma nonneg : 0 ≤ f x := nonneg _ lemma le_one : f x ≤ 1 := le_one _ lemma pos_of_mem_ball (hx : x ∈ ball c f.R) : 0 < f x := pos_of_pos $ div_pos (sub_pos.2 hx) (sub_pos.2 f.r_lt_R) lemma lt_one_of_lt_dist (h : f.r < dist x c) : f x < 1 := lt_one_of_lt_one $ (div_lt_one (sub_pos.2 f.r_lt_R)).2 $ sub_lt_sub_left h _ lemma zero_of_le_dist (hx : f.R ≤ dist x c) : f x = 0 := zero_of_nonpos $ div_nonpos_of_nonpos_of_nonneg (sub_nonpos.2 hx) (sub_nonneg.2 f.r_lt_R.le) lemma support_eq : support (f : E → ℝ) = metric.ball c f.R := begin ext x, suffices : f x ≠ 0 ↔ dist x c < f.R, by simpa [mem_support], cases lt_or_le (dist x c) f.R with hx hx, { simp [hx, (f.pos_of_mem_ball hx).ne'] }, { simp [hx.not_lt, f.zero_of_le_dist hx] } end lemma eventually_eq_one_of_mem_ball (h : x ∈ ball c f.r) : f =ᶠ[𝓝 x] 1 := ((is_open_lt (continuous_id.dist continuous_const) continuous_const).eventually_mem h).mono $ λ z hz, f.one_of_mem_closed_ball (le_of_lt hz) lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 := f.eventually_eq_one_of_mem_ball (mem_ball_self f.r_pos) protected lemma times_cont_diff_at {n} : times_cont_diff_at ℝ n f x := begin rcases em (x = c) with rfl|hx, { refine times_cont_diff_at.congr_of_eventually_eq _ f.eventually_eq_one, rw pi.one_def, exact times_cont_diff_at_const }, { exact real.smooth_transition.times_cont_diff_at.comp x (times_cont_diff_at.div_const $ times_cont_diff_at_const.sub $ times_cont_diff_at_id.dist times_cont_diff_at_const hx) } end protected lemma times_cont_diff {n} : times_cont_diff ℝ n f := times_cont_diff_iff_times_cont_diff_at.2 $ λ y, f.times_cont_diff_at protected lemma times_cont_diff_within_at {s n} : times_cont_diff_within_at ℝ n f s x := f.times_cont_diff_at.times_cont_diff_within_at end times_cont_diff_bump_of_inner /-- `f : times_cont_diff_bump c`, where `c` is a point in a finite dimensional real vector space, is a bundled smooth function such that - `f` is equal to `1` in `euclidean.closed_ball c f.r`; - `support f = euclidean.ball c f.R`; - `0 ≤ f x ≤ 1` for all `x`. The structure `times_cont_diff_bump` contains the data required to construct the function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`.-/ structure times_cont_diff_bump [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] (c : E) extends times_cont_diff_bump_of_inner (to_euclidean c) namespace times_cont_diff_bump variables [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {c x : E} (f : times_cont_diff_bump c) /-- The function defined by `f : times_cont_diff_bump c`. Use automatic coercion to function instead. -/ def to_fun (f : times_cont_diff_bump c) : E → ℝ := f.to_times_cont_diff_bump_of_inner ∘ to_euclidean instance : has_coe_to_fun (times_cont_diff_bump c) (λ _, E → ℝ) := ⟨to_fun⟩ instance (c : E) : inhabited (times_cont_diff_bump c) := ⟨⟨default⟩⟩ lemma R_pos : 0 < f.R := f.to_times_cont_diff_bump_of_inner.R_pos lemma coe_eq_comp : ⇑f = f.to_times_cont_diff_bump_of_inner ∘ to_euclidean := rfl lemma one_of_mem_closed_ball (hx : x ∈ euclidean.closed_ball c f.r) : f x = 1 := f.to_times_cont_diff_bump_of_inner.one_of_mem_closed_ball hx lemma nonneg : 0 ≤ f x := f.to_times_cont_diff_bump_of_inner.nonneg lemma le_one : f x ≤ 1 := f.to_times_cont_diff_bump_of_inner.le_one lemma pos_of_mem_ball (hx : x ∈ euclidean.ball c f.R) : 0 < f x := f.to_times_cont_diff_bump_of_inner.pos_of_mem_ball hx lemma lt_one_of_lt_dist (h : f.r < euclidean.dist x c) : f x < 1 := f.to_times_cont_diff_bump_of_inner.lt_one_of_lt_dist h lemma zero_of_le_dist (hx : f.R ≤ euclidean.dist x c) : f x = 0 := f.to_times_cont_diff_bump_of_inner.zero_of_le_dist hx lemma support_eq : support (f : E → ℝ) = euclidean.ball c f.R := by rw [euclidean.ball_eq_preimage, ← f.to_times_cont_diff_bump_of_inner.support_eq, ← support_comp_eq_preimage, coe_eq_comp] lemma closure_support_eq : closure (support f) = euclidean.closed_ball c f.R := by rw [f.support_eq, euclidean.closure_ball _ f.R_pos] lemma compact_closure_support : is_compact (closure (support f)) := by { rw f.closure_support_eq, exact euclidean.is_compact_closed_ball } lemma eventually_eq_one_of_mem_ball (h : x ∈ euclidean.ball c f.r) : f =ᶠ[𝓝 x] 1 := to_euclidean.continuous_at (f.to_times_cont_diff_bump_of_inner.eventually_eq_one_of_mem_ball h) lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 := f.eventually_eq_one_of_mem_ball $ euclidean.mem_ball_self f.r_pos protected lemma times_cont_diff {n} : times_cont_diff ℝ n f := f.to_times_cont_diff_bump_of_inner.times_cont_diff.comp (to_euclidean : E ≃L[ℝ] _).times_cont_diff protected lemma times_cont_diff_at {n} : times_cont_diff_at ℝ n f x := f.times_cont_diff.times_cont_diff_at protected lemma times_cont_diff_within_at {s n} : times_cont_diff_within_at ℝ n f s x := f.times_cont_diff_at.times_cont_diff_within_at lemma exists_closure_support_subset {s : set E} (hs : s ∈ 𝓝 c) : ∃ f : times_cont_diff_bump c, closure (support f) ⊆ s := let ⟨R, h0, hR⟩ := euclidean.nhds_basis_closed_ball.mem_iff.1 hs in ⟨⟨⟨R / 2, R, half_pos h0, half_lt_self h0⟩⟩, by rwa closure_support_eq⟩ lemma exists_closure_subset {R : ℝ} (hR : 0 < R) {s : set E} (hs : is_closed s) (hsR : s ⊆ euclidean.ball c R) : ∃ f : times_cont_diff_bump c, f.R = R ∧ s ⊆ euclidean.ball c f.r := begin rcases euclidean.exists_pos_lt_subset_ball hR hs hsR with ⟨r, hr, hsr⟩, exact ⟨⟨⟨r, R, hr.1, hr.2⟩⟩, rfl, hsr⟩ end end times_cont_diff_bump open finite_dimensional metric /-- If `E` is a finite dimensional normed space over `ℝ`, then for any point `x : E` and its neighborhood `s` there exists an infinitely smooth function with the following properties: * `f y = 1` in a neighborhood of `x`; * `f y = 0` outside of `s`; * moreover, `closure (support f) ⊆ s` and `closure (support f)` is a compact set; * `f y ∈ [0, 1]` for all `y`. This lemma is a simple wrapper around lemmas about bundled smooth bump functions, see `times_cont_diff_bump`. -/ lemma exists_times_cont_diff_bump_function_of_mem_nhds [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {x : E} {s : set E} (hs : s ∈ 𝓝 x) : ∃ f : E → ℝ, f =ᶠ[𝓝 x] 1 ∧ (∀ y, f y ∈ Icc (0 : ℝ) 1) ∧ times_cont_diff ℝ ⊤ f ∧ is_compact (closure $ support f) ∧ closure (support f) ⊆ s := let ⟨f, hf⟩ := times_cont_diff_bump.exists_closure_support_subset hs in ⟨f, f.eventually_eq_one, λ y, ⟨f.nonneg, f.le_one⟩, f.times_cont_diff, f.compact_closure_support, hf⟩
22d73a0d32ae9e1ebab57488d717dc2b6e3bf6cc
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/protected_auto.lean
4d61ed03dc249f5a01e065c6e533cff7fda09e1b
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,258
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.core import Mathlib.PostPort namespace Mathlib /-! ## `protected` and `protect_proj` user attributes `protected` is an attribute to protect a declaration. If a declaration `foo.bar` is marked protected, then it must be referred to by its full name `foo.bar`, even when the `foo` namespace is open. `protect_proj` attribute to protect the projections of a structure. If a structure `foo` is marked with the `protect_proj` user attribute, then all of the projections become protected. `protect_proj without bar baz` will protect all projections except for `bar` and `baz`. # Examples In this example all of `foo.bar`, `foo.baz` and `foo.qux` will be protected. ``` @[protect_proj] structure foo : Type := (bar : unit) (baz : unit) (qux : unit) ``` The following code example define the structure `foo`, and the projections `foo.qux` will be protected, but not `foo.baz` or `foo.bar` ``` @[protect_proj without baz bar] structure foo : Type := (bar : unit) (baz : unit) (qux : unit) ``` -/ namespace tactic /-- Attribute to protect a declaration. If a declaration `foo.bar` is marked protected, then it must be referred to by its full name `foo.bar`, even when the `foo` namespace is open. Protectedness is a built in parser feature that is independent of this attribute. A declaration may be protected even if it does not have the `@[protected]` attribute. This provides a convenient way to protect many declarations at once. -/ /-- Tactic that is executed when a structure is marked with the `protect_proj` attribute -/ /-- Attribute to protect the projections of a structure. If a structure `foo` is marked with the `protect_proj` user attribute, then all of the projections become protected, meaning they must always be referred to by their full name `foo.bar`, even when the `foo` namespace is open. `protect_proj without bar baz` will protect all projections except for `bar` and `baz`. ```lean @[protect_proj without baz bar] structure foo : Type := (bar : unit) (baz : unit) (qux : unit) ``` -/ end Mathlib
080ed959be1bf53a4a527867f68c0413b6dd997f
26ac254ecb57ffcb886ff709cf018390161a9225
/src/logic/embedding.lean
013f57258f29b581eb6ebb6cb7dafeda1a20af61
[ "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
10,016
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.equiv.basic import data.sigma /-! # Injective functions -/ universes u v w x namespace function /-- `α ↪ β` is a bundled injective function. -/ structure embedding (α : Sort*) (β : Sort*) := (to_fun : α → β) (inj' : injective to_fun) infixr ` ↪ `:25 := embedding instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) := ⟨_, embedding.to_fun⟩ end function /-- Convert an `α ≃ β` to `α ↪ β`. -/ protected def equiv.to_embedding {α : Sort u} {β : Sort v} (f : α ≃ β) : α ↪ β := ⟨f, f.injective⟩ @[simp] theorem equiv.to_embedding_coe_fn {α : Sort u} {β : Sort v} (f : α ≃ β) : (f.to_embedding : α → β) = f := rfl namespace function namespace embedding @[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g := by cases f; cases g; simpa using funext h lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g := ⟨ext, λ h _, by rw h⟩ @[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl @[simp] theorem coe_fn_mk {α β} (f : α → β) (i) : (@mk _ _ f i : α → β) = f := rfl theorem injective {α β} (f : α ↪ β) : injective f := f.inj' @[refl] protected def refl (α : Sort*) : α ↪ α := ⟨id, injective_id⟩ @[trans] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ := ⟨g ∘ f, g.injective.comp f.injective⟩ @[simp] theorem refl_apply {α} (x : α) : embedding.refl α x = x := rfl @[simp] theorem trans_apply {α β γ} (f : α ↪ β) (g : β ↪ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) : function.embedding.trans (e.to_embedding) (e.symm.to_embedding) = function.embedding.refl _ := by { ext, simp, } @[simp] lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) : function.embedding.trans (e.symm.to_embedding) (e.to_embedding) = function.embedding.refl _ := by { ext, simp, } protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) := (equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding) /-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/ protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) : α ↪ β := ⟨surj_inv hf, injective_surj_inv _⟩ /-- Convert a surjective `embedding` to an `equiv` -/ protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) : α ≃ β := equiv.of_bijective f ⟨f.injective, hf⟩ protected def of_not_nonempty {α β} (hα : ¬ nonempty α) : α ↪ β := ⟨λa, (hα ⟨a⟩).elim, assume a, (hα ⟨a⟩).elim⟩ /-- Change the value of an embedding `f` at one point. If the prescribed image is already occupied by some `f a'`, then swap the values at these two points. -/ def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : α ↪ β := ⟨λ a', if a' = a then b else if f a' = b then f a else f a', begin intros x y h, dsimp at h, split_ifs at h; try { substI b }; try { simp only [f.injective.eq_iff] at * }; cc end⟩ theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : set_value f a b a = b := by simp [set_value] /-- Embedding into `option` -/ protected def some {α} : α ↪ option α := ⟨some, option.some_injective α⟩ /-- Embedding of a `subtype`. -/ def subtype {α} (p : α → Prop) : subtype p ↪ α := ⟨coe, λ _ _, subtype.ext_val⟩ @[simp] lemma coe_subtype {α} (p : α → Prop) : ⇑(subtype p) = coe := rfl /-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/ def punit {β : Sort*} (b : β) : punit ↪ β := ⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩ /-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/ def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β := ⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩ /-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/ def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β := ⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩ /-- Restrict the codomain of an embedding. -/ def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p := ⟨λ a, ⟨f a, H a⟩, λ a b h, f.injective (@congr_arg _ _ _ _ subtype.val h)⟩ @[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/ def prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ := ⟨prod.map e₁ e₂, e₁.injective.prod_map e₂.injective⟩ @[simp] lemma coe_prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(e₁.prod_map e₂) = prod.map e₁ e₂ := rfl section sum open sum /-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/ def sum_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ := ⟨sum.map e₁ e₂, assume s₁ s₂ h, match s₁, s₂, h with | inl a₁, inl a₂, h := congr_arg inl $ e₁.injective $ inl.inj h | inr b₁, inr b₂, h := congr_arg inr $ e₂.injective $ inr.inj h end⟩ @[simp] theorem coe_sum_map {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(sum_map e₁ e₂) = sum.map e₁ e₂ := rfl /-- The embedding of `α` into the sum `α ⊕ β`. -/ def inl {α β : Type*} : α ↪ α ⊕ β := ⟨sum.inl, λ a b, sum.inl.inj⟩ /-- The embedding of `β` into the sum `α ⊕ β`. -/ def inr {α β : Type*} : β ↪ α ⊕ β := ⟨sum.inr, λ a b, sum.inr.inj⟩ end sum section sigma variables {α α' : Type*} {β : α → Type*} {β' : α' → Type*} /-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family of embeddings, then `sigma.map f g` is an embedding. -/ def sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) : (Σ a, β a) ↪ Σ a', β' a' := ⟨sigma.map f (λ a, g a), f.injective.sigma_map (λ a, (g a).injective)⟩ @[simp] lemma coe_sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) : ⇑(f.sigma_map g) = sigma.map f (λ a, g a) := rfl end sigma def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) := ⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).injective (congr_fun h a)⟩ def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ (γ → β) := Pi_congr_right (λ _, e) noncomputable def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ] (e : α ↪ β) : (α → γ) ↪ (β → γ) := by haveI := classical.prop_decidable; exact let f' : (α → γ) → (β → γ) := λf b, if h : ∃c, e c = b then f (classical.some h) else default γ in ⟨f', assume f₁ f₂ h, funext $ assume c, have ∃c', e c' = e c, from ⟨c, rfl⟩, have eq' : f' f₁ (e c) = f' f₂ (e c), from congr_fun h _, have eq_b : classical.some this = c, from e.injective $ classical.some_spec this, by simp [f', this, if_pos, eq_b] at eq'; assumption⟩ protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β) (h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} := ⟨subtype.map f h, subtype.map_injective h f.2⟩ open set /-- `set.image` as an embedding `set α ↪ set β`. -/ protected def image {α β} (f : α ↪ β) : set α ↪ set β := ⟨image f, f.2.image_injective⟩ @[simp] lemma coe_image {α β} (f : α ↪ β) : ⇑f.image = image f := rfl end embedding end function namespace equiv @[simp] lemma refl_to_embedding {α : Type*} : (equiv.refl α).to_embedding = function.embedding.refl α := rfl @[simp] lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) : (e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl end equiv namespace set /-- The injection map is an embedding between subsets. -/ def embedding_of_subset {α} (s t : set α) (h : s ⊆ t) : s ↪ t := ⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by congr; injection h⟩ @[simp] lemma embedding_of_subset_apply_mk {α} {s t : set α} (h : s ⊆ t) (x : α) (hx : x ∈ s) : embedding_of_subset s t h ⟨x, hx⟩ = ⟨x, h hx⟩ := rfl @[simp] lemma coe_embedding_of_subset_apply {α} {s t : set α} (h : s ⊆ t) (x : s) : (embedding_of_subset s t h x : α) = x := rfl end set /-- The embedding of a left cancellative semigroup into itself by left multiplication by a fixed element. -/ @[to_additive "The embedding of a left cancellative additive semigroup into itself by left translation by a fixed element."] def mul_left_embedding {G : Type u} [left_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, g * h, inj' := λ h h', (mul_right_inj g).mp, } @[simp] lemma mul_left_embedding_apply {G : Type u} [left_cancel_semigroup G] (g h : G) : mul_left_embedding g h = g * h := rfl /-- The embedding of a right cancellative semigroup into itself by right multiplication by a fixed element. -/ @[to_additive "The embedding of a right cancellative additive semigroup into itself by right translation by a fixed element."] def mul_right_embedding {G : Type u} [right_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, h * g, inj' := λ h h', (mul_left_inj g).mp, } @[simp] lemma mul_right_embedding_apply {G : Type u} [right_cancel_semigroup G] (g h : G) : mul_right_embedding g h = h * g := rfl
cee6c602fa2be2d3448940d918b51a69c1bddd5b
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/ordered_monoid.lean
08f98ad49c400098e738d7fd83f0fca0cab2a65c
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
48,746
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.group.with_one import algebra.group.type_tags import algebra.group.prod import algebra.order_functions import order.bounded_lattice /-! # Ordered monoids This file develops the basics of ordered monoids. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ set_option old_structure_cmd true universe u variable {α : Type u} /-- An ordered commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c * a ≤ c * b` (multiplication is monotone) * `a * b < a * c → b < c`. -/ @[protect_proj, ancestor comm_monoid partial_order] class ordered_comm_monoid (α : Type*) extends comm_monoid α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (lt_of_mul_lt_mul_left : ∀ a b c : α, a * b < a * c → b < c) /-- An ordered (additive) commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c + a ≤ c + b` (addition is monotone) * `a + b < a + c → b < c`. -/ @[protect_proj, ancestor add_comm_monoid partial_order] class ordered_add_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c) attribute [to_additive] ordered_comm_monoid /-- An `ordered_comm_monoid` with one-sided 'division' in the sense that if `a ≤ b`, there is some `c` for which `a * c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_monoid`. -/ class has_exists_mul_of_le (α : Type u) [ordered_comm_monoid α] : Prop := (exists_mul_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a * c) export has_exists_mul_of_le (exists_mul_of_le) /-- An `ordered_add_comm_monoid` with one-sided 'subtraction' in the sense that if `a ≤ b`, then there is some `c` for which `a + c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_add_monoid`. -/ class has_exists_add_of_le (α : Type u) [ordered_add_comm_monoid α] : Prop := (exists_add_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a + c) export has_exists_add_of_le (exists_add_of_le) attribute [to_additive] has_exists_mul_of_le /-- A linearly ordered additive commutative monoid. -/ @[protect_proj, ancestor linear_order ordered_add_comm_monoid] class linear_ordered_add_comm_monoid (α : Type*) extends linear_order α, ordered_add_comm_monoid α := (lt_of_add_lt_add_left := λ x y z, by { apply imp_of_not_imp_not, intro h, apply not_lt_of_le, apply add_le_add_left, -- type-class inference uses `a : linear_order α` which it can't unfold, unless we provide this! -- `lt_iff_le_not_le` gets filled incorrectly with `autoparam` if we don't provide that field. letI : linear_order α := by refine { le := le, lt := lt, lt_iff_le_not_le := _, .. }; assumption, exact le_of_not_lt h }) /-- A linearly ordered commutative monoid. -/ @[protect_proj, ancestor linear_order ordered_comm_monoid, to_additive] class linear_ordered_comm_monoid (α : Type*) extends linear_order α, ordered_comm_monoid α := (lt_of_mul_lt_mul_left := λ x y z, by { apply imp_of_not_imp_not, intro h, apply not_lt_of_le, apply mul_le_mul_left, -- type-class inference uses `a : linear_order α` which it can't unfold, unless we provide this! -- `lt_iff_le_not_le` gets filled incorrectly with `autoparam` if we don't provide that field. letI : linear_order α := by refine { le := le, lt := lt, lt_iff_le_not_le := _, .. }; assumption, exact le_of_not_lt h }) /-- A linearly ordered commutative monoid with a zero element. -/ class linear_ordered_comm_monoid_with_zero (α : Type*) extends linear_ordered_comm_monoid α, comm_monoid_with_zero α := (zero_le_one : (0 : α) ≤ 1) /-- A linearly ordered commutative monoid with an additively absorbing `⊤` element. Instances should include number systems with an infinite element adjoined.` -/ @[protect_proj, ancestor linear_ordered_add_comm_monoid order_top] class linear_ordered_add_comm_monoid_with_top (α : Type*) extends linear_ordered_add_comm_monoid α, order_top α := (top_add' : ∀ x : α, ⊤ + x = ⊤) section linear_ordered_add_comm_monoid_with_top variables [linear_ordered_add_comm_monoid_with_top α] {a b : α} @[simp] lemma top_add (a : α) : ⊤ + a = ⊤ := linear_ordered_add_comm_monoid_with_top.top_add' a @[simp] lemma add_top (a : α) : a + ⊤ = ⊤ := by rw [add_comm, top_add] end linear_ordered_add_comm_monoid_with_top section ordered_comm_monoid variables [ordered_comm_monoid α] {a b c d : α} @[to_additive add_le_add_left] lemma mul_le_mul_left' (h : a ≤ b) (c) : c * a ≤ c * b := ordered_comm_monoid.mul_le_mul_left a b h c @[to_additive add_le_add_right] lemma mul_le_mul_right' (h : a ≤ b) (c) : a * c ≤ b * c := by { convert mul_le_mul_left' h c using 1; rw mul_comm } @[to_additive] lemma mul_lt_of_mul_lt_left (h : a * b < c) (hle : d ≤ b) : a * d < c := (mul_le_mul_left' hle a).trans_lt h @[to_additive] lemma mul_lt_of_mul_lt_right (h : a * b < c) (hle : d ≤ a) : d * b < c := (mul_le_mul_right' hle b).trans_lt h @[to_additive] lemma mul_le_of_mul_le_left (h : a * b ≤ c) (hle : d ≤ b) : a * d ≤ c := (mul_le_mul_left' hle a).trans h @[to_additive] lemma mul_le_of_mul_le_right (h : a * b ≤ c) (hle : d ≤ a) : d * b ≤ c := (mul_le_mul_right' hle b).trans h @[to_additive] lemma lt_mul_of_lt_mul_left (h : a < b * c) (hle : c ≤ d) : a < b * d := h.trans_le (mul_le_mul_left' hle b) @[to_additive] lemma lt_mul_of_lt_mul_right (h : a < b * c) (hle : b ≤ d) : a < d * c := h.trans_le (mul_le_mul_right' hle c) @[to_additive] lemma le_mul_of_le_mul_left (h : a ≤ b * c) (hle : c ≤ d) : a ≤ b * d := h.trans (mul_le_mul_left' hle b) @[to_additive] lemma le_mul_of_le_mul_right (h : a ≤ b * c) (hle : b ≤ d) : a ≤ d * c := h.trans (mul_le_mul_right' hle c) @[to_additive lt_of_add_lt_add_left] lemma lt_of_mul_lt_mul_left' : a * b < a * c → b < c := ordered_comm_monoid.lt_of_mul_lt_mul_left a b c @[to_additive lt_of_add_lt_add_right] lemma lt_of_mul_lt_mul_right' (h : a * b < c * b) : a < c := lt_of_mul_lt_mul_left' (show b * a < b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) @[to_additive add_le_add] lemma mul_le_mul' (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := (mul_le_mul_right' h₁ _).trans $ mul_le_mul_left' h₂ _ @[to_additive] lemma mul_le_mul_three {e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a * b * c ≤ d * e * f := mul_le_mul' (mul_le_mul' h₁ h₂) h₃ -- here we start using properties of one. @[to_additive le_add_of_nonneg_right] lemma le_mul_of_one_le_right' (h : 1 ≤ b) : a ≤ a * b := by simpa only [mul_one] using mul_le_mul_left' h a @[to_additive le_add_of_nonneg_left] lemma le_mul_of_one_le_left' (h : 1 ≤ b) : a ≤ b * a := by simpa only [one_mul] using mul_le_mul_right' h a @[to_additive add_le_of_nonpos_right] lemma mul_le_of_le_one_right' (h : b ≤ 1) : a * b ≤ a := by simpa only [mul_one] using mul_le_mul_left' h a @[to_additive add_le_of_nonpos_left] lemma mul_le_of_le_one_left' (h : b ≤ 1) : b * a ≤ a := by simpa only [one_mul] using mul_le_mul_right' h a @[to_additive] lemma lt_of_mul_lt_of_one_le_left (h : a * b < c) (hle : 1 ≤ b) : a < c := (le_mul_of_one_le_right' hle).trans_lt h @[to_additive] lemma lt_of_mul_lt_of_one_le_right (h : a * b < c) (hle : 1 ≤ a) : b < c := (le_mul_of_one_le_left' hle).trans_lt h @[to_additive] lemma le_of_mul_le_of_one_le_left (h : a * b ≤ c) (hle : 1 ≤ b) : a ≤ c := (le_mul_of_one_le_right' hle).trans h @[to_additive] lemma le_of_mul_le_of_one_le_right (h : a * b ≤ c) (hle : 1 ≤ a) : b ≤ c := (le_mul_of_one_le_left' hle).trans h @[to_additive] lemma lt_of_lt_mul_of_le_one_left (h : a < b * c) (hle : c ≤ 1) : a < b := h.trans_le (mul_le_of_le_one_right' hle) @[to_additive] lemma lt_of_lt_mul_of_le_one_right (h : a < b * c) (hle : b ≤ 1) : a < c := h.trans_le (mul_le_of_le_one_left' hle) @[to_additive] lemma le_of_le_mul_of_le_one_left (h : a ≤ b * c) (hle : c ≤ 1) : a ≤ b := h.trans (mul_le_of_le_one_right' hle) @[to_additive] lemma le_of_le_mul_of_le_one_right (h : a ≤ b * c) (hle : b ≤ 1) : a ≤ c := h.trans (mul_le_of_le_one_left' hle) @[to_additive] lemma le_mul_of_one_le_of_le (ha : 1 ≤ a) (hbc : b ≤ c) : b ≤ a * c := one_mul b ▸ mul_le_mul' ha hbc @[to_additive] lemma le_mul_of_le_of_one_le (hbc : b ≤ c) (ha : 1 ≤ a) : b ≤ c * a := mul_one b ▸ mul_le_mul' hbc ha @[to_additive add_nonneg] lemma one_le_mul (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := le_mul_of_one_le_of_le ha hb @[to_additive add_pos_of_pos_of_nonneg] lemma one_lt_mul_of_lt_of_le' (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := lt_of_lt_of_le ha $ le_mul_of_one_le_right' hb @[to_additive add_pos_of_nonneg_of_pos] lemma one_lt_mul_of_le_of_lt' (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := lt_of_lt_of_le hb $ le_mul_of_one_le_left' ha @[to_additive add_pos] lemma one_lt_mul' (ha : 1 < a) (hb : 1 < b) : 1 < a * b := one_lt_mul_of_lt_of_le' ha hb.le @[to_additive add_nonpos] lemma mul_le_one' (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := one_mul (1:α) ▸ (mul_le_mul' ha hb) @[to_additive] lemma mul_le_of_le_one_of_le' (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one' (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one' (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := (mul_le_of_le_of_le_one' le_rfl hb).trans_lt ha @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one' (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := (mul_le_of_le_one_of_le' ha le_rfl).trans_lt hb @[to_additive] lemma mul_lt_one' (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_one_of_le_one_of_lt_one' ha.le hb @[to_additive] lemma lt_mul_of_one_le_of_lt' (ha : 1 ≤ a) (hbc : b < c) : b < a * c := hbc.trans_le $ le_mul_of_one_le_left' ha @[to_additive] lemma lt_mul_of_lt_of_one_le' (hbc : b < c) (ha : 1 ≤ a) : b < c * a := hbc.trans_le $ le_mul_of_one_le_right' ha @[to_additive] lemma lt_mul_of_one_lt_of_lt' (ha : 1 < a) (hbc : b < c) : b < a * c := lt_mul_of_one_le_of_lt' ha.le hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt' (hbc : b < c) (ha : 1 < a) : b < c * a := lt_mul_of_lt_of_one_le' hbc ha.le @[to_additive] lemma mul_lt_of_le_one_of_lt' (ha : a ≤ 1) (hbc : b < c) : a * b < c := lt_of_le_of_lt (mul_le_of_le_one_of_le' ha le_rfl) hbc @[to_additive] lemma mul_lt_of_lt_of_le_one' (hbc : b < c) (ha : a ≤ 1) : b * a < c := lt_of_le_of_lt (mul_le_of_le_of_le_one' le_rfl ha) hbc @[to_additive] lemma mul_lt_of_lt_one_of_lt' (ha : a < 1) (hbc : b < c) : a * b < c := mul_lt_of_le_one_of_lt' ha.le hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one' (hbc : b < c) (ha : a < 1) : b * a < c := mul_lt_of_lt_of_le_one' hbc ha.le @[to_additive] lemma mul_eq_one_iff' (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := iff.intro (assume hab : a * b = 1, have a ≤ 1, from hab ▸ le_mul_of_le_of_one_le le_rfl hb, have a = 1, from le_antisymm this ha, have b ≤ 1, from hab ▸ le_mul_of_one_le_of_le ha le_rfl, have b = 1, from le_antisymm this hb, and.intro ‹a = 1› ‹b = 1›) (assume ⟨ha', hb'⟩, by rw [ha', hb', mul_one]) /-- Pullback an `ordered_comm_monoid` under an injective map. -/ @[to_additive function.injective.ordered_add_comm_monoid "Pullback an `ordered_add_comm_monoid` under an injective map."] def function.injective.ordered_comm_monoid {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_comm_monoid β := { mul_le_mul_left := λ a b ab c, show f (c * a) ≤ f (c * b), by simp [mul, mul_le_mul_left' ab], lt_of_mul_lt_mul_left := λ a b c bc, @lt_of_mul_lt_mul_left' _ _ (f a) _ _ (by rwa [← mul, ← mul]), ..partial_order.lift f hf, ..hf.comm_monoid f one mul } section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add] lemma monotone.mul' (hf : monotone f) (hg : monotone g) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul' (hf h) (hg h) @[to_additive monotone.add_const] lemma monotone.mul_const' (hf : monotone f) (a : α) : monotone (λ x, f x * a) := hf.mul' monotone_const @[to_additive monotone.const_add] lemma monotone.const_mul' (hf : monotone f) (a : α) : monotone (λ x, a * f x) := monotone_const.mul' hf end mono end ordered_comm_monoid /-- Pullback a `linear_ordered_comm_monoid` under an injective map. -/ @[to_additive function.injective.linear_ordered_add_comm_monoid "Pullback an `ordered_add_comm_monoid` under an injective map."] def function.injective.linear_ordered_comm_monoid [linear_ordered_comm_monoid α] {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : linear_ordered_comm_monoid β := { .. hf.ordered_comm_monoid f one mul, .. linear_order.lift f hf } lemma bit0_pos [ordered_add_comm_monoid α] {a : α} (h : 0 < a) : 0 < bit0 a := add_pos h h namespace units @[to_additive] instance [monoid α] [preorder α] : preorder (units α) := preorder.lift (coe : units α → α) @[simp, norm_cast, to_additive] theorem coe_le_coe [monoid α] [preorder α] {a b : units α} : (a : α) ≤ b ↔ a ≤ b := iff.rfl -- should `to_additive` do this? attribute [norm_cast] add_units.coe_le_coe @[simp, norm_cast, to_additive] theorem coe_lt_coe [monoid α] [preorder α] {a b : units α} : (a : α) < b ↔ a < b := iff.rfl attribute [norm_cast] add_units.coe_lt_coe @[to_additive] instance [monoid α] [partial_order α] : partial_order (units α) := partial_order.lift coe units.ext @[to_additive] instance [monoid α] [linear_order α] : linear_order (units α) := linear_order.lift coe units.ext @[simp, norm_cast, to_additive] theorem max_coe [monoid α] [linear_order α] {a b : units α} : (↑(max a b) : α) = max a b := by by_cases b ≤ a; simp [max, h] attribute [norm_cast] add_units.max_coe @[simp, norm_cast, to_additive] theorem min_coe [monoid α] [linear_order α] {a b : units α} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [min, h] attribute [norm_cast] add_units.min_coe end units namespace with_zero local attribute [semireducible] with_zero instance [preorder α] : preorder (with_zero α) := with_bot.preorder instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order instance [partial_order α] : order_bot (with_zero α) := with_bot.order_bot lemma zero_le [partial_order α] (a : with_zero α) : 0 ≤ a := order_bot.bot_le a lemma zero_lt_coe [partial_order α] (a : α) : (0 : with_zero α) < a := with_bot.bot_lt_coe a @[simp, norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_zero α) < b ↔ a < b := with_bot.coe_lt_coe @[simp, norm_cast] lemma coe_le_coe [partial_order α] {a b : α} : (a : with_zero α) ≤ b ↔ a ≤ b := with_bot.coe_le_coe instance [lattice α] : lattice (with_zero α) := with_bot.lattice instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order lemma mul_le_mul_left {α : Type u} [ordered_comm_monoid α] : ∀ (a b : with_zero α), a ≤ b → ∀ (c : with_zero α), c * a ≤ c * b := begin rintro (_ | a) (_ | b) h (_ | c), { apply with_zero.zero_le }, { apply with_zero.zero_le }, { apply with_zero.zero_le }, { apply with_zero.zero_le }, { apply with_zero.zero_le }, { exact false.elim (not_lt_of_le h (with_zero.zero_lt_coe a))}, { apply with_zero.zero_le }, { simp_rw [some_eq_coe] at h ⊢, norm_cast at h ⊢, exact mul_le_mul_left' h c } end lemma lt_of_mul_lt_mul_left {α : Type u} [ordered_comm_monoid α] : ∀ (a b c : with_zero α), a * b < a * c → b < c := begin rintro (_ | a) (_ | b) (_ | c) h, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact with_zero.zero_lt_coe c }, { exact false.elim (not_le_of_lt h (with_zero.zero_le _)) }, { simp_rw [some_eq_coe] at h ⊢, norm_cast at h ⊢, apply lt_of_mul_lt_mul_left' h } end instance [ordered_comm_monoid α] : ordered_comm_monoid (with_zero α) := { mul_le_mul_left := with_zero.mul_le_mul_left, lt_of_mul_lt_mul_left := with_zero.lt_of_mul_lt_mul_left, ..with_zero.comm_monoid_with_zero, ..with_zero.partial_order } /- Note 1 : the below is not an instance because it requires `zero_le`. It seems like a rather pathological definition because α already has a zero. Note 2 : there is no multiplicative analogue because it does not seem necessary. Mathematicians might be more likely to use the order-dual version, where all elements are ≤ 1 and then 1 is the top element. -/ /-- If `0` is the least element in `α`, then `with_zero α` is an `ordered_add_comm_monoid`. -/ def ordered_add_comm_monoid [ordered_add_comm_monoid α] (zero_le : ∀ a : α, 0 ≤ a) : ordered_add_comm_monoid (with_zero α) := begin suffices, refine { add_le_add_left := this, ..with_zero.partial_order, ..with_zero.add_comm_monoid, .. }, { intros a b c h, have h' := lt_iff_le_not_le.1 h, rw lt_iff_le_not_le at ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases c with c, { cases h'.2 (this _ _ bot_le a) }, { refine ⟨_, rfl, _⟩, cases a with a, { exact with_bot.some_le_some.1 h'.1 }, { exact le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h), } } }, { intros a b h c ca h₂, cases b with b, { rw le_antisymm h bot_le at h₂, exact ⟨_, h₂, le_refl _⟩ }, cases a with a, { change c + 0 = some ca at h₂, simp at h₂, simp [h₂], exact ⟨_, rfl, by simpa using add_le_add_left (zero_le b) _⟩ }, { simp at h, cases c with c; change some _ = _ at h₂; simp [-add_comm] at h₂; subst ca; refine ⟨_, rfl, _⟩, { exact h }, { exact add_le_add_left h _ } } } end end with_zero namespace with_top section has_one variables [has_one α] @[to_additive] instance : has_one (with_top α) := ⟨(1 : α)⟩ @[simp, to_additive] lemma coe_one : ((1 : α) : with_top α) = 1 := rfl @[simp, to_additive] lemma coe_eq_one {a : α} : (a : with_top α) = 1 ↔ a = 1 := coe_eq_coe @[simp, to_additive] theorem one_eq_coe {a : α} : 1 = (a : with_top α) ↔ a = 1 := by rw [eq_comm, coe_eq_one] attribute [norm_cast] coe_one coe_eq_one coe_zero coe_eq_zero one_eq_coe zero_eq_coe @[simp, to_additive] theorem top_ne_one : ⊤ ≠ (1 : with_top α) . @[simp, to_additive] theorem one_ne_top : (1 : with_top α) ≠ ⊤ . end has_one instance [has_add α] : has_add (with_top α) := ⟨λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a + b))⟩ local attribute [reducible] with_zero instance [add_semigroup α] : add_semigroup (with_top α) := { add := (+), ..@additive.add_semigroup _ $ @with_zero.semigroup (multiplicative α) _ } @[norm_cast] lemma coe_add [has_add α] {a b : α} : ((a + b : α) : with_top α) = a + b := rfl @[norm_cast] lemma coe_bit0 [has_add α] {a : α} : ((bit0 a : α) : with_top α) = bit0 a := rfl @[norm_cast] lemma coe_bit1 [has_add α] [has_one α] {a : α} : ((bit1 a : α) : with_top α) = bit1 a := rfl @[simp] lemma add_top [has_add α] : ∀{a : with_top α}, a + ⊤ = ⊤ | none := rfl | (some a) := rfl @[simp] lemma top_add [has_add α] {a : with_top α} : ⊤ + a = ⊤ := rfl lemma add_eq_top [has_add α] {a b : with_top α} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by {cases a; cases b; simp [none_eq_top, some_eq_coe, ←with_top.coe_add, ←with_zero.coe_add]} lemma add_lt_top [has_add α] [partial_order α] {a b : with_top α} : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ := by simp [lt_top_iff_ne_top, add_eq_top, not_or_distrib] lemma add_eq_coe [has_add α] : ∀ {a b : with_top α} {c : α}, a + b = c ↔ ∃ (a' b' : α), ↑a' = a ∧ ↑b' = b ∧ a' + b' = c | none b c := by simp [none_eq_top] | (some a) none c := by simp [none_eq_top] | (some a) (some b) c := by simp only [some_eq_coe, ← coe_add, coe_eq_coe, exists_and_distrib_left, exists_eq_left] instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) := { ..@additive.add_comm_semigroup _ $ @with_zero.comm_semigroup (multiplicative α) _ } instance [add_monoid α] : add_monoid (with_top α) := { zero := some 0, add := (+), ..@additive.add_monoid _ $ @monoid_with_zero.to_monoid _ $ @with_zero.monoid_with_zero (multiplicative α) _ } instance [add_comm_monoid α] : add_comm_monoid (with_top α) := { zero := 0, add := (+), ..@additive.add_comm_monoid _ $ @comm_monoid_with_zero.to_comm_monoid _ $ @with_zero.comm_monoid_with_zero (multiplicative α) _ } instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_top α) := { add_le_add_left := begin rintros a b h (_|c), { simp [none_eq_top] }, rcases b with (_|b), { simp [none_eq_top] }, rcases le_coe_iff.1 h with ⟨a, rfl, h⟩, simp only [some_eq_coe, ← coe_add, coe_le_coe] at h ⊢, exact add_le_add_left h c end, lt_of_add_lt_add_left := begin intros a b c h, rcases lt_iff_exists_coe.1 h with ⟨ab, hab, hlt⟩, rcases add_eq_coe.1 hab with ⟨a, b, rfl, rfl, rfl⟩, rw coe_lt_iff, rintro c rfl, exact lt_of_add_lt_add_left (coe_lt_coe.1 hlt) end, ..with_top.partial_order, ..with_top.add_comm_monoid } instance [linear_ordered_add_comm_monoid α] : linear_ordered_add_comm_monoid_with_top (with_top α) := { top_add' := λ x, with_top.top_add, ..with_top.order_top, ..with_top.linear_order, ..with_top.ordered_add_comm_monoid, ..option.nontrivial } /-- Coercion from `α` to `with_top α` as an `add_monoid_hom`. -/ def coe_add_hom [add_monoid α] : α →+ with_top α := ⟨coe, rfl, λ _ _, rfl⟩ @[simp] lemma coe_coe_add_hom [add_monoid α] : ⇑(coe_add_hom : α →+ with_top α) = coe := rfl @[simp] lemma zero_lt_top [ordered_add_comm_monoid α] : (0 : with_top α) < ⊤ := coe_lt_top 0 @[simp, norm_cast] lemma zero_lt_coe [ordered_add_comm_monoid α] (a : α) : (0 : with_top α) < a ↔ 0 < a := coe_lt_coe end with_top namespace with_bot instance [has_zero α] : has_zero (with_bot α) := with_top.has_zero instance [has_one α] : has_one (with_bot α) := with_top.has_one instance [add_semigroup α] : add_semigroup (with_bot α) := with_top.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (with_bot α) := with_top.add_comm_semigroup instance [add_monoid α] : add_monoid (with_bot α) := with_top.add_monoid instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_bot α) := begin suffices, refine { add_le_add_left := this, ..with_bot.partial_order, ..with_bot.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim bot_le }, cases c with c, { exact (not_le_of_lt h).elim bot_le }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases a with a; cases h₂, cases b with b, {cases le_antisymm h bot_le}, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_zero [has_zero α] : ((0 : α) : with_bot α) = 0 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_one [has_one α] : ((1 : α) : with_bot α) = 1 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_eq_zero {α : Type*} [add_monoid α] {a : α} : (a : with_bot α) = 0 ↔ a = 0 := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_add [add_semigroup α] (a b : α) : ((a + b : α) : with_bot α) = a + b := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit0 [add_semigroup α] {a : α} : ((bit0 a : α) : with_bot α) = bit0 a := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit1 [add_semigroup α] [has_one α] {a : α} : ((bit1 a : α) : with_bot α) = bit1 a := by norm_cast @[simp] lemma bot_add [ordered_add_comm_monoid α] (a : with_bot α) : ⊥ + a = ⊥ := rfl @[simp] lemma add_bot [ordered_add_comm_monoid α] (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl end with_bot /-- A canonically ordered additive monoid is an ordered commutative additive monoid in which the ordering coincides with the subtractibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other nontrivial `ordered_add_comm_group`s. -/ @[protect_proj, ancestor ordered_add_comm_monoid order_bot] class canonically_ordered_add_monoid (α : Type*) extends ordered_add_comm_monoid α, order_bot α := (le_iff_exists_add : ∀ a b : α, a ≤ b ↔ ∃ c, b = a + c) /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a * c`. Example seem rare; it seems more likely that the `order_dual` of a naturally-occurring lattice satisfies this than the lattice itself (for example, dual of the lattice of ideals of a PID or Dedekind domain satisfy this; collections of all things ≤ 1 seem to be more natural that collections of all things ≥ 1). -/ @[protect_proj, ancestor ordered_comm_monoid order_bot, to_additive] class canonically_ordered_monoid (α : Type*) extends ordered_comm_monoid α, order_bot α := (le_iff_exists_mul : ∀ a b : α, a ≤ b ↔ ∃ c, b = a * c) section canonically_ordered_monoid variables [canonically_ordered_monoid α] {a b c d : α} @[to_additive] lemma le_iff_exists_mul : a ≤ b ↔ ∃c, b = a * c := canonically_ordered_monoid.le_iff_exists_mul a b @[to_additive] lemma self_le_mul_right (a b : α) : a ≤ a * b := le_iff_exists_mul.mpr ⟨b, rfl⟩ @[to_additive] lemma self_le_mul_left (a b : α) : a ≤ b * a := by { rw [mul_comm], exact self_le_mul_right a b } @[simp, to_additive zero_le] lemma one_le (a : α) : 1 ≤ a := le_iff_exists_mul.mpr ⟨a, by simp⟩ @[simp, to_additive] lemma bot_eq_one : (⊥ : α) = 1 := le_antisymm bot_le (one_le ⊥) @[simp, to_additive] lemma mul_eq_one_iff : a * b = 1 ↔ a = 1 ∧ b = 1 := mul_eq_one_iff' (one_le _) (one_le _) @[simp, to_additive] lemma le_one_iff_eq_one : a ≤ 1 ↔ a = 1 := iff.intro (assume h, le_antisymm h (one_le a)) (assume h, h ▸ le_refl a) @[to_additive] lemma one_lt_iff_ne_one : 1 < a ↔ a ≠ 1 := iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (one_le _) hne.symm @[to_additive] lemma exists_pos_mul_of_lt (h : a < b) : ∃ c > 1, a * c = b := begin obtain ⟨c, hc⟩ := le_iff_exists_mul.1 h.le, refine ⟨c, one_lt_iff_ne_one.2 _, hc.symm⟩, rintro rfl, simpa [hc, lt_irrefl] using h end @[to_additive] lemma le_mul_left (h : a ≤ c) : a ≤ b * c := calc a = 1 * a : by simp ... ≤ b * c : mul_le_mul' (one_le _) h @[to_additive] lemma le_mul_right (h : a ≤ b) : a ≤ b * c := calc a = a * 1 : by simp ... ≤ b * c : mul_le_mul' h (one_le _) local attribute [semireducible] with_zero -- This instance looks absurd: a monoid already has a zero /-- Adding a new zero to a canonically ordered additive monoid produces another one. -/ instance with_zero.canonically_ordered_add_monoid {α : Type u} [canonically_ordered_add_monoid α] : canonically_ordered_add_monoid (with_zero α) := { le_iff_exists_add := λ a b, begin cases a with a, { exact iff_of_true bot_le ⟨b, (zero_add b).symm⟩ }, cases b with b, { exact iff_of_false (mt (le_antisymm bot_le) (by simp)) (λ ⟨c, h⟩, by cases c; cases h) }, { simp [le_iff_exists_add, -add_comm], split; intro h; rcases h with ⟨c, h⟩, { exact ⟨some c, congr_arg some h⟩ }, { cases c; cases h, { exact ⟨_, (add_zero _).symm⟩ }, { exact ⟨_, rfl⟩ } } } end, bot := 0, bot_le := assume a a' h, option.no_confusion h, .. with_zero.ordered_add_comm_monoid zero_le } instance with_top.canonically_ordered_add_monoid {α : Type u} [canonically_ordered_add_monoid α] : canonically_ordered_add_monoid (with_top α) := { le_iff_exists_add := assume a b, match a, b with | a, none := show a ≤ ⊤ ↔ ∃c, ⊤ = a + c, by simp; refine ⟨⊤, _⟩; cases a; refl | (some a), (some b) := show (a:with_top α) ≤ ↑b ↔ ∃c:with_top α, ↑b = ↑a + c, begin simp [canonically_ordered_add_monoid.le_iff_exists_add, -add_comm], split, { rintro ⟨c, rfl⟩, refine ⟨c, _⟩, norm_cast }, { exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end } end | none, some b := show (⊤ : with_top α) ≤ b ↔ ∃c:with_top α, ↑b = ⊤ + c, by simp end, .. with_top.order_bot, .. with_top.ordered_add_comm_monoid } @[priority 100, to_additive] instance canonically_ordered_monoid.has_exists_mul_of_le (α : Type u) [canonically_ordered_monoid α] : has_exists_mul_of_le α := { exists_mul_of_le := λ a b hab, le_iff_exists_mul.mp hab } end canonically_ordered_monoid /-- A canonically linear-ordered additive monoid is a canonically ordered additive monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_add_monoid linear_order] class canonically_linear_ordered_add_monoid (α : Type*) extends canonically_ordered_add_monoid α, linear_order α /-- A canonically linear-ordered monoid is a canonically ordered monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_monoid linear_order, to_additive] class canonically_linear_ordered_monoid (α : Type*) extends canonically_ordered_monoid α, linear_order α section canonically_linear_ordered_monoid variables @[priority 100, to_additive] -- see Note [lower instance priority] instance canonically_linear_ordered_monoid.semilattice_sup_bot [canonically_linear_ordered_monoid α] : semilattice_sup_bot α := { ..lattice_of_linear_order, ..canonically_ordered_monoid.to_order_bot α } instance with_top.canonically_linear_ordered_add_monoid (α : Type*) [canonically_linear_ordered_add_monoid α] : canonically_linear_ordered_add_monoid (with_top α) := { .. (infer_instance : canonically_ordered_add_monoid (with_top α)), .. (infer_instance : linear_order (with_top α)) } @[to_additive] lemma min_mul_distrib [canonically_linear_ordered_monoid α] (a b c : α) : min a (b * c) = min a (min a b * min a c) := begin cases le_total a b with hb hb, { simp [hb, le_mul_right] }, { cases le_total a c with hc hc, { simp [hc, le_mul_left] }, { simp [hb, hc] } } end @[to_additive] lemma min_mul_distrib' [canonically_linear_ordered_monoid α] (a b c : α) : min (a * b) c = min (min a c * min b c) c := by simpa [min_comm _ c] using min_mul_distrib c a b end canonically_linear_ordered_monoid /-- An ordered cancellative additive commutative monoid is an additive commutative monoid with a partial order, in which addition is cancellative and monotone. -/ @[protect_proj, ancestor add_cancel_comm_monoid partial_order] class ordered_cancel_add_comm_monoid (α : Type u) extends add_cancel_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (le_of_add_le_add_left : ∀ a b c : α, a + b ≤ a + c → b ≤ c) /-- An ordered cancellative commutative monoid is a commutative monoid with a partial order, in which multiplication is cancellative and monotone. -/ @[protect_proj, ancestor cancel_comm_monoid partial_order, to_additive] class ordered_cancel_comm_monoid (α : Type u) extends cancel_comm_monoid α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (le_of_mul_le_mul_left : ∀ a b c : α, a * b ≤ a * c → b ≤ c) section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] {a b c d : α} @[to_additive le_of_add_le_add_left] lemma le_of_mul_le_mul_left' : ∀ {a b c : α}, a * b ≤ a * c → b ≤ c := ordered_cancel_comm_monoid.le_of_mul_le_mul_left @[priority 100, to_additive] -- see Note [lower instance priority] instance ordered_cancel_comm_monoid.to_ordered_comm_monoid : ordered_comm_monoid α := { lt_of_mul_lt_mul_left := λ a b c h, lt_of_le_not_le (le_of_mul_le_mul_left' h.le) $ mt (λ h, ordered_cancel_comm_monoid.mul_le_mul_left _ _ h _) (not_le_of_gt h), ..‹ordered_cancel_comm_monoid α› } @[to_additive add_lt_add_left] lemma mul_lt_mul_left' (h : a < b) (c : α) : c * a < c * b := lt_of_le_not_le (mul_le_mul_left' h.le _) $ mt le_of_mul_le_mul_left' (not_le_of_gt h) @[to_additive add_lt_add_right] lemma mul_lt_mul_right' (h : a < b) (c : α) : a * c < b * c := begin rw [mul_comm a c, mul_comm b c], exact (mul_lt_mul_left' h c) end @[to_additive add_lt_add] lemma mul_lt_mul''' (h₁ : a < b) (h₂ : c < d) : a * c < b * d := lt_trans (mul_lt_mul_right' h₁ c) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_le_of_lt (h₁ : a ≤ b) (h₂ : c < d) : a * c < b * d := lt_of_le_of_lt (mul_le_mul_right' h₁ _) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_lt_of_le (h₁ : a < b) (h₂ : c ≤ d) : a * c < b * d := lt_of_lt_of_le (mul_lt_mul_right' h₁ c) (mul_le_mul_left' h₂ _) @[to_additive lt_add_of_pos_right] lemma lt_mul_of_one_lt_right' (a : α) {b : α} (h : 1 < b) : a < a * b := have a * 1 < a * b, from mul_lt_mul_left' h a, by rwa [mul_one] at this @[to_additive lt_add_of_pos_left] lemma lt_mul_of_one_lt_left' (a : α) {b : α} (h : 1 < b) : a < b * a := have 1 * a < b * a, from mul_lt_mul_right' h a, by rwa [one_mul] at this @[to_additive le_of_add_le_add_right] lemma le_of_mul_le_mul_right' (h : a * b ≤ c * b) : a ≤ c := le_of_mul_le_mul_left' (show b * a ≤ b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) @[to_additive] lemma mul_lt_one (ha : a < 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul''' ha hb) @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_lt_of_le ha hb) @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_le_of_lt ha hb) @[to_additive] lemma lt_mul_of_one_lt_of_le (ha : 1 < a) (hbc : b ≤ c) : b < a * c := one_mul b ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma lt_mul_of_le_of_one_lt (hbc : b ≤ c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma mul_le_of_le_one_of_le (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_le (ha : a < 1) (hbc : b ≤ c) : a * b < c := one_mul c ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma mul_lt_of_le_of_lt_one (hbc : b ≤ c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma lt_mul_of_one_le_of_lt (ha : 1 ≤ a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_le (hbc : b < c) (ha : 1 ≤ a) : b < c * a := mul_one b ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma lt_mul_of_one_lt_of_lt (ha : 1 < a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul''' ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt (hbc : b < c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul''' hbc ha @[to_additive] lemma mul_lt_of_le_one_of_lt (ha : a ≤ 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma mul_lt_of_lt_of_le_one (hbc : b < c) (ha : a ≤ 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_lt (ha : a < 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul''' ha hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one (hbc : b < c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul''' hbc ha @[simp, to_additive] lemma mul_le_mul_iff_left (a : α) {b c : α} : a * b ≤ a * c ↔ b ≤ c := ⟨le_of_mul_le_mul_left', λ h, mul_le_mul_left' h _⟩ @[simp, to_additive] lemma mul_le_mul_iff_right (c : α) : a * c ≤ b * c ↔ a ≤ b := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_iff_left c @[simp, to_additive] lemma mul_lt_mul_iff_left (a : α) {b c : α} : a * b < a * c ↔ b < c := ⟨lt_of_mul_lt_mul_left', λ h, mul_lt_mul_left' h _⟩ @[simp, to_additive] lemma mul_lt_mul_iff_right (c : α) : a * c < b * c ↔ a < b := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_iff_left c @[simp, to_additive le_add_iff_nonneg_right] lemma le_mul_iff_one_le_right' (a : α) {b : α} : a ≤ a * b ↔ 1 ≤ b := have a * 1 ≤ a * b ↔ 1 ≤ b, from mul_le_mul_iff_left a, by rwa mul_one at this @[simp, to_additive le_add_iff_nonneg_left] lemma le_mul_iff_one_le_left' (a : α) {b : α} : a ≤ b * a ↔ 1 ≤ b := by rw [mul_comm, le_mul_iff_one_le_right'] @[simp, to_additive lt_add_iff_pos_right] lemma lt_mul_iff_one_lt_right' (a : α) {b : α} : a < a * b ↔ 1 < b := have a * 1 < a * b ↔ 1 < b, from mul_lt_mul_iff_left a, by rwa mul_one at this @[simp, to_additive lt_add_iff_pos_left] lemma lt_mul_iff_one_lt_left' (a : α) {b : α} : a < b * a ↔ 1 < b := by rw [mul_comm, lt_mul_iff_one_lt_right'] @[simp, to_additive add_le_iff_nonpos_left] lemma mul_le_iff_le_one_left' : a * b ≤ b ↔ a ≤ 1 := by { convert mul_le_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_le_iff_nonpos_right] lemma mul_le_iff_le_one_right' : a * b ≤ a ↔ b ≤ 1 := by { convert mul_le_mul_iff_left a, rw [mul_one] } @[simp, to_additive add_lt_iff_neg_right] lemma mul_lt_iff_lt_one_right' : a * b < b ↔ a < 1 := by { convert mul_lt_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_lt_iff_neg_left] lemma mul_lt_iff_lt_one_left' : a * b < a ↔ b < 1 := by { convert mul_lt_mul_iff_left a, rw [mul_one] } @[to_additive] lemma mul_eq_one_iff_eq_one_of_one_le (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := ⟨λ hab : a * b = 1, by split; apply le_antisymm; try {assumption}; rw ← hab; simp [ha, hb], λ ⟨ha', hb'⟩, by rw [ha', hb', mul_one]⟩ /-- Pullback an `ordered_cancel_comm_monoid` under an injective map. -/ @[to_additive function.injective.ordered_cancel_add_comm_monoid "Pullback an `ordered_cancel_add_comm_monoid` under an injective map."] def function.injective.ordered_cancel_comm_monoid {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_cancel_comm_monoid β := { le_of_mul_le_mul_left := λ a b c (ab : f (a * b) ≤ f (a * c)), (by { rw [mul, mul] at ab, exact le_of_mul_le_mul_left' ab }), ..hf.left_cancel_semigroup f mul, ..hf.right_cancel_semigroup f mul, ..hf.ordered_comm_monoid f one mul } section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add_strict_mono] lemma monotone.mul_strict_mono' (hf : monotone f) (hg : strict_mono g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_le_of_lt (hf $ le_of_lt h) (hg h) @[to_additive strict_mono.add_monotone] lemma strict_mono.mul_monotone' (hf : strict_mono f) (hg : monotone g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_lt_of_le (hf h) (hg $ le_of_lt h) @[to_additive strict_mono.add_const] lemma strict_mono.mul_const' (hf : strict_mono f) (c : α) : strict_mono (λ x, f x * c) := hf.mul_monotone' monotone_const @[to_additive strict_mono.const_add] lemma strict_mono.const_mul' (hf : strict_mono f) (c : α) : strict_mono (λ x, c * f x) := monotone_const.mul_strict_mono' hf end mono end ordered_cancel_comm_monoid section ordered_cancel_add_comm_monoid variable [ordered_cancel_add_comm_monoid α] lemma with_top.add_lt_add_iff_left : ∀{a b c : with_top α}, a < ⊤ → (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊤ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe], { norm_cast, exact with_top.coe_lt_top _ }, { norm_cast, exact add_lt_add_iff_left _ } end lemma with_bot.add_lt_add_iff_left : ∀{a b c : with_bot α}, ⊥ < a → (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊥ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_bot.none_eq_bot, with_bot.some_eq_coe, with_bot.bot_lt_coe, with_bot.coe_lt_coe], { norm_cast, exact with_bot.bot_lt_coe _ }, { norm_cast, exact add_lt_add_iff_left _ } end local attribute [reducible] with_zero lemma with_top.add_lt_add_iff_right {a b c : with_top α} : a < ⊤ → (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c lemma with_bot.add_lt_add_iff_right {a b c : with_bot α} : ⊥ < a → (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_bot.add_lt_add_iff_left _ _ a b c end ordered_cancel_add_comm_monoid /-! Some lemmas about types that have an ordering and a binary operation, with no rules relating them. -/ @[to_additive] lemma fn_min_mul_fn_max {β} [linear_order α] [comm_semigroup β] (f : α → β) (n m : α) : f (min n m) * f (max n m) = f n * f m := by { cases le_total n m with h h; simp [h, mul_comm] } @[to_additive] lemma min_mul_max [linear_order α] [comm_semigroup α] (n m : α) : min n m * max n m = n * m := fn_min_mul_fn_max id n m /-- A linearly ordered cancellative additive commutative monoid is an additive commutative monoid with a decidable linear order in which addition is cancellative and monotone. -/ @[protect_proj, ancestor ordered_cancel_add_comm_monoid linear_ordered_add_comm_monoid] class linear_ordered_cancel_add_comm_monoid (α : Type u) extends ordered_cancel_add_comm_monoid α, linear_ordered_add_comm_monoid α /-- A linearly ordered cancellative commutative monoid is a commutative monoid with a linear order in which multiplication is cancellative and monotone. -/ @[protect_proj, ancestor ordered_cancel_comm_monoid linear_ordered_comm_monoid, to_additive] class linear_ordered_cancel_comm_monoid (α : Type u) extends ordered_cancel_comm_monoid α, linear_ordered_comm_monoid α section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_comm_monoid α] @[to_additive] lemma min_mul_mul_left (a b c : α) : min (a * b) (a * c) = a * min b c := (monotone_id.const_mul' a).map_min.symm @[to_additive] lemma min_mul_mul_right (a b c : α) : min (a * c) (b * c) = min a b * c := (monotone_id.mul_const' c).map_min.symm @[to_additive] lemma max_mul_mul_left (a b c : α) : max (a * b) (a * c) = a * max b c := (monotone_id.const_mul' a).map_max.symm @[to_additive] lemma max_mul_mul_right (a b c : α) : max (a * c) (b * c) = max a b * c := (monotone_id.mul_const' c).map_max.symm @[to_additive] lemma min_le_mul_of_one_le_right {a b : α} (hb : 1 ≤ b) : min a b ≤ a * b := min_le_iff.2 $ or.inl $ le_mul_of_one_le_right' hb @[to_additive] lemma min_le_mul_of_one_le_left {a b : α} (ha : 1 ≤ a) : min a b ≤ a * b := min_le_iff.2 $ or.inr $ le_mul_of_one_le_left' ha @[to_additive] lemma max_le_mul_of_one_le {a b : α} (ha : 1 ≤ a) (hb : 1 ≤ b) : max a b ≤ a * b := max_le_iff.2 ⟨le_mul_of_one_le_right' hb, le_mul_of_one_le_left' ha⟩ /-- Pullback a `linear_ordered_cancel_comm_monoid` under an injective map. -/ @[to_additive function.injective.linear_ordered_cancel_add_comm_monoid "Pullback a `linear_ordered_cancel_add_comm_monoid` under an injective map."] def function.injective.linear_ordered_cancel_comm_monoid {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : linear_ordered_cancel_comm_monoid β := { ..hf.linear_ordered_comm_monoid f one mul, ..hf.ordered_cancel_comm_monoid f one mul } end linear_ordered_cancel_comm_monoid namespace order_dual @[to_additive] instance [ordered_comm_monoid α] : ordered_comm_monoid (order_dual α) := { mul_le_mul_left := λ a b h c, @mul_le_mul_left' α _ b a h _, lt_of_mul_lt_mul_left := λ a b c h, @lt_of_mul_lt_mul_left' α _ a c b h, ..order_dual.partial_order α, ..show comm_monoid α, by apply_instance } @[to_additive] instance [ordered_cancel_comm_monoid α] : ordered_cancel_comm_monoid (order_dual α) := { le_of_mul_le_mul_left := λ a b c : α, le_of_mul_le_mul_left', mul_left_cancel := @mul_left_cancel α _, mul_right_cancel := @mul_right_cancel α _, ..order_dual.ordered_comm_monoid } @[to_additive] instance [linear_ordered_cancel_comm_monoid α] : linear_ordered_cancel_comm_monoid (order_dual α) := { .. order_dual.linear_order α, .. order_dual.ordered_cancel_comm_monoid } end order_dual namespace prod variables {M N : Type*} @[to_additive] instance [ordered_cancel_comm_monoid M] [ordered_cancel_comm_monoid N] : ordered_cancel_comm_monoid (M × N) := { mul_le_mul_left := λ a b h c, ⟨mul_le_mul_left' h.1 _, mul_le_mul_left' h.2 _⟩, le_of_mul_le_mul_left := λ a b c h, ⟨le_of_mul_le_mul_left' h.1, le_of_mul_le_mul_left' h.2⟩, .. prod.comm_monoid, .. prod.left_cancel_semigroup, .. prod.right_cancel_semigroup, .. prod.partial_order M N } end prod section type_tags instance : Π [preorder α], preorder (multiplicative α) := id instance : Π [preorder α], preorder (additive α) := id instance : Π [partial_order α], partial_order (multiplicative α) := id instance : Π [partial_order α], partial_order (additive α) := id instance : Π [linear_order α], linear_order (multiplicative α) := id instance : Π [linear_order α], linear_order (additive α) := id instance [ordered_add_comm_monoid α] : ordered_comm_monoid (multiplicative α) := { mul_le_mul_left := @ordered_add_comm_monoid.add_le_add_left α _, lt_of_mul_lt_mul_left := @ordered_add_comm_monoid.lt_of_add_lt_add_left α _, ..multiplicative.partial_order, ..multiplicative.comm_monoid } instance [ordered_comm_monoid α] : ordered_add_comm_monoid (additive α) := { add_le_add_left := @ordered_comm_monoid.mul_le_mul_left α _, lt_of_add_lt_add_left := @ordered_comm_monoid.lt_of_mul_lt_mul_left α _, ..additive.partial_order, ..additive.add_comm_monoid } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_comm_monoid (multiplicative α) := { le_of_mul_le_mul_left := @ordered_cancel_add_comm_monoid.le_of_add_le_add_left α _, ..multiplicative.right_cancel_semigroup, ..multiplicative.left_cancel_semigroup, ..multiplicative.ordered_comm_monoid } instance [ordered_cancel_comm_monoid α] : ordered_cancel_add_comm_monoid (additive α) := { le_of_add_le_add_left := @ordered_cancel_comm_monoid.le_of_mul_le_mul_left α _, ..additive.add_right_cancel_semigroup, ..additive.add_left_cancel_semigroup, ..additive.ordered_add_comm_monoid } instance [linear_ordered_add_comm_monoid α] : linear_ordered_comm_monoid (multiplicative α) := { ..multiplicative.linear_order, ..multiplicative.ordered_comm_monoid } instance [linear_ordered_comm_monoid α] : linear_ordered_add_comm_monoid (additive α) := { ..additive.linear_order, ..additive.ordered_add_comm_monoid } end type_tags
3946f9c3bbef485b897c17e5448cd21cf38ee483
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/int/modeq.lean
f76b7e7b989b23a29c2d5f2cfe27f4b7f14dd8cf
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,489
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 data.nat.modeq import tactic.ring /-! # Congruences modulo an integer This file defines the equivalence relation `a ≡ b [ZMOD n]` on the integers, similarly to how `data.nat.modeq` defines them for the natural numbers. The notation is short for `n.modeq a b`, which is defined to be `a % n = b % n` for integers `a b n`. ## Tags modeq, congruence, mod, MOD, modulo, integers -/ namespace int /-- `a ≡ b [ZMOD n]` when `a % n = b % n`. -/ @[derive decidable] def modeq (n a b : ℤ) := a % n = b % n notation a ` ≡ `:50 b ` [ZMOD `:50 n `]`:0 := modeq n a b variables {m n a b c d : ℤ} namespace modeq @[refl] protected theorem refl (a : ℤ) : a ≡ a [ZMOD n] := @rfl _ _ protected theorem rfl : a ≡ a [ZMOD n] := modeq.refl _ @[symm] protected theorem symm : a ≡ b [ZMOD n] → b ≡ a [ZMOD n] := eq.symm @[trans] protected theorem trans : a ≡ b [ZMOD n] → b ≡ c [ZMOD n] → a ≡ c [ZMOD n] := eq.trans end modeq lemma coe_nat_modeq_iff {a b n : ℕ} : a ≡ b [ZMOD n] ↔ a ≡ b [MOD n] := by unfold modeq nat.modeq; rw ← int.coe_nat_eq_coe_nat_iff; simp [coe_nat_mod] theorem modeq_zero_iff_dvd : a ≡ 0 [ZMOD n] ↔ n ∣ a := by rw [modeq, zero_mod, dvd_iff_mod_eq_zero] lemma _root_.has_dvd.dvd.modeq_zero_int (h : n ∣ a) : a ≡ 0 [ZMOD n] := modeq_zero_iff_dvd.2 h lemma _root_.has_dvd.dvd.zero_modeq_int (h : n ∣ a) : 0 ≡ a [ZMOD n] := h.modeq_zero_int.symm theorem modeq_iff_dvd : a ≡ b [ZMOD n] ↔ n ∣ b - a := by rw [modeq, eq_comm]; simp [mod_eq_mod_iff_mod_sub_eq_zero, dvd_iff_mod_eq_zero, -euclidean_domain.mod_eq_zero] theorem modeq.dvd : a ≡ b [ZMOD n] → n ∣ b - a := modeq_iff_dvd.1 theorem modeq_of_dvd : n ∣ b - a → a ≡ b [ZMOD n] := modeq_iff_dvd.2 theorem mod_modeq (a n) : a % n ≡ a [ZMOD n] := mod_mod _ _ namespace modeq protected theorem modeq_of_dvd (d : m ∣ n) (h : a ≡ b [ZMOD n]) : a ≡ b [ZMOD m] := modeq_iff_dvd.2 $ d.trans h.dvd protected theorem mul_left' (hc : 0 ≤ c) (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD (c * n)] := or.cases_on hc.lt_or_eq (λ hc, by unfold modeq; simp [mul_mod_mul_of_pos hc, (show _ = _, from h)] ) (λ hc, by simp [hc.symm]) protected theorem mul_right' (hc : 0 ≤ c) (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD (n * c)] := by rw [mul_comm a, mul_comm b, mul_comm n]; exact h.mul_left' hc protected theorem add (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a + c ≡ b + d [ZMOD n] := modeq_iff_dvd.2 $ by { convert dvd_add h₁.dvd h₂.dvd, ring } protected theorem add_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c + a ≡ c + b [ZMOD n] := modeq.rfl.add h protected theorem add_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a + c ≡ b + c [ZMOD n] := h.add modeq.rfl protected theorem add_left_cancel (h₁ : a ≡ b [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : c ≡ d [ZMOD n] := have d - c = b + d - (a + c) - (b - a) := by ring, modeq_iff_dvd.2 $ by { rw [this], exact dvd_sub h₂.dvd h₁.dvd } protected theorem add_left_cancel' (c : ℤ) (h : c + a ≡ c + b [ZMOD n]) : a ≡ b [ZMOD n] := modeq.rfl.add_left_cancel h protected theorem add_right_cancel (h₁ : c ≡ d [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : a ≡ b [ZMOD n] := by { rw [add_comm a, add_comm b] at h₂, exact h₁.add_left_cancel h₂ } protected theorem add_right_cancel' (c : ℤ) (h : a + c ≡ b + c [ZMOD n]) : a ≡ b [ZMOD n] := modeq.rfl.add_right_cancel h protected theorem neg (h : a ≡ b [ZMOD n]) : -a ≡ -b [ZMOD n] := h.add_left_cancel (by simp_rw [←sub_eq_add_neg, sub_self]) protected theorem sub (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a - c ≡ b - d [ZMOD n] := by { rw [sub_eq_add_neg, sub_eq_add_neg], exact h₁.add h₂.neg } protected theorem sub_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c - a ≡ c - b [ZMOD n] := modeq.rfl.sub h protected theorem sub_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a - c ≡ b - c [ZMOD n] := h.sub modeq.rfl protected theorem mul_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD n] := or.cases_on (le_total 0 c) (λ hc, (h.mul_left' hc).modeq_of_dvd (dvd_mul_left _ _) ) (λ hc, by rw [← neg_neg c, ← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul _ b]; exact ((h.mul_left' $ neg_nonneg.2 hc).modeq_of_dvd (dvd_mul_left _ _)).neg) protected theorem mul_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD n] := by { rw [mul_comm a, mul_comm b], exact h.mul_left c } protected theorem mul (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a * c ≡ b * d [ZMOD n] := (h₂.mul_left _).trans (h₁.mul_right _) protected theorem pow (m : ℕ) (h : a ≡ b [ZMOD n]) : a ^ m ≡ b ^ m [ZMOD n] := begin induction m with d hd, {refl}, rw [pow_succ, pow_succ], exact h.mul hd, end theorem of_modeq_mul_left (m : ℤ) (h : a ≡ b [ZMOD m * n]) : a ≡ b [ZMOD n] := by rw [modeq_iff_dvd] at *; exact (dvd_mul_left n m).trans h theorem of_modeq_mul_right (m : ℤ) : a ≡ b [ZMOD n * m] → a ≡ b [ZMOD n] := mul_comm m n ▸ of_modeq_mul_left _ end modeq theorem modeq_one : a ≡ b [ZMOD 1] := modeq_of_dvd (one_dvd _) lemma modeq_sub (a b : ℤ) : a ≡ b [ZMOD a - b] := (modeq_of_dvd dvd_rfl).symm lemma modeq_and_modeq_iff_modeq_mul {a b m n : ℤ} (hmn : m.nat_abs.coprime n.nat_abs) : a ≡ b [ZMOD m] ∧ a ≡ b [ZMOD n] ↔ (a ≡ b [ZMOD m * n]) := ⟨λ h, begin rw [modeq_iff_dvd, modeq_iff_dvd] at h, rw [modeq_iff_dvd, ← nat_abs_dvd, ← dvd_nat_abs, coe_nat_dvd, nat_abs_mul], refine hmn.mul_dvd_of_dvd_of_dvd _ _; rw [← coe_nat_dvd, nat_abs_dvd, dvd_nat_abs]; tauto end, λ h, ⟨h.of_modeq_mul_right _, h.of_modeq_mul_left _⟩⟩ lemma gcd_a_modeq (a b : ℕ) : (a : ℤ) * nat.gcd_a a b ≡ nat.gcd a b [ZMOD b] := by { rw [← add_zero ((a : ℤ) * _), nat.gcd_eq_gcd_ab], exact (dvd_mul_right _ _).zero_modeq_int.add_left _ } theorem modeq_add_fac {a b n : ℤ} (c : ℤ) (ha : a ≡ b [ZMOD n]) : a + n*c ≡ b [ZMOD n] := calc a + n*c ≡ b + n*c [ZMOD n] : ha.add_right _ ... ≡ b + 0 [ZMOD n] : (dvd_mul_right _ _).modeq_zero_int.add_left _ ... ≡ b [ZMOD n] : by rw add_zero lemma mod_coprime {a b : ℕ} (hab : nat.coprime a b) : ∃ y : ℤ, a * y ≡ 1 [ZMOD b] := ⟨ nat.gcd_a a b, have hgcd : nat.gcd a b = 1, from nat.coprime.gcd_eq_one hab, calc ↑a * nat.gcd_a a b ≡ ↑a * nat.gcd_a a b + ↑b * nat.gcd_b a b [ZMOD ↑b] : modeq.symm $ modeq_add_fac _ $ modeq.refl _ ... ≡ 1 [ZMOD ↑b] : by rw [← nat.gcd_eq_gcd_ab, hgcd]; reflexivity ⟩ lemma exists_unique_equiv (a : ℤ) {b : ℤ} (hb : 0 < b) : ∃ z : ℤ, 0 ≤ z ∧ z < b ∧ z ≡ a [ZMOD b] := ⟨ a % b, mod_nonneg _ (ne_of_gt hb), have a % b < abs b, from mod_lt _ (ne_of_gt hb), by rwa abs_of_pos hb at this, by simp [modeq] ⟩ lemma exists_unique_equiv_nat (a : ℤ) {b : ℤ} (hb : 0 < b) : ∃ z : ℕ, ↑z < b ∧ ↑z ≡ a [ZMOD b] := let ⟨z, hz1, hz2, hz3⟩ := exists_unique_equiv a hb in ⟨z.nat_abs, by split; rw [←of_nat_eq_coe, of_nat_nat_abs_eq_of_nonneg hz1]; assumption⟩ @[simp] lemma mod_mul_right_mod (a b c : ℤ) : a % (b * c) % b = a % b := (mod_modeq _ _).of_modeq_mul_right _ @[simp] lemma mod_mul_left_mod (a b c : ℤ) : a % (b * c) % c = a % c := (mod_modeq _ _).of_modeq_mul_left _ end int
db9a0ab409c7255a8a302c42afc15a9fa9b741be
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/test/induction-1pxpownlt1pnx.lean
e38be2738a4fcc7b1d55f4817267f21fb6edfc32
[ "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
269
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 example (x : ℝ) ( n : ℕ+) (h₀ : -1 < x) : (1 + x) ^ (n:ℕ) ≤ (1 + n*x) := begin sorry end
7bdc32e2429dee357df19ea5943d6869dc036088
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/exercises_sources/thursday/afternoon/category_theory/exercise3.lean
93e2af673f1c6c704f83b48f7948b79570617f12
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
813
lean
import for_mathlib.category_theory -- This imports some simp lemmas that I realised belong in mathlib while writing this exercise. open category_theory variables {C : Type*} [category C] variables {D : Type*} [category D] lemma equiv_reflects_mono {X Y : C} (f : X ⟶ Y) (e : C ≌ D) (hef : mono (e.functor.map f)) : mono f := -- Hint: when `e : C ≌ D`, `e.functor.map_injective` says -- `∀ f g, e.functor.map f = e.functor.map g → f = g` -- Hint: use `cancel_mono`. sorry lemma equiv_preserves_mono {X Y : C} (f : X ⟶ Y) [mono f] (e : C ≌ D) : mono (e.functor.map f) := -- Hint: if `w : f = g`, to obtain `F.map f = F.map G`, -- you can use `have w' := congr_arg (λ k, F.map k) w`. sorry /-! There are some further hints in `src/hints/thursday/afternoon/category_theory/exercise3/` -/
dd22fd80b8afb5cf2e8aeeb86dade4bb08e0ffbb
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/cubic_discriminant.lean
a235d3255df215bac09d93376d8ff127ff732994
[ "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
11,408
lean
/- Copyright (c) 2022 David Kurniadi Angdinata. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Kurniadi Angdinata -/ import field_theory.splitting_field /-! # Cubics and discriminants This file defines cubic polynomials over a semiring and their discriminants over a splitting field. ## Main definitions * `cubic`: the structure representing a cubic polynomial. * `disc`: the discriminant of a cubic polynomial. ## Main statements * `disc_ne_zero_iff_roots_nodup`: the cubic discriminant is not equal to zero if and only if the cubic has no duplicate roots. ## References * https://en.wikipedia.org/wiki/Cubic_equation * https://en.wikipedia.org/wiki/Discriminant ## Tags cubic, discriminant, polynomial, root -/ noncomputable theory /-- The structure representing a cubic polynomial. -/ @[ext] structure cubic (R : Type*) := (a b c d : R) namespace cubic open cubic polynomial open_locale polynomial variables {R S F K : Type*} instance [inhabited R] : inhabited (cubic R) := ⟨⟨default, default, default, default⟩⟩ instance [has_zero R] : has_zero (cubic R) := ⟨⟨0, 0, 0, 0⟩⟩ section basic variables {P : cubic R} [semiring R] /-- Convert a cubic polynomial to a polynomial. -/ def to_poly (P : cubic R) : R[X] := C P.a * X ^ 3 + C P.b * X ^ 2 + C P.c * X + C P.d /-! ### Coefficients -/ section coeff private lemma coeffs : (∀ n > 3, P.to_poly.coeff n = 0) ∧ P.to_poly.coeff 3 = P.a ∧ P.to_poly.coeff 2 = P.b ∧ P.to_poly.coeff 1 = P.c ∧ P.to_poly.coeff 0 = P.d := begin simp only [to_poly, coeff_add, coeff_C, coeff_C_mul_X, coeff_C_mul_X_pow], norm_num, intros n hn, repeat { rw [if_neg] }, any_goals { linarith only [hn] }, repeat { rw [zero_add] } end @[simp] lemma coeff_gt_three (n : ℕ) (hn : 3 < n) : P.to_poly.coeff n = 0 := coeffs.1 n hn @[simp] lemma coeff_three : P.to_poly.coeff 3 = P.a := coeffs.2.1 @[simp] lemma coeff_two : P.to_poly.coeff 2 = P.b := coeffs.2.2.1 @[simp] lemma coeff_one : P.to_poly.coeff 1 = P.c := coeffs.2.2.2.1 @[simp] lemma coeff_zero : P.to_poly.coeff 0 = P.d := coeffs.2.2.2.2 lemma a_of_eq {Q : cubic R} (h : P.to_poly = Q.to_poly) : P.a = Q.a := by rw [← coeff_three, h, coeff_three] lemma b_of_eq {Q : cubic R} (h : P.to_poly = Q.to_poly) : P.b = Q.b := by rw [← coeff_two, h, coeff_two] lemma c_of_eq {Q : cubic R} (h : P.to_poly = Q.to_poly) : P.c = Q.c := by rw [← coeff_one, h, coeff_one] lemma d_of_eq {Q : cubic R} (h : P.to_poly = Q.to_poly) : P.d = Q.d := by rw [← coeff_zero, h, coeff_zero] @[simp] lemma to_poly_injective (P Q : cubic R) : P.to_poly = Q.to_poly ↔ P = Q := ⟨λ h, cubic.ext _ _ (a_of_eq h) (b_of_eq h) (c_of_eq h) (d_of_eq h), congr_arg _⟩ @[simp] lemma of_a_eq_zero (ha : P.a = 0) : P.to_poly = C P.b * X ^ 2 + C P.c * X + C P.d := by rw [to_poly, C_eq_zero.mpr ha, zero_mul, zero_add] @[simp] lemma of_a_b_eq_zero (ha : P.a = 0) (hb : P.b = 0) : P.to_poly = C P.c * X + C P.d := by rw [of_a_eq_zero ha, C_eq_zero.mpr hb, zero_mul, zero_add] @[simp] lemma of_a_b_c_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) : P.to_poly = C P.d := by rw [of_a_b_eq_zero ha hb, C_eq_zero.mpr hc, zero_mul, zero_add] @[simp] lemma of_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) (hd : P.d = 0) : P.to_poly = 0 := by rw [of_a_b_c_eq_zero ha hb hc, C_eq_zero.mpr hd] @[simp] lemma zero : (0 : cubic R).to_poly = 0 := of_zero rfl rfl rfl rfl @[simp] lemma eq_zero_iff : P.to_poly = 0 ↔ P = 0 := by rw [← zero, to_poly_injective] lemma ne_zero (h0 : ¬P.a = 0 ∨ ¬P.b = 0 ∨ ¬P.c = 0 ∨ ¬P.d = 0) : P.to_poly ≠ 0 := by { contrapose! h0, rw [eq_zero_iff.mp h0], exact ⟨rfl, rfl, rfl, rfl⟩ } lemma ne_zero_of_a_ne_zero (ha : P.a ≠ 0) : P.to_poly ≠ 0 := (or_imp_distrib.mp ne_zero).1 ha lemma ne_zero_of_b_ne_zero (hb : P.b ≠ 0) : P.to_poly ≠ 0 := (or_imp_distrib.mp (or_imp_distrib.mp ne_zero).2).1 hb lemma ne_zero_of_c_ne_zero (hc : P.c ≠ 0) : P.to_poly ≠ 0 := (or_imp_distrib.mp (or_imp_distrib.mp (or_imp_distrib.mp ne_zero).2).2).1 hc lemma ne_zero_of_d_ne_zero (hd : P.d ≠ 0) : P.to_poly ≠ 0 := (or_imp_distrib.mp (or_imp_distrib.mp (or_imp_distrib.mp ne_zero).2).2).2 hd end coeff /-! ### Degrees -/ section degree /-- The equivalence between cubic polynomials and polynomials of degree at most three. -/ @[simps] def equiv : cubic R ≃ {p : R[X] // p.degree ≤ 3} := { to_fun := λ P, ⟨P.to_poly, degree_cubic_le⟩, inv_fun := λ f, ⟨coeff f 3, coeff f 2, coeff f 1, coeff f 0⟩, left_inv := λ P, by ext; simp only [subtype.coe_mk, coeffs], right_inv := λ f, begin ext (_ | _ | _ | _ | n); simp only [subtype.coe_mk, coeffs], have h3 : 3 < n + 4 := by linarith only, rw [coeff_gt_three _ h3, (degree_le_iff_coeff_zero (f : R[X]) 3).mp f.2 _ $ with_bot.coe_lt_coe.mpr h3] end } lemma degree (ha : P.a ≠ 0) : P.to_poly.degree = 3 := degree_cubic ha lemma degree_of_a_eq_zero (ha : P.a = 0) (hb : P.b ≠ 0) : P.to_poly.degree = 2 := by rw [of_a_eq_zero ha, degree_quadratic hb] lemma degree_of_a_b_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c ≠ 0) : P.to_poly.degree = 1 := by rw [of_a_b_eq_zero ha hb, degree_linear hc] lemma degree_of_a_b_c_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) (hd : P.d ≠ 0) : P.to_poly.degree = 0 := by rw [of_a_b_c_eq_zero ha hb hc, degree_C hd] lemma degree_of_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) (hd : P.d = 0) : P.to_poly.degree = ⊥ := by rw [of_zero ha hb hc hd, degree_zero] lemma leading_coeff (ha : P.a ≠ 0) : P.to_poly.leading_coeff = P.a := leading_coeff_cubic ha lemma leading_coeff_of_a_eq_zero (ha : P.a = 0) (hb : P.b ≠ 0) : P.to_poly.leading_coeff = P.b := by rw [of_a_eq_zero ha, leading_coeff_quadratic hb] lemma leading_coeff_of_a_b_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c ≠ 0) : P.to_poly.leading_coeff = P.c := by rw [of_a_b_eq_zero ha hb, leading_coeff_linear hc] lemma leading_coeff_of_a_b_c_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) : P.to_poly.leading_coeff = P.d := by rw [of_a_b_c_eq_zero ha hb hc, leading_coeff_C] end degree /-! ### Map across a homomorphism -/ section map variables [semiring S] {φ : R →+* S} /-- Map a cubic polynomial across a semiring homomorphism. -/ def map (φ : R →+* S) (P : cubic R) : cubic S := ⟨φ P.a, φ P.b, φ P.c, φ P.d⟩ lemma map_to_poly : (map φ P).to_poly = polynomial.map φ P.to_poly := by simp only [map, to_poly, map_C, map_X, polynomial.map_add, polynomial.map_mul, polynomial.map_pow] end map end basic section roots open multiset /-! ### Roots over an extension -/ section extension variables {P : cubic R} [comm_ring R] [comm_ring S] {φ : R →+* S} /-- The roots of a cubic polynomial. -/ def roots [is_domain R] (P : cubic R) : multiset R := P.to_poly.roots lemma map_roots [is_domain S] : (map φ P).roots = (polynomial.map φ P.to_poly).roots := by rw [roots, map_to_poly] theorem mem_roots_iff [is_domain R] (h0 : P.to_poly ≠ 0) (x : R) : x ∈ P.roots ↔ P.a * x ^ 3 + P.b * x ^ 2 + P.c * x + P.d = 0 := begin rw [roots, mem_roots h0, is_root, to_poly], simp only [eval_C, eval_X, eval_add, eval_mul, eval_pow] end theorem card_roots_le [is_domain R] [decidable_eq R] : P.roots.to_finset.card ≤ 3 := begin apply (to_finset_card_le P.to_poly.roots).trans, by_cases hP : P.to_poly = 0, { exact (card_roots' P.to_poly).trans (by { rw [hP, nat_degree_zero], exact zero_le 3 }) }, { exact with_bot.coe_le_coe.1 ((card_roots hP).trans degree_cubic_le) } end end extension variables {P : cubic F} [field F] [field K] {φ : F →+* K} {x y z : K} /-! ### Roots over a splitting field -/ section split theorem splits_iff_card_roots (ha : P.a ≠ 0) : splits φ P.to_poly ↔ (map φ P).roots.card = 3 := begin replace ha : (map φ P).a ≠ 0 := (ring_hom.map_ne_zero φ).mpr ha, nth_rewrite_lhs 0 [← ring_hom.id_comp φ], rw [roots, ← splits_map_iff, ← map_to_poly, splits_iff_card_roots, ← ((degree_eq_iff_nat_degree_eq $ ne_zero_of_a_ne_zero ha).mp $ degree ha : _ = 3)] end theorem splits_iff_roots_eq_three (ha : P.a ≠ 0) : splits φ P.to_poly ↔ ∃ x y z : K, (map φ P).roots = {x, y, z} := by rw [splits_iff_card_roots ha, card_eq_three] theorem eq_prod_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) : (map φ P).to_poly = C (φ P.a) * (X - C x) * (X - C y) * (X - C z) := begin rw [map_to_poly, eq_prod_roots_of_splits $ (splits_iff_roots_eq_three ha).mpr $ exists.intro x $ exists.intro y $ exists.intro z h3, leading_coeff ha, ← map_roots, h3], change C (φ P.a) * ((X - C x) ::ₘ (X - C y) ::ₘ {X - C z}).prod = _, rw [prod_cons, prod_cons, prod_singleton, mul_assoc, mul_assoc] end theorem eq_sum_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) : map φ P = ⟨φ P.a, φ P.a * -(x + y + z), φ P.a * (x * y + x * z + y * z), φ P.a * -(x * y * z)⟩ := begin apply_fun to_poly, any_goals { exact λ P Q, (to_poly_injective P Q).mp }, rw [eq_prod_three_roots ha h3, to_poly], simp only [C_neg, C_add, C_mul], ring1 end theorem b_eq_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) : φ P.b = φ P.a * -(x + y + z) := by injection eq_sum_three_roots ha h3 theorem c_eq_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) : φ P.c = φ P.a * (x * y + x * z + y * z) := by injection eq_sum_three_roots ha h3 theorem d_eq_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) : φ P.d = φ P.a * -(x * y * z) := by injection eq_sum_three_roots ha h3 end split /-! ### Discriminant over a splitting field -/ section discriminant /-- The discriminant of a cubic polynomial. -/ def disc {R : Type*} [ring R] (P : cubic R) : R := P.b ^ 2 * P.c ^ 2 - 4 * P.a * P.c ^ 3 - 4 * P.b ^ 3 * P.d - 27 * P.a ^ 2 * P.d ^ 2 + 18 * P.a * P.b * P.c * P.d theorem disc_eq_prod_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) : φ P.disc = (φ P.a * φ P.a * (x - y) * (x - z) * (y - z)) ^ 2 := begin simp only [disc, ring_hom.map_add, ring_hom.map_sub, ring_hom.map_mul, map_pow], simp only [ring_hom.map_one, map_bit0, map_bit1], rw [b_eq_three_roots ha h3, c_eq_three_roots ha h3, d_eq_three_roots ha h3], ring1 end theorem disc_ne_zero_iff_roots_ne (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) : P.disc ≠ 0 ↔ x ≠ y ∧ x ≠ z ∧ y ≠ z := begin rw [← ring_hom.map_ne_zero φ, disc_eq_prod_three_roots ha h3, pow_two], simp only [mul_ne_zero_iff, sub_ne_zero], rw [ring_hom.map_ne_zero], tautology end theorem disc_ne_zero_iff_roots_nodup (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) : P.disc ≠ 0 ↔ (map φ P).roots.nodup := begin rw [disc_ne_zero_iff_roots_ne ha h3, h3], change _ ↔ (x ::ₘ y ::ₘ {z}).nodup, rw [nodup_cons, nodup_cons, mem_cons, mem_singleton, mem_singleton], simp only [nodup_singleton], tautology end theorem card_roots_of_disc_ne_zero [decidable_eq K] (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) (hd : P.disc ≠ 0) : (map φ P).roots.to_finset.card = 3 := begin rw [to_finset_card_of_nodup $ (disc_ne_zero_iff_roots_nodup ha h3).mp hd, ← splits_iff_card_roots ha, splits_iff_roots_eq_three ha], exact ⟨x, ⟨y, ⟨z, h3⟩⟩⟩ end end discriminant end roots end cubic
0121aeafc5b609bf9f7909649647e8d76cf7bcf8
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/src/uexp/rules/transitiveInferenceProject.lean
fa8932f99184d198d93d2e96e4b5ad0f44cc0439
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
2,344
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..meta.ucongr import ..meta.TDP set_option profiler true open Expr open Proj open Pred open SQL open tree open binary_operators set_option profiler true notation `int` := datatypes.int variable integer_1: const datatypes.int variable integer_7: const datatypes.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 (e2p (constantExpr integer_1)) FROM1 (product ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt))) (table rel_emp)) WHERE (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅emp_deptno)))) :SQL Γ _) = denoteSQL ((SELECT1 (e2p (constantExpr integer_1)) FROM1 (product ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt))) ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt)))) WHERE (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅emp_deptno)))) :SQL Γ _) := begin intros, unfold_all_denotations, funext, dsimp, print_size, try {simp}, print_size, TDP, end
bde6242f382d14cc4763d72862c26060517238dd
c9b68131de1dfe4e7f0ea5749b11e67a774bc839
/src/range_check.lean
2a33e0452a820f243d1bc496a7ea508a3ad14e93
[]
no_license
congge666/formal-proofs
2013f158f310abcfc07c156bb2a5113fb78f7831
b5f6964d0220c8f89668357f2c08e44861128fe3
refs/heads/master
1,691,374,567,671
1,632,704,604,000
1,632,706,366,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,116
lean
/- Range check constraints. -/ import memory noncomputable theory open_locale big_operators /- trace data -/ variables {F : Type*} [field F] variables {n : ℕ} {a a' p : fin (n + 1) → F} variables {z : F} variables {rc_min rc_max : ℕ} variable {T : ℕ} variables {off_op0_tilde off_op1_tilde off_dst_tilde : fin T → F} variables {embed_off_op0 embed_off_op1 embed_off_dst : fin T → fin (n + 1)} /- constraints -/ variable h_continuity : ∀ i : fin n, (a' i.succ - a' i.cast_succ) * (a' i.succ - a' i.cast_succ - 1) = 0 variable h_initial : (z - a' 0) * p 0 = z - a 0 variable h_cumulative : ∀ i : fin n, (z - a' i.succ) * p i.succ = (z - a i.succ) * p i.cast_succ variable h_final : p (fin.last n) = 1 variable h_rc_min : a' 0 = rc_min variable h_rc_max : a' (fin.last n) = rc_max variable h_embed_op0 : ∀ i, a (embed_off_op0 i) = off_op0_tilde i variable h_embed_op1 : ∀ i, a (embed_off_op1 i) = off_op1_tilde i variable h_embed_dst : ∀ i, a (embed_off_dst i) = off_dst_tilde i variable h_n_lt : n < ring_char F variable h_rc_lt : rc_max < 2^16 variable h_rc_le : rc_min ≤ rc_max variable h_ring_char_gt : 2^16 < ring_char F section include h_continuity h_rc_min lemma rc_a'_eq (j : fin (n + 1)) : a' j = ↑(rc_min + a'_nat_offset a' j) := by rw [a'_nat_offset_spec h_continuity j, h_rc_min, nat.cast_add] include h_rc_max h_rc_le h_rc_lt h_n_lt h_ring_char_gt lemma rc_nat_offset_eq : rc_min + a'_nat_offset a' (fin.last n) = rc_max := begin have h₀ : (↑rc_min : F) + ↑(a'_nat_offset a' (fin.last n)) = ↑rc_min + ↑(rc_max - rc_min), { rw [←nat.cast_add, ←nat.cast_add, ←rc_a'_eq h_continuity h_rc_min, h_rc_max, nat.add_sub_cancel' h_rc_le] }, have h₁ : a'_nat_offset a' (fin.last n) < ring_char F := lt_of_le_of_lt (a'_nat_offset_le _) h_n_lt, have h₂ : rc_max - rc_min < ring_char F := lt_of_le_of_lt (nat.sub_le_self _ _) (lt_trans h_rc_lt h_ring_char_gt), have := add_left_cancel h₀, rw nat.cast_inj_of_lt_char h₁ h₂ this, apply nat.add_sub_cancel' h_rc_le end lemma rc_nat_offset_le (j : fin (n + 1)): rc_min + a'_nat_offset a' j ≤ rc_max := begin rw ←rc_nat_offset_eq h_continuity h_rc_min h_rc_max h_n_lt h_rc_lt h_rc_le h_ring_char_gt, apply add_le_add_left, apply monotone_a'_nat_offset, apply fin.le_last end end section variable [fintype F] def bad_set_3 (a a' : fin (n + 1) → F) : finset F := polynomial_aux.exceptional_set a a' theorem card_bad_set_3_le : (bad_set_3 a a').card ≤ n + 1 := by { transitivity, apply polynomial_aux.card_exceptional_set_le, simp } theorem bad_set_3_spec {z : F} (h₁ : z ∉ bad_set_3 a a') (h₂ : ∏ i : fin (n + 1), (z - a i) = ∏ i, (z - a' i)) : ∀ i, ∃ j, a i = a' j := exceptional_set_spec _ _ h₁ h₂ theorem bad_set_3_spec' {z : F} (h₁ : z ∉ bad_set_3 a a') (h₂ : ∏ i : fin (n + 1), (z - a i) = ∏ i, (z - a' i)) : ∀ i, ∃ j, a' i = a j:= exceptional_set_spec' _ _ h₁ h₂ end section permutation include h_initial h_cumulative lemma rc_permutation_aux (j : fin (n + 1)) : ∏ i in fin.range j.succ, (z - a i) = (∏ i in fin.range j.succ, (z - a' i)) * p j := begin apply fin.induction_on j, { rw [←fin.one_eq_succ_zero, fin.prod_range_one, fin.prod_range_one, h_initial] }, intros j ih, rw [fin.prod_range_succ, fin.prod_range_succ, ←fin.succ_cast_succ, ih, ←mul_assoc], conv { to_rhs, rw [mul_right_comm, h_cumulative, mul_right_comm] } end include h_final lemma rc_permutation_prod_eq : ∏ i, (z - a i) = ∏ i, (z - a' i) := by rw [←fin.range_last, ←fin.succ_last, rc_permutation_aux h_initial h_cumulative, h_final, mul_one] end permutation variable [fintype F] variable hprob₃ : z ∉ bad_set_3 a a' lemma rc_permutation : ∀ i, ∃ j, a i = a' j := λ i, bad_set_3_spec hprob₃ (rc_permutation_prod_eq h_initial h_cumulative h_final) i include h_continuity h_initial h_cumulative h_final hprob₃ include h_rc_min h_rc_max h_rc_le h_rc_lt h_n_lt h_ring_char_gt section include h_embed_op0 theorem off_op0_in_range (i : fin T) : ∃ k : ℕ, k < 2^16 ∧ off_op0_tilde i = ↑k := begin rcases (rc_permutation h_initial h_cumulative h_final hprob₃ (embed_off_op0 i)) with ⟨j, hj⟩, have : a' j = a' 0 + a'_nat_offset a' j := a'_nat_offset_spec h_continuity _, rw [this, h_embed_op0, h_rc_min, ←nat.cast_add] at hj, use [rc_min + a'_nat_offset a' j], split, { apply lt_of_le_of_lt _ h_rc_lt, apply rc_nat_offset_le h_continuity h_rc_min h_rc_max h_n_lt h_rc_lt h_rc_le h_ring_char_gt }, exact hj end end theorem off_op1_in_range (i : fin T) : ∃ k : ℕ, k < 2^16 ∧ off_op1_tilde i = ↑k := off_op0_in_range h_continuity h_initial h_cumulative h_final h_rc_min h_rc_max h_embed_op1 h_n_lt h_rc_lt h_rc_le h_ring_char_gt hprob₃ i theorem off_dst_in_range (i : fin T) : ∃ k : ℕ, k < 2^16 ∧ off_dst_tilde i = ↑k := off_op0_in_range h_continuity h_initial h_cumulative h_final h_rc_min h_rc_max h_embed_dst h_n_lt h_rc_lt h_rc_le h_ring_char_gt hprob₃ i
9c200542d105dd967e0e02438e210a4c3c35a01d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/monotonicity/default_auto.lean
5a10245a0fe3be2aed0cd31d7d64b06539b1c5f3
[]
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
351
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.tactic.monotonicity.interactive import Mathlib.tactic.monotonicity.lemmas import Mathlib.PostPort namespace Mathlib end Mathlib
0853e54185ad883ee02c6454bc2e023ad6e7edbf
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/init/nat.hlean
d6b63d941ad57470a54d64069a19f01fd0e85179
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
9,981
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import init.tactic init.num init.types init.path open eq eq.ops decidable open algebra sum set_option class.force_new true notation `ℕ` := nat namespace nat protected definition rec_on [reducible] [recursor] [unfold 2] {C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C a → C (succ a)) : C n := nat.rec H₁ H₂ n protected definition cases [reducible] [unfold 4] {M : ℕ → Type} (mz : M zero) (ms : Πn, M (succ n)) : Πn, M n := nat.rec mz (λn dummy, ms n) protected definition cases_on [reducible] [recursor] [unfold 2] {C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C (succ a)) : C n := nat.rec H₁ (λ a ih, H₂ a) n protected definition no_confusion_type.{u} [reducible] (P : Type.{u}) (v₁ v₂ : ℕ) : Type.{u} := nat.rec (nat.rec (P → lift P) (λ a₂ ih, lift P) v₂) (λ a₁ ih, nat.rec (lift P) (λ a₂ ih, (a₁ = a₂ → P) → lift P) v₂) v₁ protected definition no_confusion [reducible] [unfold 4] {P : Type} {v₁ v₂ : ℕ} (H : v₁ = v₂) : nat.no_confusion_type P v₁ v₂ := eq.rec (λ H₁ : v₁ = v₁, nat.rec (λ h, lift.up h) (λ a ih h, lift.up (h (eq.refl a))) v₁) H H /- basic definitions on natural numbers -/ inductive le (a : ℕ) : ℕ → Type := | nat_refl : le a a -- use nat_refl to avoid overloading le.refl | step : Π {b}, le a b → le a (succ b) definition nat_has_le [instance] [priority nat.prio]: has_le nat := has_le.mk nat.le protected definition le_refl [refl] : Π a : nat, a ≤ a := le.nat_refl protected definition lt [reducible] (n m : ℕ) := succ n ≤ m definition nat_has_lt [instance] [priority nat.prio] : has_lt nat := has_lt.mk nat.lt definition pred [unfold 1] (a : nat) : nat := nat.cases_on a zero (λ a₁, a₁) -- add is defined in init.reserved_notation protected definition sub (a b : nat) : nat := nat.rec_on b a (λ b₁, pred) protected definition mul (a b : nat) : nat := nat.rec_on b zero (λ b₁ r, r + a) definition nat_has_sub [instance] [priority nat.prio] : has_sub nat := has_sub.mk nat.sub definition nat_has_mul [instance] [priority nat.prio] : has_mul nat := has_mul.mk nat.mul /- properties of ℕ -/ protected definition is_inhabited [instance] : inhabited nat := inhabited.mk zero protected definition has_decidable_eq [instance] [priority nat.prio] : Π x y : nat, decidable (x = y) | has_decidable_eq zero zero := inl rfl | has_decidable_eq (succ x) zero := inr (by contradiction) | has_decidable_eq zero (succ y) := inr (by contradiction) | has_decidable_eq (succ x) (succ y) := match has_decidable_eq x y with | inl xeqy := inl (by rewrite xeqy) | inr xney := inr (λ h : succ x = succ y, by injection h with xeqy; exact absurd xeqy xney) end /- properties of inequality -/ protected definition le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := p ▸ !nat.le_refl definition le_succ (n : ℕ) : n ≤ succ n := le.step !nat.le_refl definition pred_le (n : ℕ) : pred n ≤ n := by cases n;repeat constructor definition le_succ_iff_unit [simp] (n : ℕ) : n ≤ succ n ↔ unit := iff_unit_intro (le_succ n) definition pred_le_iff_unit [simp] (n : ℕ) : pred n ≤ n ↔ unit := iff_unit_intro (pred_le n) protected definition le_trans {n m k : ℕ} (H1 : n ≤ m) : m ≤ k → n ≤ k := le.rec H1 (λp H2, le.step) definition le_succ_of_le {n m : ℕ} (H : n ≤ m) : n ≤ succ m := le.step H definition le_of_succ_le {n m : ℕ} (H : succ n ≤ m) : n ≤ m := by induction H with H m H'; exact le_succ n; exact le.step H' protected definition le_of_lt {n m : ℕ} (H : n < m) : n ≤ m := le_of_succ_le H definition succ_le_succ {n m : ℕ} : n ≤ m → succ n ≤ succ m := le.rec !nat.le_refl (λa b, le.step) theorem pred_le_pred {n m : ℕ} : n ≤ m → pred n ≤ pred m := le.rec !nat.le_refl (nat.rec (λa b, b) (λa b c, le.step)) theorem le_of_succ_le_succ {n m : ℕ} : succ n ≤ succ m → n ≤ m := pred_le_pred theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m := nat.cases_on n le.step (λa, succ_le_succ) theorem not_succ_le_zero (n : ℕ) : ¬succ n ≤ 0 := by intro H; cases H theorem succ_le_zero_iff_empty (n : ℕ) : succ n ≤ 0 ↔ empty := iff_empty_intro !not_succ_le_zero theorem not_succ_le_self : Π {n : ℕ}, ¬succ n ≤ n := nat.rec !not_succ_le_zero (λa b c, b (le_of_succ_le_succ c)) theorem succ_le_self_iff_empty [simp] (n : ℕ) : succ n ≤ n ↔ empty := iff_empty_intro not_succ_le_self definition zero_le : Π (n : ℕ), 0 ≤ n := nat.rec !nat.le_refl (λa, le.step) theorem zero_le_iff_unit [simp] (n : ℕ) : 0 ≤ n ↔ unit := iff_unit_intro !zero_le theorem lt.step {n m : ℕ} : n < m → n < succ m := le.step theorem zero_lt_succ (n : ℕ) : 0 < succ n := succ_le_succ !zero_le theorem zero_lt_succ_iff_unit [simp] (n : ℕ) : 0 < succ n ↔ unit := iff_unit_intro (zero_lt_succ n) protected theorem lt_trans {n m k : ℕ} (H1 : n < m) : m < k → n < k := nat.le_trans (le.step H1) protected theorem lt_of_le_of_lt {n m k : ℕ} (H1 : n ≤ m) : m < k → n < k := nat.le_trans (succ_le_succ H1) protected theorem lt_of_lt_of_le {n m k : ℕ} : n < m → m ≤ k → n < k := nat.le_trans protected theorem lt_irrefl (n : ℕ) : ¬n < n := not_succ_le_self theorem lt_self_iff_empty (n : ℕ) : n < n ↔ empty := iff_empty_intro (λ H, absurd H (nat.lt_irrefl n)) theorem self_lt_succ (n : ℕ) : n < succ n := !nat.le_refl theorem self_lt_succ_iff_unit [simp] (n : ℕ) : n < succ n ↔ unit := iff_unit_intro (self_lt_succ n) theorem lt.base (n : ℕ) : n < succ n := !nat.le_refl theorem le_lt_antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m < n) : empty := !nat.lt_irrefl (nat.lt_of_le_of_lt H1 H2) protected theorem le_antisymm {n m : ℕ} (H1 : n ≤ m) : m ≤ n → n = m := le.cases_on H1 (λa, rfl) (λa b c, absurd (nat.lt_of_le_of_lt b c) !nat.lt_irrefl) theorem lt_le_antisymm {n m : ℕ} (H1 : n < m) (H2 : m ≤ n) : empty := le_lt_antisymm H2 H1 protected theorem nat.lt_asymm {n m : ℕ} (H1 : n < m) : ¬ m < n := le_lt_antisymm (nat.le_of_lt H1) theorem not_lt_zero (a : ℕ) : ¬ a < 0 := !not_succ_le_zero theorem lt_zero_iff_empty [simp] (a : ℕ) : a < 0 ↔ empty := iff_empty_intro (not_lt_zero a) protected theorem eq_sum_lt_of_le {a b : ℕ} (H : a ≤ b) : a = b ⊎ a < b := le.cases_on H (inl rfl) (λn h, inr (succ_le_succ h)) protected theorem le_of_eq_sum_lt {a b : ℕ} (H : a = b ⊎ a < b) : a ≤ b := sum.rec_on H !nat.le_of_eq !nat.le_of_lt theorem succ_lt_succ {a b : ℕ} : a < b → succ a < succ b := succ_le_succ theorem lt_of_succ_lt {a b : ℕ} : succ a < b → a < b := le_of_succ_le theorem lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b := le_of_succ_le_succ definition decidable_le [instance] [priority nat.prio] : Π a b : nat, decidable (a ≤ b) := nat.rec (λm, (decidable.inl !zero_le)) (λn IH m, !nat.cases_on (decidable.inr (not_succ_le_zero n)) (λm, decidable.rec (λH, inl (succ_le_succ H)) (λH, inr (λa, H (le_of_succ_le_succ a))) (IH m))) definition decidable_lt [instance] [priority nat.prio] : Π a b : nat, decidable (a < b) := λ a b, decidable_le (succ a) b protected theorem lt_sum_ge (a b : ℕ) : a < b ⊎ a ≥ b := nat.rec (inr !zero_le) (λn, sum.rec (λh, inl (le_succ_of_le h)) (λh, sum.rec_on (nat.eq_sum_lt_of_le h) (λe, inl (eq.subst e !nat.le_refl)) inr)) b protected definition lt_ge_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a ≥ b → P) : P := by_cases H1 (λh, H2 (sum.rec_on !nat.lt_sum_ge (λa, absurd a h) (λa, a))) protected definition lt_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := nat.lt_ge_by_cases H1 (λh₁, nat.lt_ge_by_cases H3 (λh₂, H2 (nat.le_antisymm h₂ h₁))) protected theorem lt_trichotomy (a b : ℕ) : a < b ⊎ a = b ⊎ b < a := nat.lt_by_cases (λH, inl H) (λH, inr (inl H)) (λH, inr (inr H)) protected theorem eq_sum_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ⊎ b < a := sum.rec_on (nat.lt_trichotomy a b) (λ hlt, absurd hlt hnlt) (λ h, h) theorem lt_succ_of_le {a b : ℕ} : a ≤ b → a < succ b := succ_le_succ theorem lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h theorem succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h theorem succ_sub_succ_eq_sub [simp] (a b : ℕ) : succ a - succ b = a - b := nat.rec (by esimp) (λ b, ap pred) b theorem sub_eq_succ_sub_succ (a b : ℕ) : a - b = succ a - succ b := inverse !succ_sub_succ_eq_sub theorem zero_sub_eq_zero [simp] (a : ℕ) : 0 - a = 0 := nat.rec rfl (λ a, ap pred) a theorem zero_eq_zero_sub (a : ℕ) : 0 = 0 - a := inverse !zero_sub_eq_zero theorem sub_le (a b : ℕ) : a - b ≤ a := nat.rec_on b !nat.le_refl (λ b₁, nat.le_trans !pred_le) theorem sub_le_iff_unit [simp] (a b : ℕ) : a - b ≤ a ↔ unit := iff_unit_intro (sub_le a b) theorem sub_lt {a b : ℕ} (H1 : 0 < a) (H2 : 0 < b) : a - b < a := !nat.cases_on (λh, absurd h !nat.lt_irrefl) (λa h, succ_le_succ (!nat.cases_on (λh, absurd h !nat.lt_irrefl) (λb c, tr_rev _ !succ_sub_succ_eq_sub !sub_le) H2)) H1 theorem sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le !sub_le theorem sub_lt_succ_iff_unit [simp] (a b : ℕ) : a - b < succ a ↔ unit := iff_unit_intro !sub_lt_succ end nat
53c5700f3e2bfd830a4ab1e5158cee9864d148a7
ec5a7ae10c533e1b1f4b0bc7713e91ecf829a3eb
/ijcar16/examples/list.lean
5fb47fac375307e01df997c71bab3502e66cd8ac
[ "MIT" ]
permissive
leanprover/leanprover.github.io
cf248934af7c7e9aeff17cf8df3c12c5e7e73f1a
071a20d2e059a2c3733e004c681d3949cac3c07a
refs/heads/master
1,692,621,047,417
1,691,396,994,000
1,691,396,994,000
19,366,263
18
27
MIT
1,693,989,071,000
1,399,006,345,000
Lean
UTF-8
Lean
false
false
5,442
lean
/- This is a file from the Lean standard library. We use it to demonstrate/test the congruence closure procedure described in the paper: "Congruence Closure for Intensional Type Theory" Daniel Selsam and Leonardo de Moura The lemmas proved using `by inst_simp` are using the congruence closure procedure described in the paper above. The lemmas proved using `by rec_inst_simp` are also using the congruence closure procedure described in the paper above. They first apply induction, and then use `inst_simp`. The tactic inst_simp uses E-matching to heuristically instantiate lemmas tagged as simplification rules (i.e., `[simp]` tag in Lean). There are 15 instances `by inst_simp` and `by rec_inst_simp` in this file. -/ import data.nat open nat inductive list (T : Type) : Type := | nil {} : list T | cons : T → list T → list T namespace list notation h :: t := cons h t notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l variable {T : Type} lemma cons_ne_nil [simp] (a : T) (l : list T) : a::l ≠ [] := by contradiction lemma head_eq_of_cons_eq {A : Type} {h₁ h₂ : A} {t₁ t₂ : list A} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := by inst_simp lemma tail_eq_of_cons_eq {A : Type} {h₁ h₂ : A} {t₁ t₂ : list A} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := by inst_simp /- append -/ definition append : list T → list T → list T | [] l := l | (h :: s) t := h :: (append s t) notation l₁ ++ l₂ := append l₁ l₂ theorem append_nil_left [simp] (t : list T) : [] ++ t = t := rfl theorem append_cons [simp] (x : T) (s t : list T) : (x::s) ++ t = x::(s ++ t) := rfl theorem append_nil_right [simp] : ∀ (t : list T), t ++ [] = t := by rec_inst_simp theorem append.assoc [simp] : ∀ (s t u : list T), s ++ t ++ u = s ++ (t ++ u) := by rec_inst_simp /- length -/ definition length : list T → nat | [] := 0 | (a :: l) := length l + 1 theorem length_nil [simp] : length (@nil T) = 0 := rfl theorem length_cons [simp] (x : T) (t : list T) : length (x::t) = length t + 1 := rfl theorem length_append [simp] : ∀ (s t : list T), length (s ++ t) = length s + length t := by rec_inst_simp theorem eq_nil_of_length_eq_zero : ∀ {l : list T}, length l = 0 → l = [] | [] H := rfl | (a::s) H := by contradiction theorem ne_nil_of_length_eq_succ : ∀ {l : list T} {n : nat}, length l = succ n → l ≠ [] | [] n h := by contradiction | (a::l) n h := by contradiction /- concat -/ definition concat : Π (x : T), list T → list T | a [] := [a] | a (b :: l) := b :: concat a l theorem concat_nil [simp] (x : T) : concat x [] = [x] := rfl theorem concat_cons [simp] (x y : T) (l : list T) : concat x (y::l) = y::(concat x l) := rfl theorem concat_eq_append [simp] (a : T) : ∀ (l : list T), concat a l = l ++ [a] := by rec_inst_simp theorem concat_ne_nil [simp] (a : T) : ∀ (l : list T), concat a l ≠ [] := by intro l; induction l; repeat contradiction theorem length_concat [simp] (a : T) : ∀ (l : list T), length (concat a l) = length l + 1 := by rec_inst_simp theorem concat_append [simp] (a : T) : ∀ (l₁ l₂ : list T), concat a l₁ ++ l₂ = l₁ ++ a :: l₂ := by rec_inst_simp theorem append_concat (a : T) : ∀(l₁ l₂ : list T), l₁ ++ concat a l₂ = concat a (l₁ ++ l₂) := by rec_inst_simp /- last -/ definition last : Π l : list T, l ≠ [] → T | [] h := absurd rfl h | [a] h := a | (a₁::a₂::l) h := last (a₂::l) !cons_ne_nil lemma last_singleton [simp] (a : T) (h : [a] ≠ []) : last [a] h = a := rfl lemma last_cons_cons [simp] (a₁ a₂ : T) (l : list T) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) !cons_ne_nil := rfl theorem last_congr {l₁ l₂ : list T} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ theorem last_concat [simp] {x : T} : ∀ {l : list T} (h : concat x l ≠ []), last (concat x l) h = x := by rec_simp -- add_rewrite append_nil append_cons /- reverse -/ definition reverse : list T → list T | [] := [] | (a :: l) := concat a (reverse l) theorem reverse_nil [simp] : reverse (@nil T) = [] := rfl theorem reverse_cons [simp] (x : T) (l : list T) : reverse (x::l) = concat x (reverse l) := rfl theorem reverse_singleton [simp] (x : T) : reverse [x] = [x] := rfl theorem reverse_append [simp] : ∀ (s t : list T), reverse (s ++ t) = (reverse t) ++ (reverse s) := by rec_inst_simp theorem reverse_reverse [simp] : ∀ (l : list T), reverse (reverse l) = l := by rec_inst_simp theorem concat_eq_reverse_cons (x : T) (l : list T) : concat x l = reverse (x :: reverse l) := by inst_simp theorem length_reverse : ∀ (l : list T), length (reverse l) = length l := by rec_inst_simp /- head and tail -/ definition head [h : inhabited T] : list T → T | [] := arbitrary T | (a :: l) := a theorem head_cons [simp] [h : inhabited T] (a : T) (l : list T) : head (a::l) = a := rfl theorem head_append [simp] [h : inhabited T] (t : list T) : ∀ {s : list T}, s ≠ [] → head (s ++ t) = head s := by rec_inst_simp definition tail : list T → list T | [] := [] | (a :: l) := l theorem tail_nil [simp] : tail (@nil T) = [] := rfl theorem tail_cons [simp] (a : T) (l : list T) : tail (a::l) = l := rfl theorem cons_head_tail [h : inhabited T] {l : list T} : l ≠ [] → (head l)::(tail l) = l := by rec_inst_simp end list
6c121ec2dc20270cf81c4c25600c9eb068c06fa1
3f7026ea8bef0825ca0339a275c03b911baef64d
/docs/tutorial/category_theory/calculating_colimits_in_Top.lean
ee51776e65f4740ed24522a3a97a12f44ccf5a08
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
3,494
lean
import topology.Top.limits import category_theory.limits.shapes import topology.instances.real /- This file contains some demos of using the (co)limits API to do topology. -/ noncomputable theory open category_theory open category_theory.limits def R : Top := Top.of ℝ def I : Top := Top.of (set.Icc 0 1 : set ℝ) def pt : Top := Top.of unit section MappingCylinder -- Let's construct the mapping cylinder. def to_pt (X : Top) : X ⟶ pt := { val := λ _, unit.star, property := continuous_const } def I₀ : pt ⟶ I := { val := λ _, ⟨(0 : ℝ), begin rw [set.left_mem_Icc], norm_num, end⟩, property := continuous_const } def I₁ : pt ⟶ I := { val := λ _, ⟨(1 : ℝ), begin rw [set.right_mem_Icc], norm_num, end⟩, property := continuous_const } def cylinder (X : Top) : Top := prod X I -- To define a map to the cylinder, we give a map to each factor. -- `prod.lift` is a helper method, providing a wrapper around `limit.lift` for binary products. def cylinder₀ (X : Top) : X ⟶ cylinder X := prod.lift (𝟙 X) (to_pt X ≫ I₀) def cylinder₁ (X : Top) : X ⟶ cylinder X := prod.lift (𝟙 X) (to_pt X ≫ I₁) -- The mapping cylinder is the pushout of the diagram -- X -- ↙ ↘ -- Y (X x I) -- (`pushout` is implemented just as a wrapper around `colimit`) is def mapping_cylinder {X Y : Top} (f : X ⟶ Y) : Top := pushout f (cylinder₁ X) /-- We construct the map from `X` into the "bottom" of the mapping cylinder for `f : X ⟶ Y`, as the composition of the inclusion of `X` into the bottom of the cylinder `prod X I`, followed by the map `pushout.inr` of `prod X I` into `mapping_cylinder f`. -/ def mapping_cylinder₀ {X Y : Top} (f : X ⟶ Y) : X ⟶ mapping_cylinder f := cylinder₀ X ≫ pushout.inr /-- The mapping cone is defined as the pushout of ``` X ↙ ↘ (Cyl f) pt ``` (where the left arrow is `mapping_cylinder₀`). This makes it an iterated colimit; one could also define it in one step as the colimit of ``` -- X X -- ↙ ↘ ↙ ↘ -- Y (X x I) pt ``` -/ def mapping_cone {X Y : Top} (f : X ⟶ Y) : Top := pushout (mapping_cylinder₀ f) (to_pt X) -- TODO Hopefully someone will write a nice tactic for generating diagrams quickly, -- and we'll be able to verify that this iterated construction is the same as the colimit -- over a single diagram. end MappingCylinder section Gluing -- Here's two copies of the real line glued together at a point. def f : pt ⟶ R := { val := λ _, (0 : ℝ), property := continuous_const } /-- Two copies of the real line glued together at 0. -/ def X : Top := pushout f f -- To define a map out of it, we define maps out of each copy of the line, -- and check the maps agree at 0. def g : X ⟶ R := pushout.desc (𝟙 _) (𝟙 _) rfl end Gluing universes v u w section Products /-- The countably infinite product of copies of `ℝ`. -/ def Y : Top := ∏ (λ n : ℕ, R) /-- We define a point of this infinite product by specifying its coordinates. -/ def q : pt ⟶ Y := pi.lift (λ (n : ℕ), ⟨λ (_ : pt), (n : ℝ), continuous_const⟩) -- "Looking under the hood", we see that `q` is a `subtype`, whose `val` is a function `unit → Y.α`. -- #check q.val -- q.val : pt.α → Y.α -- `q.property` is the fact this function is continous (i.e. no content) -- We can check that this function is definitionally just the function we specified. example : (q.val ()).val (57 : ℕ) = ((57 : ℕ) : ℝ) := rfl end Products
21e95a2537587d41817888024ce7841f21339869
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/complex/cauchy_integral.lean
7e49ef907682b4cc41f067f3ed71cdf10e674a0a
[ "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
37,922
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 measure_theory.measure.lebesgue.complex import measure_theory.integral.divergence_theorem import measure_theory.integral.circle_integral import analysis.calculus.dslope import analysis.analytic.basic import analysis.complex.re_im_topology import analysis.calculus.diff_cont_on_cl import data.real.cardinality /-! # Cauchy integral formula > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove the Cauchy-Goursat theorem and the Cauchy integral formula for integrals over circles. Most results are formulated for a function `f : ℂ → E` that takes values in a complex Banach space with second countable topology. ## Main statements In the following theorems, if the name ends with `off_countable`, then the actual theorem assumes differentiability at all but countably many points of the set mentioned below. * `complex.integral_boundary_rect_of_has_fderiv_within_at_real_off_countable`: If a function `f : ℂ → E` is continuous on a closed rectangle and *real* differentiable on its interior, then its integral over the boundary of this rectangle is equal to the integral of `I • f' (x + y * I) 1 - f' (x + y * I) I` over the rectangle, where `f' z w : E` is the derivative of `f` at `z` in the direction `w` and `I = complex.I` is the imaginary unit. * `complex.integral_boundary_rect_eq_zero_of_differentiable_on_off_countable`: If a function `f : ℂ → E` is continuous on a closed rectangle and is *complex* differentiable on its interior, then its integral over the boundary of this rectangle is equal to zero. * `complex.circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable`: If a function `f : ℂ → E` is continuous on a closed annulus `{z | r ≤ |z - c| ≤ R}` and is complex differentiable on its interior `{z | r < |z - c| < R}`, then the integrals of `(z - c)⁻¹ • f z` over the outer boundary and over the inner boundary are equal. * `complex.circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto`, `complex.circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable`: If a function `f : ℂ → E` is continuous on a punctured closed disc `{z | |z - c| ≤ R ∧ z ≠ c}`, is complex differentiable on the corresponding punctured open disc, and tends to `y` as `z → c`, `z ≠ c`, then the integral of `(z - c)⁻¹ • f z` over the circle `|z - c| = R` is equal to `2πiy`. In particular, if `f` is continuous on the whole closed disc and is complex differentiable on the corresponding open disc, then this integral is equal to `2πif(c)`. * `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`, `complex.two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable` **Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is complex differentiable on the corresponding open disc, then for any `w` in the corresponding open disc the integral of `(z - w)⁻¹ • f z` over the boundary of the disc is equal to `2πif(w)`. Two versions of the lemma put the multiplier `2πi` at the different sides of the equality. * `complex.has_fpower_series_on_ball_of_differentiable_off_countable`: If `f : ℂ → E` is continuous on a closed disc of positive radius and is complex differentiable on the corresponding open disc, then it is analytic on the corresponding open disc, and the coefficients of the power series are given by Cauchy integral formulas. * `differentiable_on.has_fpower_series_on_ball`: If `f : ℂ → E` is complex differentiable on a closed disc of positive radius, then it is analytic on the corresponding open disc, and the coefficients of the power series are given by Cauchy integral formulas. * `differentiable_on.analytic_at`, `differentiable.analytic_at`: If `f : ℂ → E` is differentiable on a neighborhood of a point, then it is analytic at this point. In particular, if `f : ℂ → E` is differentiable on the whole `ℂ`, then it is analytic at every point `z : ℂ`. * `differentiable.has_power_series_on_ball`: If `f : ℂ → E` is differentiable everywhere then the `cauchy_power_series f z R` is a formal power series representing `f` at `z` with infinite radius of convergence (this holds for any choice of `0 < R`). ## Implementation details The proof of the Cauchy integral formula in this file is based on a very general version of the divergence theorem, see `measure_theory.integral_divergence_of_has_fderiv_within_at_off_countable` (a version for functions defined on `fin (n + 1) → ℝ`), `measure_theory.integral_divergence_prod_Icc_of_has_fderiv_within_at_off_countable_of_le`, and `measure_theory.integral2_divergence_prod_of_has_fderiv_within_at_off_countable` (versions for functions defined on `ℝ × ℝ`). Usually, the divergence theorem is formulated for a $C^1$ smooth function. The theorems formulated above deal with a function that is * continuous on a closed box/rectangle; * differentiable at all but countably many points of its interior; * have divergence integrable over the closed box/rectangle. First, we reformulate the theorem for a *real*-differentiable map `ℂ → E`, and relate the integral of `f` over the boundary of a rectangle in `ℂ` to the integral of the derivative $\frac{\partial f}{\partial \bar z}$ over the interior of this box. In particular, for a *complex* differentiable function, the latter derivative is zero, hence the integral over the boundary of a rectangle is zero. Thus we get the Cauchy-Goursat theorem for a rectangle in `ℂ`. Next, we apply the this theorem to the function $F(z)=f(c+e^{z})$ on the rectangle $[\ln r, \ln R]\times [0, 2\pi]$ to prove that $$ \oint_{|z-c|=r}\frac{f(z)\,dz}{z-c}=\oint_{|z-c|=R}\frac{f(z)\,dz}{z-c} $$ provided that `f` is continuous on the closed annulus `r ≤ |z - c| ≤ R` and is complex differentiable on its interior `r < |z - c| < R` (possibly, at all but countably many points). Here and below, we write $\frac{f(z)}{z-c}$ in the documentation while the actual lemmas use `(z - c)⁻¹ • f z` because `f z` belongs to some Banach space over `ℂ` and `f z / (z - c)` is undefined. Taking the limit of this equality as `r` tends to `𝓝[>] 0`, we prove $$ \oint_{|z-c|=R}\frac{f(z)\,dz}{z-c}=2\pi if(c) $$ provided that `f` is continuous on the closed disc `|z - c| ≤ R` and is differentiable at all but countably many points of its interior. This is the Cauchy integral formula for the center of a circle. In particular, if we apply this function to `F z = (z - c) • f z`, then we get $$ \oint_{|z-c|=R} f(z)\,dz=0. $$ In order to deduce the Cauchy integral formula for any point `w`, `|w - c| < R`, we consider the slope function `g : ℂ → E` given by `g z = (z - w)⁻¹ • (f z - f w)` if `z ≠ w` and `g w = f' w`. This function satisfies assumptions of the previous theorem, so we have $$ \oint_{|z-c|=R} \frac{f(z)\,dz}{z-w}=\oint_{|z-c|=R} \frac{f(w)\,dz}{z-w}= \left(\oint_{|z-c|=R} \frac{dz}{z-w}\right)f(w). $$ The latter integral was computed in `circle_integral.integral_sub_inv_of_mem_ball` and is equal to `2 * π * complex.I`. There is one more step in the actual proof. Since we allow `f` to be non-differentiable on a countable set `s`, we cannot immediately claim that `g` is continuous at `w` if `w ∈ s`. So, we use the proof outlined in the previous paragraph for `w ∉ s` (see `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux`), then use continuity of both sides of the formula and density of `sᶜ` to prove the formula for all points of the open ball, see `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`. Finally, we use the properties of the Cauchy integrals established elsewhere (see `has_fpower_series_on_cauchy_integral`) and Cauchy integral formula to prove that the original function is analytic on the open ball. ## Tags Cauchy-Goursat theorem, Cauchy integral formula -/ open topological_space set measure_theory interval_integral metric filter function open_locale interval real nnreal ennreal topology big_operators noncomputable theory universes u variables {E : Type u} [normed_add_comm_group E] [normed_space ℂ E] [complete_space E] namespace complex /-- Suppose that a function `f : ℂ → E` is continuous on a closed rectangle with opposite corners at `z w : ℂ`, is *real* differentiable at all but countably many points of the corresponding open rectangle, and $\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then the integral of `f` over the boundary of the rectangle is equal to the integral of $2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$ over the rectangle. -/ lemma integral_boundary_rect_of_has_fderiv_at_real_off_countable (f : ℂ → E) (f' : ℂ → ℂ →L[ℝ] E) (z w : ℂ) (s : set ℂ) (hs : s.countable) (Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im])) (Hd : ∀ x ∈ (Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im)) \ s, has_fderiv_at f (f' x) x) (Hi : integrable_on (λ z, I • f' z 1 - f' z I) ([z.re, w.re] ×ℂ [z.im, w.im])) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = ∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im, I • f' (x + y * I) 1 - f' (x + y * I) I := begin set e : (ℝ × ℝ) ≃L[ℝ] ℂ := equiv_real_prod_clm.symm, have he : ∀ x y : ℝ, ↑x + ↑y * I = e (x, y), from λ x y, (mk_eq_add_mul_I x y).symm, have he₁ : e (1, 0) = 1 := rfl, have he₂ : e (0, 1) = I := rfl, simp only [he] at *, set F : (ℝ × ℝ) → E := f ∘ e, set F' : (ℝ × ℝ) → (ℝ × ℝ) →L[ℝ] E := λ p, (f' (e p)).comp (e : (ℝ × ℝ) →L[ℝ] ℂ), have hF' : ∀ p : ℝ × ℝ, (-(I • F' p)) (1, 0) + F' p (0, 1) = -(I • f' (e p) 1 - f' (e p) I), { rintro ⟨x, y⟩, simp only [continuous_linear_map.neg_apply, continuous_linear_map.smul_apply, F', continuous_linear_map.comp_apply, continuous_linear_equiv.coe_coe, he₁, he₂, neg_add_eq_sub, neg_sub], }, set R : set (ℝ × ℝ) := [z.re, w.re] ×ˢ [w.im, z.im], set t : set (ℝ × ℝ) := e ⁻¹' s, rw [uIcc_comm z.im] at Hc Hi, rw [min_comm z.im, max_comm z.im] at Hd, have hR : e ⁻¹' ([z.re, w.re] ×ℂ [w.im, z.im]) = R := rfl, have htc : continuous_on F R, from Hc.comp e.continuous_on hR.ge, have htd : ∀ p ∈ Ioo (min z.re w.re) (max z.re w.re) ×ˢ Ioo (min w.im z.im) (max w.im z.im) \ t, has_fderiv_at F (F' p) p := λ p hp, (Hd (e p) hp).comp p e.has_fderiv_at, simp_rw [← interval_integral.integral_smul, interval_integral.integral_symm w.im z.im, ← interval_integral.integral_neg, ← hF'], refine (integral2_divergence_prod_of_has_fderiv_within_at_off_countable (λ p, -(I • F p)) F (λ p, - (I • F' p)) F' z.re w.im w.re z.im t (hs.preimage e.injective) (htc.const_smul _).neg htc (λ p hp, ((htd p hp).const_smul I).neg) htd _).symm, rw [← (volume_preserving_equiv_real_prod.symm _).integrable_on_comp_preimage (measurable_equiv.measurable_embedding _)] at Hi, simpa only [hF'] using Hi.neg end /-- Suppose that a function `f : ℂ → E` is continuous on a closed rectangle with opposite corners at `z w : ℂ`, is *real* differentiable on the corresponding open rectangle, and $\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then the integral of `f` over the boundary of the rectangle is equal to the integral of $2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$ over the rectangle. -/ lemma integral_boundary_rect_of_continuous_on_of_has_fderiv_at_real (f : ℂ → E) (f' : ℂ → ℂ →L[ℝ] E) (z w : ℂ) (Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im])) (Hd : ∀ x ∈ (Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im)), has_fderiv_at f (f' x) x) (Hi : integrable_on (λ z, I • f' z 1 - f' z I) ([z.re, w.re] ×ℂ [z.im, w.im])) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = ∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im, I • f' (x + y * I) 1 - f' (x + y * I) I := integral_boundary_rect_of_has_fderiv_at_real_off_countable f f' z w ∅ countable_empty Hc (λ x hx, Hd x hx.1) Hi /-- Suppose that a function `f : ℂ → E` is *real* differentiable on a closed rectangle with opposite corners at `z w : ℂ` and $\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then the integral of `f` over the boundary of the rectangle is equal to the integral of $2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$ over the rectangle. -/ lemma integral_boundary_rect_of_differentiable_on_real (f : ℂ → E) (z w : ℂ) (Hd : differentiable_on ℝ f ([z.re, w.re] ×ℂ [z.im, w.im])) (Hi : integrable_on (λ z, I • fderiv ℝ f z 1 - fderiv ℝ f z I) ([z.re, w.re] ×ℂ [z.im, w.im])) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = ∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im, I • fderiv ℝ f (x + y * I) 1 - fderiv ℝ f (x + y * I) I := integral_boundary_rect_of_has_fderiv_at_real_off_countable f (fderiv ℝ f) z w ∅ countable_empty Hd.continuous_on (λ x hx, Hd.has_fderiv_at $ by simpa only [← mem_interior_iff_mem_nhds, interior_re_prod_im, uIcc, interior_Icc] using hx.1) Hi /-- **Cauchy-Goursat theorem** for a rectangle: the integral of a complex differentiable function over the boundary of a rectangle equals zero. More precisely, if `f` is continuous on a closed rectangle and is complex differentiable at all but countably many points of the corresponding open rectangle, then its integral over the boundary of the rectangle equals zero. -/ lemma integral_boundary_rect_eq_zero_of_differentiable_on_off_countable (f : ℂ → E) (z w : ℂ) (s : set ℂ) (hs : s.countable) (Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im])) (Hd : ∀ x ∈ (Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im)) \ s, differentiable_at ℂ f x) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 := by refine (integral_boundary_rect_of_has_fderiv_at_real_off_countable f (λ z, (fderiv ℂ f z).restrict_scalars ℝ) z w s hs Hc (λ x hx, (Hd x hx).has_fderiv_at.restrict_scalars ℝ) _).trans _; simp [← continuous_linear_map.map_smul] /-- **Cauchy-Goursat theorem for a rectangle**: the integral of a complex differentiable function over the boundary of a rectangle equals zero. More precisely, if `f` is continuous on a closed rectangle and is complex differentiable on the corresponding open rectangle, then its integral over the boundary of the rectangle equals zero. -/ lemma integral_boundary_rect_eq_zero_of_continuous_on_of_differentiable_on (f : ℂ → E) (z w : ℂ) (Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im])) (Hd : differentiable_on ℂ f (Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im))) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 := integral_boundary_rect_eq_zero_of_differentiable_on_off_countable f z w ∅ countable_empty Hc $ λ x hx, Hd.differentiable_at $ (is_open_Ioo.re_prod_im is_open_Ioo).mem_nhds hx.1 /-- **Cauchy-Goursat theorem** for a rectangle: the integral of a complex differentiable function over the boundary of a rectangle equals zero. More precisely, if `f` is complex differentiable on a closed rectangle, then its integral over the boundary of the rectangle equals zero. -/ lemma integral_boundary_rect_eq_zero_of_differentiable_on (f : ℂ → E) (z w : ℂ) (H : differentiable_on ℂ f ([z.re, w.re] ×ℂ [z.im, w.im])) : (∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) + (I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 := integral_boundary_rect_eq_zero_of_continuous_on_of_differentiable_on f z w H.continuous_on $ H.mono $ inter_subset_inter (preimage_mono Ioo_subset_Icc_self) (preimage_mono Ioo_subset_Icc_self) /-- If `f : ℂ → E` is continuous the closed annulus `r ≤ ‖z - c‖ ≤ R`, `0 < r ≤ R`, and is complex differentiable at all but countably many points of its interior, then the integrals of `f z / (z - c)` (formally, `(z - c)⁻¹ • f z`) over the circles `‖z - c‖ = r` and `‖z - c‖ = R` are equal to each other. -/ lemma circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable {c : ℂ} {r R : ℝ} (h0 : 0 < r) (hle : r ≤ R) {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R \ ball c r)) (hd : ∀ z ∈ ball c R \ closed_ball c r \ s, differentiable_at ℂ f z) : ∮ z in C(c, R), (z - c)⁻¹ • f z = ∮ z in C(c, r), (z - c)⁻¹ • f z := begin /- We apply the previous lemma to `λ z, f (c + exp z)` on the rectangle `[log r, log R] × [0, 2 * π]`. -/ set A := closed_ball c R \ ball c r, obtain ⟨a, rfl⟩ : ∃ a, real.exp a = r, from ⟨real.log r, real.exp_log h0⟩, obtain ⟨b, rfl⟩ : ∃ b, real.exp b = R, from ⟨real.log R, real.exp_log (h0.trans_le hle)⟩, rw [real.exp_le_exp] at hle, -- Unfold definition of `circle_integral` and cancel some terms. suffices : ∫ θ in 0..2 * π, I • f (circle_map c (real.exp b) θ) = ∫ θ in 0..2 * π, I • f (circle_map c (real.exp a) θ), by simpa only [circle_integral, add_sub_cancel', of_real_exp, ← exp_add, smul_smul, ← div_eq_mul_inv, mul_div_cancel_left _ (circle_map_ne_center (real.exp_pos _).ne'), circle_map_sub_center, deriv_circle_map], set R := [a, b] ×ℂ [0, 2 * π], set g : ℂ → ℂ := (+) c ∘ exp, have hdg : differentiable ℂ g := differentiable_exp.const_add _, replace hs : (g ⁻¹' s).countable := (hs.preimage (add_right_injective c)).preimage_cexp, have h_maps : maps_to g R A, { rintro z ⟨h, -⟩, simpa [dist_eq, g, abs_exp, hle] using h.symm }, replace hc : continuous_on (f ∘ g) R, from hc.comp hdg.continuous.continuous_on h_maps, replace hd : ∀ z ∈ (Ioo (min a b) (max a b) ×ℂ Ioo (min 0 (2 * π)) (max 0 (2 * π))) \ g ⁻¹' s, differentiable_at ℂ (f ∘ g) z, { refine λ z hz, (hd (g z) ⟨_, hz.2⟩).comp z (hdg _), simpa [g, dist_eq, abs_exp, hle, and.comm] using hz.1.1 }, simpa [g, circle_map, exp_periodic _, sub_eq_zero, ← exp_add] using integral_boundary_rect_eq_zero_of_differentiable_on_off_countable _ ⟨a, 0⟩ ⟨b, 2 * π⟩ _ hs hc hd end /-- **Cauchy-Goursat theorem** for an annulus. If `f : ℂ → E` is continuous on the closed annulus `r ≤ ‖z - c‖ ≤ R`, `0 < r ≤ R`, and is complex differentiable at all but countably many points of its interior, then the integrals of `f` over the circles `‖z - c‖ = r` and `‖z - c‖ = R` are equal to each other. -/ lemma circle_integral_eq_of_differentiable_on_annulus_off_countable {c : ℂ} {r R : ℝ} (h0 : 0 < r) (hle : r ≤ R) {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R \ ball c r)) (hd : ∀ z ∈ ball c R \ closed_ball c r \ s, differentiable_at ℂ f z) : ∮ z in C(c, R), f z = ∮ z in C(c, r), f z := calc ∮ z in C(c, R), f z = ∮ z in C(c, R), (z - c)⁻¹ • (z - c) • f z : (circle_integral.integral_sub_inv_smul_sub_smul _ _ _ _).symm ... = ∮ z in C(c, r), (z - c)⁻¹ • (z - c) • f z : circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable h0 hle hs ((continuous_on_id.sub continuous_on_const).smul hc) (λ z hz, (differentiable_at_id.sub_const _).smul (hd z hz)) ... = ∮ z in C(c, r), f z : circle_integral.integral_sub_inv_smul_sub_smul _ _ _ _ /-- **Cauchy integral formula** for the value at the center of a disc. If `f` is continuous on a punctured closed disc of radius `R`, is differentiable at all but countably many points of the interior of this disc, and has a limit `y` at the center of the disc, then the integral $\oint_{‖z-c‖=R} \frac{f(z)}{z-c}\,dz$ is equal to $2πiy`. -/ lemma circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto {c : ℂ} {R : ℝ} (h0 : 0 < R) {f : ℂ → E} {y : E} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R \ {c})) (hd : ∀ z ∈ ball c R \ {c} \ s, differentiable_at ℂ f z) (hy : tendsto f (𝓝[{c}ᶜ] c) (𝓝 y)) : ∮ z in C(c, R), (z - c)⁻¹ • f z = (2 * π * I : ℂ) • y := begin rw [← sub_eq_zero, ← norm_le_zero_iff], refine le_of_forall_le_of_dense (λ ε ε0, _), obtain ⟨δ, δ0, hδ⟩ : ∃ δ > (0 : ℝ), ∀ z ∈ closed_ball c δ \ {c}, dist (f z) y < ε / (2 * π), from ((nhds_within_has_basis nhds_basis_closed_ball _).tendsto_iff nhds_basis_ball).1 hy _ (div_pos ε0 real.two_pi_pos), obtain ⟨r, hr0, hrδ, hrR⟩ : ∃ r, 0 < r ∧ r ≤ δ ∧ r ≤ R := ⟨min δ R, lt_min δ0 h0, min_le_left _ _, min_le_right _ _⟩, have hsub : closed_ball c R \ ball c r ⊆ closed_ball c R \ {c}, from diff_subset_diff_right (singleton_subset_iff.2 $ mem_ball_self hr0), have hsub' : ball c R \ closed_ball c r ⊆ ball c R \ {c}, from diff_subset_diff_right (singleton_subset_iff.2 $ mem_closed_ball_self hr0.le), have hzne : ∀ z ∈ sphere c r, z ≠ c, from λ z hz, ne_of_mem_of_not_mem hz (λ h, hr0.ne' $ dist_self c ▸ eq.symm h), /- The integral `∮ z in C(c, r), f z / (z - c)` does not depend on `0 < r ≤ R` and tends to `2πIy` as `r → 0`. -/ calc ‖(∮ z in C(c, R), (z - c)⁻¹ • f z) - (2 * ↑π * I) • y‖ = ‖(∮ z in C(c, r), (z - c)⁻¹ • f z) - ∮ z in C(c, r), (z - c)⁻¹ • y‖ : begin congr' 2, { exact circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable hr0 hrR hs (hc.mono hsub) (λ z hz, hd z ⟨hsub' hz.1, hz.2⟩) }, { simp [hr0.ne'] } end ... = ‖∮ z in C(c, r), (z - c)⁻¹ • (f z - y)‖ : begin simp only [smul_sub], have hc' : continuous_on (λ z, (z - c)⁻¹) (sphere c r), from (continuous_on_id.sub continuous_on_const).inv₀ (λ z hz, sub_ne_zero.2 $ hzne _ hz), rw circle_integral.integral_sub; refine (hc'.smul _).circle_integrable hr0.le, { exact hc.mono (subset_inter (sphere_subset_closed_ball.trans $ closed_ball_subset_closed_ball hrR) hzne) }, { exact continuous_on_const } end ... ≤ 2 * π * r * (r⁻¹ * (ε / (2 * π))) : begin refine circle_integral.norm_integral_le_of_norm_le_const hr0.le (λ z hz, _), specialize hzne z hz, rw [mem_sphere, dist_eq_norm] at hz, rw [norm_smul, norm_inv, hz, ← dist_eq_norm], refine mul_le_mul_of_nonneg_left (hδ _ ⟨_, hzne⟩).le (inv_nonneg.2 hr0.le), rwa [mem_closed_ball_iff_norm, hz] end ... = ε : by { field_simp [hr0.ne', real.two_pi_pos.ne'], ac_refl } end /-- **Cauchy integral formula** for the value at the center of a disc. If `f : ℂ → E` is continuous on a closed disc of radius `R` and is complex differentiable at all but countably many points of its interior, then the integral $\oint_{|z-c|=R} \frac{f(z)}{z-c}\,dz$ is equal to $2πiy`. -/ lemma circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable {R : ℝ} (h0 : 0 < R) {f : ℂ → E} {c : ℂ} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R)) (hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) : ∮ z in C(c, R), (z - c)⁻¹ • f z = (2 * π * I : ℂ) • f c := circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto h0 hs (hc.mono $ diff_subset _ _) (λ z hz, hd z ⟨hz.1.1, hz.2⟩) (hc.continuous_at $ closed_ball_mem_nhds _ h0).continuous_within_at /-- **Cauchy-Goursat theorem** for a disk: if `f : ℂ → E` is continuous on a closed disk `{z | ‖z - c‖ ≤ R}` and is complex differentiable at all but countably many points of its interior, then the integral $\oint_{|z-c|=R}f(z)\,dz$ equals zero. -/ lemma circle_integral_eq_zero_of_differentiable_on_off_countable {R : ℝ} (h0 : 0 ≤ R) {f : ℂ → E} {c : ℂ} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R)) (hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) : ∮ z in C(c, R), f z = 0 := begin rcases h0.eq_or_lt with rfl|h0, { apply circle_integral.integral_radius_zero }, calc ∮ z in C(c, R), f z = ∮ z in C(c, R), (z - c)⁻¹ • (z - c) • f z : (circle_integral.integral_sub_inv_smul_sub_smul _ _ _ _).symm ... = (2 * ↑π * I : ℂ) • (c - c) • f c : circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable h0 hs ((continuous_on_id.sub continuous_on_const).smul hc) (λ z hz, (differentiable_at_id.sub_const _).smul (hd z hz)) ... = 0 : by rw [sub_self, zero_smul, smul_zero] end /-- An auxiliary lemma for `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`. This lemma assumes `w ∉ s` while the main lemma drops this assumption. -/ lemma circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux {R : ℝ} {c w : ℂ} {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hw : w ∈ ball c R \ s) (hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) : ∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w := begin have hR : 0 < R := dist_nonneg.trans_lt hw.1, set F : ℂ → E := dslope f w, have hws : (insert w s).countable := hs.insert w, have hnhds : closed_ball c R ∈ 𝓝 w, from closed_ball_mem_nhds_of_mem hw.1, have hcF : continuous_on F (closed_ball c R), from (continuous_on_dslope $ closed_ball_mem_nhds_of_mem hw.1).2 ⟨hc, hd _ hw⟩, have hdF : ∀ z ∈ ball (c : ℂ) R \ (insert w s), differentiable_at ℂ F z, from λ z hz, (differentiable_at_dslope_of_ne (ne_of_mem_of_not_mem (mem_insert _ _) hz.2).symm).2 (hd _ (diff_subset_diff_right (subset_insert _ _) hz)), have HI := circle_integral_eq_zero_of_differentiable_on_off_countable hR.le hws hcF hdF, have hne : ∀ z ∈ sphere c R, z ≠ w, from λ z hz, ne_of_mem_of_not_mem hz (ne_of_lt hw.1), have hFeq : eq_on F (λ z, (z - w)⁻¹ • f z - (z - w)⁻¹ • f w) (sphere c R), { intros z hz, calc F z = (z - w)⁻¹ • (f z - f w) : update_noteq (hne z hz) _ _ ... = (z - w)⁻¹ • f z - (z - w)⁻¹ • f w : smul_sub _ _ _ }, have hc' : continuous_on (λ z, (z - w)⁻¹) (sphere c R), from (continuous_on_id.sub continuous_on_const).inv₀ (λ z hz, sub_ne_zero.2 $ hne z hz), rw [← circle_integral.integral_sub_inv_of_mem_ball hw.1, ← circle_integral.integral_smul_const, ← sub_eq_zero, ← circle_integral.integral_sub, ← circle_integral.integral_congr hR.le hFeq, HI], exacts [(hc'.smul (hc.mono sphere_subset_closed_ball)).circle_integrable hR.le, (hc'.smul continuous_on_const).circle_integrable hR.le] end /-- **Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is complex differentiable at all but countably many points of its interior, then for any `w` in this interior we have $\frac{1}{2πi}\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=f(w)$. -/ lemma two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable {R : ℝ} {c w : ℂ} {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hw : w ∈ ball c R) (hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) : (2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z = f w := begin have hR : 0 < R := dist_nonneg.trans_lt hw, suffices : w ∈ closure (ball c R \ s), { lift R to ℝ≥0 using hR.le, have A : continuous_at (λ w, (2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z) w, { have := has_fpower_series_on_cauchy_integral ((hc.mono sphere_subset_closed_ball).circle_integrable R.coe_nonneg) hR, refine this.continuous_on.continuous_at (emetric.is_open_ball.mem_nhds _), rwa metric.emetric_ball_nnreal }, have B : continuous_at f w, from hc.continuous_at (closed_ball_mem_nhds_of_mem hw), refine tendsto_nhds_unique_of_frequently_eq A B ((mem_closure_iff_frequently.1 this).mono _), intros z hz, rw [circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux hs hz hc hd, inv_smul_smul₀], simp [real.pi_ne_zero, I_ne_zero] }, refine mem_closure_iff_nhds.2 (λ t ht, _), -- TODO: generalize to any vector space over `ℝ` set g : ℝ → ℂ := λ x, w + x, have : tendsto g (𝓝 0) (𝓝 w), from (continuous_const.add continuous_of_real).tendsto' 0 w (add_zero _), rcases mem_nhds_iff_exists_Ioo_subset.1 (this $ inter_mem ht $ is_open_ball.mem_nhds hw) with ⟨l, u, hlu₀, hlu_sub⟩, obtain ⟨x, hx⟩ : (Ioo l u \ g ⁻¹' s).nonempty, { refine nonempty_diff.2 (λ hsub, _), have : (Ioo l u).countable, from (hs.preimage ((add_right_injective w).comp of_real_injective)).mono hsub, rw [← cardinal.le_aleph_0_iff_set_countable, cardinal.mk_Ioo_real (hlu₀.1.trans hlu₀.2)] at this, exact this.not_lt cardinal.aleph_0_lt_continuum }, exact ⟨g x, (hlu_sub hx.1).1, (hlu_sub hx.1).2, hx.2⟩ end /-- **Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is complex differentiable at all but countably many points of its interior, then for any `w` in this interior we have $\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$. -/ lemma circle_integral_sub_inv_smul_of_differentiable_on_off_countable {R : ℝ} {c w : ℂ} {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hw : w ∈ ball c R) (hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) : ∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w := by { rw [← two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable hs hw hc hd, smul_inv_smul₀], simp [real.pi_ne_zero, I_ne_zero] } /-- **Cauchy integral formula**: if `f : ℂ → E` is complex differentiable on an open disc and is continuous on its closure, then for any `w` in this open ball we have $\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$. -/ lemma _root_.diff_cont_on_cl.circle_integral_sub_inv_smul {R : ℝ} {c w : ℂ} {f : ℂ → E} (h : diff_cont_on_cl ℂ f (ball c R)) (hw : w ∈ ball c R) : ∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w := circle_integral_sub_inv_smul_of_differentiable_on_off_countable countable_empty hw h.continuous_on_ball $ λ x hx, h.differentiable_at is_open_ball hx.1 /-- **Cauchy integral formula**: if `f : ℂ → E` is complex differentiable on an open disc and is continuous on its closure, then for any `w` in this open ball we have $\frac{1}{2πi}\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=f(w)$. -/ lemma _root_.diff_cont_on_cl.two_pi_I_inv_smul_circle_integral_sub_inv_smul {R : ℝ} {c w : ℂ} {f : ℂ → E} (hf : diff_cont_on_cl ℂ f (ball c R)) (hw : w ∈ ball c R) : (2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z = f w := begin have hR : 0 < R := not_le.mp (ball_eq_empty.not.mp (nonempty_of_mem hw).ne_empty), refine two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable countable_empty hw _ _, { simpa only [closure_ball c hR.ne.symm] using hf.continuous_on }, { simpa only [diff_empty] using λ z hz, hf.differentiable_at is_open_ball hz } end /-- **Cauchy integral formula**: if `f : ℂ → E` is complex differentiable on a closed disc of radius `R`, then for any `w` in its interior we have $\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$. -/ lemma _root_.differentiable_on.circle_integral_sub_inv_smul {R : ℝ} {c w : ℂ} {f : ℂ → E} (hd : differentiable_on ℂ f (closed_ball c R)) (hw : w ∈ ball c R) : ∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w := (hd.mono closure_ball_subset_closed_ball).diff_cont_on_cl.circle_integral_sub_inv_smul hw /-- **Cauchy integral formula**: if `f : ℂ → ℂ` is continuous on a closed disc of radius `R` and is complex differentiable at all but countably many points of its interior, then for any `w` in this interior we have $\oint_{|z-c|=R}\frac{f(z)}{z-w}dz=2\pi i\,f(w)$. -/ lemma circle_integral_div_sub_of_differentiable_on_off_countable {R : ℝ} {c w : ℂ} {s : set ℂ} (hs : s.countable) (hw : w ∈ ball c R) {f : ℂ → ℂ} (hc : continuous_on f (closed_ball c R)) (hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) : ∮ z in C(c, R), f z / (z - w) = 2 * π * I * f w := by simpa only [smul_eq_mul, div_eq_inv_mul] using circle_integral_sub_inv_smul_of_differentiable_on_off_countable hs hw hc hd /-- If `f : ℂ → E` is continuous on a closed ball of positive radius and is differentiable at all but countably many points of the corresponding open ball, then it is analytic on the open ball with coefficients of the power series given by Cauchy integral formulas. -/ lemma has_fpower_series_on_ball_of_differentiable_off_countable {R : ℝ≥0} {c : ℂ} {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R)) (hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) (hR : 0 < R) : has_fpower_series_on_ball f (cauchy_power_series f c R) c R := { r_le := le_radius_cauchy_power_series _ _ _, r_pos := ennreal.coe_pos.2 hR, has_sum := λ w hw, begin have hw' : c + w ∈ ball c R, by simpa only [add_mem_ball_iff_norm, ← coe_nnnorm, mem_emetric_ball_zero_iff, nnreal.coe_lt_coe, ennreal.coe_lt_coe] using hw, rw ← two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable hs hw' hc hd, exact (has_fpower_series_on_cauchy_integral ((hc.mono sphere_subset_closed_ball).circle_integrable R.2) hR).has_sum hw end } /-- If `f : ℂ → E` is complex differentiable on an open disc of positive radius and is continuous on its closure, then it is analytic on the open disc with coefficients of the power series given by Cauchy integral formulas. -/ lemma _root_.diff_cont_on_cl.has_fpower_series_on_ball {R : ℝ≥0} {c : ℂ} {f : ℂ → E} (hf : diff_cont_on_cl ℂ f (ball c R)) (hR : 0 < R) : has_fpower_series_on_ball f (cauchy_power_series f c R) c R := has_fpower_series_on_ball_of_differentiable_off_countable countable_empty hf.continuous_on_ball (λ z hz, hf.differentiable_at is_open_ball hz.1) hR /-- If `f : ℂ → E` is complex differentiable on a closed disc of positive radius, then it is analytic on the corresponding open disc, and the coefficients of the power series are given by Cauchy integral formulas. See also `complex.has_fpower_series_on_ball_of_differentiable_off_countable` for a version of this lemma with weaker assumptions. -/ protected lemma _root_.differentiable_on.has_fpower_series_on_ball {R : ℝ≥0} {c : ℂ} {f : ℂ → E} (hd : differentiable_on ℂ f (closed_ball c R)) (hR : 0 < R) : has_fpower_series_on_ball f (cauchy_power_series f c R) c R := (hd.mono closure_ball_subset_closed_ball).diff_cont_on_cl.has_fpower_series_on_ball hR /-- If `f : ℂ → E` is complex differentiable on some set `s`, then it is analytic at any point `z` such that `s ∈ 𝓝 z` (equivalently, `z ∈ interior s`). -/ protected lemma _root_.differentiable_on.analytic_at {s : set ℂ} {f : ℂ → E} {z : ℂ} (hd : differentiable_on ℂ f s) (hz : s ∈ 𝓝 z) : analytic_at ℂ f z := begin rcases nhds_basis_closed_ball.mem_iff.1 hz with ⟨R, hR0, hRs⟩, lift R to ℝ≥0 using hR0.le, exact ((hd.mono hRs).has_fpower_series_on_ball hR0).analytic_at end lemma _root_.differentiable_on.analytic_on {s : set ℂ} {f : ℂ → E} (hd : differentiable_on ℂ f s) (hs : is_open s) : analytic_on ℂ f s := λ z hz, hd.analytic_at (hs.mem_nhds hz) /-- A complex differentiable function `f : ℂ → E` is analytic at every point. -/ protected lemma _root_.differentiable.analytic_at {f : ℂ → E} (hf : differentiable ℂ f) (z : ℂ) : analytic_at ℂ f z := hf.differentiable_on.analytic_at univ_mem /-- When `f : ℂ → E` is differentiable, the `cauchy_power_series f z R` represents `f` as a power series centered at `z` in the entirety of `ℂ`, regardless of `R : ℝ≥0`, with `0 < R`. -/ protected lemma _root_.differentiable.has_fpower_series_on_ball {f : ℂ → E} (h : differentiable ℂ f) (z : ℂ) {R : ℝ≥0} (hR : 0 < R) : has_fpower_series_on_ball f (cauchy_power_series f z R) z ∞ := (h.differentiable_on.has_fpower_series_on_ball hR).r_eq_top_of_exists $ λ r hr, ⟨_, h.differentiable_on.has_fpower_series_on_ball hr⟩ end complex
b52305141b4d0743918b49c92754887d96efb038
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/data/padics/padic_numbers.lean
513b420f0365cb41315d906ebbb499a0f7ca433f
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
29,139
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis Define the p-adic numbers (rationals) ℚ_p as the completion of ℚ wrt the p-adic norm. Show that the p-adic norm extends to ℚ_p, that ℚ is embedded in ℚ_p, and that ℚ_p is complete -/ import data.real.cau_seq_completion topology.metric_space.cau_seq_filter import data.padics.padic_norm algebra.archimedean analysis.normed_space.basic noncomputable theory local attribute [instance, priority 1] classical.prop_decidable local attribute [instance, priority 0] nat.cast_coe local attribute [instance, priority 0] int.cast_coe local attribute [instance, priority 0] rat.cast_coe open nat multiplicity padic_norm cau_seq cau_seq.completion metric @[reducible] def padic_seq (p : ℕ) [p.prime] := cau_seq _ (padic_norm p) namespace padic_seq section variables {p : ℕ} [nat.prime p] lemma stationary {f : cau_seq ℚ (padic_norm p)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, m ≥ N → n ≥ N → padic_norm p (f n) = padic_norm p (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm p (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this, ⟨N2, hN2⟩ := cau_seq.cauchy₂ f hε in ⟨ max N1 N2, λ n m hn hm, have padic_norm p (f n - f m) < ε, from hN2 _ _ (max_le_iff.1 hn).2 (max_le_iff.1 hm).2, have padic_norm p (f n - f m) < padic_norm p (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm p (f n - f m) < max (padic_norm p (f n)) (padic_norm p (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ←padic_norm.neg p (f m) at hne, have hnam := add_eq_max_of_ne p hne, rw [padic_norm.neg, max_comm] at hnam, rw ←hnam at this, apply _root_.lt_irrefl _ (by simp at this; exact this) end ⟩ def stationary_point {f : padic_seq p} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq p} (hf : ¬ f ≈ 0) : ∀ {m n}, m ≥ stationary_point hf → n ≥ stationary_point hf → padic_norm p (f n) = padic_norm p (f m) := classical.some_spec $ stationary hf def norm (f : padic_seq p) : ℚ := if hf : f ≈ 0 then 0 else padic_norm p (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq p) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf (le_refl _) hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} [nat.prime p] lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq p} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm p k ∧ k ≠ 0 := have heq : f.norm = padic_norm p (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm p) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ (const (padic_norm p) q) ≈ 0 := λ h : lim_zero (const (padic_norm p) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq p) : f.norm ≥ 0 := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] lemma lift_index_left_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v2 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max (stationary_point hf) (max v2 v3))) := let i := max (stationary_point hf) (max v2 v3) in begin apply stationary_point_spec hf, { apply le_max_left }, { apply le_refl } end lemma lift_index_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max (stationary_point hf) v3))) := let i := max v1 (max (stationary_point hf) v3) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_left _ v3 }, { apply le_max_right } }, { apply le_refl } end lemma lift_index_right {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v2 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max v2 (stationary_point hf)))) := let i := max v1 (max v2 (stationary_point hf)) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_right v2 }, { apply le_max_right } }, { apply le_refl } end end embedding end padic_seq section open padic_seq meta def index_simp_core (hh hf hg : expr) (at_ : interactive.loc := interactive.loc.ns [none]) : tactic unit := do [v1, v2, v3] ← [hh, hf, hg].mmap (λ n, tactic.mk_app ``stationary_point [n] <|> return n), e1 ← tactic.mk_app ``lift_index_left_left [hh, v2, v3] <|> return `(true), e2 ← tactic.mk_app ``lift_index_left [hf, v1, v3] <|> return `(true), e3 ← tactic.mk_app ``lift_index_right [hg, v1, v2] <|> return `(true), sl ← [e1, e2, e3].mfoldl (λ s e, simp_lemmas.add s e) simp_lemmas.mk, when at_.include_goal (tactic.simp_target sl), hs ← at_.get_locals, hs.mmap' (tactic.simp_hyp sl []) /-- This is a special-purpose tactic that lifts padic_norm (f (stationary_point f)) to padic_norm (f (max _ _ _)). -/ meta def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list) (at_ : interactive.parse interactive.types.location) : tactic unit := do [h, f, g] ← l.mmap tactic.i_to_expr, index_simp_core h f g at_ end namespace padic_seq section embedding open cau_seq variables {p : ℕ} [hp : nat.prime p] include hp lemma norm_mul (f g : padic_seq p) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp [hf, hg, norm] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp [hf, hg, norm] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.mul end lemma eq_zero_iff_equiv_zero (f : padic_seq p) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq p) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm p) q) = padic_norm p q := if hq : q = 0 then have (const (padic_norm p) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm p) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm p) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_image (a : padic_seq p) (ha : ¬ a ≈ 0) : (∃ (n : ℤ), a.norm = ↑p ^ (-n)) := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.image p hk' lemma norm_one : norm (1 : padic_seq p) = 1 := have h1 : ¬ (1 : padic_seq p) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.gt_one] private lemma norm_eq_of_equiv_aux {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm p (f (stationary_point hf)) ≠ padic_norm p (g (stationary_point hg))) (hgt : padic_norm p (f (stationary_point hf)) > padic_norm p (g (stationary_point hg))) : false := begin have hpn : padic_norm p (f (stationary_point hf)) - padic_norm p (g (stationary_point hg)) > 0, from sub_pos_of_lt hgt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hi : i ≥ N, from le_max_left _ _, have hN' := hN _ hi, padic_index_simp [N, hf, hg] at hN' h hgt, have hpne : padic_norm p (f i) ≠ padic_norm p (-(g i)), by rwa [ ←padic_norm.neg p (g i)] at h, let hpnem := add_eq_max_of_ne p hpne, have hpeq : padic_norm p ((f - g) i) = max (padic_norm p (f i)) (padic_norm p (g i)), { rwa padic_norm.neg at hpnem }, rw [hpeq, max_eq_left_of_lt hgt] at hN', have : padic_norm p (f i) < padic_norm p (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm p (f (stationary_point hf)) = padic_norm p (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm p (f (stationary_point hf)) > padic_norm p (g (stationary_point hg)))) with hgt hngt, { exact norm_eq_of_equiv_aux hf hg hfg h hgt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hngt, apply h } end theorem norm_equiv {f g : padic_seq p} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq p} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max (f.norm) (g.norm) := begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq p) : (f + g).norm ≤ max (f.norm) (g.norm) := if hfg : f + g ≈ 0 then have 0 ≤ max (f.norm) (g.norm), from le_max_left_of_le (norm_nonneg _), by simpa [hfg, norm] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max (f.norm) (g.norm) = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa [add_sub_cancel'] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max (f.norm) (g.norm) = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp [hf, hg, norm] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp [h]) hg, begin simp [hg, hf, norm], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm p (f (stationary_point hf)) = padic_norm p (f i), { apply stationary_point_spec, apply le_max_left, apply le_refl }, have hpg : padic_norm p (g (stationary_point hg)) = padic_norm p (g i), { apply stationary_point_spec, apply le_max_right, apply le_refl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq p) : (-a).norm = a.norm := norm_eq $ by simp lemma norm_eq_of_add_equiv_zero {f g : padic_seq p} (h : f + g ≈ 0) : f.norm = g.norm := have lim_zero (f + g - 0), from h, have f ≈ -g, from show lim_zero (f - (-g)), by simpa, have f.norm = (-g).norm, from norm_equiv this, by simpa [norm_neg] using this lemma add_eq_max_of_ne {f g : padic_seq p} (hfgne : f.norm ≠ g.norm) : (f + g).norm = max f.norm g.norm := have hfg : ¬f + g ≈ 0, from mt norm_eq_of_add_equiv_zero hfgne, if hf : f ≈ 0 then have lim_zero (f - 0), from hf, have f + g ≈ g, from show lim_zero ((f + g) - g), by simpa, have h1 : (f+g).norm = g.norm, from norm_equiv this, have h2 : f.norm = 0, from (norm_zero_iff _).2 hf, by rw [h1, h2]; rw max_eq_right (norm_nonneg _) else if hg : g ≈ 0 then have lim_zero (g - 0), from hg, have f + g ≈ f, from show lim_zero ((f + g) - f), by rw [add_sub_cancel']; simpa, have h1 : (f+g).norm = f.norm, from norm_equiv this, have h2 : g.norm = 0, from (norm_zero_iff _).2 hg, by rw [h1, h2]; rw max_eq_left (norm_nonneg _) else begin unfold norm at ⊢ hfgne, split_ifs at ⊢ hfgne, padic_index_simp [hfg, hf, hg] at ⊢ hfgne, apply padic_norm.add_eq_max_of_ne, simpa [hf, hg, norm] using hfgne end end embedding end padic_seq def padic (p : ℕ) [nat.prime p] := @cau_seq.completion.Cauchy _ _ _ _ (padic_norm p) _ notation `ℚ_[` p `]` := padic p namespace padic section completion variables {p : ℕ} [nat.prime p] instance discrete_field : discrete_field (ℚ_[p]) := cau_seq.completion.discrete_field -- short circuits instance : has_zero ℚ_[p] := by apply_instance instance : has_one ℚ_[p] := by apply_instance instance : has_add ℚ_[p] := by apply_instance instance : has_mul ℚ_[p] := by apply_instance instance : has_sub ℚ_[p] := by apply_instance instance : has_neg ℚ_[p] := by apply_instance instance : has_div ℚ_[p] := by apply_instance instance : add_comm_group ℚ_[p] := by apply_instance instance : comm_ring ℚ_[p] := by apply_instance def mk : padic_seq p → ℚ_[p] := quotient.mk end completion section completion variables (p : ℕ) [nat.prime p] lemma mk_eq {f g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq def of_rat : ℚ → ℚ_[p] := cau_seq.completion.of_rat @[simp] lemma of_rat_add : ∀ (x y : ℚ), of_rat p (x + y) = of_rat p x + of_rat p y := cau_seq.completion.of_rat_add @[simp] lemma of_rat_neg : ∀ (x : ℚ), of_rat p (-x) = -of_rat p x := cau_seq.completion.of_rat_neg @[simp] lemma of_rat_mul : ∀ (x y : ℚ), of_rat p (x * y) = of_rat p x * of_rat p y := cau_seq.completion.of_rat_mul @[simp] lemma of_rat_sub : ∀ (x y : ℚ), of_rat p (x - y) = of_rat p x - of_rat p y := cau_seq.completion.of_rat_sub @[simp] lemma of_rat_div : ∀ (x y : ℚ), of_rat p (x / y) = of_rat p x / of_rat p y := cau_seq.completion.of_rat_div @[simp] lemma of_rat_one : of_rat p 1 = 1 := rfl @[simp] lemma of_rat_zero : of_rat p 0 = 0 := rfl @[simp] lemma cast_eq_of_rat_of_nat (n : ℕ) : (↑n : ℚ_[p]) = of_rat p n := begin induction n with n ih, { refl }, { simpa using ih } end -- without short circuits, this needs an increase of class.instance_max_depth @[simp] lemma cast_eq_of_rat_of_int (n : ℤ) : ↑n = of_rat p n := by induction n; simp lemma cast_eq_of_rat : ∀ (q : ℚ), (↑q : ℚ_[p]) = of_rat p q | ⟨n, d, h1, h2⟩ := show ↑n / ↑d = _, from have (⟨n, d, h1, h2⟩ : ℚ) = rat.mk n d, from rat.num_denom _, by simp [this, rat.mk_eq_div, of_rat_div] lemma const_equiv {q r : ℚ} : const (padic_norm p) q ≈ const (padic_norm p) r ↔ q = r := ⟨ λ heq : lim_zero (const (padic_norm p) (q - r)), eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ lemma of_rat_eq {q r : ℚ} : of_rat p q = of_rat p r ↔ q = r := ⟨(const_equiv p).1 ∘ quotient.eq.1, λ h, by rw h⟩ instance : char_zero ℚ_[p] := ⟨ λ m n, suffices of_rat p ↑m = of_rat p ↑n ↔ m = n, by simpa using this, by simp [of_rat_eq] ⟩ end completion end padic def padic_norm_e {p : ℕ} [hp : nat.prime p] : ℚ_[p] → ℚ := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _ namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} [nat.prime p] lemma defn (f : padic_seq p) {ε : ℚ} (hε : ε > 0) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin simp only [padic.cast_eq_of_rat], change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contradiction h, cases cauchy₂ f hε with N hN, have : ∀ N, ∃ i ≥ N, (f - const _ (f i)).norm ≥ ε, by simpa [not_forall] using h, rcases this N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm p) (f i)) ≈ 0, { intro h, unfold padic_seq.norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold padic_seq.norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases decidable.em ((stationary_point hne) ≥ N) with hgen hngen, { apply hN; assumption }, { have := stationary_point_spec hne (le_refl _) (le_of_not_le hngen), rw ←this, apply hN, apply le_refl, assumption } end protected lemma nonneg (q : ℚ_[p]) : padic_norm_e q ≥ 0 := quotient.induction_on q $ norm_nonneg lemma zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl lemma zero_iff (q : ℚ_[p]) : padic_norm_e q = 0 ↔ q = 0 := quotient.induction_on q $ by simpa only [zero_def, quotient.eq] using norm_zero_iff @[simp] protected lemma zero : padic_norm_e (0 : ℚ_[p]) = 0 := (zero_iff _).2 rfl @[simp] protected lemma one' : padic_norm_e (1 : ℚ_[p]) = 1 := norm_one @[simp] protected lemma neg (q : ℚ_[p]) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q $ norm_neg theorem nonarchimedean' (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean theorem add_eq_max_of_ne' {q r : ℚ_[p]} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ λ _ _, padic_seq.add_eq_max_of_ne lemma triangle_ineq (x y z : ℚ_[p]) : padic_norm_e (x - z) ≤ padic_norm_e (x - y) + padic_norm_e (y - z) := calc padic_norm_e (x - z) = padic_norm_e ((x - y) + (y - z)) : by rw sub_add_sub_cancel ... ≤ max (padic_norm_e (x - y)) (padic_norm_e (y - z)) : padic_norm_e.nonarchimedean' _ _ ... ≤ padic_norm_e (x - y) + padic_norm_e (y - z) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma add (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ (padic_norm_e q) + (padic_norm_e r) := calc padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean' _ _ ... ≤ (padic_norm_e q) + (padic_norm_e r) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma mul' (q r : ℚ_[p]) : padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) := quotient.induction_on₂ q r $ norm_mul instance : is_absolute_value (@padic_norm_e p _) := { abv_nonneg := padic_norm_e.nonneg, abv_eq_zero := zero_iff, abv_add := padic_norm_e.add, abv_mul := padic_norm_e.mul' } @[simp] lemma eq_padic_norm' (q : ℚ) : padic_norm_e (padic.of_rat p q) = padic_norm p q := norm_const _ protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = p ^ (-n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_image f this lemma sub_rev (q r : ℚ_[p]) : padic_norm_e (q - r) = padic_norm_e (r - q) := by rw ←(padic_norm_e.neg); simp end embedding end padic_norm_e namespace padic section complete open padic_seq padic theorem rat_dense' {p : ℕ} [nat.prime p] (q : ℚ_[p]) {ε : ℚ} (hε : ε > 0) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm p (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin simp only [padic.cast_eq_of_rat], change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm p) (q' N)) ≈ 0) with heq hne', { simpa only [heq, padic_seq.norm, dif_pos] }, { simp only [padic_seq.norm, dif_neg hne'], change padic_norm p (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (N ≥ stationary_point hne') with hle hle, { have := eq.symm (this (le_refl _) hle), simp at this, simpa [this] }, { apply hN, apply le_of_lt, apply lt_of_not_ge, apply hle, apply le_refl }} end⟩ variables {p : ℕ} [nat.prime p] (f : cau_seq _ (@padic_norm_e p _)) open classical private lemma cast_succ_nat_pos (n : ℕ) : (↑(n + 1) : ℚ) > 0 := nat.cast_pos.2 $ succ_pos _ private lemma div_nat_pos (n : ℕ) : (1 / ((n + 1): ℚ)) > 0 := div_pos zero_lt_one (cast_succ_nat_pos _) def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense' (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - of_rat p ((lim_seq f) i)) < ε := begin refine (exists_nat_gt (1/ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense' (f i) (div_nat_pos i)), rw ← cast_eq_of_rat, refine lt_of_lt_of_le h (div_le_of_le_mul (cast_succ_nat_pos _) _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact le_mul_of_div_le hε (le_trans (le_of_lt hN) (nat.cast_le.2 hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm p) (lim_seq f) := assume ε hε, have hε3 : ε / 3 > 0, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, rw [←padic_norm_e.eq_padic_norm', padic.of_rat_sub], suffices : padic_norm_e ((↑(lim_seq f j) - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring at this ⊢, simpa only [cast_eq_of_rat] }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { apply eq_of_mul_eq_mul_left this, simp [left_distrib, mul_div_cancel' _ this ], ring }, rw this, apply add_lt_add, { suffices : padic_norm_e ((↑(lim_seq f j) - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa, apply lt_of_le_of_lt, { apply padic_norm_e.add }, { apply add_lt_add, { rw [padic_norm_e.sub_rev, cast_eq_of_rat], apply hN, apply le_of_max_le_left hj }, { apply hN2, apply le_of_max_le_right hj, apply le_max_right } } }, { rw cast_eq_of_rat, apply hN, apply le_max_left }}} end private def lim' : padic_seq p := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[p] := ⟦lim' f⟧ theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, let ⟨N, hN⟩ := exi_rat_seq_conv f (show ε / 2 > 0, from div_pos hε (by norm_num)), ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (show ε / 2 > 0, from div_pos hε (by norm_num)) in begin existsi max N N2, intros i hi, suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < ε, { ring at this; exact this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (2 : ℚ) ≠ 0, by norm_num, have : ε = ε / 2 + ε / 2, by rw ←(add_self_div_two ε); simp, rw this, apply add_lt_add, { apply hN2, apply le_of_max_le_right hi }, { rw [padic_norm_e.sub_rev, cast_eq_of_rat], apply hN, apply le_of_max_le_left hi } } } end ⟩ end complete section normed_space variables (p : ℕ) [nat.prime p] instance : has_dist ℚ_[p] := ⟨λ x y, padic_norm_e (x - y)⟩ instance : metric_space ℚ_[p] := { dist_self := by simp [dist], dist_comm := λ x y, by unfold dist; rw ←padic_norm_e.neg (x - y); simp, dist_triangle := begin intros, unfold dist, rw ←rat.cast_add, apply rat.cast_le.2, apply padic_norm_e.triangle_ineq end, eq_of_dist_eq_zero := begin unfold dist, intros _ _ h, apply eq_of_sub_eq_zero, apply (padic_norm_e.zero_iff _).1, simpa using h end } instance : has_norm ℚ_[p] := ⟨λ x, padic_norm_e x⟩ instance : normed_field ℚ_[p] := { dist_eq := λ _ _, rfl, norm_mul := by simp [has_norm.norm, padic_norm_e.mul'] } instance : is_absolute_value (λ a : ℚ_[p], ∥a∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := norm_eq_zero, abv_add := norm_triangle, abv_mul := by simp [has_norm.norm, padic_norm_e.mul'] } theorem rat_dense {p : ℕ} {hp : p.prime} (q : ℚ_[p]) {ε : ℝ} (hε : ε > 0) : ∃ r : ℚ, ∥q - r∥ < ε := let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨r, hr⟩ := rat_dense' q (by simpa using hε'l) in ⟨r, lt.trans (by simpa [has_norm.norm] using hr) hε'r⟩ end normed_space end padic namespace padic_norm_e section normed_space variables {p : ℕ} [hp : p.prime] include hp @[simp] protected lemma mul (q r : ℚ_[p]) : ∥q * r∥ = ∥q∥ * ∥r∥ := by simp [has_norm.norm, padic_norm_e.mul'] protected lemma is_norm (q : ℚ_[p]) : ↑(padic_norm_e q) = ∥q∥ := rfl theorem nonarchimedean (q r : ℚ_[p]) : ∥q + r∥ ≤ max (∥q∥) (∥r∥) := begin unfold has_norm.norm, rw ←rat.cast_max, apply rat.cast_le.2, apply nonarchimedean' end theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ∥q∥ ≠ ∥r∥) : ∥q+r∥ = max (∥q∥) (∥r∥) := begin unfold has_norm.norm, rw ←rat.cast_max, congr, apply add_eq_max_of_ne', intro h', apply h, unfold has_norm.norm, congr, apply h' end @[simp] lemma eq_padic_norm (q : ℚ) : ∥padic.of_rat p q∥ = padic_norm p q := by unfold has_norm.norm; congr; apply padic_seq.norm_const instance : nondiscrete_normed_field ℚ_[p] := { non_trivial := ⟨padic.of_rat p (p⁻¹), begin have : 1 < p := prime.gt_one hp, have : p ≠ 0 := ne_of_gt (hp.pos), simp only [padic_norm, padic_val_rat.inv, *, inv_eq_zero, if_false, ne.def, nat.cast_eq_zero, not_false_iff, neg_neg, padic_norm_e.eq_padic_norm, padic_val_rat.padic_val_rat_self, nat.cast_ne_zero], erw _root_.pow_one, simp only [rat.cast_coe_nat], rwa [← cast_one, cast_lt] end⟩ } protected theorem image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ∥q∥ = ↑((↑p : ℚ) ^ (-n)) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (padic_seq.ne_zero_iff_nequiv_zero f).1 hf, let ⟨n, hn⟩ := padic_seq.norm_image f this in ⟨n, congr_arg rat.cast hn⟩ protected lemma is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ∥q∥ = ↑q' := if h : q = 0 then ⟨0, by simp [h]⟩ else let ⟨n, hn⟩ := padic_norm_e.image h in ⟨_, hn⟩ def rat_norm (q : ℚ_[p]) : ℚ := classical.some (padic_norm_e.is_rat q) lemma eq_rat_norm (q : ℚ_[p]) : ∥q∥ = rat_norm q := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one : ∀ {q : ℚ} (hq : ¬ p ∣ q.denom), ∥(q : ℚ_[p])∥ ≤ 1 | ⟨n, d, hn, hd⟩ := λ hq : ¬ p ∣ d, if hnz : n = 0 then have (⟨n, d, hn, hd⟩ : ℚ) = 0, from rat.zero_of_num_zero hnz, by simp [this, padic.cast_eq_of_rat, zero_le_one] else have hnz' : {rat . num := n, denom := d, pos := hn, cop := hd} ≠ 0, from mt rat.zero_iff_num_zero.1 hnz, have (p : ℚ) ^ (-(multiplicity (p : ℤ) n).get (finite_int_iff.2 ⟨hp.ne_one, hnz⟩) : ℤ) ≤ 1, from fpow_le_one_of_nonpos (show (↑p : ℚ) ≥ ↑(1: ℕ), from le_of_lt (nat.cast_lt.2 hp.gt_one)) (neg_nonpos_of_nonneg (int.coe_nat_nonneg _)), have (((p : ℚ) ^ (-(multiplicity (p : ℤ) n).get (finite_int_iff.2 ⟨hp.ne_one, hnz⟩) : ℤ) : ℚ) : ℝ) ≤ (1 : ℚ), from rat.cast_le.2 this, by simpa [padic.cast_eq_of_rat, hnz', padic_norm, padic_val_rat_def p hnz', multiplicity_eq_zero_of_not_dvd (mt int.coe_nat_dvd.1 hq)] lemma eq_of_norm_add_lt_right {p : ℕ} {hp : p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {p : ℕ} {hp : p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_left) h end normed_space end padic_norm_e namespace padic variables {p : ℕ} [nat.prime p] set_option eqn_compiler.zeta true instance complete : cau_seq.is_complete ℚ_[p] norm := ⟨λ f, let f' : cau_seq ℚ_[p] padic_norm_e := ⟨λ n, f n, λ ε hε, let ⟨N, hN⟩ := is_cau f ↑ε (rat.cast_pos.2 hε) in ⟨N, λ j hj, rat.cast_lt.1 (hN _ hj)⟩⟩ in let ⟨q, hq⟩ := padic.complete' f' in ⟨ q, setoid.symm $ λ ε hε, let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨N, hN⟩ := hq _ (by simpa using hε'l) in ⟨N, λ i hi, lt.trans (rat.cast_lt.2 (hN _ hi)) hε'r ⟩⟩⟩ lemma padic_norm_e_lim_le {f : cau_seq ℚ_[p] norm} {a : ℝ} (ha : a > 0) (hf : ∀ i, ∥f i∥ ≤ a) : ∥f.lim∥ ≤ a := let ⟨N, hN⟩ := setoid.symm (cau_seq.equiv_lim f) _ ha in calc ∥f.lim∥ = ∥f.lim - f N + f N∥ : by simp ... ≤ max (∥f.lim - f N∥) (∥f N∥) : padic_norm_e.nonarchimedean _ _ ... ≤ a : max_le (le_of_lt (hN _ (le_refl _))) (hf _) end padic
777a61fd2e391b90f72ee755a156bc441cce553a
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/meta/pexpr.lean
fa48989be522722455c6ff5691abc9189ab7389f
[ "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
1,027
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.expr universe u /- Quoted expressions. They can be converted into expressions by using a tactic. -/ @[reducible] meta def pexpr := expr ff protected meta constant pexpr.of_expr : expr → pexpr meta constant pexpr.mk_placeholder : pexpr meta constant pexpr.mk_field_macro : pexpr → name → pexpr meta constant pexpr.mk_explicit : pexpr → pexpr /- Choice macros are used to implement overloading. -/ meta constant pexpr.is_choice_macro : pexpr → bool meta class has_to_pexpr (α : Sort u) := (to_pexpr : α → pexpr) meta def to_pexpr {α : Sort u} [has_to_pexpr α] : α → pexpr := has_to_pexpr.to_pexpr meta instance : has_to_pexpr pexpr := ⟨id⟩ meta instance : has_to_pexpr expr := ⟨pexpr.of_expr⟩ meta instance (α : Sort u) (a : α) : has_to_pexpr (reflected a) := ⟨pexpr.of_expr ∘ reflected.to_expr⟩