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
6091ac02b56d0ce939635e2fef863736f6c11856
0d9b0a832bc57849732c5bd008a7a142f7e49656
/src/direction.lean
85b05f63858078c3784592aa2fda3e7745b4dfd8
[]
no_license
mirefek/sokoban.lean
bb9414af67894e4d8ce75f8c8d7031df02d371d0
451c92308afb4d3f8e566594b9751286f93b899b
refs/heads/master
1,681,025,245,267
1,618,997,832,000
1,618,997,832,000
359,491,681
10
0
null
null
null
null
UTF-8
Lean
false
false
1,346
lean
import data.fintype.basic import data.prod inductive direction : Type | up | down | left | right namespace direction def luniv := [up, down, left, right] def opposite : direction -> direction | up := down | down := up | left := right | right := left def transpose : direction -> direction | up := left | down := right | left := up | right := down def shift : direction -> (ℕ × ℕ) -> (ℕ × ℕ) | up (x, y) := (x, y.pred) | down (x, y) := (x, y.succ) | left (x, y) := (x.pred, y) | right (x, y) := (x.succ, y) lemma luniv_complete {d : direction} : d ∈ luniv := begin unfold luniv, cases d, all_goals {simp, } end lemma opposite_opposite {d : direction} : opposite (opposite d) = d := begin cases d, all_goals { unfold opposite, } end theorem transpose_shift : ∀ (d : direction) (xy : ℕ×ℕ), d.transpose.shift xy = (d.shift xy.swap).swap := begin intros, cases xy with x y, cases d, all_goals { refl, }, end theorem opposite_shift : ∀ (d : direction) (xy : ℕ×ℕ), d.shift xy = xy ∨ d.opposite.shift (d.shift xy) = xy | up (x, 0) := by simp! [opposite, shift] | up (x, y+1) := by simp! [opposite, shift] | down (x, y) := by simp! [opposite, shift] | left (0, y) := by simp! [opposite, shift] | left (x+1, y) := by simp! [opposite, shift] | right (x, y) := by simp! [opposite, shift] end direction
0a14f24aa601009bd50a0df3d4204f0303dc5414
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/pi_instances.lean
1cdff1c2c61b1057863c79b0e24f484d6660ac23
[]
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
759
lean
/- Copyright (c) 2018 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.order.basic import Mathlib.PostPort namespace Mathlib /-! # `pi_instance` Automation for creating instances of mathematical structures for pi types -/ namespace tactic /-- Attempt to clear a goal obtained by refining a `pi_instance` goal. -/ /-- `pi_instance` constructs an instance of `my_class (Π i : I, f i)` where we know `Π i, my_class (f i)`. If an order relation is required, it defaults to `pi.partial_order`. Any field of the instance that `pi_instance` cannot construct is left untouched and generated as a new goal. -/
859bf88ba8c43898d76110ac82e1434e6317f5e3
c777c32c8e484e195053731103c5e52af26a25d1
/archive/miu_language/decision_nec.lean
d70116a20b054dd043b4b39b8ea684511ad1e8cf
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
6,734
lean
/- Copyright (c) 2020 Gihan Marasingha. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gihan Marasingha -/ import .basic import data.list.count import data.nat.modeq import tactic.ring /-! # Decision procedure: necessary condition We introduce a condition `decstr` and show that if a string `en` is `derivable`, then `decstr en` holds. Using this, we give a negative answer to the question: is `"MU"` derivable? ## Tags miu, decision procedure -/ namespace miu open miu_atom nat list /-! ### Numerical condition on the `I` count Suppose `st : miustr`. Then `count I st` is the number of `I`s in `st`. We'll show, if `derivable st`, then `count I st` must be 1 or 2 modulo 3. To do this, it suffices to show that if the `en : miustr` is derived from `st`, then `count I en` moudulo 3 is either equal to or is twice `count I st`, modulo 3. -/ /-- Given `st en : miustr`, the relation `count_equiv_or_equiv_two_mul_mod3 st en` holds if `st` and `en` either have equal `count I`, modulo 3, or `count I en` is twice `count I st`, modulo 3. -/ def count_equiv_or_equiv_two_mul_mod3 (st en : miustr) : Prop := let a := (count I st) in let b := (count I en) in b ≡ a [MOD 3] ∨ b ≡ 2*a [MOD 3] example : count_equiv_or_equiv_two_mul_mod3 "II" "MIUI" := or.inl rfl example : count_equiv_or_equiv_two_mul_mod3 "IUIM" "MI" := or.inr rfl /-- If `a` is 1 or 2 mod 3 and if `b` is `a` or twice `a` mod 3, then `b` is 1 or 2 mod 3. -/ lemma mod3_eq_1_or_mod3_eq_2 {a b : ℕ} (h1 : a % 3 = 1 ∨ a % 3 = 2) (h2 : b % 3 = a % 3 ∨ b % 3 = (2 * a % 3)) : b % 3 = 1 ∨ b % 3 = 2 := begin cases h2, { rw h2, exact h1, }, { cases h1, { right, simp [h2,mul_mod,h1, nat.succ_lt_succ] }, { left, simpa [h2,mul_mod,h1], }, }, end /-- `count_equiv_one_or_two_mod3_of_derivable` shows any derivable string must have a `count I` that is 1 or 2 modulo 3. -/ theorem count_equiv_one_or_two_mod3_of_derivable (en : miustr): derivable en → (count I en) % 3 = 1 ∨ (count I en) % 3 = 2:= begin intro h, induction h, { left, apply mod_def, }, any_goals {apply mod3_eq_1_or_mod3_eq_2 h_ih}, { left, simp only [count_append], refl, }, { right, simp only [count, countp, count_append, if_false,two_mul], }, { left, simp only [count, count_append, countp, if_false, if_pos], rw [add_right_comm, add_mod_right], }, { left, simp only [count ,countp, countp_append, if_false, add_zero], }, end /-- Using the above theorem, we solve the MU puzzle, showing that `"MU"` is not derivable. Once we have proved that `derivable` is an instance of `decidable_pred`, this will follow immediately from `dec_trivial`. -/ theorem not_derivable_mu : ¬(derivable "MU") := begin intro h, cases (count_equiv_one_or_two_mod3_of_derivable _ h); contradiction, end /-! ### Condition on `M` That solves the MU puzzle, but we'll proceed by demonstrating the other necessary condition for a string to be derivable, namely that the string must start with an M and contain no M in its tail. -/ /-- `goodm xs` holds if `xs : miustr` begins with `M` and has no `M` in its tail. -/ @[derive decidable_pred] def goodm (xs : miustr) : Prop := list.head xs = M ∧ ¬(M ∈ list.tail xs) /-- Demonstration that `"MI"` starts with `M` and has no `M` in its tail. -/ lemma goodmi : goodm [M,I] := begin split, { refl }, { rw [tail ,mem_singleton], trivial }, end /-! We'll show, for each `i` from 1 to 4, that if `en` follows by Rule `i` from `st` and if `goodm st` holds, then so does `goodm en`. -/ lemma goodm_of_rule1 (xs : miustr) (h₁ : derivable (xs ++ [I])) (h₂ : goodm (xs ++ [I])) : goodm (xs ++ [I,U]) := begin cases h₂ with mhead nmtail, have : xs ≠ nil, { intro h, rw h at *, rw [nil_append, head] at mhead, contradiction, }, split, { rwa [head_append] at *; exact this, }, { change [I,U] with [I] ++ [U], rw [←append_assoc, tail_append_singleton_of_ne_nil], { simp only [mem_append, nmtail, false_or, mem_singleton, not_false_iff], }, { exact append_ne_nil_of_ne_nil_left _ _ this, }, }, end lemma goodm_of_rule2 (xs : miustr) (h₁ : derivable (M :: xs)) (h₂ : goodm (M :: xs)) : goodm (M :: xs ++ xs) := begin split, { refl, }, { cases h₂ with mhead mtail, contrapose! mtail, rw cons_append at mtail, rw tail at *, exact (or_self _).mp (mem_append.mp mtail), }, end lemma goodm_of_rule3 (as bs : miustr) (h₁ : derivable (as ++ [I,I,I] ++ bs)) (h₂ : goodm (as ++ [I,I,I] ++ bs)) : goodm (as ++ U :: bs) := begin cases h₂ with mhead nmtail, have k : as ≠ nil , { intro h, rw h at mhead, rw [nil_append] at mhead, contradiction, }, split, { revert mhead, simp only [append_assoc,head_append _ k], exact id, }, { contrapose! nmtail, rcases (exists_cons_of_ne_nil k) with ⟨x,xs,rfl⟩, simp only [cons_append, tail, mem_append, mem_cons_iff, false_or, mem_nil_iff, or_false] at *, exact nmtail, }, end /-! The proof of the next lemma is identical, on the tactic level, to the previous proof. -/ lemma goodm_of_rule4 (as bs : miustr) (h₁ : derivable (as ++ [U,U] ++ bs)) (h₂ : goodm (as ++ [U,U] ++ bs)) : goodm (as ++ bs) := begin cases h₂ with mhead nmtail, have k : as ≠ nil , { intro h, rw h at mhead, rw [nil_append] at mhead, contradiction, }, split, { revert mhead, simp only [append_assoc,head_append _ k], exact id, }, { contrapose! nmtail, rcases (exists_cons_of_ne_nil k) with ⟨x,xs,rfl⟩, simp only [cons_append, tail, mem_append, mem_cons_iff, false_or, mem_nil_iff, or_false] at *, exact nmtail, }, end /-- Any derivable string must begin with `M` and have no `M` in its tail. -/ theorem goodm_of_derivable (en : miustr): derivable en → goodm en:= begin intro h, induction h, { exact goodmi, }, { apply goodm_of_rule1; assumption, }, { apply goodm_of_rule2; assumption, }, { apply goodm_of_rule3; assumption, }, { apply goodm_of_rule4; assumption, }, end /-! We put togther our two conditions to give one necessary condition `decstr` for an `miustr` to be derivable. -/ /-- `decstr en` is the condition that `count I en` is 1 or 2 modulo 3, that `en` starts with `M`, and that `en` has no `M` in its tail. We automatically derive that this is a decidable predicate. -/ @[derive decidable_pred] def decstr (en : miustr) := goodm en ∧ ((count I en) % 3 = 1 ∨ (count I en) % 3 = 2) /-- Suppose `en : miustr`. If `en` is `derivable`, then the condition `decstr en` holds. -/ theorem decstr_of_der {en : miustr} : derivable en → decstr en := begin intro h, split, { exact goodm_of_derivable en h, }, { exact count_equiv_one_or_two_mod3_of_derivable en h, }, end end miu
6bee371d723397f9d1506ea08bb6e5cf9630724a
c9b68131de1dfe4e7f0ea5749b11e67a774bc839
/src/correctness.lean
55ac67fe5f44985c2b6168701192664c9429944d
[]
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
6,608
lean
/- A proof of the main theorem of the whitepaper: Given a collection of data meeting all the constraints in `constraints`, assuming the extra probabilistic assumptions hold, there is an execution trace according to the semantics given in `cpu`, with the given length, start state, and final value of the program counter. -/ import cpu constraints memory range_check instruction step open_locale classical open_locale disable_subsingleton_simps /- assume F is a sufficiently large finite field -/ variables {F : Type} [field F] [fintype F] /- The probabilistic assumptions. -/ structure hprob {inp : input_data_aux F} (c : constraints inp) := (hprob₁ : c.mc.mb.alpha ∉ bad_set_1 (real_a inp.mem_star c.mc.a c.mc.em.embed_mem) (real_v inp.mem_star c.mc.v c.mc.em.embed_mem) c.mc.mb.a' c.mc.mb.v') (hprob₂ : c.mc.mb.z ∉ bad_set_2 (real_a inp.mem_star c.mc.a c.mc.em.embed_mem) (real_v inp.mem_star c.mc.v c.mc.em.embed_mem) c.mc.mb.a' c.mc.mb.v' c.mc.mb.alpha) (hprob₃ : c.mc.mb.z ≠ 0) (hprob₄ : c.rc.z ∉ bad_set_3 c.rc.a c.rc.a') /-- The main theorem: if the constraints hold for the trace data, then for any memory assignment that agrees with the input data, there is an execution trace that agrees with the input data. -/ theorem execution_exists (char_ge : ring_char F ≥ 2^63) (inp : input_data_aux F) (c : constraints inp) (hp : hprob c) : ∃ mem : F → F, option.fn_extends mem inp.mem_star ∧ ∃ exec : fin (inp.T + 1) → register_state F, (exec 0).pc = inp.pc_I ∧ (exec 0).ap = inp.ap_I ∧ (exec 0).fp = inp.ap_I ∧ (exec (fin.last inp.T)).pc = inp.pc_F ∧ (exec (fin.last inp.T)).ap = inp.ap_F ∧ ∀ i : fin inp.T, next_state mem (exec i.cast_succ) (exec i.succ) := begin have char_gt : ring_char F > 2^16, { apply lt_of_lt_of_le _ char_ge, apply pow_lt_pow; norm_num }, let m := mem c.mc.mb.a' c.mc.mb.v', have mem_extends : option.fn_extends m inp.mem_star := mem_extends c.mc.mb.h_continuity c.mc.mb.h_single_valued c.mc.mb.h_initial c.mc.mb.h_cumulative c.mc.mb.h_final c.mc.em.h_embed_dom c.mc.em.h_embed_val c.mc.em.h_embed_mem_inj hp.hprob₃ hp.hprob₁ hp.hprob₂ c.mc.h_n_lt, have mem_pc_addr : ∀ i : fin inp.T, m (c.pc i.cast_succ) = c.inst i := mem_pc c.mc.mb.h_continuity c.mc.mb.h_single_valued c.mc.mb.h_initial c.mc.mb.h_cumulative c.mc.mb.h_final c.mc.em.h_embed_pc c.mc.em.h_embed_inst c.mc.em.h_embed_dom c.mc.em.h_embed_val c.mc.em.h_embed_mem_inj c.mc.em.h_embed_mem_disj_inst hp.hprob₃ hp.hprob₁ hp.hprob₂ c.mc.h_n_lt, have mem_dst_addr : ∀ i, m (c.dst_addr i) = c.dst i := mem_dst_addr c.mc.mb.h_continuity c.mc.mb.h_single_valued c.mc.mb.h_initial c.mc.mb.h_cumulative c.mc.mb.h_final c.mc.em.h_embed_dst_addr c.mc.em.h_embed_dst c.mc.em.h_embed_dom c.mc.em.h_embed_val c.mc.em.h_embed_mem_inj c.mc.em.h_embed_mem_disj_dst hp.hprob₃ hp.hprob₁ hp.hprob₂ c.mc.h_n_lt, have mem_op0_addr : ∀ i, m (c.op0_addr i) = c.op0 i := mem_op0_addr c.mc.mb.h_continuity c.mc.mb.h_single_valued c.mc.mb.h_initial c.mc.mb.h_cumulative c.mc.mb.h_final c.mc.em.h_embed_op0_addr c.mc.em.h_embed_op0 c.mc.em.h_embed_dom c.mc.em.h_embed_val c.mc.em.h_embed_mem_inj c.mc.em.h_embed_mem_disj_op0 hp.hprob₃ hp.hprob₁ hp.hprob₂ c.mc.h_n_lt, have mem_op1_addr : ∀ i, m (c.op1_addr i) = c.op1 i := mem_op1_addr c.mc.mb.h_continuity c.mc.mb.h_single_valued c.mc.mb.h_initial c.mc.mb.h_cumulative c.mc.mb.h_final c.mc.em.h_embed_op1_addr c.mc.em.h_embed_op1 c.mc.em.h_embed_dom c.mc.em.h_embed_val c.mc.em.h_embed_mem_inj c.mc.em.h_embed_mem_disj_op1 hp.hprob₃ hp.hprob₁ hp.hprob₂ c.mc.h_n_lt, have off_op0_in_range : ∀ i, ∃ k : ℕ, k < 2^16 ∧ c.off_op0_tilde i = ↑k := off_op0_in_range c.rc.h_continuity c.rc.h_initial c.rc.h_cumulative c.rc.h_final c.rc.h_rc_min c.rc.h_rc_max c.rc.h_embed_op0 c.rc.h_n_lt inp.h_rc_lt inp.h_rc_le char_gt hp.hprob₄, have off_op1_in_range : ∀ i, ∃ k : ℕ, k < 2^16 ∧ c.off_op1_tilde i = ↑k := off_op1_in_range c.rc.h_continuity c.rc.h_initial c.rc.h_cumulative c.rc.h_final c.rc.h_rc_min c.rc.h_rc_max c.rc.h_embed_op1 c.rc.h_n_lt inp.h_rc_lt inp.h_rc_le char_gt hp.hprob₄, have off_dst_in_range : ∀ i, ∃ k : ℕ, k < 2^16 ∧ c.off_dst_tilde i = ↑k := off_dst_in_range c.rc.h_continuity c.rc.h_initial c.rc.h_cumulative c.rc.h_final c.rc.h_rc_min c.rc.h_rc_max c.rc.h_embed_dst c.rc.h_n_lt inp.h_rc_lt inp.h_rc_le char_gt hp.hprob₄, use [m, mem_extends], let e := λ i : fin (inp.T + 1), register_state.mk (c.pc i) (c.ap i) (c.fp i), use [e, c.h_pc_I, c.h_ap_I, c.h_fp_I, c.h_pc_F, c.h_ap_F], intro i, show next_state m (e i.cast_succ) (e i.succ), let inst' := the_instruction (c.ic i).h_bit (off_op0_in_range i) (off_op1_in_range i) (off_dst_in_range i), have inst_eq : c.inst i = ↑(inst'.to_nat) := inst_eq (c.ic i).h_instruction (c.ic i).h_bit (c.ic i).h_last_value (off_op0_in_range i) (off_op1_in_range i) (off_dst_in_range i), have off_dst_tilde_eq : c.off_dst_tilde i = ↑(inst'.off_dst.to_natr) := off_dst_tilde_eq (c.ic i).h_bit (off_op0_in_range i) (off_op1_in_range i) (off_dst_in_range i), have off_op0_tilde_eq : c.off_op0_tilde i = ↑(inst'.off_op0.to_natr) := off_op0_tilde_eq (c.ic i).h_bit (off_op0_in_range i) (off_op1_in_range i) (off_dst_in_range i), have off_op1_tilde_eq : c.off_op1_tilde i = ↑(inst'.off_op1.to_natr) := off_op1_tilde_eq (c.ic i).h_bit (off_op0_in_range i) (off_op1_in_range i) (off_dst_in_range i), have f_tilde_to_f_eq : ∀ j, (c.f_tilde i).to_f j = ↑((inst'.flags.nth j).to_nat) := f_tilde_to_f_eq (c.ic i).h_bit (off_op0_in_range i) (off_op1_in_range i) (off_dst_in_range i), exact next_state_eq off_dst_tilde_eq off_op0_tilde_eq off_op1_tilde_eq f_tilde_to_f_eq ((mem_pc_addr i).trans inst_eq) (mem_dst_addr i) (mem_op0_addr i) (mem_op1_addr i) (c.sc i).h_dst_addr (c.sc i).h_op0_addr (c.sc i).h_op1_addr (c.sc i).h_mul (c.sc i).h_res (c.sc i).h_t0_eq (c.sc i).h_t1_eq (c.sc i).h_next_pc_eq (c.sc i).h_next_pc_eq' (c.sc i).h_opcode_call (c.sc i).h_opcode_call' (c.sc i).h_opcode_assert_eq (c.sc i).h_next_ap (c.sc i).h_next_fp end
3589aabf1c9885ef327642d9877d5d8bf8bafc34
690889011852559ee5ac4dfea77092de8c832e7e
/src/tactic/lift.lean
23c22f7398318078356895b7579e2b343ba34c0e
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
7,162
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import tactic.rcases /-! # lift tactic This file defines the lift tactic, allowing the user to lift elements from one type to another under a specified condition. ## Tags lift, tactic -/ universe variables u v /-- A class specifying that you can lift elements from `α` to `β` assuming `cond` is true. Used by the tactic `lift`. -/ class can_lift (α : Type u) (β : Type v) : Type (max u v) := (coe : β → α) (cond : α → Prop) (prf : ∀(x : α), cond x → ∃(y : β), coe y = x) open tactic @[user_attribute] meta def can_lift_attr : user_attribute (list name) := { name := "_can_lift", descr := "internal attribute used by the lift tactic", cache_cfg := { mk_cache := λ _, do { ls ← attribute.get_instances `instance, ls.mfilter $ λ l, do { (_,t) ← mk_const l >>= infer_type >>= mk_local_pis, return $ t.is_app_of `can_lift } }, dependencies := [`instance] } } instance : can_lift ℤ ℕ := ⟨coe, λ n, 0 ≤ n, λ n hn, ⟨n.nat_abs, int.nat_abs_of_nonneg hn⟩⟩ namespace tactic /- Construct the proof of `cond x` in the lift tactic. `e` is the expression being lifted and `h` is the specified proof of `can_lift.cond e`. `old_tp` and `new_tp` are the arguments to `can_lift` and `inst` is the `can_lift`-instance. `s` and `to_unfold` contain the information of the simp set used to simplify. If the proof was specified, we check whether it has the correct type. If it doesn't have the correct type, we display an error message (but first call dsimp on the expression in the message). If the proof was not specified, we create assert it as a local constant. (The name of this local constant doesn't matter, since `lift` will remove it from the context) -/ meta def get_lift_prf (h : option pexpr) (old_tp new_tp inst e : expr) (s : simp_lemmas) (to_unfold : list name) : tactic expr := if h_some : h.is_some then (do prf ← i_to_expr (option.get h_some), prf_ty ← infer_type prf, expected_prf_ty ← mk_app `can_lift.cond [old_tp, new_tp, inst, e], unify prf_ty expected_prf_ty <|> (do expected_prf_ty2 ← s.dsimplify to_unfold expected_prf_ty, pformat!"lift tactic failed. The type of\n {prf}\nis\n {prf_ty}\nbut it is expected to be\n {expected_prf_ty2}" >>= fail), return prf) else (do prf_nm ← get_unused_name, prf ← mk_app `can_lift.cond [old_tp, new_tp, inst, e] >>= assert prf_nm, dsimp_target s to_unfold {}, swap, return prf) /-- Lift the expression `p` to the type `t`, with proof obligation given by `h`. The list `n` is used for the two newly generated names, and to specify whether `h` should remain in the local context. See the doc string of `tactic.interactive.lift` for more information. -/ meta def lift (p : pexpr) (t : pexpr) (h : option pexpr) (n : list name) : tactic unit := do e ← i_to_expr p, old_tp ← infer_type e, new_tp ← i_to_expr t, inst_type ← mk_app ``can_lift [old_tp, new_tp], inst ← mk_instance inst_type <|> pformat!"Failed to find a lift from {old_tp} to {new_tp}. Provide an instance of\n {inst_type}" >>= fail, /- make the simp set to get rid of `can_lift` projections -/ can_lift_instances ← can_lift_attr.get_cache >>= λ l, l.mmap resolve_name, (s, to_unfold) ← mk_simp_set tt [] $ can_lift_instances.map simp_arg_type.expr, prf_cond ← get_lift_prf h old_tp new_tp inst e s to_unfold, let prf_nm := if prf_cond.is_local_constant then some prf_cond.local_pp_name else none, /- We use mk_mapp to apply `can_lift.prf` to all but one argument, and then just use expr.app for the last argument. For some reason we get an error when applying mk_mapp it to all arguments. -/ prf_ex0 ← mk_mapp `can_lift.prf [old_tp, new_tp, inst, e], let prf_ex := prf_ex0 prf_cond, /- Find the name of the new variable -/ new_nm ← if n ≠ [] then return n.head else if e.is_local_constant then return e.local_pp_name else get_unused_name, /- Find the name of the proof of the equation -/ eq_nm ← if hn : 1 < n.length then return (n.nth_le 1 hn) else if e.is_local_constant then return `rfl else get_unused_name `h, /- We add the proof of the existential statement to the context and then apply `dsimp` to it, unfolding all `can_lift` instances. -/ temp_nm ← get_unused_name, temp_e ← note temp_nm none prf_ex, dsimp_hyp temp_e s to_unfold {}, /- We case on the existential. We use `rcases` because `eq_nm` could be `rfl`. -/ rcases (pexpr.of_expr temp_e) [[rcases_patt.one new_nm, rcases_patt.one eq_nm]], /- If the lifted variable is not a local constant, try to rewrite it away using the new equality-/ when (¬ e.is_local_constant) (get_local eq_nm >>= λ e, interactive.rw ⟨[⟨⟨0, 0⟩, tt, (pexpr.of_expr e)⟩], none⟩ interactive.loc.wildcard), /- If the proof `prf_cond` is a local constant, remove it from the context, unless `n` specifies to keep it. -/ if h_prf_nm : prf_nm.is_some ∧ n.nth 2 ≠ prf_nm then get_local (option.get h_prf_nm.1) >>= clear else skip open lean.parser interactive interactive.types local postfix `?`:9001 := optional meta def using_texpr := (tk "using" *> texpr)? reserve notation `to` meta def to_texpr := (tk "to" *> texpr) namespace interactive /-- Lift an expression to another type. * Usage: `'lift' expr 'to' expr ('using' expr)? ('with' id (id id?)?)?`. * If `n : ℤ` and `hn : n ≥ 0` then the tactic `lift n to ℕ using hn` creates a new constant of type ℕ, also named `n` and replaces all occurrences of the old variable `(n : ℤ)` with `↑n` (where `n` in the new variable). It will remove `n` and `hn` from the context. * The argument `using hn` is optional, the tactic `lift n to ℕ` does the same, but also creates a new subgoal that `n ≥ 0` (where `n` is the old variable). * You can also use `lift n to ℕ using e` where `e` is any expression of type `n ≥ 0`. * Use `lift n to ℕ with k` to specify the name of the new variable. * Use `lift n to ℕ with k hk` to also specify the name of the equality `↑k = n`. In this case, `n` will remain in the context. You can use `rfl` for the name of `hk` to substitute it away. * You can also use `lift e to ℕ with k hk` where `e` is any expression of type `ℤ`. In this case, the `hk` will always stay in the context, but it will be used to rewrite `e` in all hypotheses and the target. * The tactic `lift n to ℕ using h` will remove `h` from the context. If you want to keep it, specify it again as the third argument to `with`, like this: `lift n to ℕ using h with n rfl h`. * More generally, this can lift an expression from `α` to `β` assuming that there is an instance of `can_lift α β`. In this case the proof obligation is specified by `can_lift.cond`. -/ meta def lift (p : parse texpr) (t : parse to_texpr) (h : parse using_texpr) (n : parse with_ident_list) : tactic unit := tactic.lift p t h n end interactive end tactic
0e6d453a55fdefdb0cceb40978fc6a5bc7ebe41d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/version.lean
6b5d539dd3db45743b32f32243a148a944d4ee10
[]
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
429
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.nat.basic import Mathlib.Lean3Lib.init.data.string.basic namespace Mathlib def lean.version : ℕ × ℕ × ℕ := (bit1 1, bit0 (bit1 (bit0 (bit1 1))), 0) def lean.githash : string := sorry def lean.is_release : Bool := to_bool (1 ≠ 0) /-- Additional version description like "nightly-2018-03-11" -/ def lean.special_version_desc : string := string.empty
241e6278808a802e4551e13378394da86d6f9359
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/presheaf.lean
4e407a134d1936caa0105ba6e9bc864db31ae8d7
[]
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
14,452
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.adjunction.default import Mathlib.category_theory.elements import Mathlib.category_theory.limits.functor_category import Mathlib.category_theory.limits.preserves.limits import Mathlib.category_theory.limits.shapes.terminal import Mathlib.category_theory.limits.types import Mathlib.PostPort universes u₁ u₂ namespace Mathlib /-! # Colimit of representables This file constructs an adjunction `yoneda_adjunction` between `(Cᵒᵖ ⥤ Type u)` and `ℰ` given a functor `A : C ⥤ ℰ`, where the right adjoint sends `(E : ℰ)` to `c ↦ (A.obj c ⟶ E)` (provided `ℰ` has colimits). This adjunction is used to show that every presheaf is a colimit of representables. Further, the left adjoint `colimit_adj.extend_along_yoneda : (Cᵒᵖ ⥤ Type u) ⥤ ℰ` satisfies `yoneda ⋙ L ≅ A`, that is, an extension of `A : C ⥤ ℰ` to `(Cᵒᵖ ⥤ Type u) ⥤ ℰ` through `yoneda : C ⥤ Cᵒᵖ ⥤ Type u`. It is the left Kan extension of `A` along the yoneda embedding, sometimes known as the Yoneda extension. `unique_extension_along_yoneda` shows `extend_along_yoneda` is unique amongst cocontinuous functors with this property, establishing the presheaf category as the free cocompletion of a small category. ## Tags colimit, representable, presheaf, free cocompletion ## References * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] * https://ncatlab.org/nlab/show/Yoneda+extension -/ namespace category_theory namespace colimit_adj /-- The functor taking `(E : ℰ) (c : Cᵒᵖ)` to the homset `(A.obj C ⟶ E)`. It is shown in `L_adjunction` that this functor has a left adjoint (provided `E` has colimits) given by taking colimits over categories of elements. In the case where `ℰ = Cᵒᵖ ⥤ Type u` and `A = yoneda`, this functor is isomorphic to the identity. Defined as in [MM92], Chapter I, Section 5, Theorem 2. -/ def restricted_yoneda {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] (A : C ⥤ ℰ) : ℰ ⥤ Cᵒᵖ ⥤ Type u₁ := yoneda ⋙ functor.obj (whiskering_left (Cᵒᵖ) (ℰᵒᵖ) (Type u₁)) (functor.op A) /-- The functor `restricted_yoneda` is isomorphic to the identity functor when evaluated at the yoneda embedding. -/ def restricted_yoneda_yoneda {C : Type u₁} [small_category C] : restricted_yoneda yoneda ≅ 𝟭 := nat_iso.of_components (fun (P : Cᵒᵖ ⥤ Type u₁) => nat_iso.of_components (fun (X : Cᵒᵖ) => yoneda_sections_small (opposite.unop X) P) sorry) sorry /-- (Implementation). The equivalence of homsets which helps construct the left adjoint to `colimit_adj.restricted_yoneda`. It is shown in `restrict_yoneda_hom_equiv_natural` that this is a natural bijection. -/ def restrict_yoneda_hom_equiv {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] (A : C ⥤ ℰ) (P : Cᵒᵖ ⥤ Type u₁) (E : ℰ) {c : limits.cocone (functor.left_op (category_of_elements.π P) ⋙ A)} (t : limits.is_colimit c) : (limits.cocone.X c ⟶ E) ≃ (P ⟶ functor.obj (restricted_yoneda A) E) := equiv.trans (iso.to_equiv (limits.is_colimit.hom_iso' t E)) (equiv.mk (fun (k : Subtype fun (p : (j : functor.elements Pᵒᵖ) → functor.obj (functor.left_op (category_of_elements.π P) ⋙ A) j ⟶ E) => ∀ {j j' : functor.elements Pᵒᵖ} (f : j ⟶ j'), functor.map (functor.left_op (category_of_elements.π P) ⋙ A) f ≫ p j' = p j) => nat_trans.mk fun (c : Cᵒᵖ) (p : functor.obj P c) => subtype.val k (opposite.op (sigma.mk c p))) (fun (τ : P ⟶ functor.obj (restricted_yoneda A) E) => { val := fun (p : functor.elements Pᵒᵖ) => nat_trans.app τ (sigma.fst (opposite.unop p)) (sigma.snd (opposite.unop p)), property := sorry }) sorry sorry) /-- (Implementation). Show that the bijection in `restrict_yoneda_hom_equiv` is natural (on the right). -/ theorem restrict_yoneda_hom_equiv_natural {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] (A : C ⥤ ℰ) (P : Cᵒᵖ ⥤ Type u₁) (E₁ : ℰ) (E₂ : ℰ) (g : E₁ ⟶ E₂) {c : limits.cocone (functor.left_op (category_of_elements.π P) ⋙ A)} (t : limits.is_colimit c) (k : limits.cocone.X c ⟶ E₁) : coe_fn (restrict_yoneda_hom_equiv A P E₂ t) (k ≫ g) = coe_fn (restrict_yoneda_hom_equiv A P E₁ t) k ≫ functor.map (restricted_yoneda A) g := sorry /-- The left adjoint to the functor `restricted_yoneda` (shown in `yoneda_adjunction`). It is also an extension of `A` along the yoneda embedding (shown in `is_extension_along_yoneda`), in particular it is the left Kan extension of `A` through the yoneda embedding. -/ def extend_along_yoneda {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] (A : C ⥤ ℰ) [limits.has_colimits ℰ] : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ := adjunction.left_adjoint_of_equiv (fun (P : Cᵒᵖ ⥤ Type u₁) (E : ℰ) => restrict_yoneda_hom_equiv A P E (limits.colimit.is_colimit (functor.left_op (category_of_elements.π P) ⋙ A))) sorry @[simp] theorem extend_along_yoneda_obj {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] (A : C ⥤ ℰ) [limits.has_colimits ℰ] (P : Cᵒᵖ ⥤ Type u₁) : functor.obj (extend_along_yoneda A) P = limits.colimit (functor.left_op (category_of_elements.π P) ⋙ A) := rfl /-- Show `extend_along_yoneda` is left adjoint to `restricted_yoneda`. The construction of [MM92], Chapter I, Section 5, Theorem 2. -/ def yoneda_adjunction {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] (A : C ⥤ ℰ) [limits.has_colimits ℰ] : extend_along_yoneda A ⊣ restricted_yoneda A := adjunction.adjunction_of_equiv_left (fun (P : Cᵒᵖ ⥤ Type u₁) (E : ℰ) => restrict_yoneda_hom_equiv A P E (limits.colimit.is_colimit (functor.left_op (category_of_elements.π P) ⋙ A))) (extend_along_yoneda._proof_4 A) /-- The initial object in the category of elements for a representable functor. In `is_initial` it is shown that this is initial. -/ def elements.initial {C : Type u₁} [small_category C] (A : C) : functor.elements (functor.obj yoneda A) := sigma.mk (opposite.op A) 𝟙 /-- Show that `elements.initial A` is initial in the category of elements for the `yoneda` functor. -/ def is_initial {C : Type u₁} [small_category C] (A : C) : limits.is_initial (elements.initial A) := limits.is_colimit.mk fun (s : limits.cocone (functor.empty (functor.elements (functor.obj yoneda A)))) => { val := has_hom.hom.op (sigma.snd (limits.cocone.X s)), property := sorry } /-- `extend_along_yoneda A` is an extension of `A` to the presheaf category along the yoneda embedding. `unique_extension_along_yoneda` shows it is unique among functors preserving colimits with this property (up to isomorphism). The first part of [MM92], Chapter I, Section 5, Corollary 4. See Property 1 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ def is_extension_along_yoneda {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] (A : C ⥤ ℰ) [limits.has_colimits ℰ] : yoneda ⋙ extend_along_yoneda A ≅ A := nat_iso.of_components (fun (X : C) => limits.is_colimit.cocone_point_unique_up_to_iso (limits.colimit.is_colimit (functor.left_op (category_of_elements.π (functor.obj yoneda X)) ⋙ A)) (limits.colimit_of_diagram_terminal (limits.terminal_op_of_initial (is_initial X)) (functor.left_op (category_of_elements.π (functor.obj yoneda X)) ⋙ A))) sorry /-- See Property 2 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ protected instance extend_along_yoneda.category_theory.limits.preserves_colimits {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] (A : C ⥤ ℰ) [limits.has_colimits ℰ] : limits.preserves_colimits (extend_along_yoneda A) := adjunction.left_adjoint_preserves_colimits (yoneda_adjunction A) end colimit_adj /-- Since `extend_along_yoneda A` is adjoint to `restricted_yoneda A`, if we use `A = yoneda` then `restricted_yoneda A` is isomorphic to the identity, and so `extend_along_yoneda A` is as well. -/ def extend_along_yoneda_yoneda {C : Type u₁} [small_category C] : colimit_adj.extend_along_yoneda yoneda ≅ 𝟭 := adjunction.nat_iso_of_right_adjoint_nat_iso (colimit_adj.yoneda_adjunction yoneda) adjunction.id colimit_adj.restricted_yoneda_yoneda /-- A functor to the presheaf category in which everything in the image is representable (witnessed by the fact that it factors through the yoneda embedding). `cocone_of_representable` gives a cocone for this functor which is a colimit and has point `P`. -/ -- Maybe this should be reducible or an abbreviation? def functor_to_representables {C : Type u₁} [small_category C] (P : Cᵒᵖ ⥤ Type u₁) : functor.elements Pᵒᵖ ⥤ Cᵒᵖ ⥤ Type u₁ := functor.left_op (category_of_elements.π P) ⋙ yoneda /-- This is a cocone with point `P` for the functor `functor_to_representables P`. It is shown in `colimit_of_representable P` that this cocone is a colimit: that is, we have exhibited an arbitrary presheaf `P` as a colimit of representables. The construction of [MM92], Chapter I, Section 5, Corollary 3. -/ def cocone_of_representable {C : Type u₁} [small_category C] (P : Cᵒᵖ ⥤ Type u₁) : limits.cocone (functor_to_representables P) := limits.cocone.extend (limits.colimit.cocone (functor_to_representables P)) (nat_trans.app (iso.hom extend_along_yoneda_yoneda) P) @[simp] theorem cocone_of_representable_X {C : Type u₁} [small_category C] (P : Cᵒᵖ ⥤ Type u₁) : limits.cocone.X (cocone_of_representable P) = P := rfl /-- An explicit formula for the legs of the cocone `cocone_of_representable`. -/ -- Marking this as a simp lemma seems to make things more awkward. theorem cocone_of_representable_ι_app {C : Type u₁} [small_category C] (P : Cᵒᵖ ⥤ Type u₁) (j : functor.elements Pᵒᵖ) : nat_trans.app (limits.cocone.ι (cocone_of_representable P)) j = iso.inv (yoneda_sections_small (functor.obj (functor.left_op (category_of_elements.π P)) j) (functor.obj (functor.obj (functor.const (functor.elements Pᵒᵖ)) (limits.cocone.X (cocone_of_representable P))) j)) (sigma.snd (opposite.unop j)) := sorry /-- The legs of the cocone `cocone_of_representable` are natural in the choice of presheaf. -/ theorem cocone_of_representable_naturality {C : Type u₁} [small_category C] {P₁ : Cᵒᵖ ⥤ Type u₁} {P₂ : Cᵒᵖ ⥤ Type u₁} (α : P₁ ⟶ P₂) (j : functor.elements P₁ᵒᵖ) : nat_trans.app (limits.cocone.ι (cocone_of_representable P₁)) j ≫ α = nat_trans.app (limits.cocone.ι (cocone_of_representable P₂)) (functor.obj (functor.op (category_of_elements.map α)) j) := sorry /-- The cocone with point `P` given by `the_cocone` is a colimit: that is, we have exhibited an arbitrary presheaf `P` as a colimit of representables. The result of [MM92], Chapter I, Section 5, Corollary 3. -/ def colimit_of_representable {C : Type u₁} [small_category C] (P : Cᵒᵖ ⥤ Type u₁) : limits.is_colimit (cocone_of_representable P) := limits.is_colimit.of_point_iso (limits.colimit.is_colimit (functor_to_representables P)) /-- Given two functors L₁ and L₂ which preserve colimits, if they agree when restricted to the representable presheaves then they agree everywhere. -/ def nat_iso_of_nat_iso_on_representables {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] (L₁ : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) (L₂ : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) [limits.preserves_colimits L₁] [limits.preserves_colimits L₂] (h : yoneda ⋙ L₁ ≅ yoneda ⋙ L₂) : L₁ ≅ L₂ := nat_iso.of_components (fun (P : Cᵒᵖ ⥤ Type u₁) => limits.is_colimit.cocone_points_iso_of_nat_iso (limits.is_colimit_of_preserves L₁ (colimit_of_representable P)) (limits.is_colimit_of_preserves L₂ (colimit_of_representable P)) (functor.associator (functor.left_op (category_of_elements.π P)) yoneda L₁ ≪≫ iso_whisker_left (functor.left_op (category_of_elements.π P)) h)) sorry /-- Show that `extend_along_yoneda` is the unique colimit-preserving functor which extends `A` to the presheaf category. The second part of [MM92], Chapter I, Section 5, Corollary 4. See Property 3 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ def unique_extension_along_yoneda {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] (A : C ⥤ ℰ) [limits.has_colimits ℰ] (L : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) (hL : yoneda ⋙ L ≅ A) [limits.preserves_colimits L] : L ≅ colimit_adj.extend_along_yoneda A := nat_iso_of_nat_iso_on_representables L (colimit_adj.extend_along_yoneda A) (hL ≪≫ iso.symm (colimit_adj.is_extension_along_yoneda A)) /-- If `L` preserves colimits and `ℰ` has them, then it is a left adjoint. This is a special case of `is_left_adjoint_of_preserves_colimits` used to prove that. -/ def is_left_adjoint_of_preserves_colimits_aux {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] [limits.has_colimits ℰ] (L : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) [limits.preserves_colimits L] : is_left_adjoint L := is_left_adjoint.mk (colimit_adj.restricted_yoneda (yoneda ⋙ L)) (adjunction.of_nat_iso_left (colimit_adj.yoneda_adjunction (yoneda ⋙ L)) (iso.symm (unique_extension_along_yoneda (yoneda ⋙ L) L (iso.refl (yoneda ⋙ L))))) /-- If `L` preserves colimits and `ℰ` has them, then it is a left adjoint. Note this is a (partial) converse to `left_adjoint_preserves_colimits`. -/ def is_left_adjoint_of_preserves_colimits {C : Type u₁} [small_category C] {ℰ : Type u₂} [category ℰ] [limits.has_colimits ℰ] (L : (C ⥤ Type u₁) ⥤ ℰ) [limits.preserves_colimits L] : is_left_adjoint L := let e : Cᵒᵖᵒᵖ ⥤ Type u₁ ≌ C ⥤ Type u₁ := equivalence.congr_left (op_op_equivalence C); let t : is_left_adjoint (equivalence.functor e ⋙ L) := is_left_adjoint_of_preserves_colimits_aux (equivalence.functor e ⋙ L); adjunction.left_adjoint_of_nat_iso (equivalence.inv_fun_id_assoc e L)
aa9920d72ef1e57f6c86ff17cefdbf72cef02654
5ee26964f602030578ef0159d46145dd2e357ba5
/src/stalk_valuation.lean
a5547a63c4cfa57ce3c2fb32a5c505385cf4b1ef
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
1,237
lean
import r_o_d_completion import valuation.field open topological_space valuation Spv spa namespace spa.presheaf variable {A : Huber_pair} -- now we can define the valuation on the stalks local attribute [instance, priority 0] classical.prop_decidable section scary_uniform_space_instance set_option class.instance_max_depth 100 local attribute [instance] uniform_space' noncomputable def stalk_to_valuation_field (x : spa A) : stalk_of_rings (spa.presheaf_of_topological_rings A).to_presheaf_of_rings x → ring_completion (valuation_field (Spv.out x.1)) := to_stalk.rec (spa.presheaf_of_topological_rings A).to_presheaf_of_rings x (ring_completion (valuation_field (Spv.out x.1))) (λ U hxU, to_valuation_field_completion hxU) (λ U V HUV r hxU, (to_valuation_field_completion_commutes hxU HUV r).symm) instance is_ring_hom' (x : spa A) : is_ring_hom (stalk_to_valuation_field x) := to_stalk.rec_is_ring_hom _ _ _ _ _ noncomputable def stalk_valuation (x : spa A) : valuation (stalk_of_rings (spa.presheaf_of_topological_rings A).to_presheaf_of_rings x) (value_group (out x.1)) := valuation.comap (valuation_on_completion (out x.1)) (stalk_to_valuation_field x) end scary_uniform_space_instance end spa.presheaf
500961814621386bfab420188fd00dd21a9d7379
3c693e12637d1cf47effc09ab5e21700d1278e73
/src/nat/even_and_odd.lean
754234d66da9ac6f468f78cd5afffa0390a78979
[]
no_license
ImperialCollegeLondon/Example-Lean-Projects
e731664ae046980921a69ccfeb2286674080c5bb
87b27ba616eaf03f3642000829a481a1932dd08e
refs/heads/master
1,685,399,670,721
1,623,092,696,000
1,623,092,696,000
275,571,570
19
1
null
1,593,361,524,000
1,593,344,124,000
Lean
UTF-8
Lean
false
false
1,517
lean
import tactic /- The theory of even and odd numbers -/ def even (n : ℕ) : Prop := ∃ d, n = 2 * d def odd (n : ℕ) : Prop := ∃ d, n = 2 * d + 1 /- see https://www.codewars.com/kata/5e998b42dcf07b0001581def/lean for a completely different approach (inductive definitions) -/ /- ## interaction with 0 -/ lemma even_zero : even 0 := begin unfold even, end /- ## interaction with succ -/ lemma even_add_one {n : ℕ} : even n → odd (n + 1) := sorry lemma odd_add_one {n : ℕ} : odd n → even (n + 1) := sorry /- ## interaction with add -/ theorem odd_add_odd {n m : ℕ} (hn : odd n) (hm : odd m) : even (n + m) := sorry theorem odd_add_even {n m : ℕ} (hn : odd n) (hm : even m) : odd (n + m) := sorry theorem even_add_odd {n m : ℕ} (hn : even n) (hm : odd m) : odd (n + m) := sorry theorem even_add_even {n m : ℕ} (hn : even n) (hm : even m) : even (n + m) := sorry /- ## interaction with one -/ theorem odd_one : odd 1 := sorry /- ## interaction with mul -/ theorem even_mul_even {n m : ℕ} (hn : even n) (hm : even m) : even (n * m) := sorry theorem even_mul_odd {n m : ℕ} (hn : even n) (hm : odd m) : even (n * m) := sorry theorem odd_mul_even {n m : ℕ} (hn : odd n) (hm : even m) : even (n * m) := sorry theorem odd_mul_odd {n m : ℕ} (hn : odd n) (hm : odd m) : odd (n * m) := sorry /- ## interaction with each other -/ lemma odd_or_even (n : ℕ) : odd n ∨ even n := sorry -- hard? lemma not_odd_and_even {n : ℕ} : ¬ (odd n ∧ even n) := sorry
ef3bb09022a7d768519ddfe1bc55f6829077338e
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/category_theory/sites/sheaf.lean
6e8c10b4a65a22e9c2591b9ad026860ac49a2d1f
[ "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
23,531
lean
/- Copyright (c) 2020 Kevin Buzzard, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Bhavik Mehta -/ import category_theory.limits.preserves.shapes.equalizers import category_theory.limits.preserves.shapes.products import category_theory.limits.yoneda import category_theory.sites.sheaf_of_types /-! # Sheaves taking values in a category If C is a category with a Grothendieck topology, we define the notion of a sheaf taking values in an arbitrary category `A`. We follow the definition in https://stacks.math.columbia.edu/tag/00VR, noting that the presheaf of sets "defined above" can be seen in the comments between tags 00VQ and 00VR on the page <https://stacks.math.columbia.edu/tag/00VL>. The advantage of this definition is that we need no assumptions whatsoever on `A` other than the assumption that the morphisms in `C` and `A` live in the same universe. * An `A`-valued presheaf `P : Cᵒᵖ ⥤ A` is defined to be a sheaf (for the topology `J`) iff for every `E : A`, the type-valued presheaves of sets given by sending `U : Cᵒᵖ` to `Hom_{A}(E, P U)` are all sheaves of sets, see `category_theory.presheaf.is_sheaf`. * When `A = Type`, this recovers the basic definition of sheaves of sets, see `category_theory.is_sheaf_iff_is_sheaf_of_type`. * An alternate definition when `C` is small, has pullbacks and `A` has products is given by an equalizer condition `category_theory.presheaf.is_sheaf'`. This is equivalent to the earlier definition, shown in `category_theory.presheaf.is_sheaf_iff_is_sheaf'`. * When `A = Type`, this is *definitionally* equal to the equalizer condition for presieves in `category_theory.sites.sheaf_of_types`. * When `A` has limits and there is a functor `s : A ⥤ Type` which is faithful, reflects isomorphisms and preserves limits, then `P : Cᵒᵖ ⥤ A` is a sheaf iff the underlying presheaf of types `P ⋙ s : Cᵒᵖ ⥤ Type` is a sheaf (`category_theory.presheaf.is_sheaf_iff_is_sheaf_forget`). Cf https://stacks.math.columbia.edu/tag/0073, which is a weaker version of this statement (it's only over spaces, not sites) and https://stacks.math.columbia.edu/tag/00YR (a), which additionally assumes filtered colimits. -/ universes w v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory open opposite category_theory category limits sieve namespace presheaf variables {C : Type u₁} [category.{v₁} C] variables {A : Type u₂} [category.{v₂} A] variables (J : grothendieck_topology C) -- We follow https://stacks.math.columbia.edu/tag/00VL definition 00VR /-- A sheaf of A is a presheaf P : Cᵒᵖ => A such that for every E : A, the presheaf of types given by sending U : C to Hom_{A}(E, P U) is a sheaf of types. https://stacks.math.columbia.edu/tag/00VR -/ def is_sheaf (P : Cᵒᵖ ⥤ A) : Prop := ∀ E : A, presieve.is_sheaf J (P ⋙ coyoneda.obj (op E)) section limit_sheaf_condition open presieve presieve.family_of_elements limits variables (P : Cᵒᵖ ⥤ A) {X : C} (S : sieve X) (R : presieve X) (E : Aᵒᵖ) /-- Given a sieve `S` on `X : C`, a presheaf `P : Cᵒᵖ ⥤ A`, and an object `E` of `A`, the cones over the natural diagram `S.arrows.diagram.op ⋙ P` associated to `S` and `P` with cone point `E` are in 1-1 correspondence with sieve_compatible family of elements for the sieve `S` and the presheaf of types `Hom (E, P -)`. -/ @[simps] def cones_equiv_sieve_compatible_family : (S.arrows.diagram.op ⋙ P).cones.obj E ≃ {x : family_of_elements (P ⋙ coyoneda.obj E) S // x.sieve_compatible} := { to_fun := λ π, ⟨λ Y f h, π.app (op ⟨over.mk f, h⟩), λ _, by { intros, apply (id_comp _).symm.trans, dsimp, convert π.naturality (quiver.hom.op (over.hom_mk _ _)); dsimp; refl }⟩, inv_fun := λ x, { app := λ f, x.1 f.unop.1.hom f.unop.2, naturality' := λ f f' g, by { refine eq.trans _ (x.2 f.unop.1.hom g.unop.left f.unop.2), erw id_comp, congr, rw over.w g.unop } }, left_inv := λ π, by { ext, dsimp, congr, rw op_eq_iff_eq_unop, ext, symmetry, apply costructured_arrow.eq_mk }, right_inv := λ x, by { ext, refl } } variables {P S E} {x : family_of_elements (P ⋙ coyoneda.obj E) S} (hx : x.sieve_compatible) /-- The cone corresponding to a sieve_compatible family of elements, dot notation enabled. -/ @[simp] def _root_.category_theory.presieve.family_of_elements.sieve_compatible.cone : cone (S.arrows.diagram.op ⋙ P) := { X := E.unop, π := (cones_equiv_sieve_compatible_family P S E).inv_fun ⟨x,hx⟩ } /-- Cone morphisms from the cone corresponding to a sieve_compatible family to the natural cone associated to a sieve `S` and a presheaf `P` are in 1-1 correspondence with amalgamations of the family. -/ def hom_equiv_amalgamation : (hx.cone ⟶ P.map_cone S.arrows.cocone.op) ≃ {t // x.is_amalgamation t} := { to_fun := λ l, ⟨l.hom, λ Y f hf, l.w (op ⟨over.mk f, hf⟩)⟩, inv_fun := λ t, ⟨t.1, λ f, t.2 f.unop.1.hom f.unop.2⟩, left_inv := λ l, by { ext, refl }, right_inv := λ t, by { ext, refl } } variables (P S) /-- Given sieve `S` and presheaf `P : Cᵒᵖ ⥤ A`, their natural associated cone is a limit cone iff `Hom (E, P -)` is a sheaf of types for the sieve `S` and all `E : A`. -/ lemma is_limit_iff_is_sheaf_for : nonempty (is_limit (P.map_cone S.arrows.cocone.op)) ↔ ∀ E : Aᵒᵖ, is_sheaf_for (P ⋙ coyoneda.obj E) S := begin dsimp [is_sheaf_for], simp_rw compatible_iff_sieve_compatible, rw ((cone.is_limit_equiv_is_terminal _).trans (is_terminal_equiv_unique _ _)).nonempty_congr, rw classical.nonempty_pi, split, { intros hu E x hx, specialize hu hx.cone, erw (hom_equiv_amalgamation hx).unique_congr.nonempty_congr at hu, exact (unique_subtype_iff_exists_unique _).1 hu }, { rintros h ⟨E,π⟩, let eqv := cones_equiv_sieve_compatible_family P S (op E), rw ← eqv.left_inv π, erw (hom_equiv_amalgamation (eqv π).2).unique_congr.nonempty_congr, rw unique_subtype_iff_exists_unique, exact h _ _ (eqv π).2 }, end /-- Given sieve `S` and presheaf `P : Cᵒᵖ ⥤ A`, their natural associated cone admits at most one morphism from every cone in the same category (i.e. over the same diagram), iff `Hom (E, P -)`is separated for the sieve `S` and all `E : A`. -/ lemma subsingleton_iff_is_separated_for : (∀ c, subsingleton (c ⟶ P.map_cone S.arrows.cocone.op)) ↔ ∀ E : Aᵒᵖ, is_separated_for (P ⋙ coyoneda.obj E) S := begin split, { intros hs E x t₁ t₂ h₁ h₂, have hx := is_compatible_of_exists_amalgamation x ⟨t₁,h₁⟩, rw compatible_iff_sieve_compatible at hx, specialize hs hx.cone, cases hs, have := (hom_equiv_amalgamation hx).symm.injective, exact subtype.ext_iff.1 (@this ⟨t₁,h₁⟩ ⟨t₂,h₂⟩ (hs _ _)) }, { rintros h ⟨E,π⟩, let eqv := cones_equiv_sieve_compatible_family P S (op E), split, rw ← eqv.left_inv π, intros f₁ f₂, let eqv' := hom_equiv_amalgamation (eqv π).2, apply eqv'.injective, ext, apply h _ (eqv π).1; exact (eqv' _).2 }, end /-- A presheaf `P` is a sheaf for the Grothendieck topology `J` iff for every covering sieve `S` of `J`, the natural cone associated to `P` and `S` is a limit cone. -/ lemma is_sheaf_iff_is_limit : is_sheaf J P ↔ ∀ ⦃X : C⦄ (S : sieve X), S ∈ J X → nonempty (is_limit (P.map_cone S.arrows.cocone.op)) := ⟨λ h X S hS, (is_limit_iff_is_sheaf_for P S).2 (λ E, h E.unop S hS), λ h E X S hS, (is_limit_iff_is_sheaf_for P S).1 (h S hS) (op E)⟩ /-- A presheaf `P` is separated for the Grothendieck topology `J` iff for every covering sieve `S` of `J`, the natural cone associated to `P` and `S` admits at most one morphism from every cone in the same category. -/ lemma is_separated_iff_subsingleton : (∀ E : A, is_separated J (P ⋙ coyoneda.obj (op E))) ↔ ∀ ⦃X : C⦄ (S : sieve X), S ∈ J X → ∀ c, subsingleton (c ⟶ P.map_cone S.arrows.cocone.op) := ⟨λ h X S hS, (subsingleton_iff_is_separated_for P S).2 (λ E, h E.unop S hS), λ h E X S hS, (subsingleton_iff_is_separated_for P S).1 (h S hS) (op E)⟩ /-- Given presieve `R` and presheaf `P : Cᵒᵖ ⥤ A`, the natural cone associated to `P` and the sieve `sieve.generate R` generated by `R` is a limit cone iff `Hom (E, P -)` is a sheaf of types for the presieve `R` and all `E : A`. -/ lemma is_limit_iff_is_sheaf_for_presieve : nonempty (is_limit (P.map_cone (generate R).arrows.cocone.op)) ↔ ∀ E : Aᵒᵖ, is_sheaf_for (P ⋙ coyoneda.obj E) R := (is_limit_iff_is_sheaf_for P _).trans (forall_congr (λ _, (is_sheaf_for_iff_generate _).symm)) /-- A presheaf `P` is a sheaf for the Grothendieck topology generated by a pretopology `K` iff for every covering presieve `R` of `K`, the natural cone associated to `P` and `sieve.generate R` is a limit cone. -/ lemma is_sheaf_iff_is_limit_pretopology [has_pullbacks C] (K : pretopology C) : is_sheaf (K.to_grothendieck C) P ↔ ∀ ⦃X : C⦄ (R : presieve X), R ∈ K X → nonempty (is_limit (P.map_cone (generate R).arrows.cocone.op)) := by { dsimp [is_sheaf], simp_rw is_sheaf_pretopology, exact ⟨λ h X R hR, (is_limit_iff_is_sheaf_for_presieve P R).2 (λ E, h E.unop R hR), λ h E X R hR, (is_limit_iff_is_sheaf_for_presieve P R).1 (h R hR) (op E)⟩ } end limit_sheaf_condition variable {J} /-- This is a wrapper around `presieve.is_sheaf_for.amalgamate` to be used below. If `P`s a sheaf, `S` is a cover of `X`, and `x` is a collection of morphisms from `E` to `P` evaluated at terms in the cover which are compatible, then we can amalgamate the `x`s to obtain a single morphism `E ⟶ P.obj (op X)`. -/ def is_sheaf.amalgamate {A : Type u₂} [category.{max v₁ u₁} A] {E : A} {X : C} {P : Cᵒᵖ ⥤ A} (hP : presheaf.is_sheaf J P) (S : J.cover X) (x : Π (I : S.arrow), E ⟶ P.obj (op I.Y)) (hx : ∀ (I : S.relation), x I.fst ≫ P.map I.g₁.op = x I.snd ≫ P.map I.g₂.op) : E ⟶ P.obj (op X) := (hP _ _ S.condition).amalgamate (λ Y f hf, x ⟨Y,f,hf⟩) $ λ Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ w, hx ⟨Y₁, Y₂, Z, g₁, g₂, f₁, f₂, h₁, h₂, w⟩ @[simp, reassoc] lemma is_sheaf.amalgamate_map {A : Type u₂} [category.{max v₁ u₁} A] {E : A} {X : C} {P : Cᵒᵖ ⥤ A} (hP : presheaf.is_sheaf J P) (S : J.cover X) (x : Π (I : S.arrow), E ⟶ P.obj (op I.Y)) (hx : ∀ (I : S.relation), x I.fst ≫ P.map I.g₁.op = x I.snd ≫ P.map I.g₂.op) (I : S.arrow) : hP.amalgamate S x hx ≫ P.map I.f.op = x _ := begin rcases I with ⟨Y,f,hf⟩, apply @presieve.is_sheaf_for.valid_glue _ _ _ _ _ _ (hP _ _ S.condition) (λ Y f hf, x ⟨Y,f,hf⟩) (λ Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ w, hx ⟨Y₁, Y₂, Z, g₁, g₂, f₁, f₂, h₁, h₂, w⟩) f hf, end lemma is_sheaf.hom_ext {A : Type u₂} [category.{max v₁ u₁} A] {E : A} {X : C} {P : Cᵒᵖ ⥤ A} (hP : presheaf.is_sheaf J P) (S : J.cover X) (e₁ e₂ : E ⟶ P.obj (op X)) (h : ∀ (I : S.arrow), e₁ ≫ P.map I.f.op = e₂ ≫ P.map I.f.op) : e₁ = e₂ := (hP _ _ S.condition).is_separated_for.ext (λ Y f hf, h ⟨Y,f,hf⟩) lemma is_sheaf_of_iso_iff {P P' : Cᵒᵖ ⥤ A} (e : P ≅ P') : is_sheaf J P ↔ is_sheaf J P' := forall_congr $ λ a, ⟨presieve.is_sheaf_iso J (iso_whisker_right e _), presieve.is_sheaf_iso J (iso_whisker_right e.symm _)⟩ variable (J) end presheaf variables {C : Type u₁} [category.{v₁} C] variables (J : grothendieck_topology C) variables (A : Type u₂) [category.{v₂} A] /-- The category of sheaves taking values in `A` on a grothendieck topology. -/ structure Sheaf := (val : Cᵒᵖ ⥤ A) (cond : presheaf.is_sheaf J val) namespace Sheaf variables {J A} /-- Morphisms between sheaves are just morphisms of presheaves. -/ @[ext] structure hom (X Y : Sheaf J A) := (val : X.val ⟶ Y.val) @[simps] instance : category (Sheaf J A) := { hom := hom, id := λ X, ⟨𝟙 _⟩, comp := λ X Y Z f g, ⟨f.val ≫ g.val⟩, id_comp' := λ X Y f, hom.ext _ _ $ id_comp _, comp_id' := λ X Y f, hom.ext _ _ $ comp_id _, assoc' := λ X Y Z W f g h, hom.ext _ _ $ assoc _ _ _ } -- Let's make the inhabited linter happy... instance (X : Sheaf J A) : inhabited (hom X X) := ⟨𝟙 X⟩ end Sheaf /-- The inclusion functor from sheaves to presheaves. -/ @[simps] def Sheaf_to_presheaf : Sheaf J A ⥤ (Cᵒᵖ ⥤ A) := { obj := Sheaf.val, map := λ _ _ f, f.val, map_id' := λ X, rfl, map_comp' := λ X Y Z f g, rfl } instance : full (Sheaf_to_presheaf J A) := { preimage := λ X Y f, ⟨f⟩ } instance : faithful (Sheaf_to_presheaf J A) := {} /--This is stated as a lemma to prevent class search from forming a loop since a sheaf morphism is monic if and only if it is monic as a presheaf morphism (under suitable assumption).-/ lemma Sheaf.hom.mono_of_presheaf_mono {F G : Sheaf J A} (f : F ⟶ G) [h : mono f.1] : mono f := (Sheaf_to_presheaf J A).mono_of_mono_map h instance Sheaf.hom.epi_of_presheaf_epi {F G : Sheaf J A} (f : F ⟶ G) [h : epi f.1] : epi f := (Sheaf_to_presheaf J A).epi_of_epi_map h /-- The sheaf of sections guaranteed by the sheaf condition. -/ @[simps] def sheaf_over {A : Type u₂} [category.{v₂} A] {J : grothendieck_topology C} (ℱ : Sheaf J A) (E : A) : SheafOfTypes J := ⟨ℱ.val ⋙ coyoneda.obj (op E), ℱ.cond E⟩ lemma is_sheaf_iff_is_sheaf_of_type (P : Cᵒᵖ ⥤ Type w) : presheaf.is_sheaf J P ↔ presieve.is_sheaf J P := begin split, { intros hP, refine presieve.is_sheaf_iso J _ (hP punit), exact iso_whisker_left _ coyoneda.punit_iso ≪≫ P.right_unitor }, { intros hP X Y S hS z hz, refine ⟨λ x, (hP S hS).amalgamate (λ Z f hf, z f hf x) _, _, _⟩, { intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ h, exact congr_fun (hz g₁ g₂ hf₁ hf₂ h) x }, { intros Z f hf, ext x, apply presieve.is_sheaf_for.valid_glue }, { intros y hy, ext x, apply (hP S hS).is_separated_for.ext, intros Y' f hf, rw [presieve.is_sheaf_for.valid_glue _ _ _ hf, ← hy _ hf], refl } } end /-- The category of sheaves taking values in Type is the same as the category of set-valued sheaves. -/ @[simps] def Sheaf_equiv_SheafOfTypes : Sheaf J (Type w) ≌ SheafOfTypes J := { functor := { obj := λ S, ⟨S.val, (is_sheaf_iff_is_sheaf_of_type _ _).1 S.2⟩, map := λ S T f, ⟨f.val⟩ }, inverse := { obj := λ S, ⟨S.val, (is_sheaf_iff_is_sheaf_of_type _ _ ).2 S.2⟩, map := λ S T f, ⟨f.val⟩ }, unit_iso := nat_iso.of_components (λ X, ⟨⟨𝟙 _⟩, ⟨𝟙 _⟩, by tidy, by tidy⟩) (by tidy), counit_iso := nat_iso.of_components (λ X, ⟨⟨𝟙 _⟩, ⟨𝟙 _⟩, by tidy, by tidy⟩) (by tidy) } instance : inhabited (Sheaf (⊥ : grothendieck_topology C) (Type w)) := ⟨(Sheaf_equiv_SheafOfTypes _).inverse.obj default⟩ variables {J} {A} /-- If the empty sieve is a cover of `X`, then `F(X)` is terminal. -/ def Sheaf.is_terminal_of_bot_cover (F : Sheaf J A) (X : C) (H : ⊥ ∈ J X) : is_terminal (F.1.obj (op X)) := begin apply_with is_terminal.of_unique { instances := ff }, intro Y, choose t h using F.2 Y _ H (by tidy) (by tidy), exact ⟨⟨t⟩, λ a, h.2 a (by tidy)⟩ end end category_theory namespace category_theory open opposite category_theory category limits sieve namespace presheaf -- Under here is the equalizer story, which is equivalent if A has products (and doesn't -- make sense otherwise). It's described in https://stacks.math.columbia.edu/tag/00VL, -- between 00VQ and 00VR. variables {C : Type u₁} [category.{v₁} C] variables {A : Type u₂} [category.{max v₁ u₁} A] variables (J : grothendieck_topology C) variables {U : C} (R : presieve U) variables (P : Cᵒᵖ ⥤ A) section multiequalizer_conditions /-- When `P` is a sheaf and `S` is a cover, the associated multifork is a limit. -/ def is_limit_of_is_sheaf {X : C} (S : J.cover X) (hP : is_sheaf J P) : is_limit (S.multifork P) := { lift := λ (E : multifork _), hP.amalgamate S (λ I, E.ι _) (λ I, E.condition _), fac' := begin rintros (E : multifork _) (a|b), { apply hP.amalgamate_map }, { rw [← E.w (walking_multicospan.hom.fst b), ← (S.multifork P).w (walking_multicospan.hom.fst b), ← assoc], congr' 1, apply hP.amalgamate_map } end, uniq' := begin rintros (E : multifork _) m hm, apply hP.hom_ext S, intros I, erw hm (walking_multicospan.left I), symmetry, apply hP.amalgamate_map end } lemma is_sheaf_iff_multifork : is_sheaf J P ↔ (∀ (X : C) (S : J.cover X), nonempty (is_limit (S.multifork P))) := begin refine ⟨λ hP X S, ⟨is_limit_of_is_sheaf _ _ _ hP⟩, _⟩, intros h E X S hS x hx, let T : J.cover X := ⟨S,hS⟩, obtain ⟨hh⟩ := h _ T, let K : multifork (T.index P) := multifork.of_ι _ E (λ I, x I.f I.hf) (λ I, hx _ _ _ _ I.w), use hh.lift K, dsimp, split, { intros Y f hf, apply hh.fac K (walking_multicospan.left ⟨Y,f,hf⟩) }, { intros e he, apply hh.uniq K, rintros (a|b), { apply he }, { rw [← K.w (walking_multicospan.hom.fst b), ← (T.multifork P).w (walking_multicospan.hom.fst b), ← assoc], congr' 1, apply he } } end lemma is_sheaf_iff_multiequalizer [∀ (X : C) (S : J.cover X), has_multiequalizer (S.index P)] : is_sheaf J P ↔ (∀ (X : C) (S : J.cover X), is_iso (S.to_multiequalizer P)) := begin rw is_sheaf_iff_multifork, refine forall₂_congr (λ X S, ⟨_, _⟩), { rintros ⟨h⟩, let e : P.obj (op X) ≅ multiequalizer (S.index P) := h.cone_point_unique_up_to_iso (limit.is_limit _), exact (infer_instance : is_iso e.hom) }, { introsI h, refine ⟨is_limit.of_iso_limit (limit.is_limit _) (cones.ext _ _)⟩, { apply (@as_iso _ _ _ _ _ h).symm }, { intros a, symmetry, erw is_iso.inv_comp_eq, change _ = limit.lift _ _ ≫ _, simp } } end end multiequalizer_conditions section variables [has_products.{(max u₁ v₁)} A] /-- The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of <https://stacks.math.columbia.edu/tag/00VM>. -/ def first_obj : A := ∏ (λ (f : Σ V, {f : V ⟶ U // R f}), P.obj (op f.1)) /-- The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of <https://stacks.math.columbia.edu/tag/00VM>. -/ def fork_map : P.obj (op U) ⟶ first_obj R P := pi.lift (λ f, P.map f.2.1.op) variables [has_pullbacks C] /-- The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which contains the data used to check a family of elements for a presieve is compatible. -/ def second_obj : A := ∏ (λ (fg : (Σ V, {f : V ⟶ U // R f}) × (Σ W, {g : W ⟶ U // R g})), P.obj (op (pullback fg.1.2.1 fg.2.2.1))) /-- The map `pr₀*` of <https://stacks.math.columbia.edu/tag/00VM>. -/ def first_map : first_obj R P ⟶ second_obj R P := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op) /-- The map `pr₁*` of <https://stacks.math.columbia.edu/tag/00VM>. -/ def second_map : first_obj R P ⟶ second_obj R P := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op) lemma w : fork_map R P ≫ first_map R P = fork_map R P ≫ second_map R P := begin apply limit.hom_ext, rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩, simp only [first_map, second_map, fork_map, limit.lift_π, limit.lift_π_assoc, assoc, fan.mk_π_app, subtype.coe_mk, subtype.val_eq_coe], rw [← P.map_comp, ← op_comp, pullback.condition], simp, end /-- An alternative definition of the sheaf condition in terms of equalizers. This is shown to be equivalent in `category_theory.presheaf.is_sheaf_iff_is_sheaf'`. -/ def is_sheaf' (P : Cᵒᵖ ⥤ A) : Prop := ∀ (U : C) (R : presieve U) (hR : generate R ∈ J U), nonempty (is_limit (fork.of_ι _ (w R P))) /-- (Implementation). An auxiliary lemma to convert between sheaf conditions. -/ def is_sheaf_for_is_sheaf_for' (P : Cᵒᵖ ⥤ A) (s : A ⥤ Type (max v₁ u₁)) [Π J, preserves_limits_of_shape (discrete.{max v₁ u₁} J) s] (U : C) (R : presieve U) : is_limit (s.map_cone (fork.of_ι _ (w R P))) ≃ is_limit (fork.of_ι _ (equalizer.presieve.w (P ⋙ s) R)) := begin apply equiv.trans (is_limit_map_cone_fork_equiv _ _) _, apply (is_limit.postcompose_hom_equiv _ _).symm.trans (is_limit.equiv_iso_limit _), { apply nat_iso.of_components _ _, { rintro (_ | _), { apply preserves_product.iso s }, { apply preserves_product.iso s } }, { rintro _ _ (_ | _), { ext : 1, dsimp [equalizer.presieve.first_map, first_map], simp only [limit.lift_π, map_lift_pi_comparison, assoc, fan.mk_π_app, functor.map_comp], erw pi_comparison_comp_π_assoc }, { ext : 1, dsimp [equalizer.presieve.second_map, second_map], simp only [limit.lift_π, map_lift_pi_comparison, assoc, fan.mk_π_app, functor.map_comp], erw pi_comparison_comp_π_assoc }, { dsimp, simp } } }, { refine fork.ext (iso.refl _) _, dsimp [equalizer.fork_map, fork_map], simp [fork.ι] } end /-- The equalizer definition of a sheaf given by `is_sheaf'` is equivalent to `is_sheaf`. -/ theorem is_sheaf_iff_is_sheaf' : is_sheaf J P ↔ is_sheaf' J P := begin split, { intros h U R hR, refine ⟨_⟩, apply coyoneda_jointly_reflects_limits, intro X, have q : presieve.is_sheaf_for (P ⋙ coyoneda.obj X) _ := h X.unop _ hR, rw ←presieve.is_sheaf_for_iff_generate at q, rw equalizer.presieve.sheaf_condition at q, replace q := classical.choice q, apply (is_sheaf_for_is_sheaf_for' _ _ _ _).symm q }, { intros h U X S hS, rw equalizer.presieve.sheaf_condition, refine ⟨_⟩, refine is_sheaf_for_is_sheaf_for' _ _ _ _ _, letI := preserves_smallest_limits_of_preserves_limits (coyoneda.obj (op U)), apply is_limit_of_preserves, apply classical.choice (h _ S _), simpa } end end section concrete variables [has_pullbacks C] /-- For a concrete category `(A, s)` where the forgetful functor `s : A ⥤ Type v` preserves limits and reflects isomorphisms, and `A` has limits, an `A`-valued presheaf `P : Cᵒᵖ ⥤ A` is a sheaf iff its underlying `Type`-valued presheaf `P ⋙ s : Cᵒᵖ ⥤ Type` is a sheaf. Note this lemma applies for "algebraic" categories, eg groups, abelian groups and rings, but not for the category of topological spaces, topological rings, etc since reflecting isomorphisms doesn't hold. -/ lemma is_sheaf_iff_is_sheaf_forget (s : A ⥤ Type (max v₁ u₁)) [has_limits A] [preserves_limits s] [reflects_isomorphisms s] : is_sheaf J P ↔ is_sheaf J (P ⋙ s) := begin rw [is_sheaf_iff_is_sheaf', is_sheaf_iff_is_sheaf'], apply forall_congr (λ U, _), apply ball_congr (λ R hR, _), letI : reflects_limits s := reflects_limits_of_reflects_isomorphisms, have : is_limit (s.map_cone (fork.of_ι _ (w R P))) ≃ is_limit (fork.of_ι _ (w R (P ⋙ s))) := is_sheaf_for_is_sheaf_for' P s U R, rw ←equiv.nonempty_congr this, split, { haveI := preserves_smallest_limits_of_preserves_limits s, exact nonempty.map (λ t, is_limit_of_preserves s t) }, { haveI := reflects_smallest_limits_of_reflects_limits s, exact nonempty.map (λ t, is_limit_of_reflects s t) } end end concrete end presheaf end category_theory
b0b8b038f378290e96d58afcc471b4734c8f3ec7
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/adjunction/whiskering.lean
16dc8b4da632e9d6df081d61b541c6b039980b4d
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,490
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.adjunction import category_theory.whiskering /-! Given categories `C D E`, functors `F : D ⥤ E` and `G : E ⥤ D` with an adjunction `F ⊣ G`, we provide the induced adjunction between the functor categories `C ⥤ D` and `C ⥤ E`, and the functor categories `E ⥤ C` and `D ⥤ C`. -/ namespace category_theory.adjunction open category_theory variables (C : Type*) {D E : Type*} [category C] [category D] [category E] {F : D ⥤ E} {G : E ⥤ D} -- `tidy` works for all the proofs in this definition, but it's fairly slow. /-- Given an adjunction `F ⊣ G`, this provides the natural adjunction `(whiskering_right C _ _).obj F ⊣ (whiskering_right C _ _).obj G`. -/ @[simps unit_app_app counit_app_app] protected def whisker_right (adj : F ⊣ G) : (whiskering_right C D E).obj F ⊣ (whiskering_right C E D).obj G := mk_of_unit_counit { unit := { app := λ X, (functor.right_unitor _).inv ≫ whisker_left X adj.unit ≫ (functor.associator _ _ _).inv, naturality' := by { intros, ext, dsimp, simp } }, counit := { app := λ X, (functor.associator _ _ _).hom ≫ whisker_left X adj.counit ≫ (functor.right_unitor _).hom, naturality' := by { intros, ext, dsimp, simp } }, left_triangle' := by { ext, dsimp, simp }, right_triangle' := by { ext, dsimp, simp } } -- `tidy` gets stuck for `left_triangle'` and `right_triangle'`. /-- Given an adjunction `F ⊣ G`, this provides the natural adjunction `(whiskering_left _ _ C).obj G ⊣ (whiskering_left _ _ C).obj F`. -/ @[simps unit_app_app counit_app_app] protected def whisker_left (adj : F ⊣ G) : (whiskering_left E D C).obj G ⊣ (whiskering_left D E C).obj F := mk_of_unit_counit { unit := { app := λ X, (functor.left_unitor _).inv ≫ whisker_right adj.unit X ≫ (functor.associator _ _ _).hom, naturality' := by { intros, ext, dsimp, simp } }, counit := { app := λ X, (functor.associator _ _ _).inv ≫ whisker_right adj.counit X ≫ (functor.left_unitor _).hom, naturality' := by { intros, ext, dsimp, simp } }, left_triangle' := by { ext x, dsimp, simp only [category.id_comp, category.comp_id, ← x.map_comp], simp }, right_triangle' := by { ext x, dsimp, simp only [category.id_comp, category.comp_id, ← x.map_comp], simp } } end category_theory.adjunction
c75c28c4a543ef3b896ce186ed5e5228c4ea87da
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/completion7.lean
2ff061d568a89f0d78f42e0776fe5c71671cd38c
[ "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
155
lean
prelude structure And where left : Type right : Type #check And --^ textDocument/completion #check And. --^ textDocument/completion
051f97c0ed5eec179f4c343d6ecd929422316240
367134ba5a65885e863bdc4507601606690974c1
/src/group_theory/group_action/group.lean
8da3371689cb4ad4dde47896b42d6515d997e088
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
3,906
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 group_theory.group_action.defs import algebra.group.units import algebra.group_with_zero import data.equiv.mul_add import group_theory.perm.basic /-! # Group actions applied to various types of group This file contains lemmas about `smul` on `units`, `group_with_zero`, and `group`. -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section mul_action section units variables [monoid α] [mul_action α β] @[simp] lemma units.inv_smul_smul (u : units α) (x : β) : (↑u⁻¹:α) • (u:α) • x = x := by rw [smul_smul, u.inv_mul, one_smul] @[simp] lemma units.smul_inv_smul (u : units α) (x : β) : (u:α) • (↑u⁻¹:α) • x = x := by rw [smul_smul, u.mul_inv, one_smul] /-- If a monoid `α` acts on `β`, then each `u : units α` defines a permutation of `β`. -/ def units.smul_perm_hom : units α →* equiv.perm β := { to_fun := λ u, ⟨λ x, (u:α) • x, λ x, (↑u⁻¹:α) • x, u.inv_smul_smul, u.smul_inv_smul⟩, map_one' := equiv.ext $ one_smul α, map_mul' := λ u₁ u₂, equiv.ext $ mul_smul (u₁:α) u₂ } @[simp] lemma units.smul_left_cancel (u : units α) {x y : β} : (u:α) • x = (u:α) • y ↔ x = y := u.smul_perm_hom.apply_eq_iff_eq lemma units.smul_eq_iff_eq_inv_smul (u : units α) {x y : β} : (u:α) • x = y ↔ x = (↑u⁻¹:α) • y := u.smul_perm_hom.apply_eq_iff_eq_symm_apply lemma is_unit.smul_left_cancel {a : α} (ha : is_unit a) {x y : β} : a • x = a • y ↔ x = y := let ⟨u, hu⟩ := ha in hu ▸ u.smul_left_cancel end units section gwz variables [group_with_zero α] [mul_action α β] @[simp] lemma inv_smul_smul' {c : α} (hc : c ≠ 0) (x : β) : c⁻¹ • c • x = x := (units.mk0 c hc).inv_smul_smul x @[simp] lemma smul_inv_smul' {c : α} (hc : c ≠ 0) (x : β) : c • c⁻¹ • x = x := (units.mk0 c hc).smul_inv_smul x lemma inv_smul_eq_iff' {a : α} (ha : a ≠ 0) {x y : β} : a⁻¹ • x = y ↔ x = a • y := by { split; intro h, rw [← h, smul_inv_smul' ha], rw [h, inv_smul_smul' ha] } lemma eq_inv_smul_iff' {a : α} (ha : a ≠ 0) {x y : β} : x = a⁻¹ • y ↔ a • x = y := by { split; intro h, rw [h, smul_inv_smul' ha], rw [← h, inv_smul_smul' ha] } end gwz section group variables [group α] [mul_action α β] @[simp] lemma inv_smul_smul (c : α) (x : β) : c⁻¹ • c • x = x := (to_units c).inv_smul_smul x @[simp] lemma smul_inv_smul (c : α) (x : β) : c • c⁻¹ • x = x := (to_units c).smul_inv_smul x lemma inv_smul_eq_iff {a : α} {x y : β} : a⁻¹ • x = y ↔ x = a • y := begin split; rintro rfl, {rw smul_inv_smul}, {rw inv_smul_smul}, end lemma eq_inv_smul_iff {a : α} {x y : β} : x = a⁻¹ • y ↔ a • x = y := begin split; rintro rfl, {rw smul_inv_smul}, {rw inv_smul_smul}, end variables (α) (β) /-- Given an action of a group `α` on a set `β`, each `g : α` defines a permutation of `β`. -/ def mul_action.to_perm : α →* equiv.perm β := units.smul_perm_hom.comp to_units.to_monoid_hom variables {α} {β} protected lemma mul_action.bijective (g : α) : function.bijective (λ b : β, g • b) := (mul_action.to_perm α β g).bijective end group end mul_action section distrib_mul_action variables [monoid α] [add_monoid β] [distrib_mul_action α β] theorem units.smul_eq_zero (u : units α) {x : β} : (u : α) • x = 0 ↔ x = 0 := ⟨λ h, by rw [← u.inv_smul_smul x, h, smul_zero], λ h, h.symm ▸ smul_zero _⟩ theorem units.smul_ne_zero (u : units α) {x : β} : (u : α) • x ≠ 0 ↔ x ≠ 0 := not_congr u.smul_eq_zero @[simp] theorem is_unit.smul_eq_zero {u : α} (hu : is_unit u) {x : β} : u • x = 0 ↔ x = 0 := exists.elim hu $ λ u hu, hu ▸ u.smul_eq_zero end distrib_mul_action
4041f2d9e8022f9b0ee15d40022bdca198c36106
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/Meta/KAbstract.lean
9ea5623f510c21b3dafefa3f93a45d385f940263
[ "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
1,793
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.ExprDefEq namespace Lean namespace Meta private partial def kabstractAux (occs : Occurrences) (p : Expr) (pHeadIdx : HeadIndex) (pNumArgs : Nat) : Expr → Nat → StateRefT Nat MetaM Expr | e, offset => let visitChildren : Unit → StateRefT Nat MetaM Expr := fun _ => match e with | Expr.app f a _ => do f ← kabstractAux f offset; a ← kabstractAux a offset; pure $ e.updateApp! f a | Expr.mdata _ b _ => do b ← kabstractAux b offset; pure $ e.updateMData! b | Expr.proj _ _ b _ => do b ← kabstractAux b offset; pure $ e.updateProj! b | Expr.letE _ t v b _ => do t ← kabstractAux t offset; v ← kabstractAux v offset; b ← kabstractAux b (offset+1); pure $ e.updateLet! t v b | Expr.lam _ d b _ => do d ← kabstractAux d offset; b ← kabstractAux b (offset+1); pure $ e.updateLambdaE! d b | Expr.forallE _ d b _ => do d ← kabstractAux d offset; b ← kabstractAux b (offset+1); pure $ e.updateForallE! d b | e => pure e; if e.hasLooseBVars then visitChildren () else if e.toHeadIndex == pHeadIdx && e.headNumArgs == pNumArgs then condM (isDefEq e p) (do i ← get; set (i+1); if occs.contains i then pure (mkBVar offset) else visitChildren ()) (visitChildren ()) else visitChildren () def kabstract {m} [MonadLiftT MetaM m] (e : Expr) (p : Expr) (occs : Occurrences := Occurrences.all) : m Expr := liftMetaM do (kabstractAux occs p p.toHeadIndex p.headNumArgs e 0).run' 1 end Meta end Lean
7cca4d1ac4d35f54fc9584d17d56e0214ec2c034
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Std/Data/Stack.lean
0de62ab5e7d5520e0dd34dc763245bbaee1015d8
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
900
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam Simple stack API implemented using an array. -/ namespace Std universes u v w structure Stack (α : Type u) := (vals : Array α := #[]) namespace Stack variable {α : Type u} def empty : Stack α := {} def isEmpty (s : Stack α) : Bool := s.vals.isEmpty def push (v : α) (s : Stack α) : Stack α := { s with vals := s.vals.push v } def peek? (s : Stack α) : Option α := if s.vals.isEmpty then none else s.vals.get? (s.vals.size-1) def peek! [Inhabited α] (s : Stack α) : α := s.vals.back def pop [Inhabited α] (s : Stack α) : Stack α := { s with vals := s.vals.pop } def modify [Inhabited α] (s : Stack α) (f : α → α) : Stack α := { s with vals := s.vals.modify (s.vals.size-1) f } end Stack end Std
b9371dcc0bbb59ace91e83c3e6f87ebebdf77516
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/gcd_domain.lean
2ad4bb211c1beef31c56b977de0bcae018c1a43d
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
28,392
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 GCD domain and integral domains with normalization functions TODO: abstract the domains to semi domains (i.e. domains on semirings) to include ℕ and ℕ[X] etc. -/ import algebra.associated import data.nat.basic import data.int.gcd variables {α : Type*} set_option old_structure_cmd true section prio set_option default_priority 100 -- see Note [default priority] /-- Normalization domain: multiplying with `norm_unit` gives a normal form for associated elements. -/ @[protect_proj] class normalization_domain (α : Type*) extends integral_domain α := (norm_unit : α → units α) (norm_unit_zero : norm_unit 0 = 1) (norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b) (norm_unit_coe_units : ∀(u : units α), norm_unit u = u⁻¹) end prio export normalization_domain (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units) attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul section normalization_domain variable [normalization_domain α] def normalize (x : α) : α := x * norm_unit x theorem associated_normalize {x : α} : associated x (normalize x) := ⟨_, rfl⟩ theorem normalize_associated {x : α} : associated (normalize x) x := associated_normalize.symm @[simp] theorem norm_unit_one : norm_unit (1:α) = 1 := norm_unit_coe_units 1 @[simp] lemma normalize_zero : normalize (0 : α) = 0 := by rw [normalize, zero_mul] @[simp] lemma normalize_one : normalize (1 : α) = 1 := by rw [normalize, norm_unit_one, units.coe_one, mul_one] lemma normalize_coe_units (u : units α) : normalize (u : α) = 1 := by rw [normalize, norm_unit_coe_units, ← units.coe_mul, mul_inv_self, units.coe_one] theorem normalize_mul (x y : α) : normalize (x * y) = normalize x * normalize y := classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, normalize_zero, zero_mul]) $ λ hx, classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, normalize_zero, mul_zero]) $ λ hy, by simp only [normalize, norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y] lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 := ⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize, by rintro rfl; exact normalize_zero⟩ lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x := ⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu ▸ normalize_coe_units u⟩ theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 := classical.by_cases (assume : a = 0, by simp only [this, norm_unit_zero, zero_mul]) $ assume h, by rw [norm_unit_mul h (units.coe_ne_zero _), norm_unit_coe_units, mul_inv_eq_one] theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by rw [normalize, normalize, norm_unit_mul_norm_unit, units.coe_one, mul_one] theorem normalize_eq_normalize {a b : α} (hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b := begin rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩, refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _), suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹, by simpa only [normalize, mul_assoc, norm_unit_mul ha u.coe_ne_zero, norm_unit_coe_units], calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹: (units.mul_inv_cancel_right _ _).symm ... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a end lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x := ⟨λ h, ⟨dvd_mul_unit_iff.1 ⟨_, h.symm⟩, dvd_mul_unit_iff.1 ⟨_, h⟩⟩, λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩ theorem dvd_antisymm_of_normalize_eq {a b : α} (ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) : a = b := ha ▸ hb ▸ normalize_eq_normalize hab hba @[simp] lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b := dvd_mul_unit_iff @[simp] lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b := mul_unit_dvd_iff end normalization_domain namespace associates variable [normalization_domain α] local attribute [instance] associated.setoid protected def out : associates α → α := quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸ normalize_eq_normalize ⟨_, rfl⟩ (mul_unit_dvd_iff.2 $ dvd_refl a) lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl @[simp] lemma out_one : (1 : associates α).out = 1 := normalize_one lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out := quotient.induction_on₂ a b $ assume a b, by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize_mul] lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] @[simp] lemma out_top : (⊤ : associates α).out = 0 := normalize_zero @[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out := quotient.induction_on a normalize_idem end associates section prio set_option default_priority 100 -- see Note [default priority] /-- GCD domain: an integral domain with normalization and `gcd` (greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and `lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the correpsonding `lcm` facts from `gcd`. -/ @[protect_proj] class gcd_domain (α : Type*) extends normalization_domain α := (gcd : α → α → α) (lcm : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) (gcd_mul_lcm : ∀a b, gcd a b * lcm a b = normalize (a * b)) (lcm_zero_left : ∀a, lcm 0 a = 0) (lcm_zero_right : ∀a, lcm a 0 = 0) end prio export gcd_domain (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right) attribute [simp] lcm_zero_left lcm_zero_right section gcd_domain variables [gcd_domain α] @[simp] theorem normalize_gcd : ∀a b:α, normalize (gcd a b) = gcd a b := gcd_domain.normalize_gcd @[simp] theorem gcd_mul_lcm : ∀a b:α, gcd a b * lcm a b = normalize (a * b) := gcd_domain.gcd_mul_lcm section gcd theorem dvd_gcd_iff (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) := iff.intro (assume h, ⟨dvd_trans h (gcd_dvd_left _ _), dvd_trans h (gcd_dvd_right _ _)⟩) (assume ⟨hab, hac⟩, dvd_gcd hab hac) theorem gcd_comm (a b : α) : gcd a b = gcd b a := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) theorem gcd_assoc (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) instance : is_commutative α gcd := ⟨gcd_comm⟩ instance : is_associative α gcd := ⟨gcd_assoc⟩ theorem gcd_eq_normalize {a b c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) : gcd a b = normalize c := normalize_gcd a b ▸ normalize_eq_normalize habc hcab @[simp] theorem gcd_zero_left (a : α) : gcd 0 a = normalize a := gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a)) @[simp] theorem gcd_zero_right (a : α) : gcd a 0 = normalize a := gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _)) @[simp] theorem gcd_eq_zero_iff (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩) (assume ⟨ha, hb⟩, by rw [ha, hb, gcd_zero_left, normalize_zero]) @[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _) @[simp] theorem gcd_one_right (a : α) : gcd a 1 = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _) theorem gcd_dvd_gcd {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d := dvd_gcd (dvd.trans (gcd_dvd_left _ _) hab) (dvd.trans (gcd_dvd_right _ _) hcd) @[simp] theorem gcd_same (a : α) : gcd a a = normalize a := gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a)) @[simp] theorem gcd_mul_left (a b c : α) : gcd (a * b) (a * c) = normalize a * gcd b c := classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices gcd (a * b) (a * c) = normalize (a * gcd b c), by simpa only [normalize_mul, normalize_gcd], let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in gcd_eq_normalize (eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from dvd_gcd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _)) (dvd_gcd (mul_dvd_mul_left a $ gcd_dvd_left _ _) (mul_dvd_mul_left a $ gcd_dvd_right _ _)) @[simp] theorem gcd_mul_right (a b c : α) : gcd (b * a) (c * a) = gcd b c * normalize a := by simp only [mul_comm, gcd_mul_left] theorem gcd_eq_left_iff (a b : α) (h : normalize a = a) : gcd a b = a ↔ a ∣ b := iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) hab) theorem gcd_eq_right_iff (a b : α) (h : normalize b = b) : gcd a b = b ↔ b ∣ a := by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h theorem gcd_dvd_gcd_mul_left (m n k : α) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd (dvd_mul_left _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_right (m n k : α) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd (dvd_mul_right _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_left_right (m n k : α) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : α) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_right _ _) end gcd section lcm lemma lcm_dvd_iff {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c := classical.by_cases (assume : a = 0 ∨ b = 0, by rcases this with rfl | rfl; simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero, eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt}) (assume this : ¬ (a = 0 ∨ b = 0), let ⟨h1, h2⟩ := not_or_distrib.1 this in have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1, by rw [← mul_dvd_mul_iff_left h, gcd_mul_lcm, normalize_dvd_iff, ← dvd_normalize_iff, normalize_mul, normalize_gcd, ← gcd_mul_right, dvd_gcd_iff, mul_comm b c, mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm]) lemma dvd_lcm_left (a b : α) : a ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).1 lemma dvd_lcm_right (a b : α) : b ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).2 lemma lcm_dvd {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b := lcm_dvd_iff.2 ⟨hab, hcb⟩ @[simp] theorem lcm_eq_zero_iff (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 := iff.intro (assume h : lcm a b = 0, have normalize (a * b) = 0, by rw [← gcd_mul_lcm _ _, h, mul_zero], by simpa only [normalize_eq_zero, mul_eq_zero, units.coe_ne_zero, or_false]) (by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right]) @[simp] lemma normalize_lcm (a b : α) : normalize (lcm a b) = lcm a b := classical.by_cases (assume : lcm a b = 0, by rw [this, normalize_zero]) $ assume h_lcm : lcm a b ≠ 0, have h1 : gcd a b ≠ 0, from mt (by rw [gcd_eq_zero_iff, lcm_eq_zero_iff]; rintros ⟨rfl, rfl⟩; left; refl) h_lcm, have h2 : normalize (gcd a b * lcm a b) = gcd a b * lcm a b, by rw [gcd_mul_lcm, normalize_idem], by simpa only [normalize_mul, normalize_gcd, one_mul, mul_right_inj' h1] using h2 theorem lcm_comm (a b : α) : lcm a b = lcm b a := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) theorem lcm_assoc (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (lcm_dvd (dvd_lcm_left _ _) (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_right _ _))) (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_right _ _))) (lcm_dvd (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (dvd_lcm_right _ _))) instance : is_commutative α lcm := ⟨lcm_comm⟩ instance : is_associative α lcm := ⟨lcm_assoc⟩ lemma lcm_eq_normalize {a b c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) : lcm a b = normalize c := normalize_lcm a b ▸ normalize_eq_normalize habc hcab theorem lcm_dvd_lcm {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) : lcm a c ∣ lcm b d := lcm_dvd (dvd.trans hab (dvd_lcm_left _ _)) (dvd.trans hcd (dvd_lcm_right _ _)) @[simp] theorem lcm_units_coe_left (u : units α) (a : α) : lcm ↑u a = normalize a := lcm_eq_normalize (lcm_dvd (units.coe_dvd _ _) (dvd_refl _)) (dvd_lcm_right _ _) @[simp] theorem lcm_units_coe_right (a : α) (u : units α) : lcm a ↑u = normalize a := (lcm_comm a u).trans $ lcm_units_coe_left _ _ @[simp] theorem lcm_one_left (a : α) : lcm 1 a = normalize a := lcm_units_coe_left 1 a @[simp] theorem lcm_one_right (a : α) : lcm a 1 = normalize a := lcm_units_coe_right a 1 @[simp] theorem lcm_same (a : α) : lcm a a = normalize a := lcm_eq_normalize (lcm_dvd (dvd_refl _) (dvd_refl _)) (dvd_lcm_left _ _) @[simp] theorem lcm_eq_one_iff (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 := iff.intro (assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩) (assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩, show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1, by rw [lcm_units_coe_left, normalize_coe_units]) @[simp] theorem lcm_mul_left (a b c : α) : lcm (a * b) (a * c) = normalize a * lcm b c := classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices lcm (a * b) (a * c) = normalize (a * lcm b c), by simpa only [normalize_mul, normalize_lcm], have a ∣ lcm (a * b) (a * c), from dvd.trans (dvd_mul_right _ _) (dvd_lcm_left _ _), let ⟨d, eq⟩ := this in lcm_eq_normalize (lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _))) (eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _))) @[simp] theorem lcm_mul_right (a b c : α) : lcm (b * a) (c * a) = lcm b c * normalize a := by simp only [mul_comm, lcm_mul_left] theorem lcm_eq_left_iff (a b : α) (h : normalize a = a) : lcm a b = a ↔ b ∣ a := iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab) (dvd_lcm_left _ _) theorem lcm_eq_right_iff (a b : α) (h : normalize b = b) : lcm a b = b ↔ a ∣ b := by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h theorem lcm_dvd_lcm_mul_left (m n k : α) : lcm m n ∣ lcm (k * m) n := lcm_dvd_lcm (dvd_mul_left _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_right (m n k : α) : lcm m n ∣ lcm (m * k) n := lcm_dvd_lcm (dvd_mul_right _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_left_right (m n k : α) : lcm m n ∣ lcm m (k * n) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_left _ _) theorem lcm_dvd_lcm_mul_right_right (m n k : α) : lcm m n ∣ lcm m (n * k) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_right _ _) end lcm end gcd_domain namespace int section normalization_domain instance : normalization_domain ℤ := { norm_unit := λa:ℤ, if 0 ≤ a then 1 else -1, norm_unit_zero := if_pos (le_refl _), norm_unit_mul := assume a b hna hnb, begin by_cases ha : 0 ≤ a; by_cases hb : 0 ≤ b; simp [ha, hb], exact if_pos (mul_nonneg ha hb), exact if_neg (assume h, hb $ nonneg_of_mul_nonneg_left h $ lt_of_le_of_ne ha hna.symm), exact if_neg (assume h, ha $ nonneg_of_mul_nonneg_right h $ lt_of_le_of_ne hb hnb.symm), exact if_pos (mul_nonneg_of_nonpos_of_nonpos (le_of_not_ge ha) (le_of_not_ge hb)) end, norm_unit_coe_units := assume u, (units_eq_one_or u).elim (assume eq, eq.symm ▸ if_pos zero_le_one) (assume eq, eq.symm ▸ if_neg (not_le_of_gt $ show (-1:ℤ) < 0, by simp [@neg_lt ℤ _ 1 0])), .. (infer_instance : integral_domain ℤ) } lemma normalize_of_nonneg {z : ℤ} (h : 0 ≤ z) : normalize z = z := show z * ↑(ite _ _ _) = z, by rw [if_pos h, units.coe_one, mul_one] lemma normalize_of_neg {z : ℤ} (h : z < 0) : normalize z = -z := show z * ↑(ite _ _ _) = -z, by rw [if_neg (not_le_of_gt h), units.coe_neg, units.coe_one, mul_neg_one] lemma normalize_coe_nat (n : ℕ) : normalize (n : ℤ) = n := normalize_of_nonneg (coe_nat_le_coe_nat_of_le $ nat.zero_le n) theorem coe_nat_abs_eq_normalize (z : ℤ) : (z.nat_abs : ℤ) = normalize z := begin by_cases 0 ≤ z, { simp [nat_abs_of_nonneg h, normalize_of_nonneg h] }, { simp [of_nat_nat_abs_of_nonpos (le_of_not_ge h), normalize_of_neg (lt_of_not_ge h)] } end end normalization_domain /-- ℤ 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 section gcd_domain 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] instance : gcd_domain ℤ := { gcd := λa b, int.gcd a b, lcm := λa b, int.lcm a b, gcd_dvd_left := assume a b, int.gcd_dvd_left _ _, gcd_dvd_right := assume a b, int.gcd_dvd_right _ _, dvd_gcd := assume a b c, dvd_gcd, normalize_gcd := assume a b, normalize_coe_nat _, gcd_mul_lcm := by intros; rw [← int.coe_nat_mul, gcd_mul_lcm, coe_nat_abs_eq_normalize], lcm_zero_left := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_left _, lcm_zero_right := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_right _, .. int.normalization_domain } lemma coe_gcd (i j : ℤ) : ↑(int.gcd i j) = gcd_domain.gcd i j := rfl lemma coe_lcm (i j : ℤ) : ↑(int.lcm i j) = gcd_domain.lcm i j := rfl lemma nat_abs_gcd (i j : ℤ) : nat_abs (gcd_domain.gcd i j) = int.gcd i j := rfl lemma nat_abs_lcm (i j : ℤ) : nat_abs (gcd_domain.lcm i j) = int.lcm i j := rfl end gcd_domain 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 simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] theorem gcd_mul_right (i j k : ℤ) : gcd (i * j) (k * j) = gcd i k * nat_abs j := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] 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 := by rw [← int.coe_nat_eq_coe_nat_iff, int.coe_nat_zero, coe_gcd, gcd_eq_zero_iff] 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 simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_comm] theorem lcm_assoc (i j k : ℤ) : lcm (lcm i j) k = lcm i (lcm j k) := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_assoc] @[simp] theorem lcm_zero_left (i : ℤ) : lcm 0 i = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_zero_right (i : ℤ) : lcm i 0 = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_one_left (i : ℤ) : lcm 1 i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_one_right (i : ℤ) : lcm i 1 = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_self (i : ℤ) : lcm i i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] theorem dvd_lcm_left (i j : ℤ) : i ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_left _ _ theorem dvd_lcm_right (i j : ℤ) : j ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_right _ _ theorem lcm_dvd {i j k : ℤ} : i ∣ k → j ∣ k → (lcm i j : ℤ) ∣ k := by rw [coe_lcm]; exact lcm_dvd end int theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a | 0 := by simp [nat.not_prime_zero] | 1 := by simp [nat.prime, one_lt_two] | (n + 2) := have h₁ : ¬n + 2 = 1, from dec_trivial, begin simp [h₁, nat.prime, irreducible, (≥), nat.le_add_left 2 n, (∣)], refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _), by_cases a = 1; simp [h], split, { assume hb, simpa [hb] using hab.symm }, { assume ha, subst ha, have : n + 2 > 0, from dec_trivial, refine nat.eq_of_mul_eq_mul_left this _, rw [← hab, mul_one] } end lemma nat.prime_iff_prime {p : ℕ} : p.prime ↔ _root_.prime (p : ℕ) := ⟨λ hp, ⟨nat.pos_iff_ne_zero.1 hp.pos, mt is_unit_iff_dvd_one.1 hp.not_dvd_one, λ a b, hp.dvd_mul.1⟩, λ hp, ⟨nat.one_lt_iff_ne_zero_and_ne_one.2 ⟨hp.1, λ h1, hp.2.1 $ h1.symm ▸ is_unit_one⟩, λ a h, let ⟨b, hab⟩ := h in (hp.2.2 a b (hab ▸ dvd_refl _)).elim (λ ha, or.inr (nat.dvd_antisymm h ha)) (λ hb, or.inl (have hpb : p = b, from nat.dvd_antisymm hb (hab.symm ▸ dvd_mul_left _ _), (nat.mul_right_inj (show 0 < p, from nat.pos_of_ne_zero hp.1)).1 $ by rw [hpb, mul_comm, ← hab, hpb, mul_one]))⟩⟩ lemma nat.prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) := ⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt is_unit_int.1 hp.ne_one, λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h; rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩, λ hp, nat.prime_iff_prime.2 ⟨int.coe_nat_ne_zero.1 hp.1, mt nat.is_unit_iff.1 $ λ h, by simpa [h, not_prime_one] using hp, λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩ def associates_int_equiv_nat : associates ℤ ≃ ℕ := begin refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩, { refine (assume a, quotient.induction_on' a $ assume a, associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩), show normalize a = int.nat_abs (normalize a), rw [int.coe_nat_abs_eq_normalize, normalize_idem] }, { assume n, show int.nat_abs (normalize n) = n, rw [← int.coe_nat_abs_eq_normalize, int.nat_abs_of_nat, int.nat_abs_of_nat] } end lemma int.prime.dvd_mul {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : p ∣ m.nat_abs ∨ p ∣ n.nat_abs := begin apply (nat.prime.dvd_mul hp).mp, rw ← int.nat_abs_mul, exact int.coe_nat_dvd_left.mp h end lemma int.prime.dvd_mul' {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : (p : ℤ) ∣ m ∨ (p : ℤ) ∣ n := begin rw [int.coe_nat_dvd_left, int.coe_nat_dvd_left], exact int.prime.dvd_mul hp h end lemma prime_two_or_dvd_of_dvd_two_mul_pow_self_two {m : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ 2 * m ^ 2) : p = 2 ∨ p ∣ int.nat_abs m := begin cases int.prime.dvd_mul hp h with hp2 hpp, { apply or.intro_left, exact le_antisymm (nat.le_of_dvd two_pos hp2) (nat.prime.two_le hp) }, { apply or.intro_right, rw [pow_two, int.nat_abs_mul] at hpp, exact (or_self _).mp ((nat.prime.dvd_mul hp).mp hpp)} end
7420ec428b07663e79fd29a6b12c8fd5e5d5157f
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/meta/default.lean
6d327f2346308b7c5987e060572f32d397249b4a
[ "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
900
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.name init.meta.options init.meta.format init.meta.rb_map import init.meta.level init.meta.expr init.meta.environment init.meta.attribute import init.meta.tactic init.meta.contradiction_tactic init.meta.constructor_tactic import init.meta.injection_tactic init.meta.relation_tactics init.meta.fun_info import init.meta.congr_lemma init.meta.match_tactic init.meta.ac_tactics import init.meta.backward init.meta.rewrite_tactic import init.meta.mk_dec_eq_instance init.meta.mk_inhabited_instance import init.meta.simp_tactic init.meta.set_get_option_tactics import init.meta.interactive init.meta.converter init.meta.vm import init.meta.comp_value_tactics init.meta.smt import init.meta.async_tactic init.meta.ref
847c20e17ae359f6efe8fcc7e78bfaef01e11a77
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/lean/run/array1.lean
652065af4487bc2e84e0e2d074be5db20af4e7bb
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
557
lean
#check @Array.mk def v : Array Nat := @Array.mk Nat 10 (fun ⟨i, _⟩ => i) def w : Array Nat := (mkArray 9 1).push 3 def f : Fin w.sz → Nat := Array.casesOn w (fun _ f => f) def arraySum (a : Array Nat) : Nat := a.foldl Nat.add 0 #exit #eval mkArray 4 1 #eval Array.map (+10) v #eval f ⟨1, sorry⟩ #eval f ⟨9, sorry⟩ #eval (((mkArray 1 1).push 2).push 3).foldl 0 (+) #eval arraySum (mkArray 10 1) #eval (mkArray 10 1).data ⟨1, decTrivial⟩ + 20 #eval (mkArray 10 1).data ⟨2, decTrivial⟩ #eval (mkArray 10 3).data ⟨2, decTrivial⟩
5f3856f9e7c9ee904fca024ca9a0f6da12ad06b5
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/inductions.lean
22d2f03d1b60c6e5fbe8b01a0e7bc4f10737b40c
[ "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
6,531
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Damiano Testa, Jens Wagemaker -/ import data.nat.interval import data.polynomial.degree.definitions /-! # Induction on polynomials This file contains lemmas dealing with different flavours of induction on polynomials. -/ noncomputable theory open_locale classical big_operators polynomial open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section semiring variables [semiring R] {p q : R[X]} /-- `div_X p` returns a polynomial `q` such that `q * X + C (p.coeff 0) = p`. It can be used in a semiring where the usual division algorithm is not possible -/ def div_X (p : R[X]) : R[X] := ∑ n in Ico 0 p.nat_degree, monomial n (p.coeff (n + 1)) @[simp] lemma coeff_div_X : (div_X p).coeff n = p.coeff (n+1) := begin simp only [div_X, coeff_monomial, true_and, finset_sum_coeff, not_lt, mem_Ico, zero_le, finset.sum_ite_eq', ite_eq_left_iff], intro h, rw coeff_eq_zero_of_nat_degree_lt (nat.lt_succ_of_le h) end lemma div_X_mul_X_add (p : R[X]) : div_X p * X + C (p.coeff 0) = p := ext $ by rintro ⟨_|_⟩; simp [coeff_C, nat.succ_ne_zero, coeff_mul_X] @[simp] lemma div_X_C (a : R) : div_X (C a) = 0 := ext $ λ n, by simp [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 lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree := by haveI := nontrivial.of_polynomial_ne hp0; calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree : if h : degree p ≤ 0 then begin have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h], rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 $ by simp [h'])), end else have hXp0 : div_X p ≠ 0, by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h, have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa, have degree (C (p.coeff 0)) < degree (div_X p * X), from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le ... < 1 : dec_trivial ... = degree (X : R[X]) : degree_X.symm ... ≤ degree (div_X p * X) : by rw [← zero_add (degree X), degree_mul' this]; exact add_le_add (by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff]; exact λ h0, h (h0.symm ▸ degree_C_le)) le_rfl, by rw [degree_add_eq_left_of_degree_lt this]; exact degree_lt_degree_mul_X hXp0 ... = p.degree : congr_arg _ (div_X_mul_X_add _) /-- An induction principle for polynomials, valued in Sort* instead of Prop. -/ @[elab_as_eliminator] noncomputable def rec_on_horner {M : R[X] → Sort*} : Π (p : R[X]), M 0 → (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) → (Π p, p ≠ 0 → M p → M (p * X)) → M p | p := λ M0 MC MX, if hp : p = 0 then eq.rec_on hp.symm M0 else have wf : degree (div_X p) < degree p, from degree_div_X_lt hp, by rw [← div_X_mul_X_add p] at *; exact if hcp0 : coeff p 0 = 0 then by rw [hcp0, C_0, add_zero]; exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp) (rec_on_horner _ M0 MC MX) else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0 then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0 else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX)) using_well_founded {dec_tac := tactic.assumption} /-- A property holds for all polynomials of positive `degree` with coefficients in a semiring `R` if it holds for * `a * X`, with `a ∈ R`, * `p * X`, with `p ∈ R[X]`, * `p + a`, with `a ∈ R`, `p ∈ R[X]`, with appropriate restrictions on each term. See `nat_degree_ne_zero_induction_on` for a similar statement involving no explicit multiplication. -/ @[elab_as_eliminator] lemma degree_pos_induction_on {P : R[X] → Prop} (p : R[X]) (h0 : 0 < degree p) (hC : ∀ {a}, a ≠ 0 → P (C a * X)) (hX : ∀ {p}, 0 < degree p → P p → P (p * X)) (hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p := rec_on_horner p (λ h, by rw degree_zero at h; exact absurd h dec_trivial) (λ p a _ _ ih h0, have 0 < degree p, from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $ by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0), hadd this (ih this)) (λ p _ ih h0', if h0 : 0 < degree p then hX h0 (ih h0) else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *; exact hC (λ h : coeff p 0 = 0, by simpa [h, nat.not_lt_zero] using h0')) h0 /-- A property holds for all polynomials of non-zero `nat_degree` with coefficients in a semiring `R` if it holds for * `p + a`, with `a ∈ R`, `p ∈ R[X]`, * `p + q`, with `p, q ∈ R[X]`, * monomials with nonzero coefficient and non-zero exponent, with appropriate restrictions on each term. Note that multiplication is "hidden" in the assumption on monomials, so there is no explicit multiplication in the statement. See `degree_pos_induction_on` for a similar statement involving more explicit multiplications. -/ @[elab_as_eliminator] lemma nat_degree_ne_zero_induction_on {M : R[X] → Prop} {f : R[X]} (f0 : f.nat_degree ≠ 0) (h_C_add : ∀ {a p}, M p → M (C a + p)) (h_add : ∀ {p q}, M p → M q → M (p + q)) (h_monomial : ∀ {n : ℕ} {a : R}, a ≠ 0 → n ≠ 0 → M (monomial n a)) : M f := suffices f.nat_degree = 0 ∨ M f, from or.dcases_on this (λ h, (f0 h).elim) id, begin apply f.induction_on, { exact λ a, or.inl (nat_degree_C _) }, { rintros p q (hp | hp) (hq | hq), { refine or.inl _, rw [eq_C_of_nat_degree_eq_zero hp, eq_C_of_nat_degree_eq_zero hq, ← C_add, nat_degree_C] }, { refine or.inr _, rw [eq_C_of_nat_degree_eq_zero hp], exact h_C_add hq }, { refine or.inr _, rw [eq_C_of_nat_degree_eq_zero hq, add_comm], exact h_C_add hp }, { exact or.inr (h_add hp hq) } }, { intros n a hi, by_cases a0 : a = 0, { exact or.inl (by rw [a0, C_0, zero_mul, nat_degree_zero]) }, { refine or.inr _, rw C_mul_X_pow_eq_monomial, exact h_monomial a0 n.succ_ne_zero } } end end semiring end polynomial
6e9538d39dc53806265c9ed53c3ac9031b118468
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/group_with_zero/default.lean
03893e3bbd7b61aca0f0589ff8d6c2251bd9da98
[ "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
37
lean
import algebra.group_with_zero.basic
8317033fe0dd1a1aa5c065d0e1a09aacfc490568
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/algebra/category/Group/basic.lean
8a4ac41e2dcf2c7b087a143237c9ecbd498be086
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
8,981
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.category.Mon.basic import category_theory.endomorphism /-! # Category instances for group, add_group, comm_group, and add_comm_group. We introduce the bundled categories: * `Group` * `AddGroup` * `CommGroup` * `AddCommGroup` along with the relevant forgetful functors between them, and to the bundled monoid categories. ## Implementation notes See the note [locally reducible category instances]. -/ universes u v open category_theory /-- The category of groups and group morphisms. -/ @[to_additive AddGroup] def Group : Type (u+1) := bundled group namespace Group @[to_additive] instance : bundled_hom.parent_projection group.to_monoid := ⟨⟩ /-- Construct a bundled Group from the underlying type and typeclass. -/ @[to_additive] def of (X : Type u) [group X] : Group := bundled.of X local attribute [reducible] Group @[to_additive] instance : has_coe_to_sort Group := infer_instance -- short-circuit type class inference @[to_additive add_group] instance (G : Group) : group G := G.str @[to_additive] instance : has_one Group := ⟨Group.of punit⟩ @[to_additive] instance : inhabited Group := ⟨1⟩ @[to_additive] instance : unique (1 : Group.{u}) := { default := 1, uniq := λ a, begin cases a, refl, end } @[simp, to_additive] lemma one_apply (G H : Group) (g : G) : (1 : G ⟶ H) g = 1 := rfl @[to_additive] instance : category Group := infer_instance -- short-circuit type class inference @[to_additive] instance : concrete_category Group := infer_instance -- short-circuit type class inference @[to_additive,ext] lemma ext (G H : Group) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by { ext1, apply w } attribute [ext] AddGroup.ext @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ Group Mon := bundled_hom.forget₂ _ _ end Group /-- The category of commutative groups and group morphisms. -/ @[to_additive AddCommGroup] def CommGroup : Type (u+1) := bundled comm_group /-- `Ab` is an abbreviation for `AddCommGroup`, for the sake of mathematicians' sanity. -/ abbreviation Ab := AddCommGroup namespace CommGroup @[to_additive] instance : bundled_hom.parent_projection comm_group.to_group := ⟨⟩ /-- Construct a bundled CommGroup from the underlying type and typeclass. -/ @[to_additive] def of (G : Type u) [comm_group G] : CommGroup := bundled.of G local attribute [reducible] CommGroup @[to_additive] instance : has_coe_to_sort CommGroup := infer_instance -- short-circuit type class inference @[to_additive add_comm_group_instance] instance comm_group_instance (G : CommGroup) : comm_group G := G.str @[to_additive] instance : has_one CommGroup := ⟨CommGroup.of punit⟩ @[to_additive] instance : inhabited CommGroup := ⟨1⟩ @[to_additive] instance : unique (1 : CommGroup.{u}) := { default := 1, uniq := λ a, begin cases a, refl, end } @[simp, to_additive] lemma one_apply (G H : CommGroup) (g : G) : (1 : G ⟶ H) g = 1 := rfl @[to_additive] instance : category CommGroup := infer_instance -- short-circuit type class inference @[to_additive] instance : concrete_category CommGroup := infer_instance -- short-circuit type class inference @[to_additive,ext] lemma ext (G H : CommGroup) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by { ext1, apply w } attribute [ext] AddCommGroup.ext @[to_additive has_forget_to_AddGroup] instance has_forget_to_Group : has_forget₂ CommGroup Group := bundled_hom.forget₂ _ _ @[to_additive has_forget_to_AddCommMon] instance has_forget_to_CommMon : has_forget₂ CommGroup CommMon := induced_category.has_forget₂ (λ G : CommGroup, CommMon.of G) end CommGroup -- This example verifies an improvement possible in Lean 3.8. -- Before that, to have `monoid_hom.map_map` usable by `simp` here, -- we had to mark all the concrete category `has_coe_to_sort` instances reducible. -- Now, it just works. @[to_additive] example {R S : CommGroup} (i : R ⟶ S) (r : R) (h : r = 1) : i r = 1 := by simp [h] namespace AddCommGroup /-- Any element of an abelian group gives a unique morphism from `ℤ` sending `1` to that element. -/ -- TODO allow other universe levels -- this will require writing a `ulift_instances.lean` file def as_hom {G : AddCommGroup.{0}} (g : G) : (AddCommGroup.of ℤ) ⟶ G := { to_fun := λ i : ℤ, i • g, map_zero' := rfl, map_add' := λ a b, gpow_add g a b } @[simp] lemma as_hom_apply {G : AddCommGroup.{0}} (g : G) (i : ℤ) : (as_hom g) i = i • g := rfl lemma as_hom_injective {G : AddCommGroup.{0}} : function.injective (@as_hom G) := λ h k w, by convert congr_arg (λ k : (AddCommGroup.of ℤ) ⟶ G, (k : ℤ → G) (1 : ℤ)) w; simp @[ext] lemma int_hom_ext {G : AddCommGroup.{0}} (f g : (AddCommGroup.of ℤ) ⟶ G) (w : f (1 : ℤ) = g (1 : ℤ)) : f = g := begin ext, change ℤ at x, rw ←gsmul_int_one x, rw [add_monoid_hom.map_gsmul, add_monoid_hom.map_gsmul, w], end -- TODO: this argument should be generalised to the situation where -- the forgetful functor is representable. lemma injective_of_mono {G H : AddCommGroup.{0}} (f : G ⟶ H) [mono f] : function.injective f := λ g₁ g₂ h, begin have t0 : as_hom g₁ ≫ f = as_hom g₂ ≫ f := begin ext, dsimp [as_hom], simpa using h, end, have t1 : as_hom g₁ = as_hom g₂ := (cancel_mono _).1 t0, apply as_hom_injective t1, end end AddCommGroup variables {X Y : Type u} /-- Build an isomorphism in the category `Group` from a `mul_equiv` between `group`s. -/ @[to_additive add_equiv.to_AddGroup_iso "Build an isomorphism in the category `AddGroup` from a `add_equiv` between `add_group`s."] def mul_equiv.to_Group_iso [group X] [group Y] (e : X ≃* Y) : Group.of X ≅ Group.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } attribute [simps] mul_equiv.to_Group_iso add_equiv.to_AddGroup_iso /-- Build an isomorphism in the category `CommGroup` from a `mul_equiv` between `comm_group`s. -/ @[to_additive add_equiv.to_AddCommGroup_iso "Build an isomorphism in the category `AddCommGroup` from a `add_equiv` between `add_comm_group`s."] def mul_equiv.to_CommGroup_iso [comm_group X] [comm_group Y] (e : X ≃* Y) : CommGroup.of X ≅ CommGroup.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } attribute [simps] mul_equiv.to_CommGroup_iso add_equiv.to_AddCommGroup_iso namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Group`. -/ @[to_additive AddGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddGroup`."] def Group_iso_to_mul_equiv {X Y : Group.{u}} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. attribute [simps] Group_iso_to_mul_equiv AddGroup_iso_to_add_equiv /-- Build a `mul_equiv` from an isomorphism in the category `CommGroup`. -/ @[to_additive AddCommGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddCommGroup`."] def CommGroup_iso_to_mul_equiv {X Y : CommGroup.{u}} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. attribute [simps] CommGroup_iso_to_mul_equiv AddCommGroup_iso_to_add_equiv end category_theory.iso /-- multiplicative equivalences between `group`s are the same as (isomorphic to) isomorphisms in `Group` -/ @[to_additive add_equiv_iso_AddGroup_iso "additive equivalences between `add_group`s are the same as (isomorphic to) isomorphisms in `AddGroup`"] def mul_equiv_iso_Group_iso {X Y : Type u} [group X] [group Y] : (X ≃* Y) ≅ (Group.of X ≅ Group.of Y) := { hom := λ e, e.to_Group_iso, inv := λ i, i.Group_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_group`s are the same as (isomorphic to) isomorphisms in `CommGroup` -/ @[to_additive add_equiv_iso_AddCommGroup_iso "additive equivalences between `add_comm_group`s are the same as (isomorphic to) isomorphisms in `AddCommGroup`"] def mul_equiv_iso_CommGroup_iso {X Y : Type u} [comm_group X] [comm_group Y] : (X ≃* Y) ≅ (CommGroup.of X ≅ CommGroup.of Y) := { hom := λ e, e.to_CommGroup_iso, inv := λ i, i.CommGroup_iso_to_mul_equiv, } namespace category_theory.Aut /-- The (bundled) group of automorphisms of a type is isomorphic to the (bundled) group of permutations. -/ def iso_perm {α : Type u} : Group.of (Aut α) ≅ Group.of (equiv.perm α) := { hom := ⟨λ g, g.to_equiv, (by tidy), (by tidy)⟩, inv := ⟨λ g, g.to_iso, (by tidy), (by tidy)⟩ } /-- The (unbundled) group of automorphisms of a type is `mul_equiv` to the (unbundled) group of permutations. -/ def mul_equiv_perm {α : Type u} : Aut α ≃* equiv.perm α := iso_perm.Group_iso_to_mul_equiv end category_theory.Aut
1ee560cb620988cc2c9eb5fff06beb31c122bc3d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/DeclUtil.lean
0347b80b288913b295ba03bf721ae3501508d1ca
[ "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
3,788
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Meta.Basic import Lean.Meta.Check namespace Lean.Meta def forallTelescopeCompatibleAux {α} (k : Array Expr → Expr → Expr → MetaM α) : Nat → Expr → Expr → Array Expr → MetaM α | 0, type₁, type₂, xs => k xs type₁ type₂ | i+1, type₁, type₂, xs => do let type₁ ← whnf type₁ let type₂ ← whnf type₂ match type₁, type₂ with | Expr.forallE n₁ d₁ b₁ c₁, Expr.forallE n₂ d₂ b₂ c₂ => unless n₁ == n₂ do throwError "parameter name mismatch '{n₁}', expected '{n₂}'" unless (← isDefEq d₁ d₂) do throwError "parameter '{n₁}' {← mkHasTypeButIsExpectedMsg d₁ d₂}" unless c₁ == c₂ do throwError "binder annotation mismatch at parameter '{n₁}'" withLocalDecl n₁ c₁ d₁ fun x => let type₁ := b₁.instantiate1 x let type₂ := b₂.instantiate1 x forallTelescopeCompatibleAux k i type₁ type₂ (xs.push x) | _, _ => throwError "unexpected number of parameters" /-- Given two forall-expressions `type₁` and `type₂`, ensure the first `numParams` parameters are compatible, and then execute `k` with the parameters and remaining types. -/ def forallTelescopeCompatible {α m} [Monad m] [MonadControlT MetaM m] (type₁ type₂ : Expr) (numParams : Nat) (k : Array Expr → Expr → Expr → m α) : m α := controlAt MetaM fun runInBase => forallTelescopeCompatibleAux (fun xs type₁ type₂ => runInBase $ k xs type₁ type₂) numParams type₁ type₂ #[] end Meta namespace Elab def expandOptDeclSig (stx : Syntax) : Syntax × Option Syntax := -- many Term.bracketedBinder >> Term.optType let binders := stx[0] let optType := stx[1] -- optional (leading_parser " : " >> termParser) if optType.isNone then (binders, none) else let typeSpec := optType[0] (binders, some typeSpec[1]) def expandDeclSig (stx : Syntax) : Syntax × Syntax := -- many Term.bracketedBinder >> Term.typeSpec let binders := stx[0] let typeSpec := stx[1] (binders, typeSpec[1]) def mkFreshInstanceName (env : Environment) (nextIdx : Nat) : Name := (env.mainModule ++ `_instance).appendIndexAfter nextIdx def isFreshInstanceName (name : Name) : Bool := match name with | .str _ s => "_instance".isPrefixOf s | _ => false /-- Sort the given list of `usedParams` using the following order: - If it is an explicit level `allUserParams`, then use user given order. - Otherwise, use lexicographical. Remark: `scopeParams` are the universe params introduced using the `universe` command. `allUserParams` contains the universe params introduced using the `universe` command *and* the `.{...}` notation. Remark: this function return an exception if there is an `u` not in `usedParams`, that is in `allUserParams` but not in `scopeParams`. Remark: `explicitParams` are in reverse declaration order. That is, the head is the last declared parameter. -/ def sortDeclLevelParams (scopeParams : List Name) (allUserParams : List Name) (usedParams : Array Name) : Except String (List Name) := match allUserParams.find? fun u => !usedParams.contains u && !scopeParams.elem u with | some u => throw s!"unused universe parameter '{u}'" | none => let result := allUserParams.foldl (fun result levelName => if usedParams.elem levelName then levelName :: result else result) [] let remaining := usedParams.filter (fun levelParam => !allUserParams.elem levelParam) let remaining := remaining.qsort Name.lt pure $ result ++ remaining.toList end Lean.Elab
600c3f16bdd5f0d98dc7c16456cab7cdb471cf32
8f67b34bba98f894155dedf263bc8d61c31e89cd
/2ltt/matching_facts.lean
0b6fe9f4533e059d37cdf1f24f203cf4a3ce01bf
[]
no_license
5HT/two-level
3b1523db242cba819681b862fbc8f490d9571a66
370f5a91311db3b463b10a31891370721e2476e2
refs/heads/master
1,648,254,367,420
1,576,269,550,000
1,576,269,550,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,788
lean
import algebra.category import .inverse .limit .fibrant .finite .matching open sigma category eq.ops function functor open reduced_coslice invcat section MO_facts variables {C : Category.{1 1}} {D : Category} open reduced_coslice reduced_coslice.coslice_obs nat subcat_obj fincat matching_object invcat open equiv equiv.ops poly_unit open natural_transformation variables {z : C} {x : C_without_z z} {φ : C ⇒ ℕop} {reflecting_id : id_reflect φ} {max_rank : ∀ x, φ x ≤ φ z} [is_obj_finite C] [invcat C] (X : C ⇒ U) definition red_coslice_to_C' (o : x//C_without_z z) : (obj x)//C := begin cases o with [t,f,non_id], refine red_coslice_obs.mk (obj t) f _, intros p, intros q, assert H : @eq (C_without_z z) x t, begin cases x, cases t, esimp at *, congruence, assumption end, apply non_id H, cases H, esimp, apply q end definition red_coslice_to_C'_hom (a b : x//C_without_z z) (f : a ⟶ b) : (red_coslice_to_C' a) ⟶ (red_coslice_to_C' b) := begin cases f with [f, comm_tr], cases a with [a,g,non_id], cases b with [b,g', non_id'], unfold red_coslice_obs.to_coslice_obs at *, unfold red_coslice_to_C' at *, esimp at *, apply ⟨f,comm_tr⟩ end -- (Danil) I pack this property as a lemma to prevent unnessesary unfolding -- which sometimes leads to errors when unfolding definitions dependent on this one lemma subcat_obj_eq {c c1: C} {P : C → Prop} {p : P c} {p1 : P c1} (q : subcat_obj.mk c p = subcat_obj.mk c1 p1) : c = c1 := begin refine subcat_obj.no_confusion q (λ x y, x) end include φ max_rank reflecting_id definition red_coslice_ne_z (t : C) (f : x ⟶ t) : t ≠ z := begin cases x with [x', x'_ne], esimp at *, cases (@fincat.has_decidable_eq _ _ t z) with [t_eq_z, t_ne_z], cases t_eq_z, exfalso, apply @no_incoming_non_id_arrows _ z φ max_rank reflecting_id, existsi x', existsi f, apply x'_ne, apply t_ne_z end definition red_coslice_from_C' [reducible] (o : (obj x)//C) : x//C_without_z z := begin cases o with [t,f,non_id], esimp at *, cases x with [x', x'_ne], esimp at *, let t' := subcat_obj.mk t (@red_coslice_ne_z _ z (mk x' x'_ne) φ reflecting_id max_rank _ _ t f), refine red_coslice_obs.mk _ _ _, apply t', apply f, intros p, intros q, have q1 : x' = t, from subcat_obj_eq p, apply non_id q1, cases q1, esimp at *, apply q end definition red_coslice_from_C'_hom {a b : x//C} (f : a ⟶ b) : (@red_coslice_from_C' _ _ _ _ reflecting_id max_rank _ _ a) ⟶ (@red_coslice_from_C' _ _ _ _ reflecting_id max_rank _ _ b) := begin cases f with [f, comm_tr], cases a with [a,g,non_id], cases b with [b,g', non_id'], unfold red_coslice_obs.to_coslice_obs at *, unfold red_coslice_from_C' at *, esimp at *, cases x, esimp at *, apply ⟨f,comm_tr⟩, end definition red_coslice_without_z_equiv : (obj x)//C ≃ₛ (x//C_without_z z) := equiv.mk (@red_coslice_from_C' C _ _ _ reflecting_id max_rank _ _) red_coslice_to_C' begin intros y, cases y with [y,f,non_id], cases x with [x, x_ne], esimp end begin intros y, cases y with [y,f,non_id], unfold red_coslice_to_C', cases y, esimp, unfold red_coslice_from_C', cases x, esimp end definition red_coslice_eq_1 : ∀ y, object X (obj (red_coslice_obs.to ((@red_coslice_without_z_equiv _ _ x _ reflecting_id max_rank _ _) ∙ y))) = X (red_coslice_obs.to y) := begin intro, unfold fn, cases y with [y,f,y_ne], cases x with [x, x_ne], esimp end definition MO'_to_MO_map : matching_object (Functor_from_C' z X) x → matching_object X (obj x) := begin let ψ := @red_coslice_without_z_equiv C z _ φ reflecting_id max_rank _ _, intros a, refine natural_transformation.mk _ _, { intros y uu, unfold functor.compose at *, unfold forget at *, esimp at *, unfold red_coslice_obs.to_coslice_obs, unfold Functor_from_C' at *, have HH : object X (red_coslice_obs.to (ψ ∙ y)), from (natural_map a) (ψ ∙ y) star, intro, unfold fn at *, cases y with [y,f,y_ne], cases x with [x', x_ne], esimp at *, apply HH }, { cases a with [η, NatSq], intros x' y, intros f', let X' := Functor_from_C' z X, let C' := C_without_z z, assert HH : #function morphism (X' ∘f forget C' x) (red_coslice_from_C'_hom f') ∘ η (red_coslice_from_C' x') = η (@red_coslice_from_C' _ _ _ _ reflecting_id max_rank _ _ y), begin apply NatSq _ end, cases x with [x,f,non_id_f], cases y with [y,g,non_id_g], esimp at *, cases f' with [a,p1], esimp, cases x' with [o, o_ne], esimp, unfold Functor_from_C' at *, unfold functor.compose at *, unfold forget at *, esimp at *, unfold red_coslice_from_C'_hom at *, esimp at *, rewrite natural_map_proj, apply funext, intros uu, esimp, esimp, cases uu, refine happly HH _ } end definition MO_equiv : matching_object (Functor_from_C' z X) x ≃ₛ matching_object X (obj x) := begin let C' := C_without_z z, let X' := Functor_from_C' z X, let ψ := @red_coslice_without_z_equiv C z x φ reflecting_id max_rank _ _, -- we got two commuting triangles using equivalence ((obj x)//C) ≃ (x//C') assert Htr1 : ∀ y, (X' ∘f !forget) (@to_fun _ _ ψ y) = (X ∘f !forget) y, begin intro, unfold functor.compose, unfold forget, unfold Functor_from_C', unfold red_coslice_obs.to_coslice_obs, esimp, refine red_coslice_eq_1 _ _, end, assert Htr2 : ∀ y, (X ∘f !forget) (@inv_fun _ _ ψ y) = (X' ∘f (!forget)) y, begin intro, unfold functor.compose, unfold forget, unfold Functor_from_C', unfold red_coslice_obs.to_coslice_obs, cases y with [y,f,y_ne], esimp end, unfold matching_object, refine equiv.mk (@MO'_to_MO_map _ _ _ _ reflecting_id max_rank _ _ X) _ _ _, { intros a, cases a with [η, NatSq], refine natural_transformation.mk _ _, intros y uu, have η' : poly_unit → (X∘f forget C (obj x)) (@equiv.inv _ _ ψ y), from η _, intro, unfold functor.compose at *, unfold forget at *, unfold Functor_from_C' at *, unfold red_coslice_obs.to_coslice_obs, cases y with [y,f,y_ne], esimp, apply η' star, intros a b f, assert HH : morphism (X∘f forget C (obj x)) (red_coslice_to_C'_hom _ _ f) ∘ η (red_coslice_to_C' a) = η (red_coslice_to_C' b), begin refine NatSq _ end, unfold Functor_from_C' at *, unfold functor.compose at *, unfold forget at *, esimp at *, unfold red_coslice_to_C'_hom at *, esimp at *, cases f with [f,comm_tr], cases a with [a, ff, non_id_ff ], cases b with [b, gg, non_id_gg], apply funext, intros uu, cases uu, refine happly HH _}, { intros a, refine nat_trans_eq, cases a with [η, NatSq], rewrite natural_map_proj, unfold MO'_to_MO_map, unfold fn, unfold equiv.inv, rewrite natural_map_proj, apply funext, intro y, apply funext, intro uu, cases uu, have Heq : (@to_fun _ _ ψ (@inv_fun (obj x//C) _ ψ y)) = y, from by apply right_inv, cases Heq, cases y with [y,f,non_id_f], esimp at *, cases x with [x,p], esimp }, { intros a, refine nat_trans_eq, cases a with [η, NatSq], esimp, rewrite natural_map_proj, unfold MO'_to_MO_map, rewrite natural_map_proj, apply funext, intro y, apply funext, intro uu, cases uu, cases y, cases x, esimp } end end MO_facts
898a4d6c1486baad9cdfac6f41460ea8c966228b
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Compiler/IR/CompilerM.lean
95964faf6dc2b26f41864c3494a3078b827a4e66
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
5,003
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.Environment import Lean.Compiler.IR.Basic import Lean.Compiler.IR.Format namespace Lean.IR inductive LogEntry where | step (cls : Name) (decls : Array Decl) | message (msg : Format) namespace LogEntry protected def fmt : LogEntry → Format | step cls decls => Format.bracket "[" (format cls) "]" ++ decls.foldl (fun fmt decl => fmt ++ Format.line ++ format decl) Format.nil | message msg => msg instance : ToFormat LogEntry := ⟨LogEntry.fmt⟩ end LogEntry abbrev Log := Array LogEntry def Log.format (log : Log) : Format := log.foldl (init := Format.nil) fun fmt entry => f!"{fmt}{Format.line}{entry}" @[export lean_ir_log_to_string] def Log.toString (log : Log) : String := log.format.pretty structure CompilerState where env : Environment log : Log := #[] abbrev CompilerM := ReaderT Options (EStateM String CompilerState) def log (entry : LogEntry) : CompilerM Unit := modify fun s => { s with log := s.log.push entry } def tracePrefixOptionName := `trace.compiler.ir private def isLogEnabledFor (opts : Options) (optName : Name) : Bool := match opts.find optName with | some (DataValue.ofBool v) => v | _ => opts.getBool tracePrefixOptionName private def logDeclsAux (optName : Name) (cls : Name) (decls : Array Decl) : CompilerM Unit := do let opts ← read if isLogEnabledFor opts optName then log (LogEntry.step cls decls) @[inline] def logDecls (cls : Name) (decl : Array Decl) : CompilerM Unit := logDeclsAux (tracePrefixOptionName ++ cls) cls decl private def logMessageIfAux {α : Type} [ToFormat α] (optName : Name) (a : α) : CompilerM Unit := do let opts ← read if isLogEnabledFor opts optName then log (LogEntry.message (format a)) @[inline] def logMessageIf {α : Type} [ToFormat α] (cls : Name) (a : α) : CompilerM Unit := logMessageIfAux (tracePrefixOptionName ++ cls) a @[inline] def logMessage {α : Type} [ToFormat α] (a : α) : CompilerM Unit := logMessageIfAux tracePrefixOptionName a @[inline] def modifyEnv (f : Environment → Environment) : CompilerM Unit := modify fun s => { s with env := f s.env } abbrev DeclMap := SMap Name Decl /-- Create an array of decls to be saved on .olean file. `decls` may contain duplicate entries, but we assume the one that occurs last is the most recent one. -/ private def mkEntryArray (decls : List Decl) : Array Decl := /- Remove duplicates by adding decls into a map -/ let map : HashMap Name Decl := {} let map := decls.foldl (init := map) fun map decl => map.insert decl.name decl map.fold (fun a _ v => a.push v) #[] builtin_initialize declMapExt : SimplePersistentEnvExtension Decl DeclMap ← registerSimplePersistentEnvExtension { name := `IRDecls, addImportedFn := fun as => let m : DeclMap := mkStateFromImportedEntries (fun s (d : Decl) => s.insert d.name d) {} as m.switch, addEntryFn := fun s d => s.insert d.name d, toArrayFn := mkEntryArray } @[export lean_ir_find_env_decl] def findEnvDecl (env : Environment) (n : Name) : Option Decl := (declMapExt.getState env).find? n def findDecl (n : Name) : CompilerM (Option Decl) := return findEnvDecl (← get).env n def containsDecl (n : Name) : CompilerM Bool := return (declMapExt.getState (← get).env).contains n def getDecl (n : Name) : CompilerM Decl := do let (some decl) ← findDecl n | throw s!"unknown declaration '{n}'" return decl @[export lean_ir_add_decl] def addDeclAux (env : Environment) (decl : Decl) : Environment := declMapExt.addEntry env decl def getDecls (env : Environment) : List Decl := declMapExt.getEntries env def getEnv : CompilerM Environment := do let s ← get; pure s.env def addDecl (decl : Decl) : CompilerM Unit := modifyEnv fun env => declMapExt.addEntry env decl def addDecls (decls : Array Decl) : CompilerM Unit := decls.forM addDecl def findEnvDecl' (env : Environment) (n : Name) (decls : Array Decl) : Option Decl := match decls.find? (fun decl => decl.name == n) with | some decl => some decl | none => (declMapExt.getState env).find? n def findDecl' (n : Name) (decls : Array Decl) : CompilerM (Option Decl) := return findEnvDecl' (← get).env n decls def containsDecl' (n : Name) (decls : Array Decl) : CompilerM Bool := do if decls.any fun decl => decl.name == n then return true else return (declMapExt.getState (← get).env).contains n def getDecl' (n : Name) (decls : Array Decl) : CompilerM Decl := do let (some decl) ← findDecl' n decls | throw s!"unknown declaration '{n}'" pure decl @[export lean_decl_get_sorry_dep] def getSorryDep (env : Environment) (declName : Name) : Option Name := match (declMapExt.getState env).find? declName with | some (.fdecl (info := { sorryDep? := dep?, .. }) ..) => dep? | _ => none end IR end Lean
6107705a7afc63a7729c769693e14f22c85022cf
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/stage0/src/Lean/Meta/Injective.lean
34db9b6280d2012159c59fe49ee3797a1439317e
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
6,477
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Injection import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Cases import Lean.Meta.Tactic.Subst import Lean.Meta.Tactic.Simp.Types import Lean.Meta.Tactic.Assumption namespace Lean.Meta private def mkAnd? (args : Array Expr) : Option Expr := do if args.isEmpty then return none else let mut result := args.back for arg in args.reverse[1:] do result := mkApp2 (mkConst ``And) arg result return result private partial def mkInjectiveTheoremTypeCore? (ctorVal : ConstructorVal) (useEq : Bool) : MetaM (Option Expr) := do let us := ctorVal.levelParams.map mkLevelParam forallBoundedTelescope ctorVal.type ctorVal.numParams fun params type => forallTelescope type fun args1 resultType => do let jp (args2 args2New : Array Expr) : MetaM (Option Expr) := do let lhs := mkAppN (mkAppN (mkConst ctorVal.name us) params) args1 let rhs := mkAppN (mkAppN (mkConst ctorVal.name us) params) args2 let eq ← mkEq lhs rhs let mut eqs := #[] for arg1 in args1, arg2 in args2 do let arg1Type ← inferType arg1 if !(← isProp arg1Type) && arg1 != arg2 then if (← isDefEq arg1Type (← inferType arg2)) then eqs := eqs.push (← mkEq arg1 arg2) else eqs := eqs.push (← mkHEq arg1 arg2) if let some andEqs ← mkAnd? eqs then let result ← if useEq then mkEq eq andEqs else mkArrow eq andEqs mkForallFVars params (← mkForallFVars args1 (← mkForallFVars args2New result)) else return none let rec mkArgs2 (i : Nat) (type : Expr) (args2 args2New : Array Expr) : MetaM (Option Expr) := do if h : i < args1.size then match (← whnf type) with | Expr.forallE n d b _ => let arg1 := args1.get ⟨i, h⟩ if arg1.occurs resultType then mkArgs2 (i + 1) (b.instantiate1 arg1) (args2.push arg1) args2New else withLocalDecl n (if useEq then BinderInfo.default else BinderInfo.implicit) d fun arg2 => mkArgs2 (i + 1) (b.instantiate1 arg2) (args2.push arg2) (args2New.push arg2) | _ => throwError "unexpected constructor type for '{ctorVal.name}'" else jp args2 args2New if useEq then mkArgs2 0 type #[] #[] else withNewBinderInfos (params.map fun param => (param.fvarId!, BinderInfo.implicit)) <| withNewBinderInfos (args1.map fun arg1 => (arg1.fvarId!, BinderInfo.implicit)) <| mkArgs2 0 type #[] #[] private def mkInjectiveTheoremType? (ctorVal : ConstructorVal) : MetaM (Option Expr) := mkInjectiveTheoremTypeCore? ctorVal false private def injTheoremFailureHeader (ctorName : Name) : MessageData := m!"failed to prove injectivity theorem for constructor '{ctorName}', use 'set_option genInjectivity false' to disable the generation" private def throwInjectiveTheoremFailure {α} (ctorName : Name) (mvarId : MVarId) : MetaM α := throwError "{injTheoremFailureHeader ctorName}{indentD <| MessageData.ofGoal mvarId}" private def solveEqOfCtorEq (ctorName : Name) (mvarId : MVarId) (h : FVarId) : MetaM Unit := do match (← injection mvarId h) with | InjectionResult.solved => unreachable! | InjectionResult.subgoal mvarId .. => (← splitAnd mvarId).forM fun mvarId => unless (← assumptionCore mvarId) do throwInjectiveTheoremFailure ctorName mvarId private def mkInjectiveTheoremValue (ctorName : Name) (targetType : Expr) : MetaM Expr := forallTelescopeReducing targetType fun xs type => do let mvar ← mkFreshExprSyntheticOpaqueMVar type solveEqOfCtorEq ctorName mvar.mvarId! xs.back.fvarId! mkLambdaFVars xs mvar def mkInjectiveTheoremNameFor (ctorName : Name) : Name := ctorName ++ `inj private def mkInjectiveTheorem (ctorVal : ConstructorVal) : MetaM Unit := do let some type ← mkInjectiveTheoremType? ctorVal | return () let value ← mkInjectiveTheoremValue ctorVal.name type addDecl <| Declaration.thmDecl { name := mkInjectiveTheoremNameFor ctorVal.name levelParams := ctorVal.levelParams type := (← instantiateMVars type) value := (← instantiateMVars value) } def mkInjectiveEqTheoremNameFor (ctorName : Name) : Name := ctorName ++ `injEq private def mkInjectiveEqTheoremType? (ctorVal : ConstructorVal) : MetaM (Option Expr) := mkInjectiveTheoremTypeCore? ctorVal true private def mkInjectiveEqTheoremValue (ctorName : Name) (targetType : Expr) : MetaM Expr := do forallTelescopeReducing targetType fun xs type => do let mvar ← mkFreshExprSyntheticOpaqueMVar type let [mvarId₁, mvarId₂] ← apply mvar.mvarId! (mkConst ``Eq.propIntro) | throwError "unexpected number of subgoals when proving injective theorem for constructor '{ctorName}'" let (h, mvarId₁) ← intro1 mvarId₁ let (_, mvarId₂) ← intro1 mvarId₂ solveEqOfCtorEq ctorName mvarId₁ h let mvarId₂ ← casesAnd mvarId₂ let mvarId₂ ← substEqs mvarId₂ applyRefl mvarId₂ (injTheoremFailureHeader ctorName) mkLambdaFVars xs mvar private def mkInjectiveEqTheorem (ctorVal : ConstructorVal) : MetaM Unit := do let some type ← mkInjectiveEqTheoremType? ctorVal | return () let value ← mkInjectiveEqTheoremValue ctorVal.name type let name := mkInjectiveEqTheoremNameFor ctorVal.name addDecl <| Declaration.thmDecl { name levelParams := ctorVal.levelParams type := (← instantiateMVars type) value := (← instantiateMVars value) } addSimpLemma name (post := true) AttributeKind.global (prio := eval_prio default) register_builtin_option genInjectivity : Bool := { defValue := true descr := "generate injectivity theorems for inductive datatype constructors" } def mkInjectiveTheorems (declName : Name) : MetaM Unit := do if (← getEnv).contains ``Eq.propIntro && genInjectivity.get (← getOptions) && !(← isInductivePredicate declName) then let info ← getConstInfoInduct declName unless info.isUnsafe do for ctor in info.ctors do let ctorVal ← getConstInfoCtor ctor if ctorVal.numFields > 0 then mkInjectiveTheorem ctorVal mkInjectiveEqTheorem ctorVal end Lean.Meta
6dd56c1bb711daf3d73fbe914b8e61a3387d1263
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/e15.lean
4ce7da5f5d309bef83553be87105b6725a1fb7ab
[ "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
542
lean
prelude inductive nat : Type | zero : nat | succ : nat → nat namespace nat end nat open nat inductive list (A : Sort*) | nil {} : list | cons : A → list → list namespace list end list open list #check nil #check nil.{1} #check @nil.{1} nat #check @nil nat #check cons zero nil inductive vector (A : Sort*) : nat → Sort* | vnil {} : vector zero | vcons : forall {n : nat}, A → vector n → vector (succ n) namespace vector end vector open vector #check vcons zero vnil constant n : nat #check vcons n vnil #check vector.rec
24952343dc17d2851455c4dd4f0bcdee7c8e8be7
26ac254ecb57ffcb886ff709cf018390161a9225
/src/order/filter/filter_product.lean
cd3ef15a1cb17ce65d891876d7fb988a427e6ce1
[ "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
8,318
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir -/ import order.filter.ultrafilter import order.filter.germ import algebra.pi_instances /-! # Ultraproducts If `φ` is an ultrafilter, then the space of germs of functions `f : α → β` at `φ` is called the *ultraproduct*. In this file we prove properties of ultraproducts that rely on `φ` being an ultrafilter. Definitions and properties that work for any filter should go to `order.filter.germ`. ## Tags ultrafilter, ultraproduct -/ universes u v variables {α : Type u} {β : Type v} {φ : filter α} open_locale classical namespace filter local notation `∀*` binders `, ` r:(scoped p, filter.eventually p φ) := r namespace germ local notation `β*` := germ φ β /-- If `φ` is an ultrafilter then the ultraproduct is a division ring. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def division_ring [division_ring β] (U : is_ultrafilter φ) : division_ring β* := { mul_inv_cancel := λ f, induction_on f $ λ f hf, coe_eq.2 $ (U.em (λ y, f y = 0)).elim (λ H, (hf $ coe_eq.2 H).elim) (λ H, H.mono $ λ x, mul_inv_cancel), inv_mul_cancel := λ f, induction_on f $ λ f hf, coe_eq.2 $ (U.em (λ y, f y = 0)).elim (λ H, (hf $ coe_eq.2 H).elim) (λ H, H.mono $ λ x, inv_mul_cancel), inv_zero := coe_eq.2 $ by simp only [(∘), inv_zero], .. germ.ring, .. germ.has_inv, .. @germ.nontrivial _ _ _ _ U.1 } /-- If `φ` is an ultrafilter then the ultraproduct is a field. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def field [field β] (U : is_ultrafilter φ) : field β* := { .. germ.comm_ring, .. germ.division_ring U } /-- If `φ` is an ultrafilter then the ultraproduct is a linear order. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def linear_order [linear_order β] (U : is_ultrafilter φ) : linear_order β* := { le_total := λ f g, induction_on₂ f g $ λ f g, U.eventually_or.1 $ eventually_of_forall $ λ x, le_total _ _, .. germ.partial_order } @[simp, norm_cast] lemma const_div [division_ring β] (U : is_ultrafilter φ) (x y : β) : (↑(x / y) : β*) = @has_div.div _ (@division_ring_has_div _ (germ.division_ring U)) ↑x ↑y := rfl lemma coe_lt [preorder β] (U : is_ultrafilter φ) {f g : α → β} : (f : β*) < g ↔ ∀* x, f x < g x := by simp only [lt_iff_le_not_le, eventually_and, coe_le, U.eventually_not, eventually_le] lemma coe_pos [preorder β] [has_zero β] (U : is_ultrafilter φ) {f : α → β} : 0 < (f : β*) ↔ ∀* x, 0 < f x := coe_lt U lemma const_lt [preorder β] (U : is_ultrafilter φ) {x y : β} : (↑x : β*) < ↑y ↔ x < y := (coe_lt U).trans $ by haveI := U.1; exact lift_rel_const_iff lemma lt_def [preorder β] (U : is_ultrafilter φ) : ((<) : β* → β* → Prop) = lift_rel (<) := by { ext ⟨f⟩ ⟨g⟩, exact coe_lt U } /-- If `φ` is an ultrafilter then the ultraproduct is an ordered ring. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def ordered_ring [ordered_ring β] (U : is_ultrafilter φ) : ordered_ring β* := { mul_pos := λ x y, induction_on₂ x y $ λ f g hf hg, (coe_pos U).2 $ ((coe_pos U).1 hg).mp $ ((coe_pos U).1 hf).mono $ λ x, mul_pos, .. germ.ring, .. germ.ordered_add_comm_group, .. @germ.nontrivial _ _ _ _ U.1 } /-- If `φ` is an ultrafilter then the ultraproduct is a linear ordered ring. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def linear_ordered_ring [linear_ordered_ring β] (U : is_ultrafilter φ) : linear_ordered_ring β* := { zero_lt_one := by rw lt_def U; show (∀* i, (0 : β) < 1); simp [zero_lt_one], .. germ.ordered_ring U, .. germ.linear_order U } /-- If `φ` is an ultrafilter then the ultraproduct is a linear ordered field. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def linear_ordered_field [linear_ordered_field β] (U : is_ultrafilter φ) : linear_ordered_field β* := { .. germ.linear_ordered_ring U, .. germ.field U } /-- If `φ` is an ultrafilter then the ultraproduct is a linear ordered commutative ring. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def linear_ordered_comm_ring [linear_ordered_comm_ring β] (U : is_ultrafilter φ) : linear_ordered_comm_ring β* := { .. germ.linear_ordered_ring U, .. germ.comm_monoid } /-- If `φ` is an ultrafilter then the ultraproduct is a decidable linear order. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected noncomputable def decidable_linear_order [decidable_linear_order β] (U : is_ultrafilter φ) : decidable_linear_order β* := { decidable_le := by apply_instance, .. germ.linear_order U } /-- If `φ` is an ultrafilter then the ultraproduct is a decidable linear ordered commutative group. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected noncomputable def decidable_linear_ordered_add_comm_group [decidable_linear_ordered_add_comm_group β] (U : is_ultrafilter φ) : decidable_linear_ordered_add_comm_group β* := { .. germ.ordered_add_comm_group, .. germ.decidable_linear_order U } /-- If `φ` is an ultrafilter then the ultraproduct is a decidable linear ordered commutative ring. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected noncomputable def decidable_linear_ordered_comm_ring [decidable_linear_ordered_comm_ring β] (U : is_ultrafilter φ) : decidable_linear_ordered_comm_ring β* := { .. germ.linear_ordered_comm_ring U, .. germ.decidable_linear_ordered_add_comm_group U } /-- If `φ` is an ultrafilter then the ultraproduct is a discrete linear ordered field. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected noncomputable def discrete_linear_ordered_field [discrete_linear_ordered_field β] (U : is_ultrafilter φ) : discrete_linear_ordered_field β* := { .. germ.linear_ordered_field U, .. germ.decidable_linear_ordered_comm_ring U, .. germ.field U } lemma max_def [K : decidable_linear_order β] (U : is_ultrafilter φ) (x y : β*) : @max β* (germ.decidable_linear_order U) x y = map₂ max x y := quotient.induction_on₂' x y $ λ a b, by unfold max; begin split_ifs, exact quotient.sound'(by filter_upwards [h] λ i hi, (max_eq_right hi).symm), exact quotient.sound'(by filter_upwards [@le_of_not_le _ (germ.linear_order U) _ _ h] λ i hi, (max_eq_left hi).symm), end lemma min_def [K : decidable_linear_order β] (U : is_ultrafilter φ) (x y : β*) : @min β* (germ.decidable_linear_order U) x y = map₂ min x y := quotient.induction_on₂' x y $ λ a b, by unfold min; begin split_ifs, exact quotient.sound'(by filter_upwards [h] λ i hi, (min_eq_left hi).symm), exact quotient.sound'(by filter_upwards [@le_of_not_le _ (germ.linear_order U) _ _ h] λ i hi, (min_eq_right hi).symm), end lemma abs_def [decidable_linear_ordered_add_comm_group β] (U : is_ultrafilter φ) (x : β*) : @abs _ (germ.decidable_linear_ordered_add_comm_group U) x = map abs x := quotient.induction_on' x $ λ a, by unfold abs; rw max_def; exact quotient.sound' (show ∀* i, abs _ = _, by simp) @[simp] lemma const_max [decidable_linear_order β] (U : is_ultrafilter φ) (x y : β) : (↑(max x y : β) : β*) = @max _ (germ.decidable_linear_order U) ↑x ↑y := begin haveI := U.1, unfold max, split_ifs, { refl }, { exact false.elim (h_1 $ const_le h) }, { exact false.elim (h (const_le_iff.mp h_1)) }, { refl } end @[simp] lemma const_min [decidable_linear_order β] (U : is_ultrafilter φ) (x y : β) : (↑(min x y : β) : β*) = @min _ (germ.decidable_linear_order U) ↑x ↑y := begin haveI := U.1, unfold min, split_ifs; try { refl }; apply false.elim, { exact (h_1 $ const_le h) }, { exact (h $ const_le_iff.mp h_1) }, end @[simp] lemma const_abs [decidable_linear_ordered_add_comm_group β] (U : is_ultrafilter φ) (x : β) : (↑(abs x) : β*) = @abs _ (germ.decidable_linear_ordered_add_comm_group U) ↑x := const_max U x (-x) end germ end filter
9a53e435c928dcf81a64f5d20ac4a9e7bd16d568
94e33a31faa76775069b071adea97e86e218a8ee
/src/ring_theory/int/basic.lean
c138a37d10f561a2ae4fd6aab86035abc64ca5e4
[ "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
13,678
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 ring_theory.coprime.basic import ring_theory.principal_ideal_domain /-! # Divisibility over ℕ and ℤ This file collects results for the integers and natural numbers that use abstract algebra in their proofs or cases of ℕ and ℤ being examples of structures in abstract algebra. ## Main statements * `nat.factors_eq`: the multiset of elements of `nat.factors` is equal to the factors given by the `unique_factorization_monoid` instance * ℤ is a `normalization_monoid` * ℤ is a `gcd_monoid` ## Tags prime, irreducible, natural numbers, integers, normalization monoid, gcd monoid, greatest common divisor, prime factorization, prime factors, unique factorization, unique factors -/ namespace nat instance : wf_dvd_monoid ℕ := ⟨begin refine rel_hom_class.well_founded (⟨λ (x : ℕ), if x = 0 then (⊤ : with_top ℕ) else x, _⟩ : dvd_not_unit →r (<)) (with_top.well_founded_lt nat.lt_wf), intros a b h, cases a, { exfalso, revert h, simp [dvd_not_unit] }, cases b, { simpa [succ_ne_zero] using with_top.coe_lt_top (a + 1) }, cases dvd_and_not_dvd_iff.2 h with h1 h2, simp only [succ_ne_zero, with_top.coe_lt_coe, if_false], apply lt_of_le_of_ne (nat.le_of_dvd (nat.succ_pos _) h1) (λ con, h2 _), rw con, end⟩ instance : unique_factorization_monoid ℕ := ⟨λ _, nat.irreducible_iff_prime⟩ end nat /-- `ℕ` is a gcd_monoid. -/ instance : gcd_monoid ℕ := { gcd := nat.gcd, lcm := nat.lcm, gcd_dvd_left := nat.gcd_dvd_left , gcd_dvd_right := nat.gcd_dvd_right, dvd_gcd := λ a b c, nat.dvd_gcd, gcd_mul_lcm := λ a b, by rw [nat.gcd_mul_lcm], lcm_zero_left := nat.lcm_zero_left, lcm_zero_right := nat.lcm_zero_right } instance : normalized_gcd_monoid ℕ := { normalize_gcd := λ a b, normalize_eq _, normalize_lcm := λ a b, normalize_eq _, .. (infer_instance : gcd_monoid ℕ), .. (infer_instance : normalization_monoid ℕ) } lemma gcd_eq_nat_gcd (m n : ℕ) : gcd m n = nat.gcd m n := rfl lemma lcm_eq_nat_lcm (m n : ℕ) : lcm m n = nat.lcm m n := rfl namespace int section normalization_monoid instance : normalization_monoid ℤ := { norm_unit := λa:ℤ, if 0 ≤ a then 1 else -1, norm_unit_zero := if_pos le_rfl, norm_unit_mul := assume a b hna hnb, begin cases hna.lt_or_lt with ha ha; cases hnb.lt_or_lt with hb hb; simp [mul_nonneg_iff, ha.le, ha.not_le, hb.le, hb.not_le] end, norm_unit_coe_units := assume u, (units_eq_one_or u).elim (assume eq, eq.symm ▸ if_pos zero_le_one) (assume eq, eq.symm ▸ if_neg (not_le_of_gt $ show (-1:ℤ) < 0, by dec_trivial)), } lemma normalize_of_nonneg {z : ℤ} (h : 0 ≤ z) : normalize z = z := show z * ↑(ite _ _ _) = z, by rw [if_pos h, units.coe_one, mul_one] lemma normalize_of_neg {z : ℤ} (h : z < 0) : normalize z = -z := show z * ↑(ite _ _ _) = -z, by rw [if_neg (not_le_of_gt h), units.coe_neg, units.coe_one, mul_neg_one] lemma normalize_coe_nat (n : ℕ) : normalize (n : ℤ) = n := normalize_of_nonneg (coe_nat_le_coe_nat_of_le $ nat.zero_le n) theorem coe_nat_abs_eq_normalize (z : ℤ) : (z.nat_abs : ℤ) = normalize z := begin by_cases 0 ≤ z, { simp [nat_abs_of_nonneg h, normalize_of_nonneg h] }, { simp [of_nat_nat_abs_of_nonpos (le_of_not_ge h), normalize_of_neg (lt_of_not_ge h)] } end lemma nonneg_of_normalize_eq_self {z : ℤ} (hz : normalize z = z) : 0 ≤ z := calc 0 ≤ (z.nat_abs : ℤ) : coe_zero_le _ ... = normalize z : coe_nat_abs_eq_normalize _ ... = z : hz lemma nonneg_iff_normalize_eq_self (z : ℤ) : normalize z = z ↔ 0 ≤ z := ⟨nonneg_of_normalize_eq_self, normalize_of_nonneg⟩ lemma eq_of_associated_of_nonneg {a b : ℤ} (h : associated a b) (ha : 0 ≤ a) (hb : 0 ≤ b) : a = b := dvd_antisymm_of_normalize_eq (normalize_of_nonneg ha) (normalize_of_nonneg hb) h.dvd h.symm.dvd end normalization_monoid section gcd_monoid instance : gcd_monoid ℤ := { gcd := λa b, int.gcd a b, lcm := λa b, int.lcm a b, gcd_dvd_left := assume a b, int.gcd_dvd_left _ _, gcd_dvd_right := assume a b, int.gcd_dvd_right _ _, dvd_gcd := assume a b c, dvd_gcd, gcd_mul_lcm := λ a b, by { rw [← int.coe_nat_mul, gcd_mul_lcm, coe_nat_abs_eq_normalize], exact normalize_associated (a * b) }, lcm_zero_left := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_left _, lcm_zero_right := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_right _} instance : normalized_gcd_monoid ℤ := { normalize_gcd := λ a b, normalize_coe_nat _, normalize_lcm := λ a b, normalize_coe_nat _, .. int.normalization_monoid, .. (infer_instance : gcd_monoid ℤ) } lemma coe_gcd (i j : ℤ) : ↑(int.gcd i j) = gcd_monoid.gcd i j := rfl lemma coe_lcm (i j : ℤ) : ↑(int.lcm i j) = gcd_monoid.lcm i j := rfl lemma nat_abs_gcd (i j : ℤ) : nat_abs (gcd_monoid.gcd i j) = int.gcd i j := rfl lemma nat_abs_lcm (i j : ℤ) : nat_abs (gcd_monoid.lcm i j) = int.lcm i j := rfl end gcd_monoid lemma exists_unit_of_abs (a : ℤ) : ∃ (u : ℤ) (h : is_unit u), (int.nat_abs a : ℤ) = u * a := begin cases (nat_abs_eq a) with h, { use [1, is_unit_one], rw [← h, one_mul], }, { use [-1, is_unit_one.neg], rw [ ← neg_eq_iff_neg_eq.mp (eq.symm h)], simp only [neg_mul, one_mul] } end lemma gcd_eq_nat_abs {a b : ℤ} : int.gcd a b = nat.gcd a.nat_abs b.nat_abs := rfl lemma gcd_eq_one_iff_coprime {a b : ℤ} : int.gcd a b = 1 ↔ is_coprime a b := begin split, { intro hg, obtain ⟨ua, hua, ha⟩ := exists_unit_of_abs a, obtain ⟨ub, hub, hb⟩ := exists_unit_of_abs b, use [(nat.gcd_a (int.nat_abs a) (int.nat_abs b)) * ua, (nat.gcd_b (int.nat_abs a) (int.nat_abs b)) * ub], rw [mul_assoc, ← ha, mul_assoc, ← hb, mul_comm, mul_comm _ (int.nat_abs b : ℤ), ← nat.gcd_eq_gcd_ab, ←gcd_eq_nat_abs, hg, int.coe_nat_one] }, { rintro ⟨r, s, h⟩, by_contradiction hg, obtain ⟨p, ⟨hp, ha, hb⟩⟩ := nat.prime.not_coprime_iff_dvd.mp hg, apply nat.prime.not_dvd_one hp, rw [←coe_nat_dvd, int.coe_nat_one, ← h], exact dvd_add ((coe_nat_dvd_left.mpr ha).mul_left _) ((coe_nat_dvd_left.mpr hb).mul_left _) } end lemma coprime_iff_nat_coprime {a b : ℤ} : is_coprime a b ↔ nat.coprime a.nat_abs b.nat_abs := by rw [←gcd_eq_one_iff_coprime, nat.coprime_iff_gcd_eq_one, gcd_eq_nat_abs] lemma sq_of_gcd_eq_one {a b c : ℤ} (h : int.gcd a b = 1) (heq : a * b = c ^ 2) : ∃ (a0 : ℤ), a = a0 ^ 2 ∨ a = - (a0 ^ 2) := begin have h' : is_unit (gcd_monoid.gcd a b), { rw [← coe_gcd, h, int.coe_nat_one], exact is_unit_one }, obtain ⟨d, ⟨u, hu⟩⟩ := exists_associated_pow_of_mul_eq_pow h' heq, use d, rw ← hu, cases int.units_eq_one_or u with hu' hu'; { rw hu', simp } end lemma sq_of_coprime {a b c : ℤ} (h : is_coprime a b) (heq : a * b = c ^ 2) : ∃ (a0 : ℤ), a = a0 ^ 2 ∨ a = - (a0 ^ 2) := sq_of_gcd_eq_one (gcd_eq_one_iff_coprime.mpr h) heq lemma nat_abs_euclidean_domain_gcd (a b : ℤ) : int.nat_abs (euclidean_domain.gcd a b) = int.gcd a b := begin apply nat.dvd_antisymm; rw ← int.coe_nat_dvd, { rw int.nat_abs_dvd, exact int.dvd_gcd (euclidean_domain.gcd_dvd_left _ _) (euclidean_domain.gcd_dvd_right _ _) }, { rw int.dvd_nat_abs, exact euclidean_domain.dvd_gcd (int.gcd_dvd_left _ _) (int.gcd_dvd_right _ _) } end end int /-- Maps an associate class of integers consisting of `-n, n` to `n : ℕ` -/ def associates_int_equiv_nat : associates ℤ ≃ ℕ := begin refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩, { refine (assume a, quotient.induction_on' a $ assume a, associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩), show normalize a = int.nat_abs (normalize a), rw [int.coe_nat_abs_eq_normalize, normalize_idem] }, { intro n, dsimp, rw [←normalize_apply, ← int.coe_nat_abs_eq_normalize, int.nat_abs_of_nat, int.nat_abs_of_nat] } end lemma int.prime.dvd_mul {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : p ∣ m.nat_abs ∨ p ∣ n.nat_abs := begin apply (nat.prime.dvd_mul hp).mp, rw ← int.nat_abs_mul, exact int.coe_nat_dvd_left.mp h end lemma int.prime.dvd_mul' {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : (p : ℤ) ∣ m ∨ (p : ℤ) ∣ n := begin rw [int.coe_nat_dvd_left, int.coe_nat_dvd_left], exact int.prime.dvd_mul hp h end lemma int.prime.dvd_pow {n : ℤ} {k p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ n ^ k) : p ∣ n.nat_abs := begin apply @nat.prime.dvd_of_dvd_pow _ _ k hp, rw ← int.nat_abs_pow, exact int.coe_nat_dvd_left.mp h end lemma int.prime.dvd_pow' {n : ℤ} {k p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ n ^ k) : (p : ℤ) ∣ n := begin rw int.coe_nat_dvd_left, exact int.prime.dvd_pow hp h end lemma prime_two_or_dvd_of_dvd_two_mul_pow_self_two {m : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ 2 * m ^ 2) : p = 2 ∨ p ∣ int.nat_abs m := begin cases int.prime.dvd_mul hp h with hp2 hpp, { apply or.intro_left, exact le_antisymm (nat.le_of_dvd zero_lt_two hp2) (nat.prime.two_le hp) }, { apply or.intro_right, rw [sq, int.nat_abs_mul] at hpp, exact (or_self _).mp ((nat.prime.dvd_mul hp).mp hpp)} end lemma int.exists_prime_and_dvd {n : ℤ} (hn : n.nat_abs ≠ 1) : ∃ p, prime p ∧ p ∣ n := begin obtain ⟨p, pp, pd⟩ := nat.exists_prime_and_dvd hn, exact ⟨p, nat.prime_iff_prime_int.mp pp, int.coe_nat_dvd_left.mpr pd⟩, end open unique_factorization_monoid theorem nat.factors_eq {n : ℕ} : normalized_factors n = n.factors := begin cases n, { simp }, rw [← multiset.rel_eq, ← associated_eq_eq], apply factors_unique (irreducible_of_normalized_factor) _, { rw [multiset.coe_prod, nat.prod_factors n.succ_ne_zero], apply normalized_factors_prod (nat.succ_ne_zero _) }, { apply_instance }, { intros x hx, rw [nat.irreducible_iff_prime, ← nat.prime_iff], exact nat.prime_of_mem_factors hx } end lemma nat.factors_multiset_prod_of_irreducible {s : multiset ℕ} (h : ∀ (x : ℕ), x ∈ s → irreducible x) : normalized_factors (s.prod) = s := begin rw [← multiset.rel_eq, ← associated_eq_eq], apply unique_factorization_monoid.factors_unique irreducible_of_normalized_factor h (normalized_factors_prod _), rw [ne.def, multiset.prod_eq_zero_iff], intro con, exact not_irreducible_zero (h 0 con), end namespace multiplicity lemma finite_int_iff_nat_abs_finite {a b : ℤ} : finite a b ↔ finite a.nat_abs b.nat_abs := by simp only [finite_def, ← int.nat_abs_dvd_iff_dvd, int.nat_abs_pow] lemma finite_int_iff {a b : ℤ} : finite a b ↔ (a.nat_abs ≠ 1 ∧ b ≠ 0) := by rw [finite_int_iff_nat_abs_finite, finite_nat_iff, pos_iff_ne_zero, int.nat_abs_ne_zero] instance decidable_nat : decidable_rel (λ a b : ℕ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_nat_iff.symm instance decidable_int : decidable_rel (λ a b : ℤ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_int_iff.symm end multiplicity lemma induction_on_primes {P : ℕ → Prop} (h₀ : P 0) (h₁ : P 1) (h : ∀ p a : ℕ, p.prime → P a → P (p * a)) (n : ℕ) : P n := begin apply unique_factorization_monoid.induction_on_prime, exact h₀, { intros n h, rw nat.is_unit_iff.1 h, exact h₁, }, { intros a p _ hp ha, exact h p a (nat.prime_iff.2 hp) ha, }, end lemma int.associated_nat_abs (k : ℤ) : associated k k.nat_abs := associated_of_dvd_dvd (int.coe_nat_dvd_right.mpr dvd_rfl) (int.nat_abs_dvd.mpr dvd_rfl) lemma int.prime_iff_nat_abs_prime {k : ℤ} : prime k ↔ nat.prime k.nat_abs := (int.associated_nat_abs k).prime_iff.trans nat.prime_iff_prime_int.symm theorem int.associated_iff_nat_abs {a b : ℤ} : associated a b ↔ a.nat_abs = b.nat_abs := begin rw [←dvd_dvd_iff_associated, ←int.nat_abs_dvd_iff_dvd, ←int.nat_abs_dvd_iff_dvd, dvd_dvd_iff_associated], exact associated_iff_eq, end lemma int.associated_iff {a b : ℤ} : associated a b ↔ (a = b ∨ a = -b) := begin rw int.associated_iff_nat_abs, exact int.nat_abs_eq_nat_abs_iff, end namespace int lemma zmultiples_nat_abs (a : ℤ) : add_subgroup.zmultiples (a.nat_abs : ℤ) = add_subgroup.zmultiples a := le_antisymm (add_subgroup.zmultiples_subset (mem_zmultiples_iff.mpr (dvd_nat_abs.mpr (dvd_refl a)))) (add_subgroup.zmultiples_subset (mem_zmultiples_iff.mpr (nat_abs_dvd.mpr (dvd_refl a)))) lemma span_nat_abs (a : ℤ) : ideal.span ({a.nat_abs} : set ℤ) = ideal.span {a} := by { rw ideal.span_singleton_eq_span_singleton, exact (associated_nat_abs _).symm } theorem eq_pow_of_mul_eq_pow_bit1_left {a b c : ℤ} (hab : is_coprime a b) {k : ℕ} (h : a * b = c ^ (bit1 k)) : ∃ d, a = d ^ (bit1 k) := begin obtain ⟨d, hd⟩ := exists_associated_pow_of_mul_eq_pow' hab h, replace hd := hd.symm, rw [associated_iff_nat_abs, nat_abs_eq_nat_abs_iff, ←neg_pow_bit1] at hd, obtain rfl|rfl := hd; exact ⟨_, rfl⟩, end theorem eq_pow_of_mul_eq_pow_bit1_right {a b c : ℤ} (hab : is_coprime a b) {k : ℕ} (h : a * b = c ^ (bit1 k)) : ∃ d, b = d ^ (bit1 k) := eq_pow_of_mul_eq_pow_bit1_left hab.symm (by rwa mul_comm at h) theorem eq_pow_of_mul_eq_pow_bit1 {a b c : ℤ} (hab : is_coprime a b) {k : ℕ} (h : a * b = c ^ (bit1 k)) : (∃ d, a = d ^ (bit1 k)) ∧ (∃ e, b = e ^ (bit1 k)) := ⟨eq_pow_of_mul_eq_pow_bit1_left hab h, eq_pow_of_mul_eq_pow_bit1_right hab h⟩ end int
10e570ca0c4e3d0c2075511c112e21f5be8ef030
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/logic/cast.lean
94ac46183d2ffb991bf043e10d5bd959097d02ea
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,052
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import logic.eq logic.heq logic.quantifiers open eq.ops -- cast.lean -- ========= section universe variable u variables {A B : Type.{u}} definition cast (H : A = B) (a : A) : B := eq.rec a H theorem cast_refl (a : A) : cast (eq.refl A) a = a := rfl theorem cast_proof_irrel (H₁ H₂ : A = B) (a : A) : cast H₁ a = cast H₂ a := rfl theorem cast_eq (H : A = A) (a : A) : cast H a = a := rfl end namespace heq universe variable u variables {A B C : Type.{u}} {a a' : A} {b b' : B} {c : C} theorem to_cast_eq (H : a == b) : cast (type_eq H) a = b := drec_on H !cast_eq theorem elim {D : Type} (H₁ : a == b) (H₂ : ∀ (Hab : A = B), cast Hab a = b → D) : D := H₂ (type_eq H₁) (to_cast_eq H₁) end heq section universe variables u v variables {A A' B C : Type.{u}} {P P' : A → Type.{v}} {a a' : A} {b : B} theorem eq_rec_heq (H : a = a') (p : P a) : eq.rec_on H p == p := eq.drec_on H !heq.refl -- should H₁ be explicit (useful in e.g. hproof_irrel) theorem eq_rec_to_heq {H₁ : a = a'} {p : P a} {p' : P a'} (H₂ : eq.rec_on H₁ p = p') : p == p' := calc p == eq.rec_on H₁ p : heq.symm (eq_rec_heq H₁ p) ... = p' : H₂ theorem cast_to_heq {H₁ : A = B} (H₂ : cast H₁ a = b) : a == b := eq_rec_to_heq H₂ theorem hproof_irrel {a b : Prop} (H : a = b) (H₁ : a) (H₂ : b) : H₁ == H₂ := eq_rec_to_heq (proof_irrel (cast H H₁) H₂) --TODO: generalize to eq.rec. This is a special case of rec_on_compose in eq.lean theorem cast_trans (Hab : A = B) (Hbc : B = C) (a : A) : cast Hbc (cast Hab a) = cast (Hab ⬝ Hbc) a := heq.to_eq (calc cast Hbc (cast Hab a) == cast Hab a : eq_rec_heq Hbc (cast Hab a) ... == a : eq_rec_heq Hab a ... == cast (Hab ⬝ Hbc) a : heq.symm (eq_rec_heq (Hab ⬝ Hbc) a)) theorem pi_eq (H : P = P') : (Π x, P x) = (Π x, P' x) := H ▸ (eq.refl (Π x, P x)) theorem hcongr_arg (f : Πx, P x) {a b : A} (H : a = b) : f a == f b := H ▸ (heq.refl (f a)) theorem rec_on_app (H : P = P') (f : Π x, P x) (a : A) : eq.rec_on H f a == f a := have aux : ∀ H : P = P, eq.rec_on H f a == f a, from take H : P = P, heq.refl (eq.rec_on H f a), (H ▸ aux) H theorem hcongr_fun {f : Π x, P x} {f' : Π x, P' x} (a : A) (H₁ : f == f') (H₂ : P = P') : f a == f' a := have aux : ∀ (f : Π x, P x) (f' : Π x, P x), f == f' → f a == f' a, from take f f' H, heq.to_eq H ▸ heq.refl (f a), (H₂ ▸ aux) f f' H₁ theorem rec_on_pull (H : P = P') (f : Π x, P x) (a : A) : eq.rec_on H f a = eq.rec_on (congr_fun H a) (f a) := heq.to_eq (calc eq.rec_on H f a == f a : rec_on_app H f a ... == eq.rec_on (congr_fun H a) (f a) : heq.symm (eq_rec_heq (congr_fun H a) (f a))) theorem cast_app (H : P = P') (f : Π x, P x) (a : A) : cast (pi_eq H) f a == f a := have H₁ : ∀ (H : (Π x, P x) = (Π x, P x)), cast H f a == f a, from assume H, heq.from_eq (congr_fun (cast_eq H f) a), have H₂ : ∀ (H : (Π x, P x) = (Π x, P' x)), cast H f a == f a, from H ▸ H₁, H₂ (pi_eq H) theorem hcongr {P' : A' → Type} {f : Π a, P a} {f' : Π a', P' a'} {a : A} {a' : A'} (Hf : f == f') (HP : P == P') (Ha : a == a') : f a == f' a' := have H1 : ∀ (B P' : A → Type) (f : Π x, P x) (f' : Π x, P' x), f == f' → (λx, P x) == (λx, P' x) → f a == f' a, from take P P' f f' Hf HB, hcongr_fun a Hf (heq.to_eq HB), have H2 : ∀ (B : A → Type) (P' : A' → Type) (f : Π x, P x) (f' : Π x, P' x), f == f' → (λx, P x) == (λx, P' x) → f a == f' a', from heq.subst Ha H1, H2 P P' f f' Hf HP end section variables {A : Type} {B : A → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {E : Πa b c, D a b c → Type} {F : Type} variables {a a' : A} {b : B a} {b' : B a'} {c : C a b} {c' : C a' b'} {d : D a b c} {d' : D a' b' c'} theorem hcongr_arg2 (f : Πa b, C a b) (Ha : a = a') (Hb : b == b') : f a b == f a' b' := hcongr (hcongr_arg f Ha) (hcongr_arg C Ha) Hb theorem hcongr_arg3 (f : Πa b c, D a b c) (Ha : a = a') (Hb : b == b') (Hc : c == c') : f a b c == f a' b' c' := hcongr (hcongr_arg2 f Ha Hb) (hcongr_arg2 D Ha Hb) Hc theorem hcongr_arg4 (f : Πa b c d, E a b c d) (Ha : a = a') (Hb : b == b') (Hc : c == c') (Hd : d == d') : f a b c d == f a' b' c' d' := hcongr (hcongr_arg3 f Ha Hb Hc) (hcongr_arg3 E Ha Hb Hc) Hd theorem dcongr_arg2 (f : Πa, B a → F) (Ha : a = a') (Hb : eq.rec_on Ha b = b') : f a b = f a' b' := heq.to_eq (hcongr_arg2 f Ha (eq_rec_to_heq Hb)) theorem dcongr_arg3 (f : Πa b, C a b → F) (Ha : a = a') (Hb : eq.rec_on Ha b = b') (Hc : cast (dcongr_arg2 C Ha Hb) c = c') : f a b c = f a' b' c' := heq.to_eq (hcongr_arg3 f Ha (eq_rec_to_heq Hb) (eq_rec_to_heq Hc)) theorem dcongr_arg4 (f : Πa b c, D a b c → F) (Ha : a = a') (Hb : eq.rec_on Ha b = b') (Hc : cast (dcongr_arg2 C Ha Hb) c = c') (Hd : cast (dcongr_arg3 D Ha Hb Hc) d = d') : f a b c d = f a' b' c' d' := heq.to_eq (hcongr_arg4 f Ha (eq_rec_to_heq Hb) (eq_rec_to_heq Hc) (eq_rec_to_heq Hd)) --mixed versions (we want them for example if C a' b' is a subsingleton, like a proposition. Then proving eq is easier than proving heq) theorem hdcongr_arg3 (f : Πa b, C a b → F) (Ha : a = a') (Hb : b == b') (Hc : cast (heq.to_eq (hcongr_arg2 C Ha Hb)) c = c') : f a b c = f a' b' c' := heq.to_eq (hcongr_arg3 f Ha Hb (eq_rec_to_heq Hc)) theorem hhdcongr_arg4 (f : Πa b c, D a b c → F) (Ha : a = a') (Hb : b == b') (Hc : c == c') (Hd : cast (dcongr_arg3 D Ha (!eq.rec_on_irrel_arg ⬝ heq.to_cast_eq Hb) (!eq.rec_on_irrel_arg ⬝ heq.to_cast_eq Hc)) d = d') : f a b c d = f a' b' c' d' := heq.to_eq (hcongr_arg4 f Ha Hb Hc (eq_rec_to_heq Hd)) theorem hddcongr_arg4 (f : Πa b c, D a b c → F) (Ha : a = a') (Hb : b == b') (Hc : cast (heq.to_eq (hcongr_arg2 C Ha Hb)) c = c') (Hd : cast (hdcongr_arg3 D Ha Hb Hc) d = d') : f a b c d = f a' b' c' d' := heq.to_eq (hcongr_arg4 f Ha Hb (eq_rec_to_heq Hc) (eq_rec_to_heq Hd)) --Is a reasonable version of "hcongr2" provable without pi_ext and funext? --It looks like you need some ugly extra conditions -- theorem hcongr2' {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type} {C' : Πa, B' a → Type} -- {f : Π a b, C a b} {f' : Π a' b', C' a' b'} {a : A} {a' : A'} {b : B a} {b' : B' a'} -- (HBB' : B == B') (HCC' : C == C') -- (Hff' : f == f') (Haa' : a == a') (Hbb' : b == b') : f a b == f' a' b' := -- hcongr (hcongr Hff' (sorry) Haa') (hcongr HCC' (sorry) Haa') Hbb' end
890b925d9dbdbf68e507f3edb558d058101774cd
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tmp/new-frontend/parser/level.lean
94b54ea1ef34430387842c034a6542f92bbaf4b7
[ "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
2,267
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich Level-Level parsers -/ prelude import init.lean.parser.pratt namespace Lean namespace Parser open Combinators Parser.HasView MonadParsec @[derive Monad Alternative MonadReader MonadParsec MonadExcept MonadRec monadBasicParser] def LevelParserM := RecT Nat Syntax BasicParserM abbrev levelParser := LevelParserM Syntax /-- A Level Parser for a suffix or infix notation that accepts a preceding Term Level. -/ @[derive Monad Alternative MonadReader MonadParsec MonadExcept MonadRec monadBasicParser] def TrailingLevelParserM := ReaderT Syntax LevelParserM abbrev trailingLevelParser := TrailingLevelParserM Syntax instance trailingLevelParserCoe : HasCoe levelParser trailingLevelParser := ⟨λ x _, x⟩ @[derive Parser.HasTokens Parser.HasView] def Level.Parser (rbp := 0) : levelParser := recurse rbp <?> "universe Level" namespace Level /-- Access leading Term -/ def getLeading : trailingLevelParser := read instance : HasTokens getLeading := default _ instance : HasView Syntax getLeading := default _ @[derive Parser.HasTokens Parser.HasView] def paren.Parser : levelParser := node! «paren» ["(":maxPrec, inner: Level.Parser 0, ")"] @[derive Parser.HasTokens Parser.HasView] def leading.Parser : levelParser := nodeChoice! leading { max: symbolOrIdent "max", imax: symbolOrIdent "imax", hole: symbol "_" maxPrec, paren: paren.Parser, lit: number.Parser, var: ident.Parser } @[derive Parser.HasTokens Parser.HasView] def app.Parser : trailingLevelParser := node! app [fn: getLeading, Arg: Level.Parser maxPrec] @[derive Parser.HasTokens Parser.HasView] def addLit.Parser : trailingLevelParser := node! addLit [lhs: getLeading, "+", rhs: number.Parser] @[derive Parser.HasTokens Parser.HasView] def trailing.Parser : trailingLevelParser := nodeChoice! trailing { app: app.Parser, addLit: addLit.Parser } end Level @[derive Parser.HasTokens Parser.HasView] def levelParser.run (p : levelParser) : basicParser := prattParser Level.leading.Parser Level.trailing.Parser p instance levelParserCoe : HasCoe levelParser basicParser := ⟨levelParser.run⟩ end Parser end Lean
083dd1b32fc93c5c525496fb470adaa67ee2b836
e94d3f31e48d06d252ee7307fe71efe1d500f274
/library/theories/topology/basic.lean
b94f75a9a810aa8350ddc2cff98fa1a0ca289ab4
[ "Apache-2.0" ]
permissive
GallagherCommaJack/lean
e4471240a069d82f97cb361d2bf1a029de3f4256
226f8bafeb9baaa5a2ac58000c83d6beb29991e2
refs/heads/master
1,610,725,100,482
1,459,194,829,000
1,459,195,377,000
55,377,224
0
0
null
1,459,731,701,000
1,459,731,700,000
null
UTF-8
Lean
false
false
11,227
lean
/- Copyright (c) 2015 Jacob Gross. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jacob Gross, Jeremy Avigad Open and closed sets, seperation axioms and generated topologies. -/ import data.set data.nat open algebra eq.ops set nat structure topology [class] (X : Type) := (opens : set (set X)) (univ_mem_opens : univ ∈ opens) (sUnion_mem_opens : ∀ {S : set (set X)}, S ⊆ opens → ⋃₀ S ∈ opens) (inter_mem_opens : ∀₀ s ∈ opens, ∀₀ t ∈ opens, s ∩ t ∈ opens) namespace topology variables {X : Type} [topology X] /- open sets -/ definition Open (s : set X) : Prop := s ∈ opens X theorem Open_empty : Open (∅ : set X) := have ∅ ⊆ opens X, from empty_subset _, have ⋃₀ ∅ ∈ opens X, from sUnion_mem_opens this, show ∅ ∈ opens X, by rewrite -sUnion_empty; apply this theorem Open_univ : Open (univ : set X) := univ_mem_opens X theorem Open_sUnion {S : set (set X)} (H : ∀₀ t ∈ S, Open t) : Open (⋃₀ S) := sUnion_mem_opens H theorem Open_Union {I : Type} {s : I → set X} (H : ∀ i, Open (s i)) : Open (⋃ i, s i) := have ∀₀ t ∈ s ' univ, Open t, from take t, suppose t ∈ s ' univ, obtain i [univi (Hi : s i = t)], from this, show Open t, by rewrite -Hi; exact H i, using this, by rewrite Union_eq_sUnion_image; apply Open_sUnion this theorem Open_union {s t : set X} (Hs : Open s) (Ht : Open t) : Open (s ∪ t) := have ∀ i, Open (bin_ext s t i), by intro i; cases i; exact Hs; exact Ht, show Open (s ∪ t), by rewrite -Union_bin_ext; exact Open_Union this theorem Open_inter {s t : set X} (Hs : Open s) (Ht : Open t) : Open (s ∩ t) := inter_mem_opens X Hs Ht theorem Open_sInter_of_finite {s : set (set X)} [fins : finite s] (H : ∀₀ t ∈ s, Open t) : Open (⋂₀ s) := begin induction fins with a s fins anins ih, {rewrite sInter_empty, exact Open_univ}, rewrite sInter_insert, apply Open_inter, show Open a, from H (mem_insert a s), apply ih, intros t ts, show Open t, from H (mem_insert_of_mem a ts) end /- closed sets -/ definition closed [reducible] (s : set X) : Prop := Open (-s) theorem closed_iff_Open_compl (s : set X) : closed s ↔ Open (-s) := !iff.refl theorem Open_iff_closed_compl (s : set X) : Open s ↔ closed (-s) := by rewrite [closed_iff_Open_compl, compl_compl] theorem closed_compl {s : set X} (H : Open s) : closed (-s) := by rewrite [-Open_iff_closed_compl]; apply H theorem closed_empty : closed (∅ : set X) := by rewrite [↑closed, compl_empty]; exact Open_univ theorem closed_univ : closed (univ : set X) := by rewrite [↑closed, compl_univ]; exact Open_empty theorem closed_sInter {S : set (set X)} (H : ∀₀ t ∈ S, closed t) : closed (⋂₀ S) := begin rewrite [↑closed, compl_sInter], apply Open_sUnion, intro t, rewrite [mem_image_compl, Open_iff_closed_compl], apply H end theorem closed_Inter {I : Type} {s : I → set X} (H : ∀ i, closed (s i : set X)) : closed (⋂ i, s i) := by rewrite [↑closed, compl_Inter]; apply Open_Union; apply H theorem closed_inter {s t : set X} (Hs : closed s) (Ht : closed t) : closed (s ∩ t) := by rewrite [↑closed, compl_inter]; apply Open_union; apply Hs; apply Ht theorem closed_union {s t : set X} (Hs : closed s) (Ht : closed t) : closed (s ∪ t) := by rewrite [↑closed, compl_union]; apply Open_inter; apply Hs; apply Ht theorem closed_sUnion_of_finite {s : set (set X)} [fins : finite s] (H : ∀₀ t ∈ s, closed t) : closed (⋂₀ s) := begin rewrite [↑closed, compl_sInter], apply Open_sUnion, intro t, rewrite [mem_image_compl, Open_iff_closed_compl], apply H end theorem open_diff {s t : set X} (Hs : Open s) (Ht : closed t) : Open (s \ t) := Open_inter Hs Ht theorem closed_diff {s t : set X} (Hs : closed s) (Ht : Open t) : closed (s \ t) := closed_inter Hs (closed_compl Ht) section open classical theorem Open_of_forall_exists_Open_nbhd {s : set X} (H : ∀₀ x ∈ s, ∃ tx : set X, Open tx ∧ x ∈ tx ∧ tx ⊆ s) : Open s := let Hset : X → set X := λ x, if Hxs : x ∈ s then some (H Hxs) else univ in let sFam := image (λ x, Hset x) s in have H_union_open : Open (⋃₀ sFam), from Open_sUnion (take t : set X, suppose t ∈ sFam, have H_preim : ∃ t', t' ∈ s ∧ Hset t' = t, from this, obtain t' (Ht' : t' ∈ s) (Ht't : Hset t' = t), from H_preim, have HHsett : t = some (H Ht'), from Ht't ▸ dif_pos Ht', show Open t, from and.left (HHsett⁻¹ ▸ some_spec (H Ht'))), have H_subset_union : s ⊆ ⋃₀ sFam, from (take x : X, suppose x ∈ s, have HxHset : x ∈ Hset x, from (dif_pos this)⁻¹ ▸ (and.left (and.right (some_spec (H this)))), show x ∈ ⋃₀ sFam, from mem_sUnion HxHset (mem_image this rfl)), have H_union_subset : ⋃₀ sFam ⊆ s, from (take x : X, suppose x ∈ ⋃₀ sFam, obtain (t : set X) (Ht : t ∈ sFam) (Hxt : x ∈ t), from this, have H_preim : ∃ t', t' ∈ s ∧ Hset t' = t, from Ht, obtain t' (Ht' : t' ∈ s) (Ht't : Hset t' = t), from H_preim, have HHsett : t = some (H Ht'), from Ht't ▸ dif_pos Ht', have t ⊆ s, from and.right (and.right (HHsett⁻¹ ▸ some_spec (H Ht'))), show x ∈ s, from this Hxt), have H_union_eq : ⋃₀ sFam = s, from eq_of_subset_of_subset H_union_subset H_subset_union, show Open s, from H_union_eq ▸ H_union_open end end topology /- separation -/ structure T0_space [class] (X : Type) extends topology X := (T0 : ∀ {x y}, x ≠ y → ∃ U, U ∈ opens ∧ ¬(x ∈ U ↔ y ∈ U)) namespace topology variables {X : Type} [T0_space X] theorem separation_T0 {x y : X} : x ≠ y ↔ ∃ U, Open U ∧ ¬(x ∈ U ↔ y ∈ U) := iff.intro (T0_space.T0) (assume H, obtain U [OpU xyU], from H, suppose x = y, have x ∈ U ↔ y ∈ U, from iff.intro (assume xU, this ▸ xU) (assume yU, this⁻¹ ▸ yU), absurd this xyU) end topology structure T1_space [class] (X : Type) extends topology X := (T1 : ∀ {x y}, x ≠ y → ∃ U, U ∈ opens ∧ x ∈ U ∧ y ∉ U) protected definition T0_space.of_T1 [trans_instance] {X : Type} [T : T1_space X] : T0_space X := ⦃T0_space, T, T0 := abstract take x y, assume H, obtain U [Uopens [xU ynU]], from T1_space.T1 H, exists.intro U (and.intro Uopens (show ¬ (x ∈ U ↔ y ∈ U), from assume H, ynU (iff.mp H xU))) end ⦄ namespace topology variables {X : Type} [T1_space X] theorem separation_T1 {x y : X} : x ≠ y ↔ (∃ U, Open U ∧ x ∈ U ∧ y ∉ U) := iff.intro (T1_space.T1) (suppose ∃ U, Open U ∧ x ∈ U ∧ y ∉ U, obtain U [OpU xU nyU], from this, suppose x = y, absurd xU (this⁻¹ ▸ nyU)) theorem closed_singleton {a : X} : closed '{a} := let T := ⋃₀ {S| Open S ∧ a ∉ S} in have Open T, from Open_sUnion (λS HS, and.elim_left HS), have T = -'{a}, from ext(take x, iff.intro (assume xT, assume xa, obtain S [[OpS aS] xS], from xT, have ∃ U, Open U ∧ x ∈ U ∧ a ∉ U, from exists.intro S (and.intro OpS (and.intro xS aS)), have x ≠ a, from (iff.elim_right separation_T1) this, absurd ((iff.elim_left !mem_singleton_iff) xa) this) (assume xa, have x ≠ a, from not.intro( assume H, absurd ((iff.elim_right !mem_singleton_iff) H) xa), obtain U [OpU xU aU], from (iff.elim_left separation_T1) this, show _, from exists.intro U (and.intro (and.intro OpU aU) xU))), show _, from this ▸ `Open T` end topology structure T2_space [class] (X : Type) extends topology X := (T2 : ∀ {x y}, x ≠ y → ∃ U V, U ∈ opens ∧ V ∈ opens ∧ x ∈ U ∧ y ∈ V ∧ U ∩ V = ∅) protected definition T1_space.of_T2 [trans_instance] {X : Type} [T : T2_space X] : T1_space X := ⦃T1_space, T, T1 := abstract take x y, assume H, obtain U [V [Uopens [Vopens [xU [yV UVempty]]]]], from T2_space.T2 H, exists.intro U (and.intro Uopens (and.intro xU (show y ∉ U, from assume yU, have y ∈ U ∩ V, from and.intro yU yV, show y ∈ ∅, from UVempty ▸ this))) end ⦄ namespace topology variables {X : Type} [T2_space X] theorem seperation_T2 {x y : X} : x ≠ y ↔ ∃ U V, Open U ∧ Open V ∧ x ∈ U ∧ y ∈ V ∧ U ∩ V = ∅ := iff.intro (T2_space.T2) (assume H, obtain U V [OpU OpV xU yV UV], from H, suppose x = y, have ¬(x ∈ U ∩ V), from not.intro( assume xUV, absurd (UV ▸ xUV) !not_mem_empty), absurd (and.intro xU (`x = y`⁻¹ ▸ yV)) this) end topology structure perfect_space [class] (X : Type) extends topology X := (perfect : ∀ x, '{x} ∉ opens) /- topology generated by a set -/ namespace topology inductive opens_generated_by {X : Type} (B : set (set X)) : set X → Prop := | generators_mem : ∀ ⦃s : set X⦄, s ∈ B → opens_generated_by B s | univ_mem : opens_generated_by B univ | inter_mem : ∀ ⦃s t⦄, opens_generated_by B s → opens_generated_by B t → opens_generated_by B (s ∩ t) | sUnion_mem : ∀ ⦃S : set (set X)⦄, S ⊆ opens_generated_by B → opens_generated_by B (⋃₀ S) protected definition generated_by [instance] {X : Type} (B : set (set X)) : topology X := ⦃topology, opens := opens_generated_by B, univ_mem_opens := opens_generated_by.univ_mem B, inter_mem_opens := λ s Hs t Ht, opens_generated_by.inter_mem Hs Ht, sUnion_mem_opens := opens_generated_by.sUnion_mem ⦄ theorem generators_mem_topology_generated_by {X : Type} (B : set (set X)) : let T := topology.generated_by B in ∀₀ s ∈ B, @Open _ T s := λ s H, opens_generated_by.generators_mem H theorem opens_generated_by_initial {X : Type} {B : set (set X)} {T : topology X} (H : B ⊆ @opens _ T) : opens_generated_by B ⊆ @opens _ T := begin intro s Hs, induction Hs with s sB s t os ot soX toX S SB SOX, {exact H sB}, {exact univ_mem_opens X}, {exact inter_mem_opens X soX toX}, exact sUnion_mem_opens SOX end theorem topology_generated_by_initial {X : Type} {B : set (set X)} {T : topology X} (H : ∀₀ s ∈ B, @Open _ T s) {s : set X} (H1 : @Open _ (topology.generated_by B) s) : @Open _ T s := opens_generated_by_initial H H1 section continuity /- continuous mappings -/ /- continuity at a point -/ variables {M N : Type} [Tm : topology M] [Tn : topology N] include Tm Tn definition continuous_at (f : M → N) (x : M) := ∀ U : set N, f x ∈ U → Open U → ∃ V : set M, x ∈ V ∧ Open V ∧ f 'V ⊆ U definition continuous (f : M → N) := ∀ x : M, continuous_at f x end continuity section boundary variables {X : Type} [TX : topology X] include TX definition on_boundary (x : X) (u : set X) := ∀ v : set X, Open v → x ∈ v → u ∩ v ≠ ∅ ∧ ¬ v ⊆ u theorem not_open_of_on_boundary {x : X} {u : set X} (Hxu : x ∈ u) (Hob : on_boundary x u) : ¬ Open u := begin intro Hop, note Hbxu := Hob _ Hop Hxu, apply and.right Hbxu, apply subset.refl end end boundary end topology
b2b3d64b36766ffaffa7358a5f90b460fc2d5e44
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/matrix/charpoly/minpoly.lean
ca0ffecda79b6646d6ae3af62d4c817b0a36cdbe
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,885
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Eric Wieser -/ import linear_algebra.matrix.charpoly.coeff import linear_algebra.matrix.to_lin import ring_theory.power_basis /-! # The minimal polynomial divides the characteristic polynomial of a matrix. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This also includes some miscellaneous results about `minpoly` on matrices. -/ noncomputable theory universes u v w open polynomial matrix variables {R : Type u} [comm_ring R] variables {n : Type v} [decidable_eq n] [fintype n] variables {N : Type w} [add_comm_group N] [module R N] open finset namespace matrix open_locale matrix variables (M : matrix n n R) @[simp] theorem minpoly_to_lin' : minpoly R M.to_lin' = minpoly R M := minpoly.minpoly_alg_equiv (to_lin_alg_equiv' : matrix n n R ≃ₐ[R] _) M @[simp] theorem minpoly_to_lin (b : basis n R N) (M : matrix n n R) : minpoly R (to_lin b b M) = minpoly R M := minpoly.minpoly_alg_equiv (to_lin_alg_equiv b : matrix n n R ≃ₐ[R] _) M theorem is_integral : is_integral R M := ⟨M.charpoly, ⟨charpoly_monic M, aeval_self_charpoly M⟩⟩ theorem minpoly_dvd_charpoly {K : Type*} [field K] (M : matrix n n K) : (minpoly K M) ∣ M.charpoly := minpoly.dvd _ _ (aeval_self_charpoly M) end matrix namespace linear_map @[simp] theorem minpoly_to_matrix' (f : (n → R) →ₗ[R] (n → R)) : minpoly R f.to_matrix' = minpoly R f := minpoly.minpoly_alg_equiv (to_matrix_alg_equiv' : _ ≃ₐ[R] matrix n n R) f @[simp] theorem minpoly_to_matrix (b : basis n R N) (f : N →ₗ[R] N) : minpoly R (to_matrix b b f) = minpoly R f := minpoly.minpoly_alg_equiv (to_matrix_alg_equiv b : _ ≃ₐ[R] matrix n n R) f end linear_map section power_basis open algebra /-- The characteristic polynomial of the map `λ x, a * x` is the minimal polynomial of `a`. In combination with `det_eq_sign_charpoly_coeff` or `trace_eq_neg_charpoly_coeff` and a bit of rewriting, this will allow us to conclude the field norm resp. trace of `x` is the product resp. sum of `x`'s conjugates. -/ lemma charpoly_left_mul_matrix {S : Type*} [ring S] [algebra R S] (h : power_basis R S) : (left_mul_matrix h.basis h.gen).charpoly = minpoly R h.gen := begin casesI subsingleton_or_nontrivial R, { apply subsingleton.elim }, apply minpoly.unique' R h.gen (charpoly_monic _), { apply (injective_iff_map_eq_zero (left_mul_matrix _)).mp (left_mul_matrix_injective h.basis), rw [← polynomial.aeval_alg_hom_apply, aeval_self_charpoly] }, refine λ q hq, or_iff_not_imp_left.2 (λ h0, _), rw [matrix.charpoly_degree_eq_dim, fintype.card_fin] at hq, contrapose! hq, exact h.dim_le_degree_of_root h0 hq, end end power_basis
857f52f0b632c32871938b354b2f3de627ccbad6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/hom/commute.lean
24e71649ed21503a9e709d707ebdec7ede1e03c5
[ "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
924
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov -/ import algebra.hom.group import algebra.group.commute /-! # Multiplicative homomorphisms respect semiconjugation and commutation. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ section commute variables {F M N : Type*} [has_mul M] [has_mul N] {a x y : M} @[simp, to_additive] protected lemma semiconj_by.map [mul_hom_class F M N] (h : semiconj_by a x y) (f : F) : semiconj_by (f a) (f x) (f y) := by simpa only [semiconj_by, map_mul] using congr_arg f h @[simp, to_additive] protected lemma commute.map [mul_hom_class F M N] (h : commute x y) (f : F) : commute (f x) (f y) := h.map f end commute
6bcf302e5c74dabc2dd6807f603cbbc6846cf729
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finsupp/indicator.lean
d2fa77851a51005d8cfccb6d02f2486fa342bb0e
[ "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
1,886
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finsupp.defs /-! # Building finitely supported functions off finsets This file defines `finsupp.indicator` to help create finsupps from finsets. ## Main declarations * `finsupp.indicator`: Turns a map from a `finset` into a `finsupp` from the entire type. -/ noncomputable theory open finset function open_locale classical variables {ι α : Type*} namespace finsupp variables [has_zero α] {s : finset ι} (f : Π i ∈ s, α) {i : ι} /-- Create an element of `ι →₀ α` from a finset `s` and a function `f` defined on this finset. -/ def indicator (s : finset ι) (f : Π i ∈ s, α) : ι →₀ α := { to_fun := λ i, if H : i ∈ s then f i H else 0, support := (s.attach.filter $ λ i : s, f i.1 i.2 ≠ 0).map $ embedding.subtype _, mem_support_to_fun := λ i, begin rw [mem_map, dite_ne_right_iff], exact ⟨λ ⟨⟨j, hj⟩, hf, rfl⟩, ⟨hj, (mem_filter.1 hf).2⟩, λ ⟨hi, hf⟩, ⟨⟨i, hi⟩, mem_filter.2 $ ⟨mem_attach _ _, hf⟩, rfl⟩⟩, end } lemma indicator_of_mem (hi : i ∈ s) (f : Π i ∈ s, α) : indicator s f i = f i hi := dif_pos hi lemma indicator_of_not_mem (hi : i ∉ s) (f : Π i ∈ s, α) : indicator s f i = 0 := dif_neg hi variables (s i) @[simp] lemma indicator_apply : indicator s f i = if hi : i ∈ s then f i hi else 0 := rfl lemma indicator_injective : injective (λ f : Π i ∈ s, α, indicator s f) := begin intros a b h, ext i hi, rw [←indicator_of_mem hi a, ←indicator_of_mem hi b], exact congr_fun h i, end lemma support_indicator_subset : ((indicator s f).support : set ι) ⊆ s := begin intros i hi, rw [mem_coe, mem_support_iff] at hi, by_contra, exact hi (indicator_of_not_mem h _), end end finsupp
de1e2862c265ca737d687d73575af0e3e67c64f2
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/pi_system.lean
6b51be17b34384c0a27d46c399b65e6968bbe326
[ "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
31,330
lean
/- Copyright (c) 2021 Martin Zinkevich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Martin Zinkevich, Rémy Degenne -/ import logic.encodable.lattice import measure_theory.measurable_space_def /-! # Induction principles for measurable sets, related to π-systems and λ-systems. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main statements * The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. * The proof of this theorem relies on the notion of `is_pi_system`, i.e., a collection of sets which is closed under binary non-empty intersections. Note that this is a small variation around the usual notion in the literature, which often requires that a π-system is non-empty, and closed also under disjoint intersections. This variation turns out to be convenient for the formalization. * The proof of Dynkin's π-λ theorem also requires the notion of `dynkin_system`, i.e., a collection of sets which contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. * `generate_pi_system g` gives the minimal π-system containing `g`. This can be considered a Galois insertion into both measurable spaces and sets. * `generate_from_generate_pi_system_eq` proves that if you start from a collection of sets `g`, take the generated π-system, and then the generated σ-algebra, you get the same result as the σ-algebra generated from `g`. This is useful because there are connections between independent sets that are π-systems and the generated independent spaces. * `mem_generate_pi_system_Union_elim` and `mem_generate_pi_system_Union_elim'` show that any element of the π-system generated from the union of a set of π-systems can be represented as the intersection of a finite number of elements from these sets. * `pi_Union_Inter` defines a new π-system from a family of π-systems `π : ι → set (set α)` and a set of indices `S : set ι`. `pi_Union_Inter π S` is the set of sets that can be written as `⋂ x ∈ t, f x` for some finset `t ∈ S` and sets `f x ∈ π x`. ## Implementation details * `is_pi_system` is a predicate, not a type. Thus, we don't explicitly define the galois insertion, nor do we define a complete lattice. In theory, we could define a complete lattice and galois insertion on the subtype corresponding to `is_pi_system`. -/ open measurable_space set open_locale classical measure_theory /-- A π-system is a collection of subsets of `α` that is closed under binary intersection of non-disjoint sets. Usually it is also required that the collection is nonempty, but we don't do that here. -/ def is_pi_system {α} (C : set (set α)) : Prop := ∀ s t ∈ C, (s ∩ t : set α).nonempty → s ∩ t ∈ C namespace measurable_space lemma is_pi_system_measurable_set {α:Type*} [measurable_space α] : is_pi_system {s : set α | measurable_set s} := λ s hs t ht _, hs.inter ht end measurable_space lemma is_pi_system.singleton {α} (S : set α) : is_pi_system ({S} : set (set α)) := begin intros s h_s t h_t h_ne, rw [set.mem_singleton_iff.1 h_s, set.mem_singleton_iff.1 h_t, set.inter_self, set.mem_singleton_iff], end lemma is_pi_system.insert_empty {α} {S : set (set α)} (h_pi : is_pi_system S) : is_pi_system (insert ∅ S) := begin intros s hs t ht hst, cases hs, { simp [hs], }, { cases ht, { simp [ht], }, { exact set.mem_insert_of_mem _ (h_pi s hs t ht hst), }, }, end lemma is_pi_system.insert_univ {α} {S : set (set α)} (h_pi : is_pi_system S) : is_pi_system (insert set.univ S) := begin intros s hs t ht hst, cases hs, { cases ht; simp [hs, ht], }, { cases ht, { simp [hs, ht], }, { exact set.mem_insert_of_mem _ (h_pi s hs t ht hst), }, }, end lemma is_pi_system.comap {α β} {S : set (set β)} (h_pi : is_pi_system S) (f : α → β) : is_pi_system {s : set α | ∃ t ∈ S, f ⁻¹' t = s} := begin rintros _ ⟨s, hs_mem, rfl⟩ _ ⟨t, ht_mem, rfl⟩ hst, rw ← set.preimage_inter at hst ⊢, refine ⟨s ∩ t, h_pi s hs_mem t ht_mem _, rfl⟩, by_contra, rw set.not_nonempty_iff_eq_empty at h, rw h at hst, simpa using hst, end lemma is_pi_system_Union_of_directed_le {α ι} (p : ι → set (set α)) (hp_pi : ∀ n, is_pi_system (p n)) (hp_directed : directed (≤) p) : is_pi_system (⋃ n, p n) := begin intros t1 ht1 t2 ht2 h, rw set.mem_Union at ht1 ht2 ⊢, cases ht1 with n ht1, cases ht2 with m ht2, obtain ⟨k, hpnk, hpmk⟩ : ∃ k, p n ≤ p k ∧ p m ≤ p k := hp_directed n m, exact ⟨k, hp_pi k t1 (hpnk ht1) t2 (hpmk ht2) h⟩, end lemma is_pi_system_Union_of_monotone {α ι} [semilattice_sup ι] (p : ι → set (set α)) (hp_pi : ∀ n, is_pi_system (p n)) (hp_mono : monotone p) : is_pi_system (⋃ n, p n) := is_pi_system_Union_of_directed_le p hp_pi (monotone.directed_le hp_mono) section order variables {α : Type*} {ι ι' : Sort*} [linear_order α] lemma is_pi_system_image_Iio (s : set α) : is_pi_system (Iio '' s) := begin rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ -, exact ⟨a ⊓ b, inf_ind a b ha hb, Iio_inter_Iio.symm⟩ end lemma is_pi_system_Iio : is_pi_system (range Iio : set (set α)) := @image_univ α _ Iio ▸ is_pi_system_image_Iio univ lemma is_pi_system_image_Ioi (s : set α) : is_pi_system (Ioi '' s) := @is_pi_system_image_Iio αᵒᵈ _ s lemma is_pi_system_Ioi : is_pi_system (range Ioi : set (set α)) := @image_univ α _ Ioi ▸ is_pi_system_image_Ioi univ lemma is_pi_system_Ixx_mem {Ixx : α → α → set α} {p : α → α → Prop} (Hne : ∀ {a b}, (Ixx a b).nonempty → p a b) (Hi : ∀ {a₁ b₁ a₂ b₂}, Ixx a₁ b₁ ∩ Ixx a₂ b₂ = Ixx (max a₁ a₂) (min b₁ b₂)) (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (hlu : p l u), Ixx l u = S} := begin rintro _ ⟨l₁, hls₁, u₁, hut₁, hlu₁, rfl⟩ _ ⟨l₂, hls₂, u₂, hut₂, hlu₂, rfl⟩, simp only [Hi, ← sup_eq_max, ← inf_eq_min], exact λ H, ⟨l₁ ⊔ l₂, sup_ind l₁ l₂ hls₁ hls₂, u₁ ⊓ u₂, inf_ind u₁ u₂ hut₁ hut₂, Hne H, rfl⟩ end lemma is_pi_system_Ixx {Ixx : α → α → set α} {p : α → α → Prop} (Hne : ∀ {a b}, (Ixx a b).nonempty → p a b) (Hi : ∀ {a₁ b₁ a₂ b₂}, Ixx a₁ b₁ ∩ Ixx a₂ b₂ = Ixx (max a₁ a₂) (min b₁ b₂)) (f : ι → α) (g : ι' → α) : @is_pi_system α ({S | ∃ i j (h : p (f i) (g j)), Ixx (f i) (g j) = S}) := by simpa only [exists_range_iff] using is_pi_system_Ixx_mem @Hne @Hi (range f) (range g) lemma is_pi_system_Ioo_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ioo l u = S} := is_pi_system_Ixx_mem (λ a b ⟨x, hax, hxb⟩, hax.trans hxb) (λ _ _ _ _, Ioo_inter_Ioo) s t lemma is_pi_system_Ioo (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ l u (h : f l < g u), Ioo (f l) (g u) = S} := is_pi_system_Ixx (λ a b ⟨x, hax, hxb⟩, hax.trans hxb) (λ _ _ _ _, Ioo_inter_Ioo) f g lemma is_pi_system_Ioc_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ioc l u = S} := is_pi_system_Ixx_mem (λ a b ⟨x, hax, hxb⟩, hax.trans_le hxb) (λ _ _ _ _, Ioc_inter_Ioc) s t lemma is_pi_system_Ioc (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ i j (h : f i < g j), Ioc (f i) (g j) = S} := is_pi_system_Ixx (λ a b ⟨x, hax, hxb⟩, hax.trans_le hxb) (λ _ _ _ _, Ioc_inter_Ioc) f g lemma is_pi_system_Ico_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ico l u = S} := is_pi_system_Ixx_mem (λ a b ⟨x, hax, hxb⟩, hax.trans_lt hxb) (λ _ _ _ _, Ico_inter_Ico) s t lemma is_pi_system_Ico (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ i j (h : f i < g j), Ico (f i) (g j) = S} := is_pi_system_Ixx (λ a b ⟨x, hax, hxb⟩, hax.trans_lt hxb) (λ _ _ _ _, Ico_inter_Ico) f g lemma is_pi_system_Icc_mem (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t) (h : l ≤ u), Icc l u = S} := is_pi_system_Ixx_mem (λ a b, nonempty_Icc.1) (λ _ _ _ _, Icc_inter_Icc) s t lemma is_pi_system_Icc (f : ι → α) (g : ι' → α) : @is_pi_system α {S | ∃ i j (h : f i ≤ g j), Icc (f i) (g j) = S} := is_pi_system_Ixx (λ a b, nonempty_Icc.1) (λ _ _ _ _, Icc_inter_Icc) f g end order /-- Given a collection `S` of subsets of `α`, then `generate_pi_system S` is the smallest π-system containing `S`. -/ inductive generate_pi_system {α} (S : set (set α)) : set (set α) | base {s : set α} (h_s : s ∈ S) : generate_pi_system s | inter {s t : set α} (h_s : generate_pi_system s) (h_t : generate_pi_system t) (h_nonempty : (s ∩ t).nonempty) : generate_pi_system (s ∩ t) lemma is_pi_system_generate_pi_system {α} (S : set (set α)) : is_pi_system (generate_pi_system S) := λ s h_s t h_t h_nonempty, generate_pi_system.inter h_s h_t h_nonempty lemma subset_generate_pi_system_self {α} (S : set (set α)) : S ⊆ generate_pi_system S := λ s, generate_pi_system.base lemma generate_pi_system_subset_self {α} {S : set (set α)} (h_S : is_pi_system S) : generate_pi_system S ⊆ S := begin intros x h, induction h with s h_s s u h_gen_s h_gen_u h_nonempty h_s h_u, { exact h_s, }, { exact h_S _ h_s _ h_u h_nonempty, }, end lemma generate_pi_system_eq {α} {S : set (set α)} (h_pi : is_pi_system S) : generate_pi_system S = S := set.subset.antisymm (generate_pi_system_subset_self h_pi) (subset_generate_pi_system_self S) lemma generate_pi_system_mono {α} {S T : set (set α)} (hST : S ⊆ T) : generate_pi_system S ⊆ generate_pi_system T := begin intros t ht, induction ht with s h_s s u h_gen_s h_gen_u h_nonempty h_s h_u, { exact generate_pi_system.base (set.mem_of_subset_of_mem hST h_s),}, { exact is_pi_system_generate_pi_system T _ h_s _ h_u h_nonempty, }, end lemma generate_pi_system_measurable_set {α} [M : measurable_space α] {S : set (set α)} (h_meas_S : ∀ s ∈ S, measurable_set s) (t : set α) (h_in_pi : t ∈ generate_pi_system S) : measurable_set t := begin induction h_in_pi with s h_s s u h_gen_s h_gen_u h_nonempty h_s h_u, { apply h_meas_S _ h_s, }, { apply measurable_set.inter h_s h_u, }, end lemma generate_from_measurable_set_of_generate_pi_system {α} {g : set (set α)} (t : set α) (ht : t ∈ generate_pi_system g) : measurable_set[generate_from g] t := @generate_pi_system_measurable_set α (generate_from g) g (λ s h_s_in_g, measurable_set_generate_from h_s_in_g) t ht lemma generate_from_generate_pi_system_eq {α} {g : set (set α)} : generate_from (generate_pi_system g) = generate_from g := begin apply le_antisymm; apply generate_from_le, { exact λ t h_t, generate_from_measurable_set_of_generate_pi_system t h_t, }, { exact λ t h_t, measurable_set_generate_from (generate_pi_system.base h_t), }, end /- Every element of the π-system generated by the union of a family of π-systems is a finite intersection of elements from the π-systems. For an indexed union version, see `mem_generate_pi_system_Union_elim'`. -/ lemma mem_generate_pi_system_Union_elim {α β} {g : β → set (set α)} (h_pi : ∀ b, is_pi_system (g b)) (t : set α) (h_t : t ∈ generate_pi_system (⋃ b, g b)) : ∃ (T : finset β) (f : β → set α), (t = ⋂ b ∈ T, f b) ∧ (∀ b ∈ T, f b ∈ g b) := begin induction h_t with s h_s s t' h_gen_s h_gen_t' h_nonempty h_s h_t', { rcases h_s with ⟨t', ⟨⟨b, rfl⟩, h_s_in_t'⟩⟩, refine ⟨{b}, (λ _, s), _⟩, simpa using h_s_in_t', }, { rcases h_t' with ⟨T_t', ⟨f_t', ⟨rfl, h_t'⟩⟩⟩, rcases h_s with ⟨T_s, ⟨f_s, ⟨rfl, h_s⟩ ⟩ ⟩, use [(T_s ∪ T_t'), (λ (b:β), if (b ∈ T_s) then (if (b ∈ T_t') then (f_s b ∩ (f_t' b)) else (f_s b)) else (if (b ∈ T_t') then (f_t' b) else (∅ : set α)))], split, { ext a, simp_rw [set.mem_inter_iff, set.mem_Inter, finset.mem_union, or_imp_distrib], rw ← forall_and_distrib, split; intros h1 b; by_cases hbs : b ∈ T_s; by_cases hbt : b ∈ T_t'; specialize h1 b; simp only [hbs, hbt, if_true, if_false, true_implies_iff, and_self, false_implies_iff, and_true, true_and] at h1 ⊢, all_goals { exact h1, }, }, intros b h_b, split_ifs with hbs hbt hbt, { refine h_pi b (f_s b) (h_s b hbs) (f_t' b) (h_t' b hbt) (set.nonempty.mono _ h_nonempty), exact set.inter_subset_inter (set.bInter_subset_of_mem hbs) (set.bInter_subset_of_mem hbt), }, { exact h_s b hbs, }, { exact h_t' b hbt, }, { rw finset.mem_union at h_b, apply false.elim (h_b.elim hbs hbt), }, }, end /- Every element of the π-system generated by an indexed union of a family of π-systems is a finite intersection of elements from the π-systems. For a total union version, see `mem_generate_pi_system_Union_elim`. -/ lemma mem_generate_pi_system_Union_elim' {α β} {g : β → set (set α)} {s : set β} (h_pi : ∀ b ∈ s, is_pi_system (g b)) (t : set α) (h_t : t ∈ generate_pi_system (⋃ b ∈ s, g b)) : ∃ (T : finset β) (f : β → set α), (↑T ⊆ s) ∧ (t = ⋂ b ∈ T, f b) ∧ (∀ b ∈ T, f b ∈ g b) := begin have : t ∈ generate_pi_system (⋃ (b : subtype s), (g ∘ subtype.val) b), { suffices h1 : (⋃ (b : subtype s), (g ∘ subtype.val) b) = (⋃ b ∈ s, g b), by rwa h1, ext x, simp only [exists_prop, set.mem_Union, function.comp_app, subtype.exists, subtype.coe_mk], refl }, rcases @mem_generate_pi_system_Union_elim α (subtype s) (g ∘ subtype.val) (λ b, h_pi b.val b.property) t this with ⟨T, ⟨f, ⟨rfl, h_t'⟩⟩⟩, refine ⟨T.image subtype.val, function.extend subtype.val f (λ b : β, (∅ : set α)), by simp, _, _⟩, { ext a, split; { simp only [set.mem_Inter, subtype.forall, finset.set_bInter_finset_image], intros h1 b h_b h_b_in_T, have h2 := h1 b h_b h_b_in_T, revert h2, rw subtype.val_injective.extend_apply, apply id } }, { intros b h_b, simp_rw [finset.mem_image, exists_prop, subtype.exists, exists_and_distrib_right, exists_eq_right] at h_b, cases h_b, have h_b_alt : b = (subtype.mk b h_b_w).val := rfl, rw [h_b_alt, subtype.val_injective.extend_apply], apply h_t', apply h_b_h }, end section Union_Inter variables {α ι : Type*} /-! ### π-system generated by finite intersections of sets of a π-system family -/ /-- From a set of indices `S : set ι` and a family of sets of sets `π : ι → set (set α)`, define the set of sets that can be written as `⋂ x ∈ t, f x` for some finset `t ⊆ S` and sets `f x ∈ π x`. If `π` is a family of π-systems, then it is a π-system. -/ def pi_Union_Inter (π : ι → set (set α)) (S : set ι) : set (set α) := {s : set α | ∃ (t : finset ι) (htS : ↑t ⊆ S) (f : ι → set α) (hf : ∀ x, x ∈ t → f x ∈ π x), s = ⋂ x ∈ t, f x} lemma pi_Union_Inter_singleton (π : ι → set (set α)) (i : ι) : pi_Union_Inter π {i} = π i ∪ {univ} := begin ext1 s, simp only [pi_Union_Inter, exists_prop, mem_union], refine ⟨_, λ h, _⟩, { rintros ⟨t, hti, f, hfπ, rfl⟩, simp only [subset_singleton_iff, finset.mem_coe] at hti, by_cases hi : i ∈ t, { have ht_eq_i : t = {i}, { ext1 x, rw finset.mem_singleton, exact ⟨λ h, hti x h, λ h, h.symm ▸ hi⟩, }, simp only [ht_eq_i, finset.mem_singleton, Inter_Inter_eq_left], exact or.inl (hfπ i hi), }, { have ht_empty : t = ∅, { ext1 x, simp only [finset.not_mem_empty, iff_false], exact λ hx, hi (hti x hx ▸ hx), }, simp only [ht_empty, Inter_false, Inter_univ, set.mem_singleton univ, or_true], }, }, { cases h with hs hs, { refine ⟨{i}, _, λ _, s, ⟨λ x hx, _, _⟩⟩, { rw finset.coe_singleton, }, { rw finset.mem_singleton at hx, rwa hx, }, { simp only [finset.mem_singleton, Inter_Inter_eq_left], }, }, { refine ⟨∅, _⟩, simpa only [finset.coe_empty, subset_singleton_iff, mem_empty_iff_false, is_empty.forall_iff, implies_true_iff, finset.not_mem_empty, Inter_false, Inter_univ, true_and, exists_const] using hs, }, }, end lemma pi_Union_Inter_singleton_left (s : ι → set α) (S : set ι) : pi_Union_Inter (λ i, ({s i} : set (set α))) S = {s' : set α | ∃ (t : finset ι) (htS : ↑t ⊆ S), s' = ⋂ i ∈ t, s i} := begin ext1 s', simp_rw [pi_Union_Inter, set.mem_singleton_iff, exists_prop, set.mem_set_of_eq], refine ⟨λ h, _, λ ⟨t, htS, h_eq⟩, ⟨t, htS, s, λ _ _, rfl, h_eq⟩⟩, obtain ⟨t, htS, f, hft_eq, rfl⟩ := h, refine ⟨t, htS, _⟩, congr' with i x, simp_rw set.mem_Inter, exact ⟨λ h hit, by { rw ← hft_eq i hit, exact h hit, }, λ h hit, by { rw hft_eq i hit, exact h hit, }⟩, end lemma generate_from_pi_Union_Inter_singleton_left (s : ι → set α) (S : set ι) : generate_from (pi_Union_Inter (λ k, {s k}) S) = generate_from {t | ∃ k ∈ S, s k = t} := begin refine le_antisymm (generate_from_le _) (generate_from_mono _), { rintro _ ⟨I, hI, f, hf, rfl⟩, refine finset.measurable_set_bInter _ (λ m hm, measurable_set_generate_from _), exact ⟨m, hI hm, (hf m hm).symm⟩, }, { rintro _ ⟨k, hk, rfl⟩, refine ⟨{k}, λ m hm, _, s, λ i hi, _, _⟩, { rw [finset.mem_coe, finset.mem_singleton] at hm, rwa hm, }, { exact set.mem_singleton _, }, { simp only [finset.mem_singleton, set.Inter_Inter_eq_left], }, }, end /-- If `π` is a family of π-systems, then `pi_Union_Inter π S` is a π-system. -/ lemma is_pi_system_pi_Union_Inter (π : ι → set (set α)) (hpi : ∀ x, is_pi_system (π x)) (S : set ι) : is_pi_system (pi_Union_Inter π S) := begin rintros t1 ⟨p1, hp1S, f1, hf1m, ht1_eq⟩ t2 ⟨p2, hp2S, f2, hf2m, ht2_eq⟩ h_nonempty, simp_rw [pi_Union_Inter, set.mem_set_of_eq], let g := λ n, (ite (n ∈ p1) (f1 n) set.univ) ∩ (ite (n ∈ p2) (f2 n) set.univ), have hp_union_ss : ↑(p1 ∪ p2) ⊆ S, { simp only [hp1S, hp2S, finset.coe_union, union_subset_iff, and_self], }, use [p1 ∪ p2, hp_union_ss, g], have h_inter_eq : t1 ∩ t2 = ⋂ i ∈ p1 ∪ p2, g i, { rw [ht1_eq, ht2_eq], simp_rw [← set.inf_eq_inter, g], ext1 x, simp only [inf_eq_inter, mem_inter_iff, mem_Inter, finset.mem_union], refine ⟨λ h i hi_mem_union, _, λ h, ⟨λ i hi1, _, λ i hi2, _⟩⟩, { split_ifs, exacts [⟨h.1 i h_1, h.2 i h_2⟩, ⟨h.1 i h_1, set.mem_univ _⟩, ⟨set.mem_univ _, h.2 i h_2⟩, ⟨set.mem_univ _, set.mem_univ _⟩], }, { specialize h i (or.inl hi1), rw if_pos hi1 at h, exact h.1, }, { specialize h i (or.inr hi2), rw if_pos hi2 at h, exact h.2, }, }, refine ⟨λ n hn, _, h_inter_eq⟩, simp_rw g, split_ifs with hn1 hn2, { refine hpi n (f1 n) (hf1m n hn1) (f2 n) (hf2m n hn2) (set.nonempty_iff_ne_empty.2 (λ h, _)), rw h_inter_eq at h_nonempty, suffices h_empty : (⋂ i ∈ p1 ∪ p2, g i) = ∅, from (set.not_nonempty_iff_eq_empty.mpr h_empty) h_nonempty, refine le_antisymm (set.Inter_subset_of_subset n _) (set.empty_subset _), refine set.Inter_subset_of_subset hn _, simp_rw [g, if_pos hn1, if_pos hn2], exact h.subset, }, { simp [hf1m n hn1], }, { simp [hf2m n h], }, { exact absurd hn (by simp [hn1, h]), }, end lemma pi_Union_Inter_mono_left {π π' : ι → set (set α)} (h_le : ∀ i, π i ⊆ π' i) (S : set ι) : pi_Union_Inter π S ⊆ pi_Union_Inter π' S := λ s ⟨t, ht_mem, ft, hft_mem_pi, h_eq⟩, ⟨t, ht_mem, ft, λ x hxt, h_le x (hft_mem_pi x hxt), h_eq⟩ lemma pi_Union_Inter_mono_right {π : ι → set (set α)} {S T : set ι} (hST : S ⊆ T) : pi_Union_Inter π S ⊆ pi_Union_Inter π T := λ s ⟨t, ht_mem, ft, hft_mem_pi, h_eq⟩, ⟨t, ht_mem.trans hST, ft, hft_mem_pi, h_eq⟩ lemma generate_from_pi_Union_Inter_le {m : measurable_space α} (π : ι → set (set α)) (h : ∀ n, generate_from (π n) ≤ m) (S : set ι) : generate_from (pi_Union_Inter π S) ≤ m := begin refine generate_from_le _, rintros t ⟨ht_p, ht_p_mem, ft, hft_mem_pi, rfl⟩, refine finset.measurable_set_bInter _ (λ x hx_mem, (h x) _ _), exact measurable_set_generate_from (hft_mem_pi x hx_mem), end lemma subset_pi_Union_Inter {π : ι → set (set α)} {S : set ι} {i : ι} (his : i ∈ S) : π i ⊆ pi_Union_Inter π S := begin have h_ss : {i} ⊆ S, { intros j hj, rw mem_singleton_iff at hj, rwa hj, }, refine subset.trans _ (pi_Union_Inter_mono_right h_ss), rw pi_Union_Inter_singleton, exact subset_union_left _ _, end lemma mem_pi_Union_Inter_of_measurable_set (m : ι → measurable_space α) {S : set ι} {i : ι} (hiS : i ∈ S) (s : set α) (hs : measurable_set[m i] s) : s ∈ pi_Union_Inter (λ n, {s | measurable_set[m n] s}) S := subset_pi_Union_Inter hiS hs lemma le_generate_from_pi_Union_Inter {π : ι → set (set α)} (S : set ι) {x : ι} (hxS : x ∈ S) : generate_from (π x) ≤ generate_from (pi_Union_Inter π S) := generate_from_mono (subset_pi_Union_Inter hxS) lemma measurable_set_supr_of_mem_pi_Union_Inter (m : ι → measurable_space α) (S : set ι) (t : set α) (ht : t ∈ pi_Union_Inter (λ n, {s | measurable_set[m n] s}) S) : measurable_set[⨆ i ∈ S, m i] t := begin rcases ht with ⟨pt, hpt, ft, ht_m, rfl⟩, refine pt.measurable_set_bInter (λ i hi, _), suffices h_le : m i ≤ (⨆ i ∈ S, m i), from h_le (ft i) (ht_m i hi), have hi' : i ∈ S := hpt hi, exact le_supr₂ i hi', end lemma generate_from_pi_Union_Inter_measurable_set (m : ι → measurable_space α) (S : set ι) : generate_from (pi_Union_Inter (λ n, {s | measurable_set[m n] s}) S) = ⨆ i ∈ S, m i := begin refine le_antisymm _ _, { rw ← @generate_from_measurable_set α (⨆ i ∈ S, m i), exact generate_from_mono (measurable_set_supr_of_mem_pi_Union_Inter m S), }, { refine supr₂_le (λ i hi, _), rw ← @generate_from_measurable_set α (m i), exact generate_from_mono (mem_pi_Union_Inter_of_measurable_set m hi), }, end end Union_Inter namespace measurable_space variable {α : Type*} /-! ## Dynkin systems and Π-λ theorem -/ /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by a collection of sets which is stable under intersection. A Dynkin system is also known as a "λ-system" or a "d-system". -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀ {a}, has a → has aᶜ) (has_Union_nat : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, has (f i)) → has (⋃ i, f i)) namespace dynkin_system @[ext] lemma ext : ∀ {d₁ d₂ : dynkin_system α}, (∀ s : set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has aᶜ ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty lemma has_Union {β} [countable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀ i, d.has (f i)) : d.has (⋃ i, f i) := by { casesI nonempty_encodable β, rw ← encodable.Union_decode₂, exact d.has_Union_nat (encodable.Union_decode₂_disjoint_on hd) (λ n, encodable.Union_decode₂_cases d.has_empty h) } theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : disjoint s₁ s₂) : d.has (s₁ ∪ s₂) := by { rw union_eq_Union, exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) } lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := begin apply d.has_compl_iff.1, simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (disjoint_compl_left.mono_right h), end instance : has_le (dynkin_system α) := { le := λ m₁ m₂, m₁.has ≤ m₂.has } lemma le_def {α} {a b : dynkin_system α} : a ≤ b ↔ a.has ≤ b.has := iff.rfl instance : partial_order (dynkin_system α) := { le_refl := assume a b, le_rfl, le_trans := assume a b c hab hbc, le_def.mpr (le_trans hab hbc), le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩, ..dynkin_system.has_le } /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.measurable_set', has_empty := m.measurable_set_empty, has_compl := m.measurable_set_compl, has_Union_nat := assume f _ hf, m.measurable_set_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀ t ∈ s, generate_has t | empty : generate_has ∅ | compl : ∀ {a}, generate_has a → generate_has aᶜ | Union : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, generate_has (f i)) → generate_has (⋃ i, f i) lemma generate_has_compl {C : set (set α)} {s : set α} : generate_has C sᶜ ↔ generate_has C s := by { refine ⟨_, generate_has.compl⟩, intro h, convert generate_has.compl h, simp } /-- The least Dynkin system containing a collection of basic sets. -/ def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } lemma generate_has_def {C : set (set α)} : (generate C).has = generate_has C := rfl instance : inhabited (dynkin_system α) := ⟨generate univ⟩ /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . measurable_set' := d.has, measurable_set_empty := d.has_empty, measurable_set_compl := assume s h, d.has_compl h, measurable_set_Union := λ f hf, begin rw ←Union_disjointed, exact d.has_Union (disjoint_disjointed _) (λ n, disjointed_rec (λ t i h, h_inter _ _ h $ d.has_compl $ hf i) (hf n)), end } lemma of_measurable_space_to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λ t, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have tᶜ ∩ s = ((t ∩ s)ᶜ) \ sᶜ, from set.ext $ assume x, by { by_cases x ∈ s; simp [h] }, by { rw [this], exact d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _) }, has_Union_nat := assume f hd hf, begin rw [Union_inter], refine d.has_Union_nat _ hf, exact hd.mono (λ i j, disjoint.mono (inter_subset_left _ _) (inter_subset_left _ _)), end } lemma generate_le {s : set (set α)} (h : ∀ t ∈ s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_has_subset_generate_measurable {C : set (set α)} {s : set α} (hs : (generate C).has s) : measurable_set[generate_from C] s := generate_le (of_measurable_space (generate_from C)) (λ t, measurable_set_generate_from) s hs lemma generate_inter {s : set (set α)} (hs : is_pi_system s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty) (λ h, generate_has.basic _ $ hs _ hs₂ _ hs₁ h), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ /-- **Dynkin's π-λ theorem**: Given a collection of sets closed under binary intersections, then the Dynkin system it generates is equal to the σ-algebra it generates. This result is known as the π-λ theorem. A collection of sets closed under binary intersection is called a π-system (often requiring additionnally that is is non-empty, but we drop this condition in the formalization). -/ lemma generate_from_eq {s : set (set α)} (hs : is_pi_system s) : generate_from s = (generate s).to_measurable_space (λ t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by { rw [of_measurable_space_to_measurable_space], exact (generate_le _ $ assume t ht, measurable_set_generate_from ht) }) end dynkin_system theorem induction_on_inter {C : set α → Prop} {s : set (set α)} [m : measurable_space α] (h_eq : m = generate_from s) (h_inter : is_pi_system s) (h_empty : C ∅) (h_basic : ∀ t ∈ s, C t) (h_compl : ∀ t, measurable_set t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, measurable_set (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, measurable_set t → C t := have eq : measurable_set = dynkin_system.generate_has s, by { rw [h_eq, dynkin_system.generate_from_eq h_inter], refl }, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by { rw [eq], exact ht }) (assume f hf ht, h_union f hf $ assume i, by { rw [eq], exact ht _ }) end measurable_space
db93a78ae9af001d41b1c193a1925a81269d12c0
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/char_p/algebra.lean
2f3343ff6b3a4194e0c31cd0aea015350e3f6a4d
[ "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
3,668
lean
/- Copyright (c) 2021 Jon Eugster. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jon Eugster, Eric Wieser -/ import algebra.char_p.basic import ring_theory.localization import algebra.free_algebra /-! # Characteristics of algebras In this file we describe the characteristic of `R`-algebras. In particular we are interested in the characteristic of free algebras over `R` and the fraction field `fraction_ring R`. ## Main results - `char_p_of_injective_algebra_map` If `R →+* A` is an injective algebra map then `A` has the same characteristic as `R`. Instances constructed from this result: - Any `free_algebra R X` has the same characteristic as `R`. - The `fraction_ring R` of an integral domain `R` has the same characteristic as `R`. -/ /-- If the algebra map `R →+* A` is injective then `A` has the same characteristic as `R`. -/ lemma char_p_of_injective_algebra_map {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] (h : function.injective (algebra_map R A)) (p : ℕ) [char_p R p] : char_p A p := { cast_eq_zero_iff := λx, begin rw ←char_p.cast_eq_zero_iff R p x, change algebra_map ℕ A x = 0 ↔ algebra_map ℕ R x = 0, rw is_scalar_tower.algebra_map_apply ℕ R A x, refine iff.trans _ h.eq_iff, rw ring_hom.map_zero, end } /-- If the algebra map `R →+* A` is injective and `R` has characteristic zero then so does `A`. -/ lemma char_zero_of_injective_algebra_map {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] (h : function.injective (algebra_map R A)) [char_zero R] : char_zero A := { cast_injective := λ x y hxy, begin change algebra_map ℕ A x = algebra_map ℕ A y at hxy, rw is_scalar_tower.algebra_map_apply ℕ R A x at hxy, rw is_scalar_tower.algebra_map_apply ℕ R A y at hxy, exact char_zero.cast_injective (h hxy), end } -- `char_p.char_p_to_char_zero A _ (char_p_of_injective_algebra_map h 0)` does not work -- here as it would require `ring A`. section variables (K L : Type*) [field K] [comm_semiring L] [nontrivial L] [algebra K L] lemma algebra.char_p_iff (p : ℕ) : char_p K p ↔ char_p L p := (algebra_map K L).char_p_iff_char_p p end namespace free_algebra variables {R X : Type*} [comm_semiring R] (p : ℕ) /-- If `R` has characteristic `p`, then so does `free_algebra R X`. -/ instance char_p [char_p R p] : char_p (free_algebra R X) p := char_p_of_injective_algebra_map free_algebra.algebra_map_left_inverse.injective p /-- If `R` has characteristic `0`, then so does `free_algebra R X`. -/ instance char_zero [char_zero R] : char_zero (free_algebra R X) := char_zero_of_injective_algebra_map free_algebra.algebra_map_left_inverse.injective end free_algebra namespace is_fraction_ring variables (R : Type*) {K : Type*} [comm_ring R] [field K] [algebra R K] [is_fraction_ring R K] variables (p : ℕ) /-- If `R` has characteristic `p`, then so does Frac(R). -/ lemma char_p_of_is_fraction_ring [char_p R p] : char_p K p := char_p_of_injective_algebra_map (is_fraction_ring.injective R K) p /-- If `R` has characteristic `0`, then so does Frac(R). -/ lemma char_zero_of_is_fraction_ring [char_zero R] : char_zero K := @char_p.char_p_to_char_zero K _ (char_p_of_is_fraction_ring R 0) variables [integral_domain R] /-- If `R` has characteristic `p`, then so does `fraction_ring R`. -/ instance char_p [char_p R p] : char_p (fraction_ring R) p := char_p_of_is_fraction_ring R p /-- If `R` has characteristic `0`, then so does `fraction_ring R`. -/ instance char_zero [char_zero R] : char_zero (fraction_ring R) := char_zero_of_is_fraction_ring R end is_fraction_ring
44fe18fe035aefee6e2dfd557c84c1eeebb826c4
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/solutions/wednesday/morning/structures.lean
326631b05f4de5bea028bfb42657948def0dc75b
[]
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
21,514
lean
import data.rat.basic import data.nat.parity import tactic.basic open nat noncomputable theory -- definitions are allowed to not compute in this file open_locale classical -- use classical logic in this file /-! ## Structures and Classes In this session we will discuss structures together, and then you can solve the exercises yourself. Before we start, run the following in a terminal: ``` cd /path/to/lftcm2020/ git pull leanproject get-mathlib-cache ``` If `git pull` didn't work because you edited one of the files in the repository, first copy the files to a backup version and then run `git checkout -- .` (this will remove all changes to files you edited, so be careful!) ### Declaring a Structure Structures are a way to bundle information together. For example, the first example below makes a new structure `even_natural_number`, which consists of pairs, where the first component is a natural number, and the second component is a proof that the natural number is even. These are called the *fields* of the structure. -/ structure even_natural_number : Type := (n : ℕ) (even_n : even n) /-! We can also group propositions together, for example this is a proposition stating that `n` is an even cube greater than 100. Note that this is a property of a natural number, while the previous structure was a natural number with a property "bundled" together. -/ structure is_even_cube_above_100 (n : ℕ) : Prop := (even : even n) (is_cube : ∃ k, n = k^3) (gt_100 : n > 100) /-! Here we give the upper bounds for a function `f`. We can omit the type of the structure. -/ structure bounds (f : ℕ → ℕ) := (bound : ℕ) (le_bound : ∀ (n : ℕ), f n ≤ bound) /-! You can use `#print` to print the type and all fields of a structure. -/ #print even_natural_number #print is_even_cube_above_100 #print bounds /-! ### Exercise 1 * Define a structure of eventually constant sequences `ℕ → ℕ`. The first field will be `seq : ℕ → ℕ`, and the second field will be the statement that `seq` is eventually constant. * Define a structure of a type with 2 points that are unequal. (hint: omit the type of the structure, Lean might complain if you give it explicitly) Lean will not tell you if you got the right definition, but it will complain if you make a syntax error. If you are unsure, ask a mentor to check whether your solution is correct. -/ -- omit /- There are different ways to do these, here is one way. -/ structure eventually_constant_sequence : Type := (seq : ℕ → ℕ) (eventually_constant : ∃ k v, ∀ n ≥ k, seq n = v) structure bipointed_type := (A : Type) (x y : A) (x_ne_y : x ≠ y) -- omit /-! ### Projections of a structure -/ /-! The field names are declared in the namespace of the structure. This means that their names have the form `<structure_name>.<field_name>`. -/ example (n : ℕ) (hn : is_even_cube_above_100 n) : n > 100 := is_even_cube_above_100.gt_100 hn /-! You can also `open` the namespace, to use the abbreviated form. We put this `open` command inside a section, so that the namespace is closed at the end of the `section`. -/ section open is_even_cube_above_100 example (n : ℕ) (hn : is_even_cube_above_100 n) : n > 100 := gt_100 hn end /-! Another useful technique is to use *projection notation*. Instead of writing `is_even_cube_above_100.even hn` we can write `hn.even`. Lean will look at the type of `hn` and see that it is `is_even_cube_above_100 n`. Then it looks for the lemma with the name `is_even_cube_above_100.even` and apply it to `hn`. -/ example (n : ℕ) (hn : is_even_cube_above_100 n) : even n := hn.even example (n : ℕ) (hn : is_even_cube_above_100 n) : even n ∧ ∃ k, n = k^3 := ⟨ hn.even, hn.is_cube ⟩ /-! You can also use `.1`, `.2`, `.3`, ... for the fields of a structure. -/ example (n : ℕ) (hn : is_even_cube_above_100 n) : even n ∧ n > 100 ∧ (∃ k, n = k^3) := ⟨ hn.1, hn.3, hn.2 ⟩ /-! We could have alternatively stated `is_even_cube_above_100` as a conjunction of three statements, as below. That gives the same proposition, but doesn't give a name to the three components. -/ def is_even_cube_above_100' (n : ℕ) : Prop := even n ∧ (∃ k, n = k^3) ∧ n > 100 /-! If we have a structure that mixes data (elements of types, like `ℕ`, `ℝ`, and so on) and properties of the data, we can alternatively declare them using *subtypes*. This consists of pairs of a natural number and a proof that the natural number is even. -/ def even_natural_number' : Type := { n : ℕ // even n } /-! The notation for subtypes is almost the same as the notation for set comprehension. Note that `//` is used for subtypes, and `|` is used for sets. -/ def set_of_even_natural_numbers : set ℕ := { n : ℕ | even n } /-! We can construct objects of a structure using the *anonymous constructor* `⟨...⟩`. This can construct an object of any structure, including conjunctions, existential statements and subtypes. -/ example : even_natural_number → even_natural_number' := λ n, ⟨n.1, n.2⟩ example (n : ℕ) : is_even_cube_above_100 n → is_even_cube_above_100' n := λ hn, ⟨hn.even, hn.is_cube, hn.gt_100⟩ /-! An alternative way is to use the *structure notation*. The syntax for this is ``` { structure_name . field1_name := value, field2_name := value, ... } ``` You can prove the fields in any order you want. -/ example : even_natural_number' → even_natural_number := λ n, { even_natural_number . n := n.1, even_n := n.2 } /-! The structure name is optional if the structure in question is clear from context. -/ example (n : ℕ) : is_even_cube_above_100' n → is_even_cube_above_100 n := λ ⟨h1n, h2n, h3n⟩, { even := h1n, is_cube := h2n, gt_100 := h3n } /-! ### Exercise 2 * Define `bounds` (given above) again, but now using a the subtype notation `{ _ : _ // _ }`. * Define functions back and forth from the structure `bounds` given above and `bounds` given here. Try different variations using the anonymous constructor and the projection notation. -/ #print bounds def bounds' (f : ℕ → ℕ) : Type := /- inline sorry -/ { n : ℕ // ∀ (m : ℕ), f m ≤ n } /- inline sorry -/ example (f : ℕ → ℕ) : bounds f → bounds' f := /- inline sorry -/ λ ⟨n, hn⟩, ⟨n, hn⟩ /- inline sorry -/ /- In the example below, replace the `sorry` by an underscore `_`. A small yellow lightbulb will appear. Click it, and then select `Generate skeleton for the structure under construction`. This will automatically give an outline of the structure for you. -/ example (f : ℕ → ℕ) : bounds' f → bounds f := λ n, /- inline sorry -/ { bound := n.1, le_bound := n.2 } /- inline sorry -/ /-! Before you continue, watch the second pre-recorded video. -/ /-! ### Classes Classes are special kind of types or propositions that Lean will automatically find inhabitants for. You can declare a class by giving it the `@[class]` attribute. As an example, in this section, we will implement square root on natural numbers, that can only be applied to natural numbers that are squares. -/ @[class] def is_square (n : ℕ) : Prop := ∃k : ℕ, k^2 = n namespace is_square /-! Hypotheses with a class as type should be written in square brackets `[...]`. This tells Lean that they are implicit, and Lean will try to fill them in automatically. We define the square root as the (unique) number `k` such that `k^2 = n`. Such `k` exists by the `is_square n` hypothesis. -/ def sqrt (n : ℕ) [hn : is_square n] : ℕ := classical.some hn prefix `√`:(max+1) := sqrt -- notation for `sqrt` /-! The following is the defining property of `√n`. Note that when we write `√n`, Lean will automatically insert the implicit argument `hn` it found it the context. This is called *type-class inference*. We mark this lemma with the `@[simp]` attribute to tell `simp` to simplify using this lemma. -/ @[simp] lemma square_sqrt (n : ℕ) [hn : is_square n] : (√n) ^ 2 = n := classical.some_spec hn /-! ### Exercise: Fill in all `sorry`s in the remainder of this section. -/ /-! Prove this lemma. Again we mark it `@[simp]` so that `simp` can simplify equalities involving `√`. Also, hypotheses in square brackets do not need a name. Hint: use `pow_left_inj` -/ @[simp] lemma sqrt_eq_iff (n k : ℕ) [is_square n] : √n = k ↔ n = k^2 := begin -- sorry split; intro h, { simp [← h] }, { exact pow_left_inj (nat.zero_le _) (nat.zero_le k) two_pos (by simp [h]) } -- sorry end /-! To help type-class inference, we have to tell it that some numbers are always squares. Here we show that `n^2` is always a square. We mark it as `instance`, which is like `lemma` or `def`, except that it is automatically used by type-class inference. -/ instance square_square (n : ℕ) : is_square (n^2) := ⟨n, rfl⟩ lemma sqrt_square (n : ℕ) : √(n ^ 2) = n := by simp /-! Instances can depend on other instances: here we show that if `n` and `m` are squares, then `n * m` is one, too. When writing `√n`, Lean will use a simple search algorithm to find a proof that `n` is a square, by repeatedly applying previously declared instances, and arguments in the local context. -/ instance square_mul (n m : ℕ) [is_square n] [is_square m] : is_square (n*m) := ⟨√n * √m, by simp [nat.mul_pow]⟩ /-! Hint: use `nat.mul_pow` -/ #check nat.mul_pow lemma sqrt_mul (n m : ℕ) [is_square n] [is_square m] : √(n * m) = √n * √m := begin -- sorry simp [nat.mul_pow] -- sorry end /-! Note that Lean automatically inserts the proof that `n * m ^ 2` is a square, using the previously declared instances. -/ example (n m : ℕ) [is_square n] : √(n * m ^ 2) = √n * m := begin -- sorry simp [sqrt_mul, sqrt_square], -- sorry end /-! Hint: use `nat.le_mul_self` and `nat.pow_two` -/ #check nat.le_mul_self #check nat.pow_two lemma sqrt_le (n : ℕ) [is_square n] : √n ≤ n := begin -- sorry conv_rhs { rw [← square_sqrt n, nat.pow_two] }, apply nat.le_mul_self -- sorry end end is_square /- At this point, feel free do the remaining exercises in any order. -/ /-! ### Exercise: Bijections and equivalences -/ section bijections open function variables {α β : Type*} /- An important structure is the type of equivalences, which gives an equivalence (bijection) between two types: ``` structure equiv (α β : Type*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) ``` In this section we show that this is the same as the bijections from `α` to `β`. -/ #print equiv structure bijection (α β : Type*) := (to_fun : α → β) (injective : injective to_fun) (surjective : surjective to_fun) /- We declare a *coercion*. This allows us to treat `f` as a function if `f : bijection α β`. -/ instance : has_coe_to_fun (bijection α β) := ⟨_, λ f, f.to_fun⟩ /-! To show that two bijections are equal, it is sufficient that the underlying functions are equal on all inputs. We mark it as `@[ext]` so that we can later use the tactic `ext` to show that two bijections are equal. -/ @[ext] def bijection.ext {f g : bijection α β} (hfg : ∀ x, f x = g x) : f = g := by { cases f, cases g, congr, ext, exact hfg x } /-! This lemma allows `simp` to reduce the application of a bijection to an argument. -/ @[simp] lemma coe_mk {f : α → β} {h1f : injective f} {h2f : surjective f} {x : α} : { bijection . to_fun := f, injective := h1f, surjective := h2f } x = f x := rfl /- There is a lemma in the library that almost states this. You can use the tactic `suggest` to get suggested lemmas from Lean (the one you want has `bijective` in the name). -/ def equiv_of_bijection (f : bijection α β) : α ≃ β := begin -- sorry exact equiv.of_bijective f ⟨f.injective, f.surjective⟩ -- sorry end def bijection_of_equiv (f : α ≃ β) : bijection α β := -- sorry { to_fun := f, injective := f.injective, surjective := f.surjective } -- sorry /-! Show that bijections are the same (i.e. equivalent) to equivalences. -/ def bijection_equiv_equiv : bijection α β ≃ (α ≃ β) := -- sorry { to_fun := equiv_of_bijection, inv_fun := bijection_of_equiv, left_inv := by { intro f, ext, simp [bijection_of_equiv, equiv_of_bijection] }, right_inv := by { intro f, ext, simp [bijection_of_equiv, equiv_of_bijection] } } -- sorry end bijections /-! ### Exercise: Bundled groups -/ /-! Below is a possible definition of a group in Lean. It's not the definition we use use in mathlib. The actual definition uses classes, and will be explained in detail in the next session. -/ structure Group := (G : Type*) (op : G → G → G) (infix * := op) -- temporary notation `*` for `op`, just inside this structure declaration (op_assoc' : ∀ (x y z : G), (x * y) * z = x * (y * z)) (id : G) (notation 1 := id) -- temporary notation `1` for `id`, just inside this structure declaration (id_op' : ∀ (x : G), 1 * x = x) (inv : G → G) (postfix ⁻¹ := inv) -- temporary notation `⁻¹` for `inv`, just inside this structure declaration (op_left_inv' : ∀ (x : G), x⁻¹ * x = 1) /-! You can use the `extend` command to define a structure that adds fields to one or more existing structures. -/ structure CommGroup extends Group := (infix * := op) (op_comm : ∀ (x y : G), x * y = y * x) /- Here is an example: the rationals form a group under addition. -/ def rat_Group : Group := { G := ℚ, op := (+), -- you can put parentheses around an infix operation to talk about the operation itself. op_assoc' := add_assoc, id := 0, id_op' := zero_add, inv := λ x, -x, op_left_inv' := neg_add_self } /-- You can extend an object of a structure by using the structure notation and using `..<existing object>`. -/ def rat_CommGroup : CommGroup := { G := ℚ, op_comm := add_comm, ..rat_Group } namespace Group variables {G : Group} /- Let `G` be a group -/ /- The following line declares that if `G : Group`, then we can also view `G` as a type. -/ instance : has_coe_to_sort Group := ⟨_, Group.G⟩ /- The following lines declare the notation `*`, `⁻¹` and `1` for the fields of `Group`. -/ instance : has_mul G := ⟨G.op⟩ instance : has_inv G := ⟨G.inv⟩ instance : has_one G := ⟨G.id⟩ /- the axioms for groups are satisfied -/ lemma op_assoc (x y z : G) : (x * y) * z = x * (y * z) := G.op_assoc' x y z lemma id_op (x : G) : 1 * x = x := G.id_op' x lemma op_left_inv (x : G) : x⁻¹ * x = 1 := G.op_left_inv' x /- Use the axioms `op_assoc`, `id_op` and `op_left_inv` to prove the following lemma. The fields `op_assoc'`, `id_op'` and `op_left_inv'` should not be used directly, nor can you use any lemmas from the library about `mul`. -/ lemma eq_id_of_op_eq_self {G : Group} {x : G} : x * x = x → x = 1 := begin -- sorry intro hx, rw [←id_op x, ← op_left_inv x, op_assoc, hx] -- sorry end /- Apply the previous lemma to show that `⁻¹` is also a right-sided inverse. -/ lemma op_right_inv {G : Group} (x : G) : x * x⁻¹ = 1 := begin -- sorry apply eq_id_of_op_eq_self, rw [op_assoc x x⁻¹ (x * x⁻¹), ← op_assoc x⁻¹ x x⁻¹, op_left_inv, id_op] -- sorry end /- we can prove that `1` is also a right identity. -/ lemma op_id {G : Group} (x : G) : x * 1 = x := begin -- sorry rw [← op_left_inv x, ← op_assoc, op_right_inv, id_op] -- sorry end /-! However, it is inconvenient to use this group instance directly. One reason is that to use these group operations we now have to write `(x y : rat_Group)` instead of `(x y : ℚ)`. That's why in Lean we use classes for algebraic structures, explained in the next lecture. -/ /- show that the cartesian product of two groups is a group. The underlying type will be `G × H`. -/ def prod_Group (G H : Group) : Group := -- sorry { G := G × H, op := λ x y, (x.1 * y.1, x.2 * y.2), op_assoc' := by { intros, ext; simp; rw [op_assoc] }, id := (1, 1), id_op' := by { intros, ext; simp; rw [id_op] }, inv := λ x, (x.1⁻¹, x.2⁻¹), op_left_inv' := by { intros, ext; simp; rw [op_left_inv] } } -- sorry end Group /-! ### Exercise: Pointed types -/ structure pointed_type := (type : Type*) (point : type) namespace pointed_type variables {A B : pointed_type} /- The following line declares that if `A : pointed_type`, then we can also view `A` as a type. -/ instance : has_coe_to_sort pointed_type := ⟨_, pointed_type.type⟩ /- The product of two pointed types is a pointed type. The `@[simps point]` is a hint to `simp` that it can unfold the point of this definition. -/ @[simps point] def prod (A B : pointed_type) : pointed_type := { type := A × B, point := (A.point, B.point) } end pointed_type structure pointed_map (A B : pointed_type) := (to_fun : A → B) (to_fun_point : to_fun A.point = B.point) namespace pointed_map infix ` →. `:25 := pointed_map variables {A B C D : pointed_type} variables {h : C →. D} {g : B →. C} {f f₁ f₂ : A →. B} instance : has_coe_to_fun (A →. B) := ⟨λ _, A → B, pointed_map.to_fun⟩ @[simp] lemma coe_mk {f : A → B} {hf : f A.point = B.point} {x : A} : { pointed_map . to_fun := f, to_fun_point := hf } x = f x := rfl @[simp] lemma coe_point : f A.point = B.point := f.to_fun_point @[ext] protected lemma ext (hf₁₂ : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := begin -- sorry cases f₁ with f₁ hf₁, cases f₂ with f₂ hf₂, congr, ext x, exact hf₁₂ x -- sorry end /-! Below we show that pointed types form a category. -/ def comp (g : B →. C) (f : A →. B) : A →. C := -- sorry { to_fun := g ∘ f, to_fun_point := by simp } -- sorry def id : A →. A := -- sorry { to_fun := id, to_fun_point := by simp } -- sorry /-! You can use projection notation for any declaration declared in the same namespace as the structure. For example, `g.comp f` means `pointed_map.comp g f` -/ lemma comp_assoc : h.comp (g.comp f) = (h.comp g).comp f := -- sorry by { ext x, refl } -- sorry lemma id_comp : f.comp id = f := -- sorry by { ext x, refl } -- sorry lemma comp_id : id.comp f = f := -- sorry by { ext x, refl } -- sorry /-! Below we show that `A.prod B` (that is, `pointed_type.prod A B`) is a product in the category of pointed types. -/ def fst : A.prod B →. A := -- sorry { to_fun := prod.fst, to_fun_point := rfl } -- sorry def snd : A.prod B →. B := -- sorry { to_fun := prod.snd, to_fun_point := rfl } -- sorry def pair (f : C →. A) (g : C →. B) : C →. A.prod B := -- sorry { to_fun := λ c, (f c, g c), to_fun_point := by simp } -- sorry lemma fst_pair (f : C →. A) (g : C →. B) : fst.comp (f.pair g) = f := -- sorry by { ext, simp [pair, fst, comp] } -- sorry lemma snd_pair (f : C →. A) (g : C →. B) : snd.comp (f.pair g) = g := -- sorry by { ext, simp [pair, snd, comp] } -- sorry lemma pair_unique (f : C →. A) (g : C →. B) (u : C →. A.prod B) (h1u : fst.comp u = f) (h2u : snd.comp u = g) : u = f.pair g := begin -- sorry ext, { have : fst (u x) = f x, { rw [←h1u], simp [comp] }, simpa using this }, { have : snd (u x) = g x, { rw [←h2u], simp [comp] }, simpa using this } -- sorry end end pointed_map /-! As an advanced exercise, you can show that the category of pointed type has coproducts. For this we need quotients, the basic interface is given with the declarations `quot r`: the quotient of the equivalence relation generated by relation `r` on `A` `quot.mk r : A → quot r`, `quot.sound` `quot.lift` (see below) -/ #print quot #print quot.mk #print quot.sound #print quot.lift open sum /-! We want to define the coproduct of pointed types `A` and `B` as the coproduct `A ⊕ B` of the underlying type, identifying the two basepoints. First define a relation that *only* relates `inl A.point ~ inr B.point`. -/ def coprod_rel (A B : pointed_type) : (A ⊕ B) → (A ⊕ B) → Prop := -- sorry λ x y, x = inl A.point ∧ y = inr B.point -- sorry namespace pointed_type -- @[simps point] -- omit @[simps point] -- omit def coprod (A B : pointed_type) : pointed_type := -- sorry { type := quot (coprod_rel A B), point := quot.mk _ (inl A.point) } -- sorry end pointed_type namespace pointed_map variables {A B C D : pointed_type} def inl : A →. A.coprod B := -- sorry { to_fun := quot.mk _ ∘ sum.inl, to_fun_point := rfl } -- sorry def inr : B →. A.coprod B := -- sorry { to_fun := quot.mk _ ∘ sum.inr, to_fun_point := by { refine (quot.sound _).symm, exact ⟨rfl, rfl⟩ } } -- sorry def elim (f : A →. C) (g : B →. C) : A.coprod B →. C := -- sorry { to_fun := quot.lift (sum.elim f g) (by { rintro _ _ ⟨rfl, rfl⟩, simp }), to_fun_point := by simp } -- sorry lemma elim_comp_inl (f : A →. C) (g : B →. C) : (f.elim g).comp inl = f := -- sorry by { ext, simp [elim, inl, comp] } -- sorry lemma elim_comp_inr (f : A →. C) (g : B →. C) : (f.elim g).comp inr = g := -- sorry by { ext, simp [elim, inr, comp] } -- sorry lemma elim_unique (f : A →. C) (g : B →. C) (u : A.coprod B →. C) (h1u : u.comp inl = f) (h2u : u.comp inr = g) : u = f.elim g := begin -- sorry ext (x|y), { have : u (inl x) = f x, { rw [←h1u], simp [comp] }, simpa [elim, inl] using this }, { have : u (inr y) = g y, { rw [←h2u], simp [comp] }, simpa [elim, inl] using this } -- sorry end end pointed_map
df7fd7a1b6f646fb1ac6360b58c40ec797a5dadd
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/fn_default.lean
a7036865aad662f128206253112d0c7cc02758e0
[ "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
129
lean
structure foo := (bar : Π n : ℕ, ℕ := id) (baz : Π {n : ℕ}, ℕ := id) (bat : Π n : ℕ, ℕ := λ n, n) #check {foo.}
4197114439ab4c14121ac8c80c50efcaf4ee2fcb
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/data/nat/prime.lean
56c18ca58223cead4ec86e8ddb917403d1f289a9
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,248
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import data.nat.sqrt import data.nat.gcd import data.list.sort import algebra.group_power import tactic.wlog import tactic.norm_num /-! # Prime numbers This file deals with prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`. ## Important declarations All the following declarations exist in the namespace `nat`. - `prime`: the predicate that expresses that a natural number `p` is prime - `primes`: the subtype of natural numbers that are prime - `min_fac n`: the minimal prime factor of a natural number `n ≠ 1` - `exists_infinite_primes`: Euclid's theorem that there exist infinitely many prime numbers - `factors n`: the prime factorization of `n` - `factors_unique`: uniqueness of the prime factorisation -/ open bool subtype open_locale nat namespace nat /-- `prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. -/ @[pp_nodot] def prime (p : ℕ) := 2 ≤ p ∧ ∀ m ∣ p, m = 1 ∨ m = p theorem prime.two_le {p : ℕ} : prime p → 2 ≤ p := and.left theorem prime.one_lt {p : ℕ} : prime p → 1 < p := prime.two_le instance prime.one_lt' (p : ℕ) [hp : _root_.fact p.prime] : _root_.fact (1 < p) := ⟨hp.1.one_lt⟩ lemma prime.ne_one {p : ℕ} (hp : p.prime) : p ≠ 1 := ne.symm $ ne_of_lt hp.one_lt theorem prime_def_lt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m < p, m ∣ p → m = 1 := and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h l d, (h d).resolve_right (ne_of_lt l), λ h d, (le_of_dvd (le_of_succ_le p2) d).lt_or_eq_dec.imp_left (λ l, h l d)⟩ theorem prime_def_lt' {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p := prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial), λ h l d, begin rcases m with _|_|m, { rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial }, { refl }, { exact (h dec_trivial l).elim d } end⟩ theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p := prime_def_lt'.trans $ and_congr_right $ λ p2, ⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2, λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from λ m k mk m1 e, a m m1 (le_sqrt.2 (e.symm ▸ nat.mul_le_mul_left m mk)) ⟨k, e⟩, λ m m2 l ⟨k, e⟩, begin cases (le_total m k) with mk km, { exact this mk m2 e }, { rw [mul_comm] at e, refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e, rwa [one_mul, ← e] } end⟩ section /-- This instance is slower than the instance `decidable_prime` defined below, but has the advantage that it works in the kernel for small values. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ local attribute [instance] def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' lemma prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 := by { rintro rfl, revert h, dec_trivial } theorem prime.pos {p : ℕ} (pp : prime p) : 0 < p := lt_of_succ_lt pp.one_lt theorem not_prime_zero : ¬ prime 0 := by simp [prime] theorem not_prime_one : ¬ prime 1 := by simp [prime] theorem prime_two : prime 2 := dec_trivial end theorem prime.pred_pos {p : ℕ} (pp : prime p) : 0 < pred p := lt_pred_iff.2 pp.one_lt theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩ theorem dvd_prime_two_le {p m : ℕ} (pp : prime p) (H : 2 ≤ m) : m ∣ p ↔ m = p := (dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H theorem prime_dvd_prime_iff_eq {p q : ℕ} (pp : p.prime) (qp : q.prime) : p ∣ q ↔ p = q := dvd_prime_two_le qp (prime.two_le pp) theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 | d := (not_le_of_gt pp.one_lt) $ le_of_dvd dec_trivial d theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) := λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $ by simpa using (dvd_prime_two_le h a1).1 (dvd_mul_right _ _) lemma not_prime_mul' {a b n : ℕ} (h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬ prime n := by { rw ← h, exact not_prime_mul h₁ h₂ } section min_fac private lemma min_fac_lemma (n k : ℕ) (h : ¬ n < k * k) : sqrt n - k < sqrt n + 2 - k := (nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $ nat.lt_add_of_pos_right dec_trivial /-- If `n < k * k`, then `min_fac_aux n k = n`, if `k | n`, then `min_fac_aux n k = k`. Otherwise, `min_fac_aux n k = min_fac_aux n (k+2)` using well-founded recursion. If `n` is odd and `1 < n`, then then `min_fac_aux n 3` is the smallest prime factor of `n`. -/ def min_fac_aux (n : ℕ) : ℕ → ℕ | k := if h : n < k * k then n else if k ∣ n then k else have _, from min_fac_lemma n k h, min_fac_aux (k + 2) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : ℕ → ℕ | 0 := 2 | 1 := 1 | (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3 @[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3 | 0 := by simp | 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl | (n+2) := have 2 ∣ n + 2 ↔ 2 ∣ n, from (nat.dvd_add_iff_left (by refl)).symm, by simp [min_fac, this]; congr private def min_fac_prop (n k : ℕ) := 2 ≤ k ∧ k ∣ n ∧ ∀ m, 2 ≤ m → m ∣ n → k ≤ m theorem min_fac_aux_has_prop {n : ℕ} (n2 : 2 ≤ n) (nd2 : ¬ 2 ∣ n) : ∀ k i, k = 2*i+3 → (∀ m, 2 ≤ m → m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) | k := λ i e a, begin rw min_fac_aux, by_cases h : n < k*k; simp [h], { have pp : prime n := prime_def_le_sqrt.2 ⟨n2, λ m m2 l d, not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩, from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq ((dvd_prime_two_le pp m2).1 d).symm⟩ }, have k2 : 2 ≤ k, { subst e, exact dec_trivial }, by_cases dk : k ∣ n; simp [dk], { exact ⟨k2, dk, a⟩ }, { refine have _, from min_fac_lemma n k h, min_fac_aux_has_prop (k+2) (i+1) (by simp [e, left_distrib]) (λ m m2 d, _), cases nat.eq_or_lt_of_le (a m m2 d) with me ml, { subst me, contradiction }, apply (nat.eq_or_lt_of_le ml).resolve_left, intro me, rw [← me, e] at d, change 2 * (i + 2) ∣ n at d, have := dvd_of_mul_right_dvd d, contradiction } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := begin by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]}, have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial }, simp [min_fac_eq], by_cases d2 : 2 ∣ n; simp [d2], { exact ⟨le_refl _, d2, λ k k2 d, k2⟩ }, { refine min_fac_aux_has_prop n2 d2 3 0 rfl (λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)), exact λ e, e.symm ▸ d } end theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := if n1 : n = 1 then by simp [n1] else (min_fac_has_prop n1).2.1 theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (d.trans fd))⟩ theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, 2 ≤ m → m ∣ n → min_fac n ≤ m := by by_cases n1 : n = 1; [exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2, exact (min_fac_has_prop n1).2.2] theorem min_fac_pos (n : ℕ) : 0 < min_fac n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos] theorem min_fac_le {n : ℕ} (H : 0 < n) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem le_min_fac {m n : ℕ} : n = 1 ∨ m ≤ min_fac n ↔ ∀ p, prime p → p ∣ n → m ≤ p := ⟨λ h p pp d, h.elim (by rintro rfl; cases pp.not_dvd_one d) (λ h, le_trans h $ min_fac_le_of_dvd pp.two_le d), λ H, or_iff_not_imp_left.2 $ λ n1, H _ (min_fac_prime n1) (min_fac_dvd _)⟩ theorem le_min_fac' {m n : ℕ} : n = 1 ∨ m ≤ min_fac n ↔ ∀ p, 2 ≤ p → p ∣ n → m ≤ p := ⟨λ h p (pp:1<p) d, h.elim (by rintro rfl; cases not_le_of_lt pp (le_of_dvd dec_trivial d)) (λ h, le_trans h $ min_fac_le_of_dvd pp d), λ H, le_min_fac.2 (λ p pp d, H p pp.two_le d)⟩ theorem prime_def_min_fac {p : ℕ} : prime p ↔ 2 ≤ p ∧ min_fac p = p := ⟨λ pp, ⟨pp.two_le, let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.one_lt in ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩ /-- This instance is faster in the virtual machine than `decidable_prime_1`, but slower in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ instance decidable_prime (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : 2 ≤ n) : ¬ prime n ↔ min_fac n < n := (not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $ (lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm lemma min_fac_le_div {n : ℕ} (pos : 0 < n) (np : ¬ prime n) : min_fac n ≤ n / min_fac n := match min_fac_dvd n with | ⟨0, h0⟩ := absurd pos $ by rw [h0, mul_zero]; exact dec_trivial | ⟨1, h1⟩ := begin rw mul_one at h1, rw [prime_def_min_fac, not_and_distrib, ← h1, eq_self_iff_true, not_true, or_false, not_le] at np, rw [le_antisymm (le_of_lt_succ np) (succ_le_of_lt pos), min_fac_one, nat.div_one] end | ⟨(x+2), hx⟩ := begin conv_rhs { congr, rw hx }, rw [nat.mul_div_cancel_left _ (min_fac_pos _)], exact min_fac_le_of_dvd dec_trivial ⟨min_fac n, by rwa mul_comm⟩ end end /-- The square of the smallest prime factor of a composite number `n` is at most `n`. -/ lemma min_fac_sq_le_self {n : ℕ} (w : 0 < n) (h : ¬ prime n) : (min_fac n)^2 ≤ n := have t : (min_fac n) ≤ (n/min_fac n) := min_fac_le_div w h, calc (min_fac n)^2 = (min_fac n) * (min_fac n) : sq (min_fac n) ... ≤ (n/min_fac n) * (min_fac n) : nat.mul_le_mul_right (min_fac n) t ... ≤ n : div_mul_le_self n (min_fac n) @[simp] lemma min_fac_eq_one_iff {n : ℕ} : min_fac n = 1 ↔ n = 1 := begin split, { intro h, by_contradiction hn, have := min_fac_prime hn, rw h at this, exact not_prime_one this, }, { rintro rfl, refl, } end @[simp] lemma min_fac_eq_two_iff (n : ℕ) : min_fac n = 2 ↔ 2 ∣ n := begin split, { intro h, convert min_fac_dvd _, rw h, }, { intro h, have ub := min_fac_le_of_dvd (le_refl 2) h, have lb := min_fac_pos n, -- If `interval_cases` and `norm_num` were already available here, -- this would be easy and pleasant. -- But they aren't, so it isn't. cases h : n.min_fac with m, { rw h at lb, cases lb, }, { cases m with m, { simp at h, subst h, cases h with n h, cases n; cases h, }, { cases m with m, { refl, }, { rw h at ub, cases ub with _ ub, cases ub with _ ub, cases ub, } } } } end end min_fac theorem exists_dvd_of_not_prime {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).one_lt, ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) : ∃ m, m ∣ n ∧ 2 ≤ m ∧ m < n := ⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).two_le, (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_prime_and_dvd {n : ℕ} (n2 : 2 ≤ n) : ∃ p, prime p ∧ p ∣ n := ⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩ /-- Euclid's theorem on the **infinitude of primes**. Here given in the form: for every `n`, there exists a prime number `p ≥ n`. -/ theorem exists_infinite_primes (n : ℕ) : ∃ p, n ≤ p ∧ prime p := let p := min_fac (n! + 1) in have f1 : n! + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ factorial_pos _, have pp : prime p, from min_fac_prime f1, have np : n ≤ p, from le_of_not_ge $ λ h, have h₁ : p ∣ n!, from dvd_factorial (min_fac_pos _) h, have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _), pp.not_dvd_one h₂, ⟨p, np, pp⟩ lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 := (nat.mod_two_eq_zero_or_one p).elim (λ h, or.inl ((hp.2 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm) or.inr theorem coprime_of_dvd {m n : ℕ} (H : ∀ k, prime k → k ∣ m → ¬ k ∣ n) : coprime m n := begin cases nat.eq_zero_or_pos (gcd m n) with g0 g1, { rw [eq_zero_of_gcd_eq_zero_left g0, eq_zero_of_gcd_eq_zero_right g0] at H, exfalso, exact H 2 prime_two (dvd_zero _) (dvd_zero _) }, apply eq.symm, change 1 ≤ _ at g1, apply (lt_or_eq_of_le g1).resolve_left, intro g2, obtain ⟨p, hp, hpdvd⟩ := exists_prime_and_dvd g2, apply H p hp; apply dvd_trans hpdvd, { exact gcd_dvd_left _ _ }, { exact gcd_dvd_right _ _ } end theorem coprime_of_dvd' {m n : ℕ} (H : ∀ k, prime k → k ∣ m → k ∣ n → k ∣ 1) : coprime m n := coprime_of_dvd $ λk kp km kn, not_le_of_gt kp.one_lt $ le_of_dvd zero_lt_one $ H k kp km kn theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 := div_lt_self dec_trivial (min_fac_prime dec_trivial).one_lt /-- `factors n` is the prime factorization of `n`, listed in increasing order. -/ def factors : ℕ → list ℕ | 0 := [] | 1 := [] | n@(k+2) := let m := min_fac n in have n / m < n := factors_lemma, m :: factors (n / m) @[simp] lemma factors_zero : factors 0 = [] := by rw factors @[simp] lemma factors_one : factors 1 = [] := by rw factors lemma prime_of_mem_factors : ∀ {n p}, p ∈ factors n → prime p | 0 := by simp | 1 := by simp | n@(k+2) := λ p h, let m := min_fac n in have n / m < n := factors_lemma, have h₁ : p = m ∨ p ∈ (factors (n / m)) := (list.mem_cons_iff _ _ _).1 (by rwa [factors] at h), or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial) prime_of_mem_factors lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n | 0 := by simp | 1 := by simp | n@(k+2) := λ h, let m := min_fac n in have n / m < n := factors_lemma, show (factors n).prod = n, from have h₁ : 0 < n / m := nat.pos_of_ne_zero $ λ h, have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h, by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this, by rw [factors, list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)] lemma factors_prime {p : ℕ} (hp : nat.prime p) : p.factors = [p] := begin have : p = (p - 2) + 2 := (nat.sub_eq_iff_eq_add hp.1).mp rfl, rw [this, nat.factors], simp only [eq.symm this], have : nat.min_fac p = p := (nat.prime_def_min_fac.mp hp).2, split, { exact this, }, { simp only [this, nat.factors, nat.div_self (nat.prime.pos hp)], }, end lemma factors_chain : ∀ {n a}, (∀ p, prime p → p ∣ n → a ≤ p) → list.chain (≤) a (factors n) | 0 := λ a h, by simp | 1 := λ a h, by simp | n@(k+2) := λ a h, let m := min_fac n in have n / m < n := factors_lemma, begin rw factors, refine list.chain.cons ((le_min_fac.2 h).resolve_left dec_trivial) (factors_chain _), exact λ p pp d, min_fac_le_of_dvd pp.two_le (d.trans $ div_dvd_of_dvd $ min_fac_dvd _), end lemma factors_chain_2 (n) : list.chain (≤) 2 (factors n) := factors_chain $ λ p pp _, pp.two_le lemma factors_chain' (n) : list.chain' (≤) (factors n) := @list.chain'.tail _ _ (_::_) (factors_chain_2 _) lemma factors_sorted (n : ℕ) : list.sorted (≤) (factors n) := (list.chain'_iff_pairwise (@le_trans _ _)).1 (factors_chain' _) /-- `factors` can be constructed inductively by extracting `min_fac`, for sufficiently large `n`. -/ lemma factors_add_two (n : ℕ) : factors (n+2) = min_fac (n+2) :: factors ((n+2) / min_fac (n+2)) := by rw factors @[simp] lemma factors_eq_nil (n : ℕ) : n.factors = [] ↔ n = 0 ∨ n = 1 := begin split; intro h, { rcases n with (_ | _ | n), { exact or.inl rfl }, { exact or.inr rfl }, { rw factors at h, injection h }, }, { rcases h with (rfl | rfl), { exact factors_zero }, { exact factors_one }, } end theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n := ⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]), λ nd, coprime_of_dvd $ λ m m2 mp, ((prime_dvd_prime_iff_eq m2 pp).1 mp).symm ▸ nd⟩ theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem prime.not_coprime_iff_dvd {m n : ℕ} : ¬ coprime m n ↔ ∃p, prime p ∧ p ∣ m ∧ p ∣ n := begin apply iff.intro, { intro h, exact ⟨min_fac (gcd m n), min_fac_prime h, ((min_fac_dvd (gcd m n)).trans (gcd_dvd_left m n)), ((min_fac_dvd (gcd m n)).trans (gcd_dvd_right m n))⟩ }, { intro h, cases h with p hp, apply nat.not_coprime_of_dvd_of_dvd (prime.one_lt hp.1) hp.2.1 hp.2.2 } end theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨λ H, or_iff_not_imp_left.2 $ λ h, (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩ theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n := mt pp.dvd_mul.1 $ by simp [Hm, Hn] theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m := by induction n with n IH; [exact pp.not_dvd_one.elim h, by { rw pow_succ at h, exact (pp.dvd_mul.1 h).elim id IH } ] lemma prime.pow_dvd_of_dvd_mul_right {p n a b : ℕ} (hp : p.prime) (h : p ^ n ∣ a * b) (hpb : ¬ p ∣ b) : p ^ n ∣ a := begin induction n with n ih, { simp }, { rw [pow_succ'] at *, rcases ih ((dvd_mul_right _ _).trans h) with ⟨c, rfl⟩, rw [mul_assoc] at h, rcases hp.dvd_mul.1 (nat.dvd_of_mul_dvd_mul_left (pow_pos hp.pos _) h) with ⟨d, rfl⟩|⟨d, rfl⟩, { rw [← mul_assoc], exact dvd_mul_right _ _ }, { exact (hpb (dvd_mul_right _ _)).elim } } end lemma prime.pow_dvd_of_dvd_mul_left {p n a b : ℕ} (hp : p.prime) (h : p ^ n ∣ a * b) (hpb : ¬ p ∣ a) : p ^ n ∣ b := by rw [mul_comm] at h; exact hp.pow_dvd_of_dvd_mul_right h hpb lemma prime.pow_not_prime {x n : ℕ} (hn : 2 ≤ n) : ¬ (x ^ n).prime := λ hp, (hp.2 x $ dvd_trans ⟨x, sq _⟩ (pow_dvd_pow _ hn)).elim (λ hx1, hp.ne_one $ hx1.symm ▸ one_pow _) (λ hxn, lt_irrefl x $ calc x = x ^ 1 : (pow_one _).symm ... < x ^ n : nat.pow_right_strict_mono (hxn.symm ▸ hp.two_le) hn ... = x : hxn.symm) lemma prime.mul_eq_prime_sq_iff {x y p : ℕ} (hp : p.prime) (hx : x ≠ 1) (hy : y ≠ 1) : x * y = p ^ 2 ↔ x = p ∧ y = p := ⟨λ h, have pdvdxy : p ∣ x * y, by rw h; simp [sq], begin wlog := hp.dvd_mul.1 pdvdxy using x y, cases case with a ha, have hap : a ∣ p, from ⟨y, by rwa [ha, sq, mul_assoc, nat.mul_right_inj hp.pos, eq_comm] at h⟩, exact ((nat.dvd_prime hp).1 hap).elim (λ _, by clear_aux_decl; simp [*, sq, nat.mul_right_inj hp.pos] at * {contextual := tt}) (λ _, by clear_aux_decl; simp [*, sq, mul_comm, mul_assoc, nat.mul_right_inj hp.pos, nat.mul_right_eq_self_iff hp.pos] at * {contextual := tt}) end, λ ⟨h₁, h₂⟩, h₁.symm ▸ h₂.symm ▸ (sq _).symm⟩ lemma prime.dvd_factorial : ∀ {n p : ℕ} (hp : prime p), p ∣ n! ↔ p ≤ n | 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos) | (n+1) p hp := begin rw [factorial_succ, hp.dvd_mul, prime.dvd_factorial hp], exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le, λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ) (λ h, or.inl $ by rw h)⟩ end theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_two_le pq pp.two_le theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p^n) (q^m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k := begin induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *}, by_cases p ∣ i, { cases h with a e, subst e, rw [pow_succ, nat.mul_dvd_mul_iff_left pp.pos, IH], split; intro h; rcases h with ⟨k, h, e⟩, { exact ⟨succ k, succ_le_succ h, by rw [e, pow_succ]; refl⟩ }, cases k with k, { apply pp.not_dvd_one.elim, simp at e, rw ← e, apply dvd_mul_right }, { refine ⟨k, le_of_succ_le_succ h, _⟩, rwa [mul_comm, pow_succ', nat.mul_left_inj pp.pos] at e } }, { split; intro d, { rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d, exact ⟨0, zero_le _, rfl⟩ }, { rcases d with ⟨k, l, e⟩, rw e, exact pow_dvd_pow _ l } } end /-- If `p` is prime, and `a` doesn't divide `p^k`, but `a` does divide `p^(k+1)` then `a = p^(k+1)`. -/ lemma eq_prime_pow_of_dvd_least_prime_pow {a p k : ℕ} (pp : prime p) (h₁ : ¬(a ∣ p^k)) (h₂ : a ∣ p^(k+1)) : a = p^(k+1) := begin obtain ⟨l, ⟨h, rfl⟩⟩ := (dvd_prime_pow pp).1 h₂, congr, exact le_antisymm h (not_le.1 ((not_congr (pow_dvd_pow_iff_le_right (prime.one_lt pp))).1 h₁)), end section open list lemma mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) : ∀ {l : list ℕ}, (∀ p ∈ l, prime p) → p ∣ prod l → p ∈ l | [] := λ h₁ h₂, absurd h₂ (prime.not_dvd_one hp) | (q :: l) := λ h₁ h₂, have h₃ : p ∣ q * prod l := @prod_cons _ _ l q ▸ h₂, have hq : prime q := h₁ q (mem_cons_self _ _), or.cases_on ((prime.dvd_mul hp).1 h₃) (λ h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h; exact h ▸ mem_cons_self _ _) (λ h, have hl : ∀ p ∈ l, prime p := λ p hlp, h₁ p ((mem_cons_iff _ _ _).2 (or.inr hlp)), (mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h))) lemma mem_factors_iff_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) : p ∈ factors n ↔ p ∣ n := ⟨λ h, prod_factors hn ▸ list.dvd_prod h, λ h, mem_list_primes_of_dvd_prod hp (@prime_of_mem_factors n) ((prod_factors hn).symm ▸ h)⟩ lemma mem_factors {n p} (hn : 0 < n) : p ∈ factors n ↔ prime p ∧ p ∣ n := ⟨λ h, ⟨prime_of_mem_factors h, (mem_factors_iff_dvd hn $ prime_of_mem_factors h).mp h⟩, λ ⟨hprime, hdvd⟩, (mem_factors_iff_dvd hn hprime).mpr hdvd⟩ lemma factors_subset_right {n k : ℕ} (h : k ≠ 0) : n.factors ⊆ (n * k).factors := begin cases n, { rw zero_mul, refl }, cases n, { rw factors_one, apply list.nil_subset }, intros p hp, rw mem_factors succ_pos' at hp, rw mem_factors (nat.mul_pos succ_pos' (nat.pos_of_ne_zero h)), exact ⟨hp.1, dvd_mul_of_dvd_left hp.2 k⟩, end lemma factors_subset_of_dvd {n k : ℕ} (h : n ∣ k) (h' : k ≠ 0) : n.factors ⊆ k.factors := begin obtain ⟨a, rfl⟩ := h, exact factors_subset_right (right_ne_zero_of_mul h'), end lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list ℕ}, prod l₁ = prod l₂ → (∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → l₁ ~ l₂ | [] [] _ _ _ := perm.nil | [] (a :: l) h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _))) | (a :: l) [] h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _))) | (a :: l₁) (b :: l₂) h hl₁ hl₂ := have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp), have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp), have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂ (h ▸ by rw prod_cons; exact dvd_mul_right _ _), have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_cons_erase ha, have hl : prod l₁ = prod ((b :: l₂).erase a) := (nat.mul_right_inj (prime.pos (hl₁ a (mem_cons_self _ _)))).1 $ by rwa [← prod_cons, ← prod_cons, ← hb.prod_eq], perm.trans ((perm_of_prod_eq_prod hl hl₁' hl₂').cons _) hb.symm /-- **Fundamental theorem of arithmetic**-/ lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n := have hn : 0 < n := nat.pos_of_ne_zero $ λ h, begin rw h at *, clear h, induction l with a l hi, { exact absurd h₁ dec_trivial }, { rw prod_cons at h₁, exact nat.mul_ne_zero (ne_of_lt (prime.pos (h₂ a (mem_cons_self _ _)))).symm (hi (λ p hp, h₂ p (mem_cons_of_mem _ hp))) h₁ } end, perm_of_prod_eq_prod (by rwa prod_factors hn) h₂ (@prime_of_mem_factors _) lemma prime.factors_pow {p : ℕ} (hp : p.prime) (n : ℕ) : (p ^ n).factors = list.repeat p n := begin symmetry, rw ← list.repeat_perm, apply nat.factors_unique (list.prod_repeat p n), { intros q hq, rwa eq_of_mem_repeat hq }, end end lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : 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 hpd : p^(k+l)*p ∣ m*n, by rwa pow_succ' at hpmn, have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd, have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [pow_add] using hpd2, have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div hpm hpn] using hpd3, have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4, suffices p^k*p ∣ m ∨ p^l*p ∣ n, by rwa [pow_succ', pow_succ'], hpd5.elim (assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this) (assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this) /-- The type of prime numbers -/ def primes := {p : ℕ // p.prime} namespace primes instance : has_repr nat.primes := ⟨λ p, repr p.val⟩ instance inhabited_primes : inhabited primes := ⟨⟨2, prime_two⟩⟩ instance coe_nat : has_coe nat.primes ℕ := ⟨subtype.val⟩ theorem coe_nat_inj (p q : nat.primes) : (p : ℕ) = (q : ℕ) → p = q := λ h, subtype.eq h end primes instance monoid.prime_pow {α : Type*} [monoid α] : has_pow α primes := ⟨λ x p, x^p.val⟩ end nat /-! ### Primality prover -/ namespace tactic namespace norm_num open norm_num lemma is_prime_helper (n : ℕ) (h₁ : 1 < n) (h₂ : nat.min_fac n = n) : nat.prime n := nat.prime_def_min_fac.2 ⟨h₁, h₂⟩ lemma min_fac_bit0 (n : ℕ) : nat.min_fac (bit0 n) = 2 := by simp [nat.min_fac_eq, show 2 ∣ bit0 n, by simp [bit0_eq_two_mul n]] /-- A predicate representing partial progress in a proof of `min_fac`. -/ def min_fac_helper (n k : ℕ) : Prop := 0 < k ∧ bit1 k ≤ nat.min_fac (bit1 n) theorem min_fac_helper.n_pos {n k : ℕ} (h : min_fac_helper n k) : 0 < n := pos_iff_ne_zero.2 $ λ e, by rw e at h; exact not_le_of_lt (nat.bit1_lt h.1) h.2 lemma min_fac_ne_bit0 {n k : ℕ} : nat.min_fac (bit1 n) ≠ bit0 k := by rw bit0_eq_two_mul; exact λ e, absurd ((nat.dvd_add_iff_right (by simp [bit0_eq_two_mul n])).2 (dvd_trans ⟨_, e⟩ (nat.min_fac_dvd _))) (by norm_num) lemma min_fac_helper_0 (n : ℕ) (h : 0 < n) : min_fac_helper n 1 := begin refine ⟨zero_lt_one, lt_of_le_of_ne _ min_fac_ne_bit0.symm⟩, refine @lt_of_le_of_ne ℕ _ _ _ (nat.min_fac_pos _) _, intro e, have := nat.min_fac_prime _, { rw ← e at this, exact nat.not_prime_one this }, { exact ne_of_gt (nat.bit1_lt h) } end lemma min_fac_helper_1 {n k k' : ℕ} (e : k + 1 = k') (np : nat.min_fac (bit1 n) ≠ bit1 k) (h : min_fac_helper n k) : min_fac_helper n k' := begin rw ← e, refine ⟨nat.succ_pos _, (lt_of_le_of_ne (lt_of_le_of_ne _ _ : k+1+k < _) min_fac_ne_bit0.symm : bit0 (k+1) < _)⟩, { rw add_right_comm, exact h.2 }, { rw add_right_comm, exact np.symm } end lemma min_fac_helper_2 (n k k' : ℕ) (e : k + 1 = k') (np : ¬ nat.prime (bit1 k)) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw ← e₁ at np, exact np (nat.min_fac_prime $ ne_of_gt $ nat.bit1_lt h.n_pos) end lemma min_fac_helper_3 (n k k' c : ℕ) (e : k + 1 = k') (nc : bit1 n % bit1 k = c) (c0 : 0 < c) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, refine mt _ (ne_of_gt c0), intro e₁, rw [← nc, ← nat.dvd_iff_mod_eq_zero, ← e₁], apply nat.min_fac_dvd end lemma min_fac_helper_4 (n k : ℕ) (hd : bit1 n % bit1 k = 0) (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 k := by rw ← nat.dvd_iff_mod_eq_zero at hd; exact le_antisymm (nat.min_fac_le_of_dvd (nat.bit1_lt h.1) hd) h.2 lemma min_fac_helper_5 (n k k' : ℕ) (e : bit1 k * bit1 k = k') (hd : bit1 n < k') (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 n := begin refine (nat.prime_def_min_fac.1 (nat.prime_def_le_sqrt.2 ⟨nat.bit1_lt h.n_pos, _⟩)).2, rw ← e at hd, intros m m2 hm md, have := le_trans h.2 (le_trans (nat.min_fac_le_of_dvd m2 md) hm), rw nat.le_sqrt at this, exact not_le_of_lt hd this end /-- Given `e` a natural numeral and `d : nat` a factor of it, return `⊢ ¬ prime e`. -/ meta def prove_non_prime (e : expr) (n d₁ : ℕ) : tactic expr := do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt_nat c `(1) e₁, let d₂ := n / d₁, let e₂ := reflect d₂, (c, e', p) ← prove_mul_nat c e₁ e₂, guard (e' =ₐ e), (c, p₂) ← prove_lt_nat c `(1) e₂, return $ `(@nat.not_prime_mul').mk_app [e₁, e₂, e, p, p₁, p₂] /-- Given `a`,`a1 := bit1 a`, `n1` the value of `a1`, `b` and `p : min_fac_helper a b`, returns `(c, ⊢ min_fac a1 = c)`. -/ meta def prove_min_fac_aux (a a1 : expr) (n1 : ℕ) : instance_cache → expr → expr → tactic (instance_cache × expr × expr) | ic b p := do k ← b.to_nat, let k1 := bit1 k, let b1 := `(bit1:ℕ→ℕ).mk_app [b], if n1 < k1*k1 then do (ic, e', p₁) ← prove_mul_nat ic b1 b1, (ic, p₂) ← prove_lt_nat ic a1 e', return (ic, a1, `(min_fac_helper_5).mk_app [a, b, e', p₁, p₂, p]) else let d := k1.min_fac in if to_bool (d < k1) then do let k' := k+1, let e' := reflect k', (ic, p₁) ← prove_succ ic b e', p₂ ← prove_non_prime b1 k1 d, prove_min_fac_aux ic e' $ `(min_fac_helper_2).mk_app [a, b, e', p₁, p₂, p] else do let nc := n1 % k1, (ic, c, pc) ← prove_div_mod ic a1 b1 tt, if nc = 0 then return (ic, b1, `(min_fac_helper_4).mk_app [a, b, pc, p]) else do (ic, p₀) ← prove_pos ic c, let k' := k+1, let e' := reflect k', (ic, p₁) ← prove_succ ic b e', prove_min_fac_aux ic e' $ `(min_fac_helper_3).mk_app [a, b, e', c, p₁, pc, p₀, p] /-- Given `a` a natural numeral, returns `(b, ⊢ min_fac a = b)`. -/ meta def prove_min_fac (ic : instance_cache) (e : expr) : tactic (instance_cache × expr × expr) := match match_numeral e with | match_numeral_result.zero := return (ic, `(2:ℕ), `(nat.min_fac_zero)) | match_numeral_result.one := return (ic, `(1:ℕ), `(nat.min_fac_one)) | match_numeral_result.bit0 e := return (ic, `(2), `(min_fac_bit0).mk_app [e]) | match_numeral_result.bit1 e := do n ← e.to_nat, c ← mk_instance_cache `(nat), (c, p) ← prove_pos c e, let a1 := `(bit1:ℕ→ℕ).mk_app [e], prove_min_fac_aux e a1 (bit1 n) c `(1) (`(min_fac_helper_0).mk_app [e, p]) | _ := failed end /-- A partial proof of `factors`. Asserts that `l` is a sorted list of primes, lower bounded by a prime `p`, which multiplies to `n`. -/ def factors_helper (n p : ℕ) (l : list ℕ) : Prop := p.prime → list.chain (≤) p l ∧ (∀ a ∈ l, nat.prime a) ∧ list.prod l = n lemma factors_helper_nil (a : ℕ) : factors_helper 1 a [] := λ pa, ⟨list.chain.nil, by rintro _ ⟨⟩, list.prod_nil⟩ lemma factors_helper_cons' (n m a b : ℕ) (l : list ℕ) (h₁ : b * m = n) (h₂ : a ≤ b) (h₃ : nat.min_fac b = b) (H : factors_helper m b l) : factors_helper n a (b :: l) := λ pa, have pb : b.prime, from nat.prime_def_min_fac.2 ⟨le_trans pa.two_le h₂, h₃⟩, let ⟨f₁, f₂, f₃⟩ := H pb in ⟨list.chain.cons h₂ f₁, λ c h, h.elim (λ e, e.symm ▸ pb) (f₂ _), by rw [list.prod_cons, f₃, h₁]⟩ lemma factors_helper_cons (n m a b : ℕ) (l : list ℕ) (h₁ : b * m = n) (h₂ : a < b) (h₃ : nat.min_fac b = b) (H : factors_helper m b l) : factors_helper n a (b :: l) := factors_helper_cons' _ _ _ _ _ h₁ h₂.le h₃ H lemma factors_helper_sn (n a : ℕ) (h₁ : a < n) (h₂ : nat.min_fac n = n) : factors_helper n a [n] := factors_helper_cons _ _ _ _ _ (mul_one _) h₁ h₂ (factors_helper_nil _) lemma factors_helper_same (n m a : ℕ) (l : list ℕ) (h : a * m = n) (H : factors_helper m a l) : factors_helper n a (a :: l) := λ pa, factors_helper_cons' _ _ _ _ _ h (le_refl _) (nat.prime_def_min_fac.1 pa).2 H pa lemma factors_helper_same_sn (a : ℕ) : factors_helper a a [a] := factors_helper_same _ _ _ _ (mul_one _) (factors_helper_nil _) lemma factors_helper_end (n : ℕ) (l : list ℕ) (H : factors_helper n 2 l) : nat.factors n = l := let ⟨h₁, h₂, h₃⟩ := H nat.prime_two in have _, from (list.chain'_iff_pairwise (@le_trans _ _)).1 (@list.chain'.tail _ _ (_::_) h₁), (list.eq_of_perm_of_sorted (nat.factors_unique h₃ h₂) this (nat.factors_sorted _)).symm /-- Given `n` and `a` natural numerals, returns `(l, ⊢ factors_helper n a l)`. -/ meta def prove_factors_aux : instance_cache → expr → expr → ℕ → ℕ → tactic (instance_cache × expr × expr) | c en ea n a := let b := n.min_fac in if b < n then do let m := n / b, (c, em) ← c.of_nat m, if b = a then do (c, _, p₁) ← prove_mul_nat c ea em, (c, l, p₂) ← prove_factors_aux c em ea m a, pure (c, `(%%ea::%%l:list ℕ), `(factors_helper_same).mk_app [en, em, ea, l, p₁, p₂]) else do (c, eb) ← c.of_nat b, (c, _, p₁) ← prove_mul_nat c eb em, (c, p₂) ← prove_lt_nat c ea eb, (c, _, p₃) ← prove_min_fac c eb, (c, l, p₄) ← prove_factors_aux c em eb m b, pure (c, `(%%eb::%%l : list ℕ), `(factors_helper_cons).mk_app [en, em, ea, eb, l, p₁, p₂, p₃, p₄]) else if b = a then pure (c, `([%%ea] : list ℕ), `(factors_helper_same_sn).mk_app [ea]) else do (c, p₁) ← prove_lt_nat c ea en, (c, _, p₂) ← prove_min_fac c en, pure (c, `([%%en] : list ℕ), `(factors_helper_sn).mk_app [en, ea, p₁, p₂]) /-- Evaluates the `prime` and `min_fac` functions. -/ @[norm_num] meta def eval_prime : expr → tactic (expr × expr) | `(nat.prime %%e) := do n ← e.to_nat, match n with | 0 := false_intro `(nat.not_prime_zero) | 1 := false_intro `(nat.not_prime_one) | _ := let d₁ := n.min_fac in if d₁ < n then prove_non_prime e n d₁ >>= false_intro else do let e₁ := reflect d₁, c ← mk_instance_cache `(ℕ), (c, p₁) ← prove_lt_nat c `(1) e₁, (c, e₁, p) ← prove_min_fac c e, true_intro $ `(is_prime_helper).mk_app [e, p₁, p] end | `(nat.min_fac %%e) := do ic ← mk_instance_cache `(ℕ), prod.snd <$> prove_min_fac ic e | `(nat.factors %%e) := do n ← e.to_nat, match n with | 0 := pure (`(@list.nil ℕ), `(nat.factors_zero)) | 1 := pure (`(@list.nil ℕ), `(nat.factors_one)) | _ := do c ← mk_instance_cache `(ℕ), (c, l, p) ← prove_factors_aux c e `(2) n 2, pure (l, `(factors_helper_end).mk_app [e, l, p]) end | _ := failed end norm_num end tactic namespace nat theorem prime_three : prime 3 := by norm_num end nat
f4eb8f50279e24f017fafc8ea3e6636459f9a939
367134ba5a65885e863bdc4507601606690974c1
/src/algebraic_geometry/Spec.lean
8bc1ce18c0bfffb04c7311f3cf6f3481b8abc621
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
1,236
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 algebraic_geometry.locally_ringed_space import algebraic_geometry.structure_sheaf import data.equiv.transfer_instance /-! # $Spec R$ as a `LocallyRingedSpace` We bundle the `structure_sheaf R` construction for `R : CommRing` as a `LocallyRingedSpace`. ## Future work Make it a functor. -/ noncomputable theory namespace algebraic_geometry /-- Spec of a commutative ring, as a `SheafedSpace`. -/ def Spec.SheafedSpace (R : CommRing) : SheafedSpace CommRing := { carrier := Top.of (prime_spectrum R), ..structure_sheaf R } /-- Spec of a commutative ring, as a `PresheafedSpace`. -/ def Spec.PresheafedSpace (R : CommRing) : PresheafedSpace CommRing := (Spec.SheafedSpace R).to_PresheafedSpace /-- Spec of a commutative ring, as a `LocallyRingedSpace`. -/ def Spec.LocallyRingedSpace (R : CommRing) : LocallyRingedSpace := { local_ring := λ x, @@ring_equiv.local_ring _ (show local_ring (localization.at_prime _), by apply_instance) _ (category_theory.iso.CommRing_iso_to_ring_equiv $ stalk_iso R x).symm, .. Spec.SheafedSpace R } end algebraic_geometry
38602ad3e8bdff95a7851db576cb09e2457a101c
78630e908e9624a892e24ebdd21260720d29cf55
/src/logic_first_order/fol_10.lean
1ff1670ef5daa2bde579e21dd925a1a58d4dd4af
[ "CC0-1.0" ]
permissive
tomasz-lisowski/lean-logic-examples
84e612466776be0a16c23a0439ff8ef6114ddbe1
2b2ccd467b49c3989bf6c92ec0358a8d6ee68c5d
refs/heads/master
1,683,334,199,431
1,621,938,305,000
1,621,938,305,000
365,041,573
1
0
null
null
null
null
UTF-8
Lean
false
false
695
lean
namespace fol_10 variable A : Prop variables P Q : A → Prop theorem fol_10 : ((∃ x, P x ∨ Q x) ∧ (¬ ∃ x, P x)) → ¬ ∀ x, (Q x → P x) := assume h1: (∃ x, P x ∨ Q x) ∧ (¬ ∃ x, P x), have h2: ∃ x, P x ∨ Q x, from and.left h1, have h3: ¬ ∃ x, P x, from and.right h1, assume h4: ∀ x, Q x → P x, show false, from exists.elim h2 (assume s (h5: P s ∨ Q s), have h6: Q s, from or.elim h5 (assume h7: P s, have h8: false, from h3 (exists.intro s h7), false.elim h8) (assume h9: Q s, h9), have h10: Q s → P s, from h4 s, have h11: P s, from h10 h6, have h12: false, from h3 (exists.intro s h11), false.elim h12) end fol_10
6ca25b345d98749101527f853e03b68254d04169
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/07_Induction_and_Recursion.org.24.lean
832c0b8efc9b0b195462927b084eb69f16a0ccfb
[]
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
472
lean
/- page 109 -/ import standard import data.examples.vector open nat vector -- BEGIN variables {A B : Type} definition tail : Π {n}, vector A (succ n) → vector A n | tail (h :: t) := t definition map (f : A → B) : Π {n : nat}, vector A n → vector B n | map nil := nil | map (a::va) := f a :: map va definition diag : Π {n : nat}, vector (vector A n) n → vector A n | diag nil := nil | diag ((a :: va) :: v) := a :: diag (map tail v) -- END
fbf9b5763fc3de98c1d6121181e1665d46ec0a31
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/finset/noncomm_prod.lean
e6ad94d1dfe979559d85ec4811c0b638cfb66482
[ "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
9,474
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import algebra.big_operators.basic /-! # Products (respectively, sums) over a finset or a multiset. The regular `finset.prod` and `multiset.prod` require `[comm_monoid α]`. Often, there are collections `s : finset α` where `[monoid α]` and we know, in a dependent fashion, that for all the terms `∀ (x ∈ s) (y ∈ s), commute x y`. This allows to still have a well-defined product over `s`. ## Main definitions - `finset.noncomm_prod`, requiring a proof of commutativity of held terms - `multiset.noncomm_prod`, requiring a proof of commutativity of held terms ## Implementation details While `list.prod` is defined via `list.foldl`, `noncomm_prod` is defined via `multiset.foldr` for neater proofs and definitions. By the commutativity assumption, the two must be equal. -/ variables {α β : Type*} (f : α → β → β) (op : α → α → α) namespace multiset /-- Fold of a `s : multiset α` with `f : α → β → β`, given a proof that `left_commutative f` on all elements `x ∈ s`. -/ def noncomm_foldr (s : multiset α) (comm : ∀ (x ∈ s) (y ∈ s) b, f x (f y b) = f y (f x b)) (b : β) : β := s.attach.foldr (f ∘ subtype.val) (λ ⟨x, hx⟩ ⟨y, hy⟩, comm x hx y hy) b @[simp] lemma noncomm_foldr_coe (l : list α) (comm : ∀ (x ∈ (l : multiset α)) (y ∈ (l : multiset α)) b, f x (f y b) = f y (f x b)) (b : β) : noncomm_foldr f (l : multiset α) comm b = l.foldr f b := begin simp only [noncomm_foldr, coe_foldr, coe_attach, list.attach], rw ←list.foldr_map, simp [list.map_pmap, list.pmap_eq_map] end @[simp] lemma noncomm_foldr_empty (h : ∀ (x ∈ (0 : multiset α)) (y ∈ (0 : multiset α)) b, f x (f y b) = f y (f x b)) (b : β) : noncomm_foldr f (0 : multiset α) h b = b := rfl lemma noncomm_foldr_cons (s : multiset α) (a : α) (h : ∀ (x ∈ (a ::ₘ s)) (y ∈ (a ::ₘ s)) b, f x (f y b) = f y (f x b)) (h' : ∀ (x ∈ s) (y ∈ s) b, f x (f y b) = f y (f x b)) (b : β) : noncomm_foldr f (a ::ₘ s) h b = f a (noncomm_foldr f s h' b) := begin induction s using quotient.induction_on, simp end lemma noncomm_foldr_eq_foldr (s : multiset α) (h : left_commutative f) (b : β) : noncomm_foldr f s (λ x _ y _, h x y) b = foldr f h b s := begin induction s using quotient.induction_on, simp end variables [assoc : is_associative α op] include assoc /-- Fold of a `s : multiset α` with an associative `op : α → α → α`, given a proofs that `op` is commutative on all elements `x ∈ s`. -/ def noncomm_fold (s : multiset α) (comm : ∀ (x ∈ s) (y ∈ s), op x y = op y x) (a : α) : α := noncomm_foldr op s (λ x hx y hy b, by rw [←assoc.assoc, comm _ hx _ hy, assoc.assoc]) a @[simp] lemma noncomm_fold_coe (l : list α) (comm : ∀ (x ∈ (l : multiset α)) (y ∈ (l : multiset α)), op x y = op y x) (a : α) : noncomm_fold op (l : multiset α) comm a = l.foldr op a := by simp [noncomm_fold] @[simp] lemma noncomm_fold_empty (h : ∀ (x ∈ (0 : multiset α)) (y ∈ (0 : multiset α)), op x y = op y x) (a : α) : noncomm_fold op (0 : multiset α) h a = a := rfl lemma noncomm_fold_cons (s : multiset α) (a : α) (h : ∀ (x ∈ a ::ₘ s) (y ∈ a ::ₘ s), op x y = op y x) (h' : ∀ (x ∈ s) (y ∈ s), op x y = op y x) (x : α) : noncomm_fold op (a ::ₘ s) h x = op a (noncomm_fold op s h' x) := begin induction s using quotient.induction_on, simp end lemma noncomm_fold_eq_fold (s : multiset α) [is_commutative α op] (a : α) : noncomm_fold op s (λ x _ y _, is_commutative.comm x y) a = fold op a s := begin induction s using quotient.induction_on, simp end omit assoc variables [monoid α] /-- Product of a `s : multiset α` with `[monoid α]`, given a proof that `*` commutes on all elements `x ∈ s`. -/ @[to_additive "Sum of a `s : multiset α` with `[add_monoid α]`, given a proof that `+` commutes on all elements `x ∈ s`." ] def noncomm_prod (s : multiset α) (comm : ∀ (x ∈ s) (y ∈ s), commute x y) : α := s.noncomm_fold (*) comm 1 @[simp, to_additive] lemma noncomm_prod_coe (l : list α) (comm : ∀ (x ∈ (l : multiset α)) (y ∈ (l : multiset α)), commute x y) : noncomm_prod (l : multiset α) comm = l.prod := begin rw [noncomm_prod], simp only [noncomm_fold_coe], induction l with hd tl hl, { simp }, { rw [list.prod_cons, list.foldr, hl], intros x hx y hy, exact comm x (list.mem_cons_of_mem _ hx) y (list.mem_cons_of_mem _ hy) } end @[simp, to_additive] lemma noncomm_prod_empty (h : ∀ (x ∈ (0 : multiset α)) (y ∈ (0 : multiset α)), commute x y) : noncomm_prod (0 : multiset α) h = 1 := rfl @[simp, to_additive] lemma noncomm_prod_cons (s : multiset α) (a : α) (comm : ∀ (x ∈ a ::ₘ s) (y ∈ a ::ₘ s), commute x y) : noncomm_prod (a ::ₘ s) comm = a * noncomm_prod s (λ x hx y hy, comm _ (mem_cons_of_mem hx) _ (mem_cons_of_mem hy)) := begin induction s using quotient.induction_on, simp end @[to_additive] lemma noncomm_prod_cons' (s : multiset α) (a : α) (comm : ∀ (x ∈ a ::ₘ s) (y ∈ a ::ₘ s), commute x y) : noncomm_prod (a ::ₘ s) comm = noncomm_prod s (λ x hx y hy, comm _ (mem_cons_of_mem hx) _ (mem_cons_of_mem hy)) * a := begin induction s using quotient.induction_on with s, simp only [quot_mk_to_coe, cons_coe, noncomm_prod_coe, list.prod_cons], induction s with hd tl IH, { simp }, { rw [list.prod_cons, mul_assoc, ←IH, ←mul_assoc, ←mul_assoc], { congr' 1, apply comm; simp }, { intros x hx y hy, simp only [quot_mk_to_coe, list.mem_cons_iff, mem_coe, cons_coe] at hx hy, apply comm, { cases hx; simp [hx] }, { cases hy; simp [hy] } } } end @[to_additive] lemma noncomm_prod_eq_prod {α : Type*} [comm_monoid α] (s : multiset α) : noncomm_prod s (λ _ _ _ _, commute.all _ _) = prod s := begin induction s using quotient.induction_on, simp end end multiset namespace finset variables [monoid β] /-- Product of a `s : finset α` mapped with `f : α → β` with `[monoid β]`, given a proof that `*` commutes on all elements `f x` for `x ∈ s`. -/ @[to_additive "Sum of a `s : finset α` mapped with `f : α → β` with `[add_monoid β]`, given a proof that `+` commutes on all elements `f x` for `x ∈ s`."] def noncomm_prod (s : finset α) (f : α → β) (comm : ∀ (x ∈ s) (y ∈ s), commute (f x) (f y)) : β := (s.1.map f).noncomm_prod (by simpa [multiset.mem_map, ←finset.mem_def] using comm) @[simp, to_additive] lemma noncomm_prod_to_finset [decidable_eq α] (l : list α) (f : α → β) (comm : ∀ (x ∈ l.to_finset) (y ∈ l.to_finset), commute (f x) (f y)) (hl : l.nodup) : noncomm_prod l.to_finset f comm = (l.map f).prod := begin rw ←list.erase_dup_eq_self at hl, simp [noncomm_prod, hl] end @[simp, to_additive] lemma noncomm_prod_empty (f : α → β) (h : ∀ (x ∈ (∅ : finset α)) (y ∈ (∅ : finset α)), commute (f x) (f y)) : noncomm_prod (∅ : finset α) f h = 1 := rfl @[simp, to_additive] lemma noncomm_prod_insert_of_not_mem [decidable_eq α] (s : finset α) (a : α) (f : α → β) (comm : ∀ (x ∈ insert a s) (y ∈ insert a s), commute (f x) (f y)) (ha : a ∉ s) : noncomm_prod (insert a s) f comm = f a * noncomm_prod s f (λ x hx y hy, comm _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy)) := by simp [insert_val_of_not_mem ha, noncomm_prod] @[to_additive] lemma noncomm_prod_insert_of_not_mem' [decidable_eq α] (s : finset α) (a : α) (f : α → β) (comm : ∀ (x ∈ insert a s) (y ∈ insert a s), commute (f x) (f y)) (ha : a ∉ s) : noncomm_prod (insert a s) f comm = noncomm_prod s f (λ x hx y hy, comm _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy)) * f a := by simp [noncomm_prod, insert_val_of_not_mem ha, multiset.noncomm_prod_cons'] @[simp, to_additive] lemma noncomm_prod_singleton (a : α) (f : α → β) : noncomm_prod ({a} : finset α) f (λ x hx y hy, by by rw [mem_singleton.mp hx, mem_singleton.mp hy]) = f a := by simp [noncomm_prod] @[to_additive] lemma noncomm_prod_eq_prod {β : Type*} [comm_monoid β] (s : finset α) (f : α → β) : noncomm_prod s f (λ _ _ _ _, commute.all _ _) = s.prod f := begin classical, induction s using finset.induction_on with a s ha IH, { simp }, { simp [ha, IH] } end /- The non-commutative version of `finset.prod_union` -/ @[to_additive /-" The non-commutative version of `finset.sum_union` "-/] lemma noncomm_prod_union_of_disjoint [decidable_eq α] {s t : finset α} (h : disjoint s t) (f : α → β) (comm : ∀ (x ∈ s ∪ t) (y ∈ s ∪ t), commute (f x) (f y)) (scomm : ∀ (x ∈ s) (y ∈ s), commute (f x) (f y) := λ _ hx _ hy, comm _ (mem_union_left _ hx) _ (mem_union_left _ hy)) (tcomm : ∀ (x ∈ t) (y ∈ t), commute (f x) (f y) := λ _ hx _ hy, comm _ (mem_union_right _ hx) _ (mem_union_right _ hy)) : noncomm_prod (s ∪ t) f comm = noncomm_prod s f scomm * noncomm_prod t f tcomm := begin obtain ⟨sl, sl', rfl⟩ := exists_list_nodup_eq s, obtain ⟨tl, tl', rfl⟩ := exists_list_nodup_eq t, rw list.disjoint_to_finset_iff_disjoint at h, simp [sl', tl', noncomm_prod_to_finset, ←list.prod_append, ←list.to_finset_append, list.nodup_append_of_nodup sl' tl' h] end end finset
b162d155e642658342031a507de66ea5d55f47ab
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/analysis/special_functions/pow.lean
22efd237b7240521ce4552ed3e67402333cd7401
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
81,067
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, Sébastien Gouëzel, Rémy Degenne -/ import analysis.special_functions.complex.log import analysis.calculus.extend_deriv import analysis.special_functions.log_deriv /-! # Power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ℝ≥0∞` We construct the power functions `x ^ y` where * `x` and `y` are complex numbers, * or `x` and `y` are real numbers, * or `x` is a nonnegative real number and `y` is a real number; * or `x` is a number from `[0, +∞]` (a.k.a. `ℝ≥0∞`) and `y` is a real number. We also prove basic properties of these functions. -/ noncomputable theory open_locale classical real topological_space nnreal ennreal filter open filter namespace complex /-- 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 lemma cpow_def_of_ne_zero {x : ℂ} (hx : x ≠ 0) (y : ℂ) : x ^ y = exp (log x * y) := if_neg hx @[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, *] lemma zero_cpow_eq_iff {x : ℂ} {a : ℂ} : 0 ^ x = a ↔ (x ≠ 0 ∧ a = 0) ∨ (x = 0 ∧ a = 1) := begin split, { intros hyp, simp [cpow_def] at hyp, by_cases x = 0, { subst h, simp only [if_true, eq_self_iff_true] at hyp, right, exact ⟨rfl, hyp.symm⟩}, { rw if_neg h at hyp, left, exact ⟨h, hyp.symm⟩, }, }, { rintro (⟨h, rfl⟩|⟨rfl,rfl⟩), { exact zero_cpow h, }, { exact cpow_zero _, }, }, end lemma eq_zero_cpow_iff {x : ℂ} {a : ℂ} : a = 0 ^ x ↔ (x ≠ 0 ∧ a = 0) ∨ (x = 0 ∧ a = 1) := by rw [←zero_cpow_eq_iff, eq_comm] @[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 : (1 : ℂ) ≠ 0), 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 only [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] lemma cpow_sub {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by rw [sub_eq_add_neg, cpow_add _ _ hx, cpow_neg, div_eq_mul_inv] lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ := by simpa using cpow_neg x 1 @[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_add, hx, pow_add, cpow_nat_cast n] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw zpow_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 := begin suffices : im (log x * n⁻¹) ∈ set.Ioc (-π) π, { rw [← cpow_nat_cast, ← cpow_mul _ this.1 this.2, inv_mul_cancel, cpow_one], exact_mod_cast hn.ne' }, rw [mul_comm, ← of_real_nat_cast, ← of_real_inv, of_real_mul_im, ← div_eq_inv_mul], have hn' : 0 < (n : ℝ), by assumption_mod_cast, have hn1 : 1 ≤ (n : ℝ), by exact_mod_cast (nat.succ_le_iff.2 hn), split, { rw lt_div_iff hn', calc -π * n ≤ -π * 1 : mul_le_mul_of_nonpos_left hn1 (neg_nonpos.2 real.pi_pos.le) ... = -π : mul_one _ ... < im (log x) : neg_pi_lt_log_im _ }, { rw div_le_iff hn', calc im (log x) ≤ π : log_im_le_pi _ ... = π * 1 : (mul_one π).symm ... ≤ π * n : mul_le_mul_of_nonneg_left hn1 real.pi_pos.le } end lemma has_strict_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := begin have A : p.1 ≠ 0, by { intro h, simpa [h, lt_irrefl] using hp }, have : (λ x : ℂ × ℂ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from ((is_open_ne.preimage continuous_fst).eventually_mem A).mono (λ p hp, cpow_def_of_ne_zero hp _), rw [cpow_sub _ _ A, cpow_one, mul_div_comm, mul_smul, mul_smul, ← smul_add], refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, simpa only [cpow_def_of_ne_zero A, div_eq_mul_inv, mul_smul, add_comm] using ((has_strict_fderiv_at_fst.clog hp).mul has_strict_fderiv_at_snd).cexp end lemma has_strict_fderiv_at_cpow' {x y : ℂ} (hp : 0 < x.re ∨ x.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((y * x ^ (y - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (x ^ y * log x) • continuous_linear_map.snd ℂ ℂ ℂ) (x, y) := @has_strict_fderiv_at_cpow (x, y) hp lemma has_strict_deriv_at_const_cpow {x y : ℂ} (h : x ≠ 0 ∨ y ≠ 0) : has_strict_deriv_at (λ y, x ^ y) (x ^ y * log x) y := begin rcases em (x = 0) with rfl|hx, { replace h := h.neg_resolve_left rfl, rw [log_zero, mul_zero], refine (has_strict_deriv_at_const _ 0).congr_of_eventually_eq _, exact (is_open_ne.eventually_mem h).mono (λ y hy, (zero_cpow hy).symm) }, { simpa only [cpow_def_of_ne_zero hx, mul_one] using ((has_strict_deriv_at_id y).const_mul (log x)).cexp } end lemma has_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := (has_strict_fderiv_at_cpow hp).has_fderiv_at end complex section lim open complex variables {α : Type*} lemma filter.tendsto.cpow {l : filter α} {f g : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) (ha : 0 < a.re ∨ a.im ≠ 0) : tendsto (λ x, f x ^ g x) l (𝓝 (a ^ b)) := (@has_fderiv_at_cpow (a, b) ha).continuous_at.tendsto.comp (hf.prod_mk_nhds hg) lemma filter.tendsto.const_cpow {l : filter α} {f : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 b)) (h : a ≠ 0 ∨ b ≠ 0) : tendsto (λ x, a ^ f x) l (𝓝 (a ^ b)) := (has_strict_deriv_at_const_cpow h).continuous_at.tendsto.comp hf variables [topological_space α] {f g : α → ℂ} {s : set α} {a : α} lemma continuous_within_at.cpow (hf : continuous_within_at f s a) (hg : continuous_within_at g s a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_within_at (λ x, f x ^ g x) s a := hf.cpow hg h0 lemma continuous_within_at.const_cpow {b : ℂ} (hf : continuous_within_at f s a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_within_at (λ x, b ^ f x) s a := hf.const_cpow h lemma continuous_at.cpow (hf : continuous_at f a) (hg : continuous_at g a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_at (λ x, f x ^ g x) a := hf.cpow hg h0 lemma continuous_at.const_cpow {b : ℂ} (hf : continuous_at f a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_at (λ x, b ^ f x) a := hf.const_cpow h lemma continuous_on.cpow (hf : continuous_on f s) (hg : continuous_on g s) (h0 : ∀ a ∈ s, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_on (λ x, f x ^ g x) s := λ a ha, (hf a ha).cpow (hg a ha) (h0 a ha) lemma continuous_on.const_cpow {b : ℂ} (hf : continuous_on f s) (h : b ≠ 0 ∨ ∀ a ∈ s, f a ≠ 0) : continuous_on (λ x, b ^ f x) s := λ a ha, (hf a ha).const_cpow (h.imp id $ λ h, h a ha) lemma continuous.cpow (hf : continuous f) (hg : continuous g) (h0 : ∀ a, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous (λ x, f x ^ g x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.cpow hg.continuous_at (h0 a)) lemma continuous.const_cpow {b : ℂ} (hf : continuous f) (h : b ≠ 0 ∨ ∀ a, f a ≠ 0) : continuous (λ x, b ^ f x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.const_cpow $ h.imp id $ λ h, h a) end lim section fderiv open complex variables {E : Type*} [normed_group E] [normed_space ℂ E] {f g : E → ℂ} {f' g' : E →L[ℂ] ℂ} {x : E} {s : set E} {c : ℂ} lemma has_strict_fderiv_at.cpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@has_strict_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_strict_fderiv_at.const_cpow (hf : has_strict_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_fderiv_at.const_cpow (hf : has_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_at x hf lemma has_fderiv_within_at.cpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_within_at.const_cpow (hf : has_fderiv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_within_at x hf lemma differentiable_at.cpow (hf : differentiable_at ℂ f x) (hg : differentiable_at ℂ g x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_at ℂ (λ x, f x ^ g x) x := (hf.has_fderiv_at.cpow hg.has_fderiv_at h0).differentiable_at lemma differentiable_at.const_cpow (hf : differentiable_at ℂ f x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_at ℂ (λ x, c ^ f x) x := (hf.has_fderiv_at.const_cpow h0).differentiable_at lemma differentiable_within_at.cpow (hf : differentiable_within_at ℂ f s x) (hg : differentiable_within_at ℂ g s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_within_at ℂ (λ x, f x ^ g x) s x := (hf.has_fderiv_within_at.cpow hg.has_fderiv_within_at h0).differentiable_within_at lemma differentiable_within_at.const_cpow (hf : differentiable_within_at ℂ f s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_within_at ℂ (λ x, c ^ f x) s x := (hf.has_fderiv_within_at.const_cpow h0).differentiable_within_at end fderiv section deriv open complex variables {f g : ℂ → ℂ} {s : set ℂ} {f' g' x c : ℂ} /-- A private lemma that rewrites the output of lemmas like `has_fderiv_at.cpow` to the form expected by lemmas like `has_deriv_at.cpow`. -/ private lemma aux : ((g x * f x ^ (g x - 1)) • (1 : ℂ →L[ℂ] ℂ).smul_right f' + (f x ^ g x * log (f x)) • (1 : ℂ →L[ℂ] ℂ).smul_right g') 1 = g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g' := by simp only [algebra.id.smul_eq_mul, one_mul, continuous_linear_map.one_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul'] lemma has_strict_deriv_at.cpow (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.cpow hg h0).has_strict_deriv_at lemma has_strict_deriv_at.const_cpow (hf : has_strict_deriv_at f f' x) (h : c ≠ 0 ∨ f x ≠ 0) : has_strict_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h).comp x hf lemma complex.has_strict_deriv_at_cpow_const (h : 0 < x.re ∨ x.im ≠ 0) : has_strict_deriv_at (λ z : ℂ, z ^ c) (c * x ^ (c - 1)) x := by simpa only [mul_zero, add_zero, mul_one] using (has_strict_deriv_at_id x).cpow (has_strict_deriv_at_const x c) h lemma has_strict_deriv_at.cpow_const (hf : has_strict_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).comp x hf lemma has_deriv_at.cpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.has_fderiv_at.cpow hg h0).has_deriv_at lemma has_deriv_at.const_cpow (hf : has_deriv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp x hf lemma has_deriv_at.cpow_const (hf : has_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp x hf lemma has_deriv_within_at.cpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') s x := by simpa only [aux] using (hf.has_fderiv_within_at.cpow hg h0).has_deriv_within_at lemma has_deriv_within_at.const_cpow (hf : has_deriv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_within_at (λ x, c ^ f x) (c ^ f x * log c * f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_deriv_within_at x hf lemma has_deriv_within_at.cpow_const (hf : has_deriv_within_at f f' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') s x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp_has_deriv_within_at x hf end deriv 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, -is_R_or_C.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 exp_mul (x y : ℝ) : exp (x * y) = (exp x) ^ y := by rw [rpow_def_of_pos (exp_pos _), log_exp] 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, real.log_neg_eq_log], 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 @[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, *] lemma zero_rpow_eq_iff {x : ℝ} {a : ℝ} : 0 ^ x = a ↔ (x ≠ 0 ∧ a = 0) ∨ (x = 0 ∧ a = 1) := begin split, { intros hyp, simp [rpow_def] at hyp, by_cases x = 0, { subst h, simp only [complex.one_re, complex.of_real_zero, complex.cpow_zero] at hyp, exact or.inr ⟨rfl, hyp.symm⟩}, { rw complex.zero_cpow (complex.of_real_ne_zero.mpr h) at hyp, exact or.inl ⟨h, hyp.symm⟩, }, }, { rintro (⟨h,rfl⟩|⟨rfl,rfl⟩), { exact zero_rpow h, }, { exact rpow_zero _, }, }, end lemma eq_zero_rpow_iff {x : ℝ} {a : ℝ} : a = 0 ^ x ↔ (x ≠ 0 ∧ a = 0) ∨ (x = 0 ∧ a = 1) := by rw [←zero_rpow_eq_iff, eq_comm] @[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 zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x := by { by_cases h : x = 0; simp [h, zero_le_one] } 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 abs_rpow_le_abs_rpow (x y : ℝ) : |x ^ y| ≤ |x| ^ y := begin rcases lt_trichotomy 0 x with (hx|rfl|hx), { rw [abs_of_pos hx, abs_of_pos (rpow_pos_of_pos hx _)] }, { rw [abs_zero, abs_of_nonneg (rpow_nonneg_of_nonneg le_rfl _)] }, { rw [abs_of_neg hx, rpow_def_of_neg hx, rpow_def_of_pos (neg_pos.2 hx), log_neg_eq_log, abs_mul, abs_of_pos (exp_pos _)], exact mul_le_of_le_one_right (exp_pos _).le (abs_cos_le_one _) } end lemma abs_rpow_le_exp_log_mul (x y : ℝ) : |x ^ y| ≤ exp (log x * y) := begin refine (abs_rpow_le_abs_rpow x y).trans _, by_cases hx : x = 0, { by_cases hy : y = 0; simp [hx, hy, zero_le_one] }, { rw [rpow_def_of_pos (abs_pos.2 hx), log_abs] } end lemma abs_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : |x ^ y| = |x| ^ y := begin have h_rpow_nonneg : 0 ≤ x ^ y, from real.rpow_nonneg_of_nonneg hx_nonneg _, rw [abs_eq_self.mpr hx_nonneg, abs_eq_self.mpr h_rpow_nonneg], end lemma norm_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : ∥x ^ y∥ = ∥x∥ ^ y := by { simp_rw real.norm_eq_abs, exact abs_rpow_of_nonneg hx_nonneg, } 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, -is_R_or_C.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 variables {x y z : ℝ} lemma rpow_add {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_add' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := begin rcases hx.eq_or_lt with rfl|pos, { rw [zero_rpow h, zero_eq_mul], have : y ≠ 0 ∨ z ≠ 0, from not_and_distrib.1 (λ ⟨hy, hz⟩, h $ hy.symm ▸ hz.symm ▸ zero_add 0), exact this.imp zero_rpow zero_rpow }, { exact rpow_add pos _ _ } end /-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for `x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish. The inequality is always true, though, and given in this lemma. -/ lemma le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { by_cases h : y + z = 0, { simp only [H.symm, h, rpow_zero], calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 : mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one ... = 1 : by simp }, { simp [rpow_add', ← H, h] } }, { simp [rpow_add pos] } end 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 * lemma rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv] lemma rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by { simp only [sub_eq_add_neg] at h ⊢, simp only [rpow_add' hx h, rpow_neg hx, div_eq_mul_inv] } lemma rpow_add_int {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℤ) : x ^ (y + n) = x ^ y * x ^ n := by rw [rpow_def, complex.of_real_add, complex.cpow_add _ _ (complex.of_real_ne_zero.mpr hx), complex.of_real_int_cast, complex.cpow_int_cast, ← complex.of_real_zpow, mul_comm, complex.of_real_mul_re, ← rpow_def, mul_comm] lemma rpow_add_nat {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℕ) : x ^ (y + n) = x ^ y * x ^ n := rpow_add_int hx y n lemma rpow_sub_int {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℤ) : x ^ (y - n) = x ^ y / x ^ n := by simpa using rpow_add_int hx y (-n) lemma rpow_sub_nat {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℕ) : x ^ (y - n) = x ^ y / x ^ n := rpow_sub_int hx y n lemma rpow_add_one {x : ℝ} (hx : x ≠ 0) (y : ℝ) : x ^ (y + 1) = x ^ y * x := by simpa using rpow_add_nat hx y 1 lemma rpow_sub_one {x : ℝ} (hx : x ≠ 0) (y : ℝ) : x ^ (y - 1) = x ^ y / x := by simpa using rpow_sub_nat hx y 1 @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, ← complex.of_real_zpow, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := rpow_int_cast x n lemma rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ := begin suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹, by exact_mod_cast H, simp only [rpow_int_cast, zpow_one, zpow_neg₀], end 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 (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]}, { exact h₁ }, { exact h }, { exact mul_nonneg h h₁ }, end lemma inv_rpow (hx : 0 ≤ x) (y : ℝ) : (x⁻¹)^y = (x^y)⁻¹ := by simp only [← rpow_neg_one, ← rpow_mul hx, mul_comm] lemma div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x^z / y^z := by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy] lemma log_rpow {x : ℝ} (hx : 0 < x) (y : ℝ) : log (x^y) = y * (log x) := begin apply exp_injective, rw [exp_log (rpow_pos_of_pos hx y), ← exp_log hx, mul_comm, rpow_def_of_pos (exp_pos (log x)) y], 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_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases eq_or_lt_of_le h₁ with rfl|h₁', { refl }, rcases eq_or_lt_of_le h₂ with rfl|h₂', { simp }, exact le_of_lt (rpow_lt_rpow h h₁' h₂') end lemma rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := ⟨lt_imp_lt_of_le_imp_le $ λ h, rpow_le_rpow hy h (le_of_lt hz), λ h, rpow_lt_rpow hx h hz⟩ lemma rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := le_iff_le_iff_lt_iff_lt.2 $ rpow_lt_rpow_iff hy hx hz 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 (le_of_lt hx0) hx1), end lemma rpow_lt_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow hx1 hx2 hz } lemma rpow_le_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := by { rw ← one_rpow z, exact rpow_le_rpow hx1 hx2 hz } lemma rpow_lt_one_of_one_lt_of_neg {x z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := by { convert rpow_lt_rpow_of_exponent_lt hx hz, exact (rpow_zero x).symm } lemma rpow_le_one_of_one_le_of_nonpos {x z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := by { convert rpow_le_rpow_of_exponent_le hx hz, exact (rpow_zero x).symm } lemma one_lt_rpow {x z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma one_le_rpow {x z : ℝ} (hx : 1 ≤ x) (hz : 0 ≤ z) : 1 ≤ x^z := by { rw ← one_rpow z, exact rpow_le_rpow zero_le_one hx hz } lemma one_lt_rpow_of_pos_of_lt_one_of_neg (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := by { convert rpow_lt_rpow_of_exponent_gt hx1 hx2 hz, exact (rpow_zero x).symm } lemma one_le_rpow_of_pos_of_le_one_of_nonpos (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := by { convert rpow_le_rpow_of_exponent_ge hx1 hx2 hz, exact (rpow_zero x).symm } lemma rpow_lt_one_iff_of_pos (hx : 0 < x) : x ^ y < 1 ↔ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := by rw [rpow_def_of_pos hx, exp_lt_one_iff, mul_neg_iff, log_pos_iff hx, log_neg_iff hx] lemma rpow_lt_one_iff (hx : 0 ≤ x) : x ^ y < 1 ↔ x = 0 ∧ y ≠ 0 ∨ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, zero_lt_one] }, { simp [rpow_lt_one_iff_of_pos hx, hx.ne.symm] } end lemma one_lt_rpow_iff_of_pos (hx : 0 < x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ x < 1 ∧ y < 0 := by rw [rpow_def_of_pos hx, one_lt_exp_iff, mul_pos_iff, log_pos_iff hx, log_neg_iff hx] lemma one_lt_rpow_iff (hx : 0 ≤ x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ 0 < x ∧ x < 1 ∧ y < 0 := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, (@zero_lt_one ℝ _ _).not_lt] }, { simp [one_lt_rpow_iff_of_pos hx, hx] } end lemma le_rpow_iff_log_le (hx : 0 < x) (hy : 0 < y) : x ≤ y^z ↔ real.log x ≤ z * real.log y := by rw [←real.log_le_log hx (real.rpow_pos_of_pos hy z), real.log_rpow hy] lemma le_rpow_of_log_le (hx : 0 ≤ x) (hy : 0 < y) (h : real.log x ≤ z * real.log y) : x ≤ y^z := begin obtain hx | rfl := hx.lt_or_eq, { exact (le_rpow_iff_log_le hx hy).2 h }, exact (real.rpow_pos_of_pos hy z).le, end lemma lt_rpow_iff_log_lt (hx : 0 < x) (hy : 0 < y) : x < y^z ↔ real.log x < z * real.log y := by rw [←real.log_lt_log_iff hx (real.rpow_pos_of_pos hy z), real.log_rpow hy] lemma lt_rpow_of_log_lt (hx : 0 ≤ x) (hy : 0 < y) (h : real.log x < z * real.log y) : x < y^z := begin obtain hx | rfl := hx.lt_or_eq, { exact (lt_rpow_iff_log_lt hx hy).2 h }, exact real.rpow_pos_of_pos hy z, end lemma rpow_le_one_iff_of_pos (hx : 0 < x) : x ^ y ≤ 1 ↔ 1 ≤ x ∧ y ≤ 0 ∨ x ≤ 1 ∧ 0 ≤ y := by rw [rpow_def_of_pos hx, exp_le_one_iff, mul_nonpos_iff, log_nonneg_iff hx, log_nonpos_iff hx] lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [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 [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one] /-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `0 < p.fst`. -/ lemma has_strict_fderiv_at_rpow_of_pos (p : ℝ × ℝ) (hp : 0 < p.1) : has_strict_fderiv_at (λ x : ℝ × ℝ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℝ ℝ ℝ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℝ ℝ ℝ) p := begin have : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from (continuous_at_fst.eventually (lt_mem_nhds hp)).mono (λ p hp, rpow_def_of_pos hp _), refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, convert ((has_strict_fderiv_at_fst.log hp.ne').mul has_strict_fderiv_at_snd).exp, rw [rpow_sub_one hp.ne', ← rpow_def_of_pos hp, smul_add, smul_smul, mul_div_comm, div_eq_mul_inv, smul_smul, smul_smul, mul_assoc, add_comm] end /-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `p.fst < 0`. -/ lemma has_strict_fderiv_at_rpow_of_neg (p : ℝ × ℝ) (hp : p.1 < 0) : has_strict_fderiv_at (λ x : ℝ × ℝ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℝ ℝ ℝ + (p.1 ^ p.2 * log p.1 - exp (log p.1 * p.2) * sin (p.2 * π) * π) • continuous_linear_map.snd ℝ ℝ ℝ) p := begin have : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2) * cos (x.2 * π)), from (continuous_at_fst.eventually (gt_mem_nhds hp)).mono (λ p hp, rpow_def_of_neg hp _), refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, convert ((has_strict_fderiv_at_fst.log hp.ne).mul has_strict_fderiv_at_snd).exp.mul (has_strict_fderiv_at_snd.mul_const _).cos using 1, simp_rw [rpow_sub_one hp.ne, smul_add, ← add_assoc, smul_smul, ← add_smul, ← mul_assoc, mul_comm (cos _), ← rpow_def_of_neg hp], rw [div_eq_mul_inv, add_comm], congr' 2; ring end /-- The function `λ (x, y), x ^ y` is infinitely smooth at `(x, y)` unless `x = 0`. -/ lemma times_cont_diff_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) {n : with_top ℕ} : times_cont_diff_at ℝ n (λ p : ℝ × ℝ, p.1 ^ p.2) p := begin cases hp.lt_or_lt with hneg hpos, exacts [(((times_cont_diff_at_fst.log hneg.ne).mul times_cont_diff_at_snd).exp.mul (times_cont_diff_at_snd.mul times_cont_diff_at_const).cos).congr_of_eventually_eq ((continuous_at_fst.eventually (gt_mem_nhds hneg)).mono (λ p hp, rpow_def_of_neg hp _)), ((times_cont_diff_at_fst.log hpos.ne').mul times_cont_diff_at_snd).exp.congr_of_eventually_eq ((continuous_at_fst.eventually (lt_mem_nhds hpos)).mono (λ p hp, rpow_def_of_pos hp _))] end lemma differentiable_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) : differentiable_at ℝ (λ p : ℝ × ℝ, p.1 ^ p.2) p := (times_cont_diff_at_rpow_of_ne p hp).differentiable_at le_rfl lemma continuous_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) : continuous_at (λ p : ℝ × ℝ, p.1 ^ p.2) p := (@times_cont_diff_at_rpow_of_ne p hp 0).continuous_at lemma _root_.has_strict_deriv_at.rpow {f g : ℝ → ℝ} {f' g' : ℝ} (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h : 0 < f x) : has_strict_deriv_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) x := begin convert (has_strict_fderiv_at_rpow_of_pos ((λ x, (f x, g x)) x) h).comp_has_strict_deriv_at _ (hf.prod hg) using 1, simp [mul_assoc, mul_comm, mul_left_comm] end lemma has_strict_deriv_at_rpow_const_of_ne {x : ℝ} (hx : x ≠ 0) (p : ℝ) : has_strict_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := begin cases hx.lt_or_lt with hx hx, { have := (has_strict_fderiv_at_rpow_of_neg (x, p) hx).comp_has_strict_deriv_at x ((has_strict_deriv_at_id x).prod (has_strict_deriv_at_const _ _)), convert this, simp }, { simpa using (has_strict_deriv_at_id x).rpow (has_strict_deriv_at_const x p) hx } end lemma has_strict_deriv_at_const_rpow {a : ℝ} (ha : 0 < a) (x : ℝ) : has_strict_deriv_at (λ x, a ^ x) (a ^ x * log a) x := by simpa using (has_strict_deriv_at_const _ _).rpow (has_strict_deriv_at_id x) ha /-- This lemma says that `λ x, a ^ x` is strictly differentiable for `a < 0`. Note that these values of `a` are outside of the "official" domain of `a ^ x`, and we may redefine `a ^ x` for negative `a` if some other definition will be more convenient. -/ lemma has_strict_deriv_at_const_rpow_of_neg {a x : ℝ} (ha : a < 0) : has_strict_deriv_at (λ x, a ^ x) (a ^ x * log a - exp (log a * x) * sin (x * π) * π) x := by simpa using (has_strict_fderiv_at_rpow_of_neg (a, x) ha).comp_has_strict_deriv_at x ((has_strict_deriv_at_const _ _).prod (has_strict_deriv_at_id _)) lemma continuous_at_rpow_of_pos (p : ℝ × ℝ) (hp : 0 < p.2) : continuous_at (λ p : ℝ × ℝ, p.1 ^ p.2) p := begin cases p with x y, obtain hx|rfl := ne_or_eq x 0, { exact continuous_at_rpow_of_ne (x, y) hx }, have A : tendsto (λ p : ℝ × ℝ, exp (log p.1 * p.2)) (𝓝[{0}ᶜ] 0 ×ᶠ 𝓝 y) (𝓝 0) := tendsto_exp_at_bot.comp ((tendsto_log_nhds_within_zero.comp tendsto_fst).at_bot_mul hp tendsto_snd), have B : tendsto (λ p : ℝ × ℝ, p.1 ^ p.2) (𝓝[{0}ᶜ] 0 ×ᶠ 𝓝 y) (𝓝 0) := squeeze_zero_norm (λ p, abs_rpow_le_exp_log_mul p.1 p.2) A, have C : tendsto (λ p : ℝ × ℝ, p.1 ^ p.2) (𝓝[{0}] 0 ×ᶠ 𝓝 y) (pure 0), { rw [nhds_within_singleton, tendsto_pure, pure_prod, eventually_map], exact (lt_mem_nhds hp).mono (λ y hy, zero_rpow hy.ne') }, simpa only [← sup_prod, ← nhds_within_union, set.compl_union_self, nhds_within_univ, nhds_prod_eq, continuous_at, zero_rpow hp.ne'] using B.sup (C.mono_right (pure_le_nhds _)) end lemma continuous_at_rpow (p : ℝ × ℝ) (h : p.1 ≠ 0 ∨ 0 < p.2) : continuous_at (λ p : ℝ × ℝ, p.1 ^ p.2) p := h.elim (λ h, continuous_at_rpow_of_ne p h) (λ h, continuous_at_rpow_of_pos p h) end real section variable {α : Type*} lemma filter.tendsto.rpow {l : filter α} {f g : α → ℝ} {x y : ℝ} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ t, f t ^ g t) l (𝓝 (x ^ y)) := (real.continuous_at_rpow (x, y) h).tendsto.comp (hf.prod_mk_nhds hg) lemma filter.tendsto.rpow_const {l : filter α} {f : α → ℝ} {x p : ℝ} (hf : tendsto f l (𝓝 x)) (h : x ≠ 0 ∨ 0 ≤ p) : tendsto (λ a, f a ^ p) l (𝓝 (x ^ p)) := if h0 : 0 = p then h0 ▸ by simp [tendsto_const_nhds] else hf.rpow tendsto_const_nhds (h.imp id $ λ h', h'.lt_of_ne h0) variables [topological_space α] {f g : α → ℝ} {s : set α} {x : α} {p : ℝ} lemma continuous_at.rpow (hf : continuous_at f x) (hg : continuous_at g x) (h : f x ≠ 0 ∨ 0 < g x) : continuous_at (λ t, f t ^ g t) x := hf.rpow hg h lemma continuous_within_at.rpow (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) (h : f x ≠ 0 ∨ 0 < g x) : continuous_within_at (λ t, f t ^ g t) s x := hf.rpow hg h lemma continuous_on.rpow (hf : continuous_on f s) (hg : continuous_on g s) (h : ∀ x ∈ s, f x ≠ 0 ∨ 0 < g x) : continuous_on (λ t, f t ^ g t) s := λ t ht, (hf t ht).rpow (hg t ht) (h t ht) lemma continuous.rpow (hf : continuous f) (hg : continuous g) (h : ∀ x, f x ≠ 0 ∨ 0 < g x) : continuous (λ x, f x ^ g x) := continuous_iff_continuous_at.2 $ λ x, (hf.continuous_at.rpow hg.continuous_at (h x)) lemma continuous_within_at.rpow_const (hf : continuous_within_at f s x) (h : f x ≠ 0 ∨ 0 ≤ p) : continuous_within_at (λ x, f x ^ p) s x := hf.rpow_const h lemma continuous_at.rpow_const (hf : continuous_at f x) (h : f x ≠ 0 ∨ 0 ≤ p) : continuous_at (λ x, f x ^ p) x := hf.rpow_const h lemma continuous_on.rpow_const (hf : continuous_on f s) (h : ∀ x ∈ s, f x ≠ 0 ∨ 0 ≤ p) : continuous_on (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const (h x hx) lemma continuous.rpow_const (hf : continuous f) (h : ∀ x, f x ≠ 0 ∨ 0 ≤ p) : continuous (λ x, f x ^ p) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.rpow_const (h x) end namespace real variables {z x y : ℝ} lemma has_deriv_at_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) : has_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := begin rcases ne_or_eq x 0 with hx | rfl, { exact (has_strict_deriv_at_rpow_const_of_ne hx _).has_deriv_at }, replace h : 1 ≤ p := h.neg_resolve_left rfl, apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, (has_strict_deriv_at_rpow_const_of_ne hx p).has_deriv_at), exacts [continuous_at_id.rpow_const (or.inr (zero_le_one.trans h)), continuous_at_const.mul (continuous_at_id.rpow_const (or.inr (sub_nonneg.2 h)))] end lemma differentiable_rpow_const {p : ℝ} (hp : 1 ≤ p) : differentiable ℝ (λ x : ℝ, x ^ p) := λ x, (has_deriv_at_rpow_const (or.inr hp)).differentiable_at lemma deriv_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) : deriv (λ x : ℝ, x ^ p) x = p * x ^ (p - 1) := (has_deriv_at_rpow_const h).deriv lemma deriv_rpow_const' {p : ℝ} (h : 1 ≤ p) : deriv (λ x : ℝ, x ^ p) = λ x, p * x ^ (p - 1) := funext $ λ x, deriv_rpow_const (or.inr h) lemma times_cont_diff_at_rpow_const_of_ne {x p : ℝ} {n : with_top ℕ} (h : x ≠ 0) : times_cont_diff_at ℝ n (λ x, x ^ p) x := (times_cont_diff_at_rpow_of_ne (x, p) h).comp x (times_cont_diff_at_id.prod times_cont_diff_at_const) lemma times_cont_diff_rpow_const_of_le {p : ℝ} {n : ℕ} (h : ↑n ≤ p) : times_cont_diff ℝ n (λ x : ℝ, x ^ p) := begin induction n with n ihn generalizing p, { exact times_cont_diff_zero.2 (continuous_id.rpow_const (λ x, or.inr h)) }, { have h1 : 1 ≤ p, from le_trans (by simp) h, rw [nat.cast_succ, ← le_sub_iff_add_le] at h, simpa [times_cont_diff_succ_iff_deriv, differentiable_rpow_const, h1, deriv_rpow_const'] using times_cont_diff_const.mul (ihn h) } end lemma times_cont_diff_at_rpow_const_of_le {x p : ℝ} {n : ℕ} (h : ↑n ≤ p) : times_cont_diff_at ℝ n (λ x : ℝ, x ^ p) x := (times_cont_diff_rpow_const_of_le h).times_cont_diff_at lemma times_cont_diff_at_rpow_const {x p : ℝ} {n : ℕ} (h : x ≠ 0 ∨ ↑n ≤ p) : times_cont_diff_at ℝ n (λ x : ℝ, x ^ p) x := h.elim times_cont_diff_at_rpow_const_of_ne times_cont_diff_at_rpow_const_of_le lemma has_strict_deriv_at_rpow_const {x p : ℝ} (hx : x ≠ 0 ∨ 1 ≤ p) : has_strict_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := times_cont_diff_at.has_strict_deriv_at' (times_cont_diff_at_rpow_const (by rwa nat.cast_one)) (has_deriv_at_rpow_const hx) le_rfl section sqrt lemma sqrt_eq_rpow (x : ℝ) : sqrt x = x ^ (1/(2:ℝ)) := begin obtain h | h := le_or_lt 0 x, { rw [← mul_self_inj_of_nonneg (sqrt_nonneg _) (rpow_nonneg_of_nonneg h _), mul_self_sqrt h, ← sq, ← rpow_nat_cast, ← rpow_mul h], norm_num }, { have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos h.le, rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end end sqrt end real section differentiability open real section fderiv variables {E : Type*} [normed_group E] [normed_space ℝ E] {f g : E → ℝ} {f' g' : E →L[ℝ] ℝ} {x : E} {s : set E} {c p : ℝ} {n : with_top ℕ} lemma has_fderiv_within_at.rpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h : 0 < f x) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).has_fderiv_at.comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_at.rpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h : 0 < f x) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).has_fderiv_at.comp x (hf.prod hg) lemma has_strict_fderiv_at.rpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h : 0 < f x) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).comp x (hf.prod hg) lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) (h : f x ≠ 0) : differentiable_within_at ℝ (λ x, f x ^ g x) s x := (differentiable_at_rpow_of_ne (f x, g x) h).comp_differentiable_within_at x (hf.prod hg) lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (h : f x ≠ 0) : differentiable_at ℝ (λ x, f x ^ g x) x := (differentiable_at_rpow_of_ne (f x, g x) h).comp x (hf.prod hg) lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) (h : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λ x, f x ^ g x) s := λ x hx, (hf x hx).rpow (hg x hx) (h x hx) lemma differentiable.rpow (hf : differentiable ℝ f) (hg : differentiable ℝ g) (h : ∀ x, f x ≠ 0) : differentiable ℝ (λ x, f x ^ g x) := λ x, (hf x).rpow (hg x) (h x) lemma has_fderiv_within_at.rpow_const (hf : has_fderiv_within_at f f' s x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_fderiv_within_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') s x := (has_deriv_at_rpow_const h).comp_has_fderiv_within_at x hf lemma has_fderiv_at.rpow_const (hf : has_fderiv_at f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_fderiv_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') x := (has_deriv_at_rpow_const h).comp_has_fderiv_at x hf lemma has_strict_fderiv_at.rpow_const (hf : has_strict_fderiv_at f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_strict_fderiv_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') x := (has_strict_deriv_at_rpow_const h).comp_has_strict_fderiv_at x hf lemma differentiable_within_at.rpow_const (hf : differentiable_within_at ℝ f s x) (h : f x ≠ 0 ∨ 1 ≤ p) : differentiable_within_at ℝ (λ x, f x ^ p) s x := (hf.has_fderiv_within_at.rpow_const h).differentiable_within_at @[simp] lemma differentiable_at.rpow_const (hf : differentiable_at ℝ f x) (h : f x ≠ 0 ∨ 1 ≤ p) : differentiable_at ℝ (λ x, f x ^ p) x := (hf.has_fderiv_at.rpow_const h).differentiable_at lemma differentiable_on.rpow_const (hf : differentiable_on ℝ f s) (h : ∀ x ∈ s, f x ≠ 0 ∨ 1 ≤ p) : differentiable_on ℝ (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const (h x hx) lemma differentiable.rpow_const (hf : differentiable ℝ f) (h : ∀ x, f x ≠ 0 ∨ 1 ≤ p) : differentiable ℝ (λ x, f x ^ p) := λ x, (hf x).rpow_const (h x) lemma has_fderiv_within_at.const_rpow (hf : has_fderiv_within_at f f' s x) (hc : 0 < c) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_rpow hc (f x)).has_deriv_at.comp_has_fderiv_within_at x hf lemma has_fderiv_at.const_rpow (hf : has_fderiv_at f f' x) (hc : 0 < c) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_rpow hc (f x)).has_deriv_at.comp_has_fderiv_at x hf lemma has_strict_fderiv_at.const_rpow (hf : has_strict_fderiv_at f f' x) (hc : 0 < c) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_rpow hc (f x)).comp_has_strict_fderiv_at x hf lemma times_cont_diff_within_at.rpow (hf : times_cont_diff_within_at ℝ n f s x) (hg : times_cont_diff_within_at ℝ n g s x) (h : f x ≠ 0) : times_cont_diff_within_at ℝ n (λ x, f x ^ g x) s x := (times_cont_diff_at_rpow_of_ne (f x, g x) h).comp_times_cont_diff_within_at x (hf.prod hg) lemma times_cont_diff_at.rpow (hf : times_cont_diff_at ℝ n f x) (hg : times_cont_diff_at ℝ n g x) (h : f x ≠ 0) : times_cont_diff_at ℝ n (λ x, f x ^ g x) x := (times_cont_diff_at_rpow_of_ne (f x, g x) h).comp x (hf.prod hg) lemma times_cont_diff_on.rpow (hf : times_cont_diff_on ℝ n f s) (hg : times_cont_diff_on ℝ n g s) (h : ∀ x ∈ s, f x ≠ 0) : times_cont_diff_on ℝ n (λ x, f x ^ g x) s := λ x hx, (hf x hx).rpow (hg x hx) (h x hx) lemma times_cont_diff.rpow (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g) (h : ∀ x, f x ≠ 0) : times_cont_diff ℝ n (λ x, f x ^ g x) := times_cont_diff_iff_times_cont_diff_at.mpr $ λ x, hf.times_cont_diff_at.rpow hg.times_cont_diff_at (h x) lemma times_cont_diff_within_at.rpow_const_of_ne (hf : times_cont_diff_within_at ℝ n f s x) (h : f x ≠ 0) : times_cont_diff_within_at ℝ n (λ x, f x ^ p) s x := hf.rpow times_cont_diff_within_at_const h lemma times_cont_diff_at.rpow_const_of_ne (hf : times_cont_diff_at ℝ n f x) (h : f x ≠ 0) : times_cont_diff_at ℝ n (λ x, f x ^ p) x := hf.rpow times_cont_diff_at_const h lemma times_cont_diff_on.rpow_const_of_ne (hf : times_cont_diff_on ℝ n f s) (h : ∀ x ∈ s, f x ≠ 0) : times_cont_diff_on ℝ n (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const_of_ne (h x hx) lemma times_cont_diff.rpow_const_of_ne (hf : times_cont_diff ℝ n f) (h : ∀ x, f x ≠ 0) : times_cont_diff ℝ n (λ x, f x ^ p) := hf.rpow times_cont_diff_const h variable {m : ℕ} lemma times_cont_diff_within_at.rpow_const_of_le (hf : times_cont_diff_within_at ℝ m f s x) (h : ↑m ≤ p) : times_cont_diff_within_at ℝ m (λ x, f x ^ p) s x := (times_cont_diff_at_rpow_const_of_le h).comp_times_cont_diff_within_at x hf lemma times_cont_diff_at.rpow_const_of_le (hf : times_cont_diff_at ℝ m f x) (h : ↑m ≤ p) : times_cont_diff_at ℝ m (λ x, f x ^ p) x := by { rw ← times_cont_diff_within_at_univ at *, exact hf.rpow_const_of_le h } lemma times_cont_diff_on.rpow_const_of_le (hf : times_cont_diff_on ℝ m f s) (h : ↑m ≤ p) : times_cont_diff_on ℝ m (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const_of_le h lemma times_cont_diff.rpow_const_of_le (hf : times_cont_diff ℝ m f) (h : ↑m ≤ p) : times_cont_diff ℝ m (λ x, f x ^ p) := times_cont_diff_iff_times_cont_diff_at.mpr $ λ x, hf.times_cont_diff_at.rpow_const_of_le h end fderiv section deriv variables {f g : ℝ → ℝ} {f' g' x y p : ℝ} {s : set ℝ} lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h : 0 < f x) : has_deriv_within_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) s x := begin convert (hf.has_fderiv_within_at.rpow hg.has_fderiv_within_at h).has_deriv_within_at using 1, dsimp, ring end lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h : 0 < f x) : has_deriv_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow hg h end lemma has_deriv_within_at.rpow_const (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0 ∨ 1 ≤ p) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x) ^ (p - 1)) s x := begin convert (has_deriv_at_rpow_const hx).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow_const (hf : has_deriv_at f f' x) (hx : f x ≠ 0 ∨ 1 ≤ p) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow_const hx end lemma deriv_within_rpow_const (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0 ∨ 1 ≤ p) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x) ^ p) s x = (deriv_within f s x) * p * (f x) ^ (p - 1) := (hf.has_deriv_within_at.rpow_const hx).deriv_within hxs @[simp] lemma deriv_rpow_const (hf : differentiable_at ℝ f x) (hx : f x ≠ 0 ∨ 1 ≤ p) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow_const hx).deriv end deriv end differentiability section limits open real filter /-- The function `x ^ y` tends to `+∞` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ y) at_top at_top := begin rw tendsto_at_top_at_top, intro b, use (max b 0) ^ (1/y), intros x hx, exact le_of_max_le_left (by { convert rpow_le_rpow (rpow_nonneg_of_nonneg (le_max_right b 0) (1/y)) hx (le_of_lt hy), rw [← rpow_mul (le_max_right b 0), (eq_div_iff (ne_of_gt hy)).mp rfl, rpow_one] }), end /-- The function `x ^ (-y)` tends to `0` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_neg_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ (-y)) at_top (𝓝 0) := tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top 0) (λ x hx, (rpow_neg (le_of_lt hx) y).symm)) (tendsto_rpow_at_top hy).inv_tendsto_at_top /-- The function `x ^ (a / (b * x + c))` tends to `1` at `+∞`, for any real numbers `a`, `b`, and `c` such that `b` is nonzero. -/ lemma tendsto_rpow_div_mul_add (a b c : ℝ) (hb : 0 ≠ b) : tendsto (λ x, x ^ (a / (b*x+c))) at_top (𝓝 1) := begin refine tendsto.congr' _ ((tendsto_exp_nhds_0_nhds_1.comp (by simpa only [mul_zero, pow_one] using ((@tendsto_const_nhds _ _ _ a _).mul (tendsto_div_pow_mul_exp_add_at_top b c 1 hb (by norm_num))))).comp (tendsto_log_at_top)), apply eventually_eq_of_mem (Ioi_mem_at_top (0:ℝ)), intros x hx, simp only [set.mem_Ioi, function.comp_app] at hx ⊢, rw [exp_log hx, ← exp_log (rpow_pos_of_pos hx (a / (b * x + c))), log_rpow hx (a / (b * x + c))], field_simp, end /-- The function `x ^ (1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_div : tendsto (λ x, x ^ ((1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (1:ℝ) _ (0:ℝ) zero_ne_one, ring_nf } /-- The function `x ^ (-1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_neg_div : tendsto (λ x, x ^ (-(1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (-(1:ℝ)) _ (0:ℝ) zero_ne_one, ring_nf } /-- The function `(1 + t/x) ^ x` tends to `exp t` at `+∞`. -/ lemma tendsto_one_plus_div_rpow_exp (t : ℝ) : tendsto (λ (x : ℝ), (1 + t / x) ^ x) at_top (𝓝 (exp t)) := begin apply ((real.continuous_exp.tendsto _).comp (tendsto_mul_log_one_plus_div_at_top t)).congr' _, have h₁ : (1:ℝ)/2 < 1 := by linarith, have h₂ : tendsto (λ x : ℝ, 1 + t / x) at_top (𝓝 1) := by simpa using (tendsto_inv_at_top_zero.const_mul t).const_add 1, refine (eventually_ge_of_tendsto_gt h₁ h₂).mono (λ x hx, _), have hx' : 0 < 1 + t / x := by linarith, simp [mul_comm x, exp_mul, exp_log hx'], end /-- The function `(1 + t/x) ^ x` tends to `exp t` at `+∞` for naturals `x`. -/ lemma tendsto_one_plus_div_pow_exp (t : ℝ) : tendsto (λ (x : ℕ), (1 + t / (x:ℝ)) ^ x) at_top (𝓝 (real.exp t)) := ((tendsto_one_plus_div_rpow_exp t).comp tendsto_coe_nat_at_top_at_top).congr (by simp) end limits namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` 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 : ℝ≥0) (y : ℝ) : ℝ≥0 := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow ℝ≥0 ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, norm_cast] lemma coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 := nnreal.eq $ real.rpow_zero _ @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0} {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 : ℝ≥0) ^ x = 0 := nnreal.eq $ real.zero_rpow h @[simp] lemma rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x := nnreal.eq $ real.rpow_one _ @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 := nnreal.eq $ real.one_rpow _ lemma rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add (pos_iff_ne_zero.2 hx) _ _ lemma rpow_add' (x : ℝ≥0) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add' x.2 h lemma rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := nnreal.eq $ real.rpow_mul x.2 y z lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := nnreal.eq $ real.rpow_neg x.2 _ lemma rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub (pos_iff_ne_zero.2 hx) y z lemma rpow_sub' (x : ℝ≥0) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub' x.2 h lemma inv_rpow (x : ℝ≥0) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ := nnreal.eq $ real.inv_rpow x.2 y lemma div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z := nnreal.eq $ real.div_rpow x.2 y.2 z lemma sqrt_eq_rpow (x : ℝ≥0) : sqrt x = x ^ (1/(2:ℝ)) := begin refine nnreal.eq _, push_cast, exact real.sqrt_eq_rpow x.1, end @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n := nnreal.eq $ by simpa only [coe_rpow, coe_pow] using real.rpow_nat_cast x n lemma mul_rpow {x y : ℝ≥0} {z : ℝ} : (x*y)^z = x^z * y^z := nnreal.eq $ real.mul_rpow x.2 y.2 lemma rpow_le_rpow {x y : ℝ≥0} {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 : ℝ≥0} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := real.rpow_lt_rpow_iff x.2 y.2 hz lemma rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := real.rpow_le_rpow_iff x.2 y.2 hz lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {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 : ℝ≥0} {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 : ℝ≥0} {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 : ℝ≥0} {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_lt_one {x : ℝ≥0} {z : ℝ} (hx : 0 ≤ x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := real.rpow_le_one x.2 hx2 hz lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := real.rpow_lt_one_of_one_lt_of_neg hx hz lemma rpow_le_one_of_one_le_of_nonpos {x : ℝ≥0} {z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := real.rpow_le_one_of_one_le_of_nonpos hx hz lemma one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := real.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz lemma one_le_rpow_of_pos_of_le_one_of_nonpos {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := real.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 hz lemma pow_nat_rpow_nat_inv (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ≥0×ℝ, p.1^p.2) (x, y) := begin have : (λp:ℝ≥0×ℝ, p.1^p.2) = real.to_nnreal ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:ℝ≥0 × ℝ, (p.1.1, p.2)), { ext p, rw [coe_rpow, real.coe_to_nnreal _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine nnreal.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 lemma _root_.real.to_nnreal_rpow_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : real.to_nnreal (x ^ y) = (real.to_nnreal x) ^ y := begin nth_rewrite 0 ← real.coe_to_nnreal x hx, rw [←nnreal.coe_rpow, real.to_nnreal_coe], end end nnreal open filter lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → ℝ≥0} {v : α → ℝ} {x : ℝ≥0} {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) (hx.prod_mk_nhds hy) namespace nnreal lemma continuous_at_rpow_const {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 ≤ y) : continuous_at (λ z, z^y) x := h.elim (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inl h)) $ λ h, h.eq_or_lt.elim (λ h, h ▸ by simp only [rpow_zero, continuous_at_const]) (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inr h)) lemma continuous_rpow_const {y : ℝ} (h : 0 ≤ y) : continuous (λ x : ℝ≥0, x^y) := continuous_iff_continuous_at.2 $ λ x, continuous_at_rpow_const (or.inr h) theorem tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ (x : ℝ≥0), x ^ y) at_top at_top := begin rw filter.tendsto_at_top_at_top, intros b, obtain ⟨c, hc⟩ := tendsto_at_top_at_top.mp (tendsto_rpow_at_top hy) b, use c.to_nnreal, intros a ha, exact_mod_cast hc a (real.to_nnreal_le_iff_le_coe.mp ha), end end nnreal namespace ennreal /-- The real power function `x^y` on extended nonnegative reals, defined for `x : ℝ≥0∞` and `y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and `⊤ ^ x = 1 / 0 ^ x`). -/ noncomputable def rpow : ℝ≥0∞ → ℝ → ℝ≥0∞ | (some x) y := if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) | none y := if 0 < y then ⊤ else if y = 0 then 1 else 0 noncomputable instance : has_pow ℝ≥0∞ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0∞) (y : ℝ) : rpow x y = x ^ y := rfl @[simp] lemma rpow_zero {x : ℝ≥0∞} : x ^ (0 : ℝ) = 1 := by cases x; { dsimp only [(^), rpow], simp [lt_irrefl] } lemma top_rpow_def (y : ℝ) : (⊤ : ℝ≥0∞) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 := rfl @[simp] lemma top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ℝ≥0∞) ^ y = ⊤ := by simp [top_rpow_def, h] @[simp] lemma top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ℝ≥0∞) ^ y = 0 := by simp [top_rpow_def, asymm h, ne_of_lt h] @[simp] lemma zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ℝ≥0∞) ^ y = 0 := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, asymm h, ne_of_gt h], end @[simp] lemma zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ℝ≥0∞) ^ y = ⊤ := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, ne_of_gt h], end lemma zero_rpow_def (y : ℝ) : (0 : ℝ≥0∞) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ := begin rcases lt_trichotomy 0 y with H|rfl|H, { simp [H, ne_of_gt, zero_rpow_of_pos, lt_irrefl] }, { simp [lt_irrefl] }, { simp [H, asymm H, ne_of_lt, zero_rpow_of_neg] } end @[simp] lemma zero_rpow_mul_self (y : ℝ) : (0 : ℝ≥0∞) ^ y * 0 ^ y = 0 ^ y := by { rw zero_rpow_def, split_ifs, exacts [zero_mul _, one_mul _, top_mul_top] } @[norm_cast] lemma coe_rpow_of_ne_zero {x : ℝ≥0} (h : x ≠ 0) (y : ℝ) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin rw [← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h] end @[norm_cast] lemma coe_rpow_of_nonneg (x : ℝ≥0) {y : ℝ} (h : 0 ≤ y) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin by_cases hx : x = 0, { rcases le_iff_eq_or_lt.1 h with H|H, { simp [hx, H.symm] }, { simp [hx, zero_rpow_of_pos H, nnreal.zero_rpow (ne_of_gt H)] } }, { exact coe_rpow_of_ne_zero hx _ } end lemma coe_rpow_def (x : ℝ≥0) (y : ℝ) : (x : ℝ≥0∞) ^ y = if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) := rfl @[simp] lemma rpow_one (x : ℝ≥0∞) : x ^ (1 : ℝ) = x := by cases x; dsimp only [(^), rpow]; simp [zero_lt_one, not_lt_of_le zero_le_one] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0∞) ^ x = 1 := by { rw [← coe_one, coe_rpow_of_ne_zero one_ne_zero], simp } @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = 0 ↔ (x = 0 ∧ 0 < y) ∨ (x = ⊤ ∧ y < 0) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end @[simp] lemma rpow_eq_top_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = ⊤ ↔ (x = 0 ∧ y < 0) ∨ (x = ⊤ ∧ 0 < y) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end lemma rpow_eq_top_iff_of_pos {x : ℝ≥0∞} {y : ℝ} (hy : 0 < y) : x ^ y = ⊤ ↔ x = ⊤ := by simp [rpow_eq_top_iff, hy, asymm hy] lemma rpow_eq_top_of_nonneg (x : ℝ≥0∞) {y : ℝ} (hy0 : 0 ≤ y) : x ^ y = ⊤ → x = ⊤ := begin rw ennreal.rpow_eq_top_iff, intro h, cases h, { exfalso, rw lt_iff_not_ge at h, exact h.right hy0, }, { exact h.left, }, end lemma rpow_ne_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y ≠ ⊤ := mt (ennreal.rpow_eq_top_of_nonneg x hy0) h lemma rpow_lt_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y < ⊤ := lt_top_iff_ne_top.mpr (ennreal.rpow_ne_top_of_nonneg hy0 h) lemma rpow_add {x : ℝ≥0∞} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y + z) = x ^ y * x ^ z := begin cases x, { exact (h'x rfl).elim }, have : x ≠ 0 := λ h, by simpa [h] using hx, simp [coe_rpow_of_ne_zero this, nnreal.rpow_add this] end lemma rpow_neg (x : ℝ≥0∞) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [top_rpow_of_pos, top_rpow_of_neg, H, neg_pos.mpr] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, zero_rpow_of_pos, zero_rpow_of_neg, H, neg_pos.mpr] }, { have A : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, ← coe_inv A, nnreal.rpow_neg] } } end lemma rpow_sub {x : ℝ≥0∞} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y - z) = x ^ y / x ^ z := by rw [sub_eq_add_neg, rpow_add _ _ hx h'x, rpow_neg, div_eq_mul_inv] lemma rpow_neg_one (x : ℝ≥0∞) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_mul (x : ℝ≥0∞) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [h, Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { have : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, coe_rpow_of_ne_zero this, nnreal.rpow_mul] } } end @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0∞) (n : ℕ) : x ^ (n : ℝ) = x ^ n := begin cases x, { cases n; simp [top_rpow_of_pos (nat.cast_add_one_pos _), top_pow (nat.succ_pos _)] }, { simp [coe_rpow_of_nonneg _ (nat.cast_nonneg n)] } end lemma mul_rpow_eq_ite (x y : ℝ≥0∞) (z : ℝ) : (x * y) ^ z = if (x = 0 ∧ y = ⊤ ∨ x = ⊤ ∧ y = 0) ∧ z < 0 then ⊤ else x ^ z * y ^ z := begin rcases eq_or_ne z 0 with rfl|hz, { simp }, replace hz := hz.lt_or_lt, wlog hxy : x ≤ y := le_total x y using [x y, y x] tactic.skip, { rcases eq_or_ne x 0 with rfl|hx0, { induction y using with_top.rec_top_coe; cases hz with hz hz; simp [*, hz.not_lt] }, rcases eq_or_ne y 0 with rfl|hy0, { exact (hx0 (bot_unique hxy)).elim }, induction x using with_top.rec_top_coe, { cases hz with hz hz; simp [hz, top_unique hxy] }, induction y using with_top.rec_top_coe, { cases hz with hz hz; simp * }, simp only [*, false_and, and_false, false_or, if_false], norm_cast at *, rw [coe_rpow_of_ne_zero (mul_ne_zero hx0 hy0), nnreal.mul_rpow] }, { convert this using 2; simp only [mul_comm, and_comm, or_comm] } end lemma mul_rpow_of_ne_top {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) (z : ℝ) : (x * y) ^ z = x^z * y^z := by simp [*, mul_rpow_eq_ite] @[norm_cast] lemma coe_mul_rpow (x y : ℝ≥0) (z : ℝ) : ((x : ℝ≥0∞) * y) ^ z = x^z * y^z := mul_rpow_of_ne_top coe_ne_top coe_ne_top z lemma mul_rpow_of_ne_zero {x y : ℝ≥0∞} (hx : x ≠ 0) (hy : y ≠ 0) (z : ℝ) : (x * y) ^ z = x ^ z * y ^ z := by simp [*, mul_rpow_eq_ite] lemma mul_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x * y) ^ z = x ^ z * y ^ z := by simp [hz.not_lt, mul_rpow_eq_ite] lemma inv_rpow (x : ℝ≥0∞) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ := begin rcases eq_or_ne y 0 with rfl|hy, { simp only [rpow_zero, inv_one] }, replace hy := hy.lt_or_lt, rcases eq_or_ne x 0 with rfl|h0, { cases hy; simp * }, rcases eq_or_ne x ⊤ with rfl|h_top, { cases hy; simp * }, apply eq_inv_of_mul_eq_one, rw [← mul_rpow_of_ne_zero (inv_ne_zero.2 h_top) h0, inv_mul_cancel h0 h_top, one_rpow] end lemma div_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x / y) ^ z = x ^ z / y ^ z := by rw [div_eq_mul_inv, mul_rpow_of_nonneg _ _ hz, inv_rpow, div_eq_mul_inv] lemma strict_mono_rpow_of_pos {z : ℝ} (h : 0 < z) : strict_mono (λ x : ℝ≥0∞, x ^ z) := begin intros x y hxy, lift x to ℝ≥0 using ne_top_of_lt hxy, rcases eq_or_ne y ∞ with rfl|hy, { simp only [top_rpow_of_pos h, coe_rpow_of_nonneg _ h.le, coe_lt_top] }, { lift y to ℝ≥0 using hy, simp only [coe_rpow_of_nonneg _ h.le, nnreal.rpow_lt_rpow (coe_lt_coe.1 hxy) h, coe_lt_coe] } end lemma monotone_rpow_of_nonneg {z : ℝ} (h : 0 ≤ z) : monotone (λ x : ℝ≥0∞, x ^ z) := h.eq_or_lt.elim (λ h0, h0 ▸ by simp only [rpow_zero, monotone_const]) (λ h0, (strict_mono_rpow_of_pos h0).monotone) lemma rpow_le_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := monotone_rpow_of_nonneg h₂ h₁ lemma rpow_lt_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := strict_mono_rpow_of_pos h₂ h₁ lemma rpow_le_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := (strict_mono_rpow_of_pos hz).le_iff_le lemma rpow_lt_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := (strict_mono_rpow_of_pos hz).lt_iff_lt lemma le_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ≤ y ^ (1 / z) ↔ x ^ z ≤ y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z hz.ne', rw [rpow_mul, ←one_div, @rpow_le_rpow_iff _ _ (1/z) (by simp [hz])], end lemma lt_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x < y ^ (1 / z) ↔ x ^ z < y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_lt_rpow_iff _ _ (1/z) (by simp [hz])], end lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0∞} {y z : ℝ} (hx : 1 < x) (hx' : x ≠ ⊤) (hyz : y < z) : x^y < x^z := begin lift x to ℝ≥0 using hx', rw [one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_rpow_of_exponent_lt hx hyz] end lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0∞} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, top_rpow_of_neg, top_rpow_of_pos, le_refl]; linarith }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_rpow_of_exponent_le hx hyz] } end lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0∞} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top), simp at hx0 hx1, simp [coe_rpow_of_ne_zero (ne_of_gt hx0), nnreal.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz] end lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0∞} {y z : ℝ} (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx1 coe_lt_top), by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, h, zero_rpow_of_neg, zero_rpow_of_pos, le_refl]; linarith }, { simp at hx1, simp [coe_rpow_of_ne_zero h, nnreal.rpow_le_rpow_of_exponent_ge (bot_lt_iff_ne_bot.mpr h) hx1 hyz] } end lemma rpow_le_self_of_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (h_one_le : 1 ≤ z) : x ^ z ≤ x := begin nth_rewrite 1 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_ge hx h_one_le, end lemma le_rpow_self_of_one_le {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (h_one_le : 1 ≤ z) : x ≤ x ^ z := begin nth_rewrite 0 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_le hx h_one_le, end lemma rpow_pos_of_nonneg {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hp_nonneg : 0 ≤ p) : 0 < x^p := begin by_cases hp_zero : p = 0, { simp [hp_zero, ennreal.zero_lt_one], }, { rw ←ne.def at hp_zero, have hp_pos := lt_of_le_of_ne hp_nonneg hp_zero.symm, rw ←zero_rpow_of_pos hp_pos, exact rpow_lt_rpow hx_pos hp_pos, }, end lemma rpow_pos {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hx_ne_top : x ≠ ⊤) : 0 < x^p := begin cases lt_or_le 0 p with hp_pos hp_nonpos, { exact rpow_pos_of_nonneg hx_pos (le_of_lt hp_pos), }, { rw [←neg_neg p, rpow_neg, inv_pos], exact rpow_ne_top_of_nonneg (by simp [hp_nonpos]) hx_ne_top, }, end lemma rpow_lt_one {x : ℝ≥0∞} {z : ℝ} (hx : x < 1) (hz : 0 < z) : x^z < 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx le_top), simp only [coe_lt_one_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.rpow_lt_one (zero_le x) hx hz], end lemma rpow_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx coe_lt_top), simp only [coe_le_one_iff] at hx, simp [coe_rpow_of_nonneg _ hz, nnreal.rpow_le_one hx hz], end lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_one_of_one_lt_of_neg hx hz] }, end lemma rpow_le_one_of_one_le_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : z < 0) : x^z ≤ 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_one_of_one_le_of_nonpos hx (le_of_lt hz)] }, end lemma one_lt_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_lt_rpow hx hz] } end lemma one_le_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : 0 < z) : 1 ≤ x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_le_rpow hx (le_of_lt hz)] }, end lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx2 le_top), simp only [coe_lt_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz], end lemma one_le_rpow_of_pos_of_le_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z < 0) : 1 ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx2 coe_lt_top), simp only [coe_le_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 (le_of_lt hz)], end lemma to_nnreal_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_nnreal) ^ z = (x ^ z).to_nnreal := begin rcases lt_trichotomy z 0 with H|H|H, { cases x, { simp [H, ne_of_lt] }, by_cases hx : x = 0, { simp [hx, H, ne_of_lt] }, { simp [coe_rpow_of_ne_zero hx] } }, { simp [H] }, { cases x, { simp [H, ne_of_gt] }, simp [coe_rpow_of_nonneg _ (le_of_lt H)] } end lemma to_real_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_real) ^ z = (x ^ z).to_real := by rw [ennreal.to_real, ennreal.to_real, ←nnreal.coe_rpow, ennreal.to_nnreal_rpow] lemma of_real_rpow_of_pos {x p : ℝ} (hx_pos : 0 < x) : ennreal.of_real x ^ p = ennreal.of_real (x ^ p) := begin simp_rw ennreal.of_real, rw [coe_rpow_of_ne_zero, coe_eq_coe, real.to_nnreal_rpow_of_nonneg hx_pos.le], simp [hx_pos], end lemma of_real_rpow_of_nonneg {x p : ℝ} (hx_nonneg : 0 ≤ x) (hp_nonneg : 0 ≤ p) : ennreal.of_real x ^ p = ennreal.of_real (x ^ p) := begin by_cases hp0 : p = 0, { simp [hp0], }, by_cases hx0 : x = 0, { rw ← ne.def at hp0, have hp_pos : 0 < p := lt_of_le_of_ne hp_nonneg hp0.symm, simp [hx0, hp_pos, hp_pos.ne.symm], }, rw ← ne.def at hx0, exact of_real_rpow_of_pos (hx_nonneg.lt_of_ne hx0.symm), end lemma rpow_left_injective {x : ℝ} (hx : x ≠ 0) : function.injective (λ y : ℝ≥0∞, y^x) := begin intros y z hyz, dsimp only at hyz, rw [←rpow_one y, ←rpow_one z, ←_root_.mul_inv_cancel hx, rpow_mul, rpow_mul, hyz], end lemma rpow_left_surjective {x : ℝ} (hx : x ≠ 0) : function.surjective (λ y : ℝ≥0∞, y^x) := λ y, ⟨y ^ x⁻¹, by simp_rw [←rpow_mul, _root_.inv_mul_cancel hx, rpow_one]⟩ lemma rpow_left_bijective {x : ℝ} (hx : x ≠ 0) : function.bijective (λ y : ℝ≥0∞, y^x) := ⟨rpow_left_injective hx, rpow_left_surjective hx⟩ lemma rpow_left_monotone_of_nonneg {x : ℝ} (hx : 0 ≤ x) : monotone (λ y : ℝ≥0∞, y^x) := λ y z hyz, rpow_le_rpow hyz hx lemma rpow_left_strict_mono_of_pos {x : ℝ} (hx : 0 < x) : strict_mono (λ y : ℝ≥0∞, y^x) := λ y z hyz, rpow_lt_rpow hyz hx theorem tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ (x : ℝ≥0∞), x ^ y) (𝓝 ⊤) (𝓝 ⊤) := begin rw tendsto_nhds_top_iff_nnreal, intros x, obtain ⟨c, _, hc⟩ := (at_top_basis_Ioi.tendsto_iff at_top_basis_Ioi).mp (nnreal.tendsto_rpow_at_top hy) x trivial, have hc' : set.Ioi (↑c) ∈ 𝓝 (⊤ : ℝ≥0∞) := Ioi_mem_nhds coe_lt_top, refine eventually_of_mem hc' _, intros a ha, by_cases ha' : a = ⊤, { simp [ha', hy] }, lift a to ℝ≥0 using ha', change ↑c < ↑a at ha, rw coe_rpow_of_nonneg _ hy.le, exact_mod_cast hc a (by exact_mod_cast ha), end private lemma continuous_at_rpow_const_of_pos {x : ℝ≥0∞} {y : ℝ} (h : 0 < y) : continuous_at (λ a : ennreal, a ^ y) x := begin by_cases hx : x = ⊤, { rw [hx, continuous_at], convert tendsto_rpow_at_top h, simp [h] }, lift x to ℝ≥0 using hx, rw continuous_at_coe_iff, convert continuous_coe.continuous_at.comp (nnreal.continuous_at_rpow_const (or.inr h.le)) using 1, ext1 x, simp [coe_rpow_of_nonneg _ h.le] end @[continuity] lemma continuous_rpow_const {y : ℝ} : continuous (λ a : ennreal, a ^ y) := begin apply continuous_iff_continuous_at.2 (λ x, _), rcases lt_trichotomy 0 y with hy|rfl|hy, { exact continuous_at_rpow_const_of_pos hy }, { simp, exact continuous_at_const }, { obtain ⟨z, hz⟩ : ∃ z, y = -z := ⟨-y, (neg_neg _).symm⟩, have z_pos : 0 < z, by simpa [hz] using hy, simp_rw [hz, rpow_neg], exact ennreal.continuous_inv.continuous_at.comp (continuous_at_rpow_const_of_pos z_pos) } end lemma tendsto_const_mul_rpow_nhds_zero_of_pos {c : ℝ≥0∞} (hc : c ≠ ∞) {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ≥0∞, c * x ^ y) (𝓝 0) (𝓝 0) := begin convert ennreal.tendsto.const_mul (ennreal.continuous_rpow_const.tendsto 0) _, { simp [hy] }, { exact or.inr hc } end end ennreal
3b706e6e366b0b0fe1c131c97defa610e1d38cd4
94e33a31faa76775069b071adea97e86e218a8ee
/src/ring_theory/noetherian.lean
a48ef2c51b355d8d409808f2fbb4370b1c42ae41
[ "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
37,585
lean
/- Copyright (c) 2018 Mario Carneiro, Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import group_theory.finiteness import data.multiset.finset_ops import algebra.algebra.tower import order.order_iso_nat import ring_theory.ideal.operations import order.compactly_generated import linear_algebra.linear_independent /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodules M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. (Note that we do not assume yet that our rings are commutative, so perhaps this should be called "left Noetherian". To avoid cumbersome names once we specialize to the commutative case, we don't make this explicit in the declaration names.) ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `submodule.fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] * [samuel1967] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators pointwise namespace submodule variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, S.finite ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ lemma fg_iff_add_submonoid_fg (P : submodule ℕ M) : P.fg ↔ P.to_add_submonoid.fg := ⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩, λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩⟩ lemma fg_iff_add_subgroup_fg {G : Type*} [add_comm_group G] (P : submodule ℤ G) : P.fg ↔ P.to_add_subgroup.fg := ⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩, λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩⟩ lemma fg_iff_exists_fin_generating_family {N : submodule R M} : N.fg ↔ ∃ (n : ℕ) (s : fin n → M), span R (range s) = N := begin rw fg_def, split, { rintros ⟨S, Sfin, hS⟩, obtain ⟨n, f, rfl⟩ := Sfin.fin_embedding, exact ⟨n, f, hS⟩, }, { rintros ⟨n, s, hs⟩, refine ⟨range s, finite_range s, hs⟩ }, end /-- **Nakayama's Lemma**. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, [Stacks 00DV](https://stacks.math.columbia.edu/tag/00DV) -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ lemma _root_.subalgebra.fg_bot_to_submodule {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] : (⊥ : subalgebra R A).to_submodule.fg := ⟨{1}, by simp [algebra.to_submodule_bot] ⟩ theorem fg_span {s : set M} (hs : s.finite) : fg (span R s) := ⟨hs.to_finset, by rw [hs.coe_to_finset]⟩ theorem fg_span_singleton (x : M) : fg (R ∙ x) := fg_span (finite_singleton x) theorem fg.sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ lemma fg_finset_sup {ι : Type*} (s : finset ι) (N : ι → submodule R M) (h : ∀ i ∈ s, (N i).fg) : (s.sup N).fg := finset.sup_induction fg_bot (λ a ha b hb, ha.sup hb) h lemma fg_bsupr {ι : Type*} (s : finset ι) (N : ι → submodule R M) (h : ∀ i ∈ s, (N i).fg) : (⨆ i ∈ s, N i).fg := by simpa only [finset.sup_eq_supr] using fg_finset_sup s N h lemma fg_supr {ι : Type*} [fintype ι] (N : ι → submodule R M) (h : ∀ i, (N i).fg) : (supr N).fg := by simpa using fg_bsupr finset.univ N (λ i hi, h i) variables {P : Type*} [add_comm_monoid P] [module R P] variables (f : M →ₗ[R] P) theorem fg.map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ variables {f} lemma fg_of_fg_map_injective (f : M →ₗ[R] P) (hf : function.injective f) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, hf h, submodule.map_injective_of_injective hf $ by { rw [f.map_span, finset.coe_preimage, set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht], rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩ lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := fg_of_fg_map_injective f (linear_map.ker_eq_bot.1 hf) hfn lemma fg_top (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg := ⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ h.map _, λ h, fg_of_fg_map_injective N.subtype subtype.val_injective $ by rwa [map_top, range_subtype]⟩ lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) : (⊤ : submodule R M).fg := e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ h.map _ theorem fg.prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ theorem fg_pi {ι : Type*} {M : ι → Type*} [fintype ι] [Π i, add_comm_monoid (M i)] [Π i, module R (M i)] {p : Π i, submodule R (M i)} (hsb : ∀ i, (p i).fg) : (submodule.pi set.univ p).fg := begin classical, simp_rw fg_def at hsb ⊢, choose t htf hts using hsb, refine ⟨ ⋃ i, (linear_map.single i : _ →ₗ[R] _) '' t i, set.finite_Union $ λ i, (htf i).image _, _⟩, simp_rw [span_Union, span_image, hts, submodule.supr_map_single], end /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_image_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_image_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end lemma fg_induction (R M : Type*) [semiring R] [add_comm_monoid M] [module R M] (P : submodule R M → Prop) (h₁ : ∀ x, P (submodule.span R {x})) (h₂ : ∀ M₁ M₂, P M₁ → P M₂ → P (M₁ ⊔ M₂)) (N : submodule R M) (hN : N.fg) : P N := begin classical, obtain ⟨s, rfl⟩ := hN, induction s using finset.induction, { rw [finset.coe_empty, submodule.span_empty, ← submodule.span_zero_singleton], apply h₁ }, { rw [finset.coe_insert, submodule.span_insert], apply h₂; apply_assumption } end /-- An ideal of `R` is finitely generated if it is the span of a finite subset of `R`. This is defeq to `submodule.fg`, but unfolds more nicely. -/ def _root_.ideal.fg (I : ideal R) : Prop := ∃ S : finset R, ideal.span ↑S = I /-- The image of a finitely generated ideal is finitely generated. This is the `ideal` version of `submodule.fg.map`. -/ lemma _root_.ideal.fg.map {R S : Type*} [semiring R] [semiring S] {I : ideal R} (h : I.fg) (f : R →+* S) : (I.map f).fg := begin classical, obtain ⟨s, hs⟩ := h, refine ⟨s.image f, _⟩, rw [finset.coe_image, ←ideal.map_span, hs], end /-- The kernel of the composition of two linear maps is finitely generated if both kernels are and the first morphism is surjective. -/ lemma fg_ker_comp {R M N P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] [add_comm_group P] [module R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf1 : f.ker.fg) (hf2 : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin rw linear_map.ker_comp, apply fg_of_fg_map_of_fg_inf_ker f, { rwa [submodule.map_comap_eq, linear_map.range_eq_top.2 hsur, top_inf_eq] }, { rwa [inf_of_le_right (show f.ker ≤ (comap f g.ker), from comap_mono bot_le)] } end lemma fg_restrict_scalars {R S M : Type*} [comm_semiring R] [semiring S] [algebra R S] [add_comm_group M] [module S M] [module R M] [is_scalar_tower R S M] (N : submodule S M) (hfin : N.fg) (h : function.surjective (algebra_map R S)) : (submodule.restrict_scalars R N).fg := begin obtain ⟨X, rfl⟩ := hfin, use X, exact submodule.span_eq_restrict_scalars R S M X h end lemma _root_.ideal.fg_ker_comp {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A] (f : R →+* S) (g : S →+* A) (hf : f.ker.fg) (hg : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin letI : algebra R S := ring_hom.to_algebra f, letI : algebra R A := ring_hom.to_algebra (g.comp f), letI : algebra S A := ring_hom.to_algebra g, letI : is_scalar_tower R S A := is_scalar_tower.of_algebra_map_eq (λ _, rfl), let f₁ := algebra.linear_map R S, let g₁ := (is_scalar_tower.to_alg_hom R S A).to_linear_map, exact fg_ker_comp f₁ g₁ hf (fg_restrict_scalars g.ker hg hsur) hsur end /-- Finitely generated submodules are precisely compact elements in the submodule lattice. -/ theorem fg_iff_compact (s : submodule R M) : s.fg ↔ complete_lattice.is_compact_element s := begin classical, -- Introduce shorthand for span of an element let sp : M → submodule R M := λ a, span R {a}, -- Trivial rewrite lemma; a small hack since simp (only) & rw can't accomplish this smoothly. have supr_rw : ∀ t : finset M, (⨆ x ∈ t, sp x) = (⨆ x ∈ (↑t : set M), sp x), from λ t, by refl, split, { rintro ⟨t, rfl⟩, rw [span_eq_supr_of_singleton_spans, ←supr_rw, ←(finset.sup_eq_supr t sp)], apply complete_lattice.finset_sup_compact_of_compact, exact λ n _, singleton_span_is_compact_element n, }, { intro h, -- s is the Sup of the spans of its elements. have sSup : s = Sup (sp '' ↑s), by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, eq_comm, span_eq], -- by h, s is then below (and equal to) the sup of the spans of finitely many elements. obtain ⟨u, ⟨huspan, husup⟩⟩ := h (sp '' ↑s) (le_of_eq sSup), have ssup : s = u.sup id, { suffices : u.sup id ≤ s, from le_antisymm husup this, rw [sSup, finset.sup_id_eq_Sup], exact Sup_le_Sup huspan, }, obtain ⟨t, ⟨hts, rfl⟩⟩ := finset.subset_image_iff.mp huspan, rw [finset.sup_finset_image, function.comp.left_id, finset.sup_eq_supr, supr_rw, ←span_eq_supr_of_singleton_spans, eq_comm] at ssup, exact ⟨t, ssup⟩, }, end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [semiring R] [add_comm_monoid M] [add_comm_monoid P] variables [module R M] [module R P] open is_noetherian include R /-- An R-module is Noetherian iff all its submodules are finitely-generated. -/ lemma is_noetherian_def : is_noetherian R M ↔ ∀ (s : submodule R M), s.fg := ⟨λ h, h.noetherian, is_noetherian.mk⟩ theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := begin refine ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, submodule.map_comap_eq_self this ▸ (hn _).map _, λ h, ⟨λ s, _⟩⟩, have f := (submodule.equiv_map_of_injective N.subtype subtype.val_injective s).symm, have h₁ := h (s.map N.subtype) (submodule.map_subtype_le N s), have h₂ : (⊤ : submodule R (s.map N.subtype)).map (↑f : _ →ₗ[R] s) = ⊤ := by simp, have h₃ := ((submodule.fg_top _).2 h₁).map (↑f : _ →ₗ[R] s), exact (submodule.fg_top _).1 (h₂ ▸ h₃), end theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N := is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _ lemma is_noetherian_of_le {s t : submodule R M} [ht : is_noetherian R t] (h : s ≤ t) : is_noetherian R s := is_noetherian_submodule.mpr (λ s' hs', is_noetherian_submodule.mp ht _ (le_trans hs' h)) variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from submodule.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ (noetherian _).map _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range lemma is_noetherian_top_iff : is_noetherian R (⊤ : submodule R M) ↔ is_noetherian R M := begin unfreezingI { split; assume h }, { exact is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) }, { exact is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl).symm }, end lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : function.injective f) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f hf).symm lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : function.injective f) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N end section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R lemma is_noetherian_of_ker_bot [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f $ linear_map.ker_eq_bot.mp hf).symm lemma fg_of_ker_bot [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_ker_bot f hf) N instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, submodule.map_comap_eq_self this ▸ (noetherian _).map _⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices on_finset : ∀ s : finset ι, is_noetherian R (Π i : s, M i), { let coe_e := equiv.subtype_univ_equiv finset.mem_univ, letI : is_noetherian R (Π i : finset.univ, M (coe_e i)) := on_finset finset.univ, exact is_noetherian_of_linear_equiv (linear_equiv.Pi_congr_left R M coe_e), }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ _ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), fconstructor, { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], } } end /-- A version of `is_noetherian_pi` for non-dependent functions. We need this instance because sometimes Lean fails to apply the dependent version in non-dependent settings (e.g., it fails to prove that `ι → ℝ` is finite dimensional over `ℝ`). -/ instance is_noetherian_pi' {R ι M : Type*} [ring R] [add_comm_group M] [module R M] [fintype ι] [is_noetherian R M] : is_noetherian R (ι → M) := is_noetherian_pi end open is_noetherian submodule function section universe w variables {R M P : Type*} {N : Type w} [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] [add_comm_monoid P] [module R P] theorem is_noetherian_iff_well_founded : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := begin rw (complete_lattice.well_founded_characterisations $ submodule R M).out 0 3, exact ⟨λ ⟨h⟩, λ k, (fg_iff_compact k).mp (h k), λ h, ⟨λ k, (fg_iff_compact k).mpr (h k)⟩⟩, end lemma is_noetherian_iff_fg_well_founded : is_noetherian R M ↔ well_founded ((>) : { N : submodule R M // N.fg } → { N : submodule R M // N.fg } → Prop) := begin let α := { N : submodule R M // N.fg }, split, { introI H, let f : α ↪o submodule R M := order_embedding.subtype _, exact order_embedding.well_founded f.dual (is_noetherian_iff_well_founded.mp H) }, { intro H, constructor, intro N, obtain ⟨⟨N₀, h₁⟩, e : N₀ ≤ N, h₂⟩ := well_founded.well_founded_iff_has_max'.mp H { N' : α | N'.1 ≤ N } ⟨⟨⊥, submodule.fg_bot⟩, bot_le⟩, convert h₁, refine (e.antisymm _).symm, by_contra h₃, obtain ⟨x, hx₁ : x ∈ N, hx₂ : x ∉ N₀⟩ := set.not_subset.mp h₃, apply hx₂, have := h₂ ⟨(R ∙ x) ⊔ N₀, _⟩ _ _, { injection this with eq, rw ← eq, exact (le_sup_left : (R ∙ x) ≤ (R ∙ x) ⊔ N₀) (submodule.mem_span_singleton_self _) }, { exact submodule.fg.sup ⟨{x}, by rw [finset.coe_singleton]⟩ h₁ }, { exact sup_le ((submodule.span_singleton_le_iff_mem _ _).mpr hx₁) e }, { show N₀ ≤ (R ∙ x) ⊔ N₀, from le_sup_right } } end variables (R M) lemma well_founded_submodule_gt (R M) [semiring R] [add_comm_monoid M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp variables {R M} /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- A module is Noetherian iff every increasing chain of submodules stabilizes. -/ theorem monotone_stabilizes_iff_noetherian : (∀ (f : ℕ →o submodule R M), ∃ n, ∀ m, n ≤ m → f n = f m) ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.monotone_chain_condition] /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma is_noetherian.induction [is_noetherian R M] {P : submodule R M → Prop} (hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I := well_founded.recursion (well_founded_submodule_gt R M) I hgt end section universe w variables {R M P : Type*} {N : Type w} [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] [add_comm_group P] [module R P] lemma finite_of_linear_independent [nontrivial R] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, (rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M)).elim' _), have f : ℕ ↪ s, from set.infinite.nat_embedding s hf, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, rfl⟩, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- If the first and final modules in a short exact sequence are noetherian, then the middle module is also noetherian. -/ theorem is_noetherian_of_range_eq_ker [is_noetherian R M] [is_noetherian R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf : function.injective f) (hg : function.surjective g) (h : f.range = g.ker) : is_noetherian R N := is_noetherian_iff_well_founded.2 $ well_founded_gt_exact_sequence (well_founded_submodule_gt R M) (well_founded_submodule_gt R P) f.range (submodule.map f) (submodule.comap f) (submodule.comap g) (submodule.map g) (submodule.gci_map_comap hf) (submodule.gi_map_comap hg) (by simp [submodule.map_comap_eq, inf_comm]) (by simp [submodule.comap_map_eq, h]) /-- For any endomorphism of a Noetherian module, there is some nontrivial iterate with disjoint kernel and range. -/ theorem is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot [I : is_noetherian R M] (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊓ (f ^ n).range = ⊥ := begin obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (f.iterate_ker.comp ⟨λ n, n+1, λ n m w, by linarith⟩), specialize w (2 * n + 1) (by linarith), dsimp at w, refine ⟨n+1, nat.succ_ne_zero _, _⟩, rw eq_bot_iff, rintros - ⟨h, ⟨y, rfl⟩⟩, rw [mem_bot, ←linear_map.mem_ker, w], erw linear_map.mem_ker at h ⊢, change ((f ^ (n + 1)) * (f ^ (n + 1))) y = 0 at h, rw ←pow_add at h, convert h using 3, linarith, end /-- Any surjective endomorphism of a Noetherian module is injective. -/ theorem is_noetherian.injective_of_surjective_endomorphism [is_noetherian R M] (f : M →ₗ[R] M) (s : surjective f) : injective f := begin obtain ⟨n, ne, w⟩ := is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot f, rw [linear_map.range_eq_top.mpr (linear_map.iterate_surjective s n), inf_top_eq, linear_map.ker_eq_bot] at w, exact linear_map.injective_of_iterate_injective ne w, end /-- Any surjective endomorphism of a Noetherian module is bijective. -/ theorem is_noetherian.bijective_of_surjective_endomorphism [is_noetherian R M] (f : M →ₗ[R] M) (s : surjective f) : bijective f := ⟨is_noetherian.injective_of_surjective_endomorphism f s, s⟩ /-- A sequence `f` of submodules of a noetherian module, with `f (n+1)` disjoint from the supremum of `f 0`, ..., `f n`, is eventually zero. -/ lemma is_noetherian.disjoint_partial_sups_eventually_bot [I : is_noetherian R M] (f : ℕ → submodule R M) (h : ∀ n, disjoint (partial_sups f n) (f (n+1))) : ∃ n : ℕ, ∀ m, n ≤ m → f m = ⊥ := begin -- A little off-by-one cleanup first: suffices t : ∃ n : ℕ, ∀ m, n ≤ m → f (m+1) = ⊥, { obtain ⟨n, w⟩ := t, use n+1, rintros (_|m) p, { cases p, }, { apply w, exact nat.succ_le_succ_iff.mp p }, }, obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (partial_sups f), exact ⟨n, λ m p, (h m).eq_bot_of_ge $ sup_eq_left.1 $ (w (m + 1) $ le_add_right p).symm.trans $ w m p⟩ end /-- If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial. -/ noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M] (f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} := begin apply nonempty.some, obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i) (f.tailings_disjoint_tailing i), specialize w n (le_refl n), apply nonempty.intro, refine (f.tailing_linear_equiv i n).symm ≪≫ₗ _, rw w, exact submodule.bot_equiv_punit, end end /-- A (semi)ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ class is_noetherian_ring (R) [semiring R] extends is_noetherian R R : Prop theorem is_noetherian_ring_iff {R} [semiring R] : is_noetherian_ring R ↔ is_noetherian R R := ⟨λ h, h.1, @is_noetherian_ring.mk _ _⟩ /-- A ring is Noetherian if and only if all its ideals are finitely-generated. -/ lemma is_noetherian_ring_iff_ideal_fg (R : Type*) [semiring R] : is_noetherian_ring R ↔ ∀ I : ideal R, I.fg := is_noetherian_ring_iff.trans is_noetherian_def @[priority 80] -- see Note [lower instance priority] instance is_noetherian_of_fintype (R M) [fintype M] [semiring R] [add_comm_monoid M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ /-- Modules over the trivial ring are Noetherian. -/ @[priority 100] -- see Note [lower instance priority] instance is_noetherian_of_subsingleton (R M) [subsingleton R] [semiring R] [add_comm_monoid M] [module R M] : is_noetherian R M := by haveI := module.subsingleton R M; exact is_noetherian_of_fintype R M @[priority 100] -- see Note [lower instance priority] instance ring.is_noetherian_of_subsingleton {R} [semiring R] [subsingleton R] : is_noetherian_ring R := ⟨⟩ theorem is_noetherian_of_submodule_of_noetherian (R M) [semiring R] [add_comm_monoid M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end instance submodule.quotient.is_noetherian {R} [ring R] {M} [add_comm_group M] [module R M] (N : submodule R M) [h : is_noetherian R M] : is_noetherian R (M ⧸ N) := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end /-- If `M / S / R` is a scalar tower, and `M / R` is Noetherian, then `M / S` is also noetherian. -/ theorem is_noetherian_of_tower (R) {S M} [semiring R] [semiring S] [add_comm_monoid M] [has_smul R S] [module S M] [module R M] [is_scalar_tower R S M] (h : is_noetherian R M) : is_noetherian S M := begin rw is_noetherian_iff_well_founded at h ⊢, refine (submodule.restrict_scalars_embedding R S M).dual.well_founded h end instance ideal.quotient.is_noetherian_ring {R : Type*} [comm_ring R] [h : is_noetherian_ring R] (I : ideal R) : is_noetherian_ring (R ⧸ I) := is_noetherian_ring_iff.mpr $ is_noetherian_of_tower R $ submodule.quotient.is_noetherian _ theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M := have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h, by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : A.finite) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [ring R] (S) [ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end instance is_noetherian_ring_range {R} [ring R] {S} [ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring f.range := is_noetherian_ring_of_surjective R f.range f.range_restrict f.range_restrict_surjective theorem is_noetherian_ring_of_ring_equiv (R) [ring R] {S} [ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule section map₂ variables {R M N P : Type*} variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] variables [module R M] [module R N] [module R P] theorem fg.map₂ (f : M →ₗ[R] N →ₗ[R] P) {p : submodule R M} {q : submodule R N} (hp : p.fg) (hq : q.fg) : (map₂ f p q).fg := let ⟨sm, hfm, hm⟩ := fg_def.1 hp, ⟨sn, hfn, hn⟩ := fg_def.1 hq in fg_def.2 ⟨set.image2 (λ m n, f m n) sm sn, hfm.image2 _ hfn, map₂_span_span R f sm sn ▸ hm ▸ hn ▸ rfl⟩ end map₂ section mul variables {R : Type*} {A : Type*} [comm_semiring R] [semiring A] [algebra R A] variables {M N : submodule R A} theorem fg.mul (hm : M.fg) (hn : N.fg) : (M * N).fg := hm.map₂ _ hn lemma fg.pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using h.mul ih) end mul end submodule
f8d8348abcff2023bcb8412e886f170a19619fed
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/coe5.lean
852fc631c6f7304ee17daa276dd4d64f8729cb36
[ "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
1,040
lean
import logic namespace setoid inductive setoid : Type := mk_setoid: Π (A : Type'), (A → A → Prop) → setoid set_option pp.universes true check setoid definition test : Type.{2} := setoid.{0} definition carrier (s : setoid) := setoid.rec (λ a eq, a) s definition eqv {s : setoid} : carrier s → carrier s → Prop := setoid.rec (λ a eqv, eqv) s infix `≈` := eqv attribute carrier [coercion] inductive morphism (s1 s2 : setoid) : Type := mk : Π (f : s1 → s2), (∀ x y, x ≈ y → f x ≈ f y) → morphism s1 s2 check morphism.mk check λ (s1 s2 : setoid), s1 check λ (s1 s2 : Type), s1 inductive morphism2 (s1 : setoid) (s2 : setoid) : Type := mk : Π (f : s1 → s2), (∀ x y, x ≈ y → f x ≈ f y) → morphism2 s1 s2 check morphism2 check morphism2.mk inductive my_struct : Type := mk_foo : Π (s1 s2 : setoid) (s3 s4 : setoid), morphism2 s1 s2 → morphism2 s3 s4 → my_struct check my_struct definition tst2 : Type.{4} := my_struct.{1 2 1 2} end setoid
b6093aad68a6f325e7fad4433b84614ec9531bdf
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Meta/Tactic/Subst.lean
c01da416d450b20275ca74bb712709cd4da09ee3
[ "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
10,335
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.MatchUtil import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.FVarSubst namespace Lean.Meta def substCore (mvarId : MVarId) (hFVarId : FVarId) (symm := false) (fvarSubst : FVarSubst := {}) (clearH := true) (tryToSkip := false) : MetaM (FVarSubst × MVarId) := mvarId.withContext do let tag ← mvarId.getTag mvarId.checkNotAssigned `subst let hFVarIdOriginal := hFVarId let hLocalDecl ← hFVarId.getDecl match (← matchEq? hLocalDecl.type) with | none => throwTacticEx `subst mvarId "argument must be an equality proof" | some (_, lhs, rhs) => do let a ← instantiateMVars <| if symm then rhs else lhs let b ← instantiateMVars <| if symm then lhs else rhs match a with | Expr.fvar aFVarId => do let aFVarIdOriginal := aFVarId trace[Meta.Tactic.subst] "substituting {a} (id: {aFVarId.name}) with {b}" if (← exprDependsOn b aFVarId) then throwTacticEx `subst mvarId m!"'{a}' occurs at{indentExpr b}" let (vars, mvarId) ← mvarId.revert #[aFVarId, hFVarId] true trace[Meta.Tactic.subst] "after revert {MessageData.ofGoal mvarId}" let (twoVars, mvarId) ← mvarId.introNP 2 trace[Meta.Tactic.subst] "after intro2 {MessageData.ofGoal mvarId}" trace[Meta.Tactic.subst] "reverted variables {vars.map (·.name)}" let aFVarId := twoVars[0]! let a := mkFVar aFVarId let hFVarId := twoVars[1]! let h := mkFVar hFVarId /- Set skip to true if there is no local variable nor the target depend on the equality -/ let skip ← if !tryToSkip || vars.size != 2 then pure false else let mvarType ← mvarId.getType if (← exprDependsOn mvarType aFVarId) then pure false else if (← exprDependsOn mvarType hFVarId) then pure false else pure true if skip then if clearH then let mvarId ← mvarId.clear hFVarId let mvarId ← mvarId.clear aFVarId pure ({}, mvarId) else pure ({}, mvarId) else mvarId.withContext do let mvarDecl ← mvarId.getDecl let type := mvarDecl.type let hLocalDecl ← hFVarId.getDecl match (← matchEq? hLocalDecl.type) with | none => unreachable! | some (_, lhs, rhs) => do let b ← instantiateMVars <| if symm then lhs else rhs let depElim ← exprDependsOn mvarDecl.type hFVarId let cont (motive : Expr) (newType : Expr) : MetaM (FVarSubst × MVarId) := do let major ← if symm then pure h else mkEqSymm h let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag let minor := newMVar let newVal ← if depElim then mkEqRec motive minor major else mkEqNDRec motive minor major mvarId.assign newVal let mvarId := newMVar.mvarId! let mvarId ← if clearH then let mvarId ← mvarId.clear hFVarId mvarId.clear aFVarId else pure mvarId let (newFVars, mvarId) ← mvarId.introNP (vars.size - 2) trace[Meta.Tactic.subst] "after intro rest {vars.size - 2} {MessageData.ofGoal mvarId}" let fvarSubst ← newFVars.size.foldM (init := fvarSubst) fun i (fvarSubst : FVarSubst) => let var := vars[i+2]! let newFVar := newFVars[i]! pure $ fvarSubst.insert var (mkFVar newFVar) let fvarSubst := fvarSubst.insert aFVarIdOriginal (if clearH then b else mkFVar aFVarId) let fvarSubst := fvarSubst.insert hFVarIdOriginal (mkFVar hFVarId) pure (fvarSubst, mvarId) if depElim then do let newType := type.replaceFVar a b let reflB ← mkEqRefl b let newType := newType.replaceFVar h reflB if symm then let motive ← mkLambdaFVars #[a, h] type cont motive newType else /- `type` depends on (h : a = b). So, we use the following trick to avoid a type incorrect motive. 1- Create a new local (hAux : b = a) 2- Create newType := type [hAux.symm / h] `newType` is type correct because `h` and `hAux.symm` are definitionally equal by proof irrelevance. 3- Create motive by abstracting `a` and `hAux` in `newType`. -/ let hAuxType ← mkEq b a let motive ← withLocalDeclD `_h hAuxType fun hAux => do let hAuxSymm ← mkEqSymm hAux /- replace h in type with hAuxSymm -/ let newType := type.replaceFVar h hAuxSymm mkLambdaFVars #[a, hAux] newType cont motive newType else let motive ← mkLambdaFVars #[a] type let newType := type.replaceFVar a b cont motive newType | _ => let eqMsg := if symm then "(t = x)" else "(x = t)" throwTacticEx `subst mvarId m!"invalid equality proof, it is not of the form {eqMsg}{indentExpr hLocalDecl.type}\nafter WHNF, variable expected, but obtained{indentExpr a}" /-- Given `h : HEq α a α b` in the given goal, produce a new goal where `h : Eq α a b`. If `h` is not of the give form, then just return `(h, mvarId)` -/ def heqToEq (mvarId : MVarId) (fvarId : FVarId) (tryToClear : Bool := true) : MetaM (FVarId × MVarId) := mvarId.withContext do let decl ← fvarId.getDecl let type ← whnf decl.type match type.heq? with | none => pure (fvarId, mvarId) | some (α, a, β, b) => if (← isDefEq α β) then let pr ← mkEqOfHEq (mkFVar fvarId) let eq ← mkEq a b let mut mvarId ← mvarId.assert decl.userName eq pr if tryToClear then mvarId ← mvarId.tryClear fvarId let (fvarId, mvarId') ← mvarId.intro1P return (fvarId, mvarId') else return (fvarId, mvarId) partial def subst (mvarId : MVarId) (h : FVarId) : MetaM MVarId := mvarId.withContext do let type ← h.getType match (← matchEq? type) with | some _ => substEq mvarId h | none => match (← matchHEq? type) with | some _ => let (h', mvarId') ← heqToEq mvarId h if mvarId == mvarId' then findEq mvarId h else subst mvarId' h' | none => findEq mvarId h where /-- Give `h : Eq α a b`, try to apply `substCore` -/ substEq (mvarId : MVarId) (h : FVarId) : MetaM MVarId := mvarId.withContext do let localDecl ← h.getDecl let some (_, lhs, rhs) ← matchEq? localDecl.type | unreachable! let substReduced (newType : Expr) (symm : Bool) : MetaM MVarId := do let mvarId ← mvarId.assert localDecl.userName newType (mkFVar h) let (hFVarId', mvarId) ← mvarId.intro1P let mvarId ← mvarId.clear h return (← substCore mvarId hFVarId' (symm := symm) (tryToSkip := true)).2 let rhs' ← whnf rhs if rhs'.isFVar then if rhs != rhs' then substReduced (← mkEq lhs rhs') true else return (← substCore mvarId h (symm := true) (tryToSkip := true)).2 else do let lhs' ← whnf lhs if lhs'.isFVar then if lhs != lhs' then substReduced (← mkEq lhs' rhs) false else return (← substCore mvarId h (symm := false) (tryToSkip := true)).2 else do throwTacticEx `subst mvarId m!"invalid equality proof, it is not of the form (x = t) or (t = x){indentExpr localDecl.type}" /-- Try to find an equation of the form `heq : h = rhs` or `heq : lhs = h` -/ findEq (mvarId : MVarId) (h : FVarId) : MetaM MVarId := mvarId.withContext do let localDecl ← h.getDecl if localDecl.isLet then throwTacticEx `subst mvarId m!"variable '{mkFVar h}' is a let-declaration" let lctx ← getLCtx let some (fvarId, symm) ← lctx.findDeclM? fun localDecl => do if localDecl.isAuxDecl then return none else match (← matchEq? localDecl.type) with | some (_, lhs, rhs) => let lhs ← instantiateMVars lhs let rhs ← instantiateMVars rhs if rhs.isFVar && rhs.fvarId! == h then if !(← exprDependsOn lhs h) then return some (localDecl.fvarId, true) if lhs.isFVar && lhs.fvarId! == h then if !(← exprDependsOn rhs h) then return some (localDecl.fvarId, false) return none | _ => return none | throwTacticEx `subst mvarId m!"did not find equation for eliminating '{mkFVar h}'" return (← substCore mvarId fvarId (symm := symm) (tryToSkip := true)).2 def subst? (mvarId : MVarId) (hFVarId : FVarId) : MetaM (Option MVarId) := observing? (subst mvarId hFVarId) def substCore? (mvarId : MVarId) (hFVarId : FVarId) (symm := false) (fvarSubst : FVarSubst := {}) (clearH := true) (tryToSkip := false) : MetaM (Option (FVarSubst × MVarId)) := observing? (substCore mvarId hFVarId symm fvarSubst clearH tryToSkip) def trySubst (mvarId : MVarId) (hFVarId : FVarId) : MetaM MVarId := do match (← subst? mvarId hFVarId) with | some mvarId => return mvarId | none => return mvarId def substSomeVar? (mvarId : MVarId) : MetaM (Option MVarId) := mvarId.withContext do for localDecl in (← getLCtx) do if let some mvarId ← subst? mvarId localDecl.fvarId then return some mvarId return none partial def substVars (mvarId : MVarId) : MetaM MVarId := do if let some mvarId ← substSomeVar? mvarId then substVars mvarId else return mvarId builtin_initialize registerTraceClass `Meta.Tactic.subst end Meta end Lean
bfc7874ceaf81f7fbb987d984be0ca0da0655d56
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/matrix/basic.lean
a0ecec1009ff68df5602e10a1f34bc0845047a4f
[ "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
63,435
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin, Lu-Ming Zhang -/ import algebra.algebra.basic import algebra.big_operators.pi import algebra.big_operators.ring import algebra.module.linear_map import algebra.module.pi import algebra.star.pi import data.equiv.ring import data.fintype.card /-! # Matrices This file defines basic properties of matrices. ## Notation The locale `matrix` gives the following notation: * `⬝ᵥ` for `matrix.dot_product` * `⬝` for `matrix.mul` * `ᵀ` for `matrix.transpose` * `ᴴ` for `matrix.conj_transpose` ## TODO Under various conditions, multiplication of infinite matrices makes sense. These have not yet been implemented. -/ universes u u' v w open_locale big_operators /-- `matrix m n` is the type of matrices whose rows are indexed by `m` and whose columns are indexed by `n`. -/ def matrix (m : Type u) (n : Type u') (α : Type v) : Type (max u u' v) := m → n → α variables {l m n o : Type*} {m' : o → Type*} {n' : o → Type*} variables {R : Type*} {S : Type*} {α : Type v} {β : Type w} {γ : Type*} namespace matrix section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[ext] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end ext /-- `M.map f` is the matrix obtained by applying `f` to each entry of the matrix `M`. This is available in bundled forms as: * `add_monoid_hom.map_matrix` * `linear_map.map_matrix` * `ring_hom.map_matrix` * `alg_hom.map_matrix` * `equiv.map_matrix` * `add_equiv.map_matrix` * `linear_equiv.map_matrix` * `ring_equiv.map_matrix` * `alg_equiv.map_matrix` -/ def map (M : matrix m n α) (f : α → β) : matrix m n β := λ i j, f (M i j) @[simp] lemma map_apply {M : matrix m n α} {f : α → β} {i : m} {j : n} : M.map f i j = f (M i j) := rfl @[simp] lemma map_id (M : matrix m n α) : M.map id = M := by { ext, refl, } @[simp] lemma map_map {M : matrix m n α} {β γ : Type*} {f : α → β} {g : β → γ} : (M.map f).map g = M.map (g ∘ f) := by { ext, refl, } /-- The transpose of a matrix. -/ def transpose (M : matrix m n α) : matrix n m α | x y := M y x localized "postfix `ᵀ`:1500 := matrix.transpose" in matrix /-- The conjugate transpose of a matrix defined in term of `star`. -/ def conj_transpose [has_star α] (M : matrix m n α) : matrix n m α := M.transpose.map star localized "postfix `ᴴ`:1500 := matrix.conj_transpose" in matrix /-- `matrix.col u` is the column matrix whose entries are given by `u`. -/ def col (w : m → α) : matrix m unit α | x y := w x /-- `matrix.row u` is the row matrix whose entries are given by `u`. -/ def row (v : n → α) : matrix unit n α | x y := v y instance [inhabited α] : inhabited (matrix m n α) := pi.inhabited _ instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_zero_class α] : add_zero_class (matrix m n α) := pi.add_zero_class instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [has_sub α] : has_sub (matrix m n α) := pi.has_sub instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group instance [unique α] : unique (matrix m n α) := pi.unique instance [subsingleton α] : subsingleton (matrix m n α) := pi.subsingleton instance [nonempty m] [nonempty n] [nontrivial α] : nontrivial (matrix m n α) := function.nontrivial instance [has_scalar R α] : has_scalar R (matrix m n α) := pi.has_scalar instance [has_scalar R α] [has_scalar S α] [smul_comm_class R S α] : smul_comm_class R S (matrix m n α) := pi.smul_comm_class instance [has_scalar R S] [has_scalar R α] [has_scalar S α] [is_scalar_tower R S α] : is_scalar_tower R S (matrix m n α) := pi.is_scalar_tower instance [has_scalar R α] [has_scalar Rᵐᵒᵖ α] [is_central_scalar R α] : is_central_scalar R (matrix m n α) := pi.is_central_scalar instance [monoid R] [mul_action R α] : mul_action R (matrix m n α) := pi.mul_action _ instance [monoid R] [add_monoid α] [distrib_mul_action R α] : distrib_mul_action R (matrix m n α) := pi.distrib_mul_action _ instance [semiring R] [add_comm_monoid α] [module R α] : module R (matrix m n α) := pi.module _ _ _ @[simp] lemma map_zero [has_zero α] [has_zero β] (f : α → β) (h : f 0 = 0) : (0 : matrix m n α).map f = 0 := by { ext, simp [h], } lemma map_add [has_add α] [has_add β] (f : α → β) (hf : ∀ a₁ a₂, f (a₁ + a₂) = f a₁ + f a₂) (M N : matrix m n α) : (M + N).map f = M.map f + N.map f := ext $ λ _ _, hf _ _ lemma map_sub [has_sub α] [has_sub β] (f : α → β) (hf : ∀ a₁ a₂, f (a₁ - a₂) = f a₁ - f a₂) (M N : matrix m n α) : (M - N).map f = M.map f - N.map f := ext $ λ _ _, hf _ _ lemma map_smul [has_scalar R α] [has_scalar R β] (f : α → β) (r : R) (hf : ∀ a, f (r • a) = r • f a) (M : matrix m n α) : (r • M).map f = r • (M.map f) := ext $ λ _ _, hf _ lemma _root_.is_smul_regular.matrix [has_scalar R S] {k : R} (hk : is_smul_regular S k) : is_smul_regular (matrix m n S) k := is_smul_regular.pi $ λ _, is_smul_regular.pi $ λ _, hk lemma _root_.is_left_regular.matrix [has_mul α] {k : α} (hk : is_left_regular k) : is_smul_regular (matrix m n α) k := hk.is_smul_regular.matrix -- TODO[gh-6025]: make this an instance once safe to do so lemma subsingleton_of_empty_left [is_empty m] : subsingleton (matrix m n α) := ⟨λ M N, by { ext, exact is_empty_elim i }⟩ -- TODO[gh-6025]: make this an instance once safe to do so lemma subsingleton_of_empty_right [is_empty n] : subsingleton (matrix m n α) := ⟨λ M N, by { ext, exact is_empty_elim j }⟩ end matrix open_locale matrix namespace matrix section diagonal variables [decidable_eq n] /-- `diagonal d` is the square matrix such that `(diagonal d) i i = d i` and `(diagonal d) i j = 0` if `i ≠ j`. Note that bundled versions exist as: * `matrix.diagonal_add_monoid_hom` * `matrix.diagonal_linear_map` * `matrix.diagonal_ring_hom` * `matrix.diagonal_alg_hom` -/ def diagonal [has_zero α] (d : n → α) : matrix n n α | i j := if i = j then d i else 0 @[simp] theorem diagonal_apply_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_apply_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_apply_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_apply_ne h.symm lemma diagonal_injective [has_zero α] : function.injective (diagonal : (n → α) → matrix n n α) := λ d₁ d₂ h, funext $ λ i, by simpa using matrix.ext_iff.mpr h i i @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by { ext, simp [diagonal] } @[simp] lemma diagonal_transpose [has_zero α] (v : n → α) : (diagonal v)ᵀ = diagonal v := begin ext i j, by_cases h : i = j, { simp [h, transpose] }, { simp [h, transpose, diagonal_apply_ne' h] } end @[simp] theorem diagonal_add [add_zero_class α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases h : i = j; simp [h] @[simp] theorem diagonal_smul [monoid R] [add_monoid α] [distrib_mul_action R α] (r : R) (d : n → α) : diagonal (r • d) = r • diagonal d := by ext i j; by_cases h : i = j; simp [h] variables (n α) /-- `matrix.diagonal` as an `add_monoid_hom`. -/ @[simps] def diagonal_add_monoid_hom [add_zero_class α] : (n → α) →+ matrix n n α := { to_fun := diagonal, map_zero' := diagonal_zero, map_add' := λ x y, (diagonal_add x y).symm,} variables (R) /-- `matrix.diagonal` as a `linear_map`. -/ @[simps] def diagonal_linear_map [semiring R] [add_comm_monoid α] [module R α] : (n → α) →ₗ[R] matrix n n α := { map_smul' := diagonal_smul, .. diagonal_add_monoid_hom n α,} variables {n α R} @[simp] lemma diagonal_map [has_zero α] [has_zero β] {f : α → β} (h : f 0 = 0) {d : n → α} : (diagonal d).map f = diagonal (λ m, f (d m)) := by { ext, simp only [diagonal, map_apply], split_ifs; simp [h], } @[simp] lemma diagonal_conj_transpose [semiring α] [star_ring α] (v : n → α) : (diagonal v)ᴴ = diagonal (star v) := begin rw [conj_transpose, diagonal_transpose, diagonal_map (star_zero _)], refl, end section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_apply {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_apply_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_apply_eq i @[simp] theorem one_apply_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_apply_ne theorem one_apply_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_apply_ne' @[simp] lemma map_one [has_zero β] [has_one β] (f : α → β) (h₀ : f 0 = 0) (h₁ : f 1 = 1) : (1 : matrix n n α).map f = (1 : matrix n n β) := by { ext, simp only [one_apply, map_apply], split_ifs; simp [h₀, h₁], } lemma one_eq_pi_single {i j} : (1 : matrix n n α) i j = pi.single i 1 j := by simp only [one_apply, pi.single_apply, eq_comm]; congr -- deal with decidable_eq end one section numeral @[simp] lemma bit0_apply [has_add α] (M : matrix m m α) (i : m) (j : m) : (bit0 M) i j = bit0 (M i j) := rfl variables [add_monoid α] [has_one α] lemma bit1_apply (M : matrix n n α) (i : n) (j : n) : (bit1 M) i j = if i = j then bit1 (M i j) else bit0 (M i j) := by dsimp [bit1]; by_cases h : i = j; simp [h] @[simp] lemma bit1_apply_eq (M : matrix n n α) (i : n) : (bit1 M) i i = bit1 (M i i) := by simp [bit1_apply] @[simp] lemma bit1_apply_ne (M : matrix n n α) {i j : n} (h : i ≠ j) : (bit1 M) i j = bit0 (M i j) := by simp [bit1_apply, h] end numeral end diagonal section dot_product variable [fintype m] /-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/ def dot_product [has_mul α] [add_comm_monoid α] (v w : m → α) : α := ∑ i, v i * w i /- The precedence of 72 comes immediately after ` • ` for `has_scalar.smul`, so that `r₁ • a ⬝ᵥ r₂ • b` is parsed as `(r₁ • a) ⬝ᵥ (r₂ • b)` here. -/ localized "infix ` ⬝ᵥ `:72 := matrix.dot_product" in matrix lemma dot_product_assoc [fintype n] [non_unital_semiring α] (u : m → α) (w : n → α) (v : matrix m n α) : (λ j, u ⬝ᵥ (λ i, v i j)) ⬝ᵥ w = u ⬝ᵥ (λ i, (v i) ⬝ᵥ w) := by simpa [dot_product, finset.mul_sum, finset.sum_mul, mul_assoc] using finset.sum_comm lemma dot_product_comm [comm_semiring α] (v w : m → α) : v ⬝ᵥ w = w ⬝ᵥ v := by simp_rw [dot_product, mul_comm] @[simp] lemma dot_product_punit [add_comm_monoid α] [has_mul α] (v w : punit → α) : v ⬝ᵥ w = v ⟨⟩ * w ⟨⟩ := by simp [dot_product] section non_unital_non_assoc_semiring variables [non_unital_non_assoc_semiring α] (u v w : m → α) @[simp] lemma dot_product_zero : v ⬝ᵥ 0 = 0 := by simp [dot_product] @[simp] lemma dot_product_zero' : v ⬝ᵥ (λ _, 0) = 0 := dot_product_zero v @[simp] lemma zero_dot_product : 0 ⬝ᵥ v = 0 := by simp [dot_product] @[simp] lemma zero_dot_product' : (λ _, (0 : α)) ⬝ᵥ v = 0 := zero_dot_product v @[simp] lemma add_dot_product : (u + v) ⬝ᵥ w = u ⬝ᵥ w + v ⬝ᵥ w := by simp [dot_product, add_mul, finset.sum_add_distrib] @[simp] lemma dot_product_add : u ⬝ᵥ (v + w) = u ⬝ᵥ v + u ⬝ᵥ w := by simp [dot_product, mul_add, finset.sum_add_distrib] end non_unital_non_assoc_semiring section non_unital_non_assoc_semiring_decidable variables [decidable_eq m] [non_unital_non_assoc_semiring α] (u v w : m → α) @[simp] lemma diagonal_dot_product (i : m) : diagonal v i ⬝ᵥ w = v i * w i := have ∀ j ≠ i, diagonal v i j * w j = 0 := λ j hij, by simp [diagonal_apply_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma dot_product_diagonal (i : m) : v ⬝ᵥ diagonal w i = v i * w i := have ∀ j ≠ i, v j * diagonal w i j = 0 := λ j hij, by simp [diagonal_apply_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma dot_product_diagonal' (i : m) : v ⬝ᵥ (λ j, diagonal w j i) = v i * w i := have ∀ j ≠ i, v j * diagonal w j i = 0 := λ j hij, by simp [diagonal_apply_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma single_dot_product (x : α) (i : m) : pi.single i x ⬝ᵥ v = x * v i := have ∀ j ≠ i, pi.single i x j * v j = 0 := λ j hij, by simp [pi.single_eq_of_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma dot_product_single (x : α) (i : m) : v ⬝ᵥ pi.single i x = v i * x := have ∀ j ≠ i, v j * pi.single i x j = 0 := λ j hij, by simp [pi.single_eq_of_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp end non_unital_non_assoc_semiring_decidable section ring variables [ring α] (u v w : m → α) @[simp] lemma neg_dot_product : -v ⬝ᵥ w = - (v ⬝ᵥ w) := by simp [dot_product] @[simp] lemma dot_product_neg : v ⬝ᵥ -w = - (v ⬝ᵥ w) := by simp [dot_product] @[simp] lemma sub_dot_product : (u - v) ⬝ᵥ w = u ⬝ᵥ w - v ⬝ᵥ w := by simp [sub_eq_add_neg] @[simp] lemma dot_product_sub : u ⬝ᵥ (v - w) = u ⬝ᵥ v - u ⬝ᵥ w := by simp [sub_eq_add_neg] end ring section distrib_mul_action variables [monoid R] [has_mul α] [add_comm_monoid α] [distrib_mul_action R α] @[simp] lemma smul_dot_product [is_scalar_tower R α α] (x : R) (v w : m → α) : (x • v) ⬝ᵥ w = x • (v ⬝ᵥ w) := by simp [dot_product, finset.smul_sum, smul_mul_assoc] @[simp] lemma dot_product_smul [smul_comm_class R α α] (x : R) (v w : m → α) : v ⬝ᵥ (x • w) = x • (v ⬝ᵥ w) := by simp [dot_product, finset.smul_sum, mul_smul_comm] end distrib_mul_action section star_ring variables [semiring α] [star_ring α] (v w : m → α) lemma star_dot_product_star : star v ⬝ᵥ star w = star (w ⬝ᵥ v) := by simp [dot_product] lemma star_dot_product : star v ⬝ᵥ w = star (star w ⬝ᵥ v) := by simp [dot_product] lemma dot_product_star : v ⬝ᵥ star w = star (w ⬝ᵥ star v) := by simp [dot_product] end star_ring end dot_product open_locale matrix /-- `M ⬝ N` is the usual product of matrices `M` and `N`, i.e. we have that `(M ⬝ N) i k` is the dot product of the `i`-th row of `M` by the `k`-th column of `N`. This is currently only defined when `m` is finite. -/ protected def mul [fintype m] [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, (λ j, M i j) ⬝ᵥ (λ j, N j k) localized "infixl ` ⬝ `:75 := matrix.mul" in matrix theorem mul_apply [fintype m] [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = ∑ j, M i j * N j k := rfl instance [fintype n] [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [fintype n] [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_apply' [fintype m] [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = (λ j, M i j) ⬝ᵥ (λ j, N j k) := rfl @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := ((diagonal_add_monoid_hom n α).map_neg d).symm lemma sum_apply [add_comm_monoid α] (i : m) (j : n) (s : finset β) (g : β → matrix m n α) : (∑ c in s, g c) i j = ∑ c in s, g c i j := (congr_fun (s.sum_apply i g) j).trans (s.sum_apply j _) section non_unital_non_assoc_semiring variables [non_unital_non_assoc_semiring α] @[simp] protected theorem mul_zero [fintype n] (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by { ext i j, apply dot_product_zero } @[simp] protected theorem zero_mul [fintype m] (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by { ext i j, apply zero_dot_product } protected theorem mul_add [fintype n] (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by { ext i j, apply dot_product_add } protected theorem add_mul [fintype m] (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by { ext i j, apply add_dot_product } instance [fintype n] : non_unital_non_assoc_semiring (matrix n n α) := { mul := (*), add := (+), zero := 0, mul_zero := matrix.mul_zero, zero_mul := matrix.zero_mul, left_distrib := matrix.mul_add, right_distrib := matrix.add_mul, .. matrix.add_comm_monoid} @[simp] theorem diagonal_mul [fintype m] [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := diagonal_dot_product _ _ _ @[simp] theorem mul_diagonal [fintype n] [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by { rw ← diagonal_transpose, apply dot_product_diagonal } @[simp] theorem diagonal_mul_diagonal [fintype n] [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal' [fintype n] [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal _ _ /-- Left multiplication by a matrix, as an `add_monoid_hom` from matrices to matrices. -/ @[simps] def add_monoid_hom_mul_left [fintype m] (M : matrix l m α) : matrix m n α →+ matrix l n α := { to_fun := λ x, M ⬝ x, map_zero' := matrix.mul_zero _, map_add' := matrix.mul_add _ } /-- Right multiplication by a matrix, as an `add_monoid_hom` from matrices to matrices. -/ @[simps] def add_monoid_hom_mul_right [fintype m] (M : matrix m n α) : matrix l m α →+ matrix l n α := { to_fun := λ x, x ⬝ M, map_zero' := matrix.zero_mul _, map_add' := λ _ _, matrix.add_mul _ _ _ } protected lemma sum_mul [fintype m] (s : finset β) (f : β → matrix l m α) (M : matrix m n α) : (∑ a in s, f a) ⬝ M = ∑ a in s, f a ⬝ M := (add_monoid_hom_mul_right M : matrix l m α →+ _).map_sum f s protected lemma mul_sum [fintype m] (s : finset β) (f : β → matrix m n α) (M : matrix l m α) : M ⬝ ∑ a in s, f a = ∑ a in s, M ⬝ f a := (add_monoid_hom_mul_left M : matrix m n α →+ _).map_sum f s end non_unital_non_assoc_semiring section non_assoc_semiring variables [non_assoc_semiring α] @[simp] protected theorem one_mul [fintype m] [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [fintype n] [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [fintype n] [decidable_eq n] : non_assoc_semiring (matrix n n α) := { one := 1, one_mul := matrix.one_mul, mul_one := matrix.mul_one, .. matrix.non_unital_non_assoc_semiring } @[simp] lemma map_mul [fintype n] {L : matrix m n α} {M : matrix n o α} [non_assoc_semiring β] {f : α →+* β} : (L ⬝ M).map f = L.map f ⬝ M.map f := by { ext, simp [mul_apply, ring_hom.map_sum], } variables (α n) /-- `matrix.diagonal` as a `ring_hom`. -/ @[simps] def diagonal_ring_hom [fintype n] [decidable_eq n] : (n → α) →+* matrix n n α := { to_fun := diagonal, map_one' := diagonal_one, map_mul' := λ _ _, (diagonal_mul_diagonal' _ _).symm, .. diagonal_add_monoid_hom n α } end non_assoc_semiring section non_unital_semiring variables [non_unital_semiring α] [fintype m] [fintype n] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by { ext, apply dot_product_assoc } instance : non_unital_semiring (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.non_unital_non_assoc_semiring } end non_unital_semiring section semiring variables [semiring α] instance [fintype n] [decidable_eq n] : semiring (matrix n n α) := { ..matrix.non_unital_semiring, ..matrix.non_assoc_semiring } end semiring section ring variables [ring α] [fintype n] @[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by { ext, apply neg_dot_product } @[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by { ext, apply dot_product_neg } protected theorem sub_mul (M M' : matrix m n α) (N : matrix n o α) : (M - M') ⬝ N = M ⬝ N - M' ⬝ N := by rw [sub_eq_add_neg, matrix.add_mul, neg_mul, sub_eq_add_neg] protected theorem mul_sub (M : matrix m n α) (N N' : matrix n o α) : M ⬝ (N - N') = M ⬝ N - M ⬝ N' := by rw [sub_eq_add_neg, matrix.mul_add, mul_neg, sub_eq_add_neg] end ring instance [fintype n] [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.semiring, ..matrix.add_comm_group } section semiring variables [semiring α] lemma smul_eq_diagonal_mul [fintype m] [decidable_eq m] (M : matrix m n α) (a : α) : a • M = diagonal (λ _, a) ⬝ M := by { ext, simp } @[simp] lemma smul_mul [fintype n] [monoid R] [distrib_mul_action R α] [is_scalar_tower R α α] (a : R) (M : matrix m n α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := by { ext, apply smul_dot_product } /-- This instance enables use with `smul_mul_assoc`. -/ instance semiring.is_scalar_tower [fintype n] [monoid R] [distrib_mul_action R α] [is_scalar_tower R α α] : is_scalar_tower R (matrix n n α) (matrix n n α) := ⟨λ r m n, matrix.smul_mul r m n⟩ @[simp] lemma mul_smul [fintype n] [monoid R] [distrib_mul_action R α] [smul_comm_class R α α] (M : matrix m n α) (a : R) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := by { ext, apply dot_product_smul } /-- This instance enables use with `mul_smul_comm`. -/ instance semiring.smul_comm_class [fintype n] [monoid R] [distrib_mul_action R α] [smul_comm_class R α α] : smul_comm_class R (matrix n n α) (matrix n n α) := ⟨λ r m n, (matrix.mul_smul m r n).symm⟩ @[simp] lemma mul_mul_left [fintype n] (M : matrix m n α) (N : matrix n o α) (a : α) : (λ i j, a * M i j) ⬝ N = a • (M ⬝ N) := smul_mul a M N /-- The ring homomorphism `α →+* matrix n n α` sending `a` to the diagonal matrix with `a` on the diagonal. -/ def scalar (n : Type u) [decidable_eq n] [fintype n] : α →+* matrix n n α := { to_fun := λ a, a • 1, map_one' := by simp, map_mul' := by { intros, ext, simp [mul_assoc], }, .. (smul_add_hom α _).flip (1 : matrix n n α) } section scalar variables [decidable_eq n] [fintype n] @[simp] lemma coe_scalar : (scalar n : α → matrix n n α) = λ a, a • 1 := rfl lemma scalar_apply_eq (a : α) (i : n) : scalar n a i i = a := by simp only [coe_scalar, smul_eq_mul, mul_one, one_apply_eq, pi.smul_apply] lemma scalar_apply_ne (a : α) (i j : n) (h : i ≠ j) : scalar n a i j = 0 := by simp only [h, coe_scalar, one_apply_ne, ne.def, not_false_iff, pi.smul_apply, smul_zero] lemma scalar_inj [nonempty n] {r s : α} : scalar n r = scalar n s ↔ r = s := begin split, { intro h, inhabit n, rw [← scalar_apply_eq r (arbitrary n), ← scalar_apply_eq s (arbitrary n), h] }, { rintro rfl, refl } end end scalar end semiring section comm_semiring variables [comm_semiring α] [fintype n] lemma smul_eq_mul_diagonal [decidable_eq n] (M : matrix m n α) (a : α) : a • M = M ⬝ diagonal (λ _, a) := by { ext, simp [mul_comm] } @[simp] lemma mul_mul_right (M : matrix m n α) (N : matrix n o α) (a : α) : M ⬝ (λ i j, a * N i j) = a • (M ⬝ N) := mul_smul M a N lemma scalar.commute [decidable_eq n] (r : α) (M : matrix n n α) : commute (scalar n r) M := by simp [commute, semiconj_by] end comm_semiring section algebra variables [fintype n] [decidable_eq n] variables [comm_semiring R] [semiring α] [semiring β] [algebra R α] [algebra R β] instance : algebra R (matrix n n α) := { commutes' := λ r x, begin ext, simp [matrix.scalar, matrix.mul_apply, matrix.one_apply, algebra.commutes, smul_ite], end, smul_def' := λ r x, begin ext, simp [matrix.scalar, algebra.smul_def r], end, ..((matrix.scalar n).comp (algebra_map R α)) } lemma algebra_map_matrix_apply {r : R} {i j : n} : algebra_map R (matrix n n α) r i j = if i = j then algebra_map R α r else 0 := begin dsimp [algebra_map, algebra.to_ring_hom, matrix.scalar], split_ifs with h; simp [h, matrix.one_apply_ne], end lemma algebra_map_eq_diagonal (r : R) : algebra_map R (matrix n n α) r = diagonal (algebra_map R (n → α) r) := matrix.ext $ λ i j, algebra_map_matrix_apply @[simp] lemma algebra_map_eq_smul (r : R) : algebra_map R (matrix n n R) r = r • (1 : matrix n n R) := rfl lemma algebra_map_eq_diagonal_ring_hom : algebra_map R (matrix n n α) = (diagonal_ring_hom n α).comp (algebra_map R _) := ring_hom.ext algebra_map_eq_diagonal @[simp] lemma map_algebra_map (r : R) (f : α → β) (hf : f 0 = 0) (hf₂ : f (algebra_map R α r) = algebra_map R β r) : (algebra_map R (matrix n n α) r).map f = algebra_map R (matrix n n β) r := begin rw [algebra_map_eq_diagonal, algebra_map_eq_diagonal, diagonal_map hf], congr' 1 with x, simp only [hf₂, pi.algebra_map_apply] end variables (R) /-- `matrix.diagonal` as an `alg_hom`. -/ @[simps] def diagonal_alg_hom : (n → α) →ₐ[R] matrix n n α := { to_fun := diagonal, commutes' := λ r, (algebra_map_eq_diagonal r).symm, .. diagonal_ring_hom n α } end algebra end matrix /-! ### Bundled versions of `matrix.map` -/ namespace equiv /-- The `equiv` between spaces of matrices induced by an `equiv` between their coefficients. This is `matrix.map` as an `equiv`. -/ @[simps apply] def map_matrix (f : α ≃ β) : matrix m n α ≃ matrix m n β := { to_fun := λ M, M.map f, inv_fun := λ M, M.map f.symm, left_inv := λ M, matrix.ext $ λ _ _, f.symm_apply_apply _, right_inv := λ M, matrix.ext $ λ _ _, f.apply_symm_apply _, } @[simp] lemma map_matrix_refl : (equiv.refl α).map_matrix = equiv.refl (matrix m n α) := rfl @[simp] lemma map_matrix_symm (f : α ≃ β) : f.map_matrix.symm = (f.symm.map_matrix : matrix m n β ≃ _) := rfl @[simp] lemma map_matrix_trans (f : α ≃ β) (g : β ≃ γ) : f.map_matrix.trans g.map_matrix = ((f.trans g).map_matrix : matrix m n α ≃ _) := rfl end equiv namespace add_monoid_hom variables [add_zero_class α] [add_zero_class β] [add_zero_class γ] /-- The `add_monoid_hom` between spaces of matrices induced by an `add_monoid_hom` between their coefficients. This is `matrix.map` as an `add_monoid_hom`. -/ @[simps] def map_matrix (f : α →+ β) : matrix m n α →+ matrix m n β := { to_fun := λ M, M.map f, map_zero' := matrix.map_zero f f.map_zero, map_add' := matrix.map_add f f.map_add } @[simp] lemma map_matrix_id : (add_monoid_hom.id α).map_matrix = add_monoid_hom.id (matrix m n α) := rfl @[simp] lemma map_matrix_comp (f : β →+ γ) (g : α →+ β) : f.map_matrix.comp g.map_matrix = ((f.comp g).map_matrix : matrix m n α →+ _) := rfl end add_monoid_hom namespace add_equiv variables [has_add α] [has_add β] [has_add γ] /-- The `add_equiv` between spaces of matrices induced by an `add_equiv` between their coefficients. This is `matrix.map` as an `add_equiv`. -/ @[simps apply] def map_matrix (f : α ≃+ β) : matrix m n α ≃+ matrix m n β := { to_fun := λ M, M.map f, inv_fun := λ M, M.map f.symm, map_add' := matrix.map_add f f.map_add, .. f.to_equiv.map_matrix } @[simp] lemma map_matrix_refl : (add_equiv.refl α).map_matrix = add_equiv.refl (matrix m n α) := rfl @[simp] lemma map_matrix_symm (f : α ≃+ β) : f.map_matrix.symm = (f.symm.map_matrix : matrix m n β ≃+ _) := rfl @[simp] lemma map_matrix_trans (f : α ≃+ β) (g : β ≃+ γ) : f.map_matrix.trans g.map_matrix = ((f.trans g).map_matrix : matrix m n α ≃+ _) := rfl end add_equiv namespace linear_map variables [semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] variables [module R α] [module R β] [module R γ] /-- The `linear_map` between spaces of matrices induced by a `linear_map` between their coefficients. This is `matrix.map` as a `linear_map`. -/ @[simps] def map_matrix (f : α →ₗ[R] β) : matrix m n α →ₗ[R] matrix m n β := { to_fun := λ M, M.map f, map_add' := matrix.map_add f f.map_add, map_smul' := λ r, matrix.map_smul f r (f.map_smul r), } @[simp] lemma map_matrix_id : linear_map.id.map_matrix = (linear_map.id : matrix m n α →ₗ[R] _) := rfl @[simp] lemma map_matrix_comp (f : β →ₗ[R] γ) (g : α →ₗ[R] β) : f.map_matrix.comp g.map_matrix = ((f.comp g).map_matrix : matrix m n α →ₗ[R] _) := rfl end linear_map namespace linear_equiv variables [semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] variables [module R α] [module R β] [module R γ] /-- The `linear_equiv` between spaces of matrices induced by an `linear_equiv` between their coefficients. This is `matrix.map` as an `linear_equiv`. -/ @[simps apply] def map_matrix (f : α ≃ₗ[R] β) : matrix m n α ≃ₗ[R] matrix m n β := { to_fun := λ M, M.map f, inv_fun := λ M, M.map f.symm, .. f.to_equiv.map_matrix, .. f.to_linear_map.map_matrix } @[simp] lemma map_matrix_refl : (linear_equiv.refl R α).map_matrix = linear_equiv.refl R (matrix m n α) := rfl @[simp] lemma map_matrix_symm (f : α ≃ₗ[R] β) : f.map_matrix.symm = (f.symm.map_matrix : matrix m n β ≃ₗ[R] _) := rfl @[simp] lemma map_matrix_trans (f : α ≃ₗ[R] β) (g : β ≃ₗ[R] γ) : f.map_matrix.trans g.map_matrix = ((f.trans g).map_matrix : matrix m n α ≃ₗ[R] _) := rfl end linear_equiv namespace ring_hom variables [fintype m] [decidable_eq m] variables [non_assoc_semiring α] [non_assoc_semiring β] [non_assoc_semiring γ] /-- The `ring_hom` between spaces of square matrices induced by a `ring_hom` between their coefficients. This is `matrix.map` as a `ring_hom`. -/ @[simps] def map_matrix (f : α →+* β) : matrix m m α →+* matrix m m β := { to_fun := λ M, M.map f, map_one' := by simp, map_mul' := λ L M, matrix.map_mul, .. f.to_add_monoid_hom.map_matrix } @[simp] lemma map_matrix_id : (ring_hom.id α).map_matrix = ring_hom.id (matrix m m α) := rfl @[simp] lemma map_matrix_comp (f : β →+* γ) (g : α →+* β) : f.map_matrix.comp g.map_matrix = ((f.comp g).map_matrix : matrix m m α →+* _) := rfl end ring_hom namespace ring_equiv variables [fintype m] [decidable_eq m] variables [non_assoc_semiring α] [non_assoc_semiring β] [non_assoc_semiring γ] /-- The `ring_equiv` between spaces of square matrices induced by a `ring_equiv` between their coefficients. This is `matrix.map` as a `ring_equiv`. -/ @[simps apply] def map_matrix (f : α ≃+* β) : matrix m m α ≃+* matrix m m β := { to_fun := λ M, M.map f, inv_fun := λ M, M.map f.symm, .. f.to_ring_hom.map_matrix, .. f.to_add_equiv.map_matrix } @[simp] lemma map_matrix_refl : (ring_equiv.refl α).map_matrix = ring_equiv.refl (matrix m m α) := rfl @[simp] lemma map_matrix_symm (f : α ≃+* β) : f.map_matrix.symm = (f.symm.map_matrix : matrix m m β ≃+* _) := rfl @[simp] lemma map_matrix_trans (f : α ≃+* β) (g : β ≃+* γ) : f.map_matrix.trans g.map_matrix = ((f.trans g).map_matrix : matrix m m α ≃+* _) := rfl end ring_equiv namespace alg_hom variables [fintype m] [decidable_eq m] variables [comm_semiring R] [semiring α] [semiring β] [semiring γ] variables [algebra R α] [algebra R β] [algebra R γ] /-- The `alg_hom` between spaces of square matrices induced by a `alg_hom` between their coefficients. This is `matrix.map` as a `alg_hom`. -/ @[simps] def map_matrix (f : α →ₐ[R] β) : matrix m m α →ₐ[R] matrix m m β := { to_fun := λ M, M.map f, commutes' := λ r, matrix.map_algebra_map r f f.map_zero (f.commutes r), .. f.to_ring_hom.map_matrix } @[simp] lemma map_matrix_id : (alg_hom.id R α).map_matrix = alg_hom.id R (matrix m m α) := rfl @[simp] lemma map_matrix_comp (f : β →ₐ[R] γ) (g : α →ₐ[R] β) : f.map_matrix.comp g.map_matrix = ((f.comp g).map_matrix : matrix m m α →ₐ[R] _) := rfl end alg_hom namespace alg_equiv variables [fintype m] [decidable_eq m] variables [comm_semiring R] [semiring α] [semiring β] [semiring γ] variables [algebra R α] [algebra R β] [algebra R γ] /-- The `alg_equiv` between spaces of square matrices induced by a `alg_equiv` between their coefficients. This is `matrix.map` as a `alg_equiv`. -/ @[simps apply] def map_matrix (f : α ≃ₐ[R] β) : matrix m m α ≃ₐ[R] matrix m m β := { to_fun := λ M, M.map f, inv_fun := λ M, M.map f.symm, .. f.to_alg_hom.map_matrix, .. f.to_ring_equiv.map_matrix } @[simp] lemma map_matrix_refl : alg_equiv.refl.map_matrix = (alg_equiv.refl : matrix m m α ≃ₐ[R] _) := rfl @[simp] lemma map_matrix_symm (f : α ≃ₐ[R] β) : f.map_matrix.symm = (f.symm.map_matrix : matrix m m β ≃ₐ[R] _) := rfl @[simp] lemma map_matrix_trans (f : α ≃ₐ[R] β) (g : β ≃ₐ[R] γ) : f.map_matrix.trans g.map_matrix = ((f.trans g).map_matrix : matrix m m α ≃ₐ[R] _) := rfl end alg_equiv open_locale matrix namespace matrix /-- For two vectors `w` and `v`, `vec_mul_vec w v i j` is defined to be `w i * v j`. Put another way, `vec_mul_vec w v` is exactly `col w ⬝ row v`. -/ def vec_mul_vec [has_mul α] (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y section non_unital_non_assoc_semiring variables [non_unital_non_assoc_semiring α] /-- `mul_vec M v` is the matrix-vector product of `M` and `v`, where `v` is seen as a column matrix. Put another way, `mul_vec M v` is the vector whose entries are those of `M ⬝ col v` (see `col_mul_vec`). -/ def mul_vec [fintype n] (M : matrix m n α) (v : n → α) : m → α | i := (λ j, M i j) ⬝ᵥ v /-- `vec_mul v M` is the vector-matrix product of `v` and `M`, where `v` is seen as a row matrix. Put another way, `vec_mul v M` is the vector whose entries are those of `row v ⬝ M` (see `row_vec_mul`). -/ def vec_mul [fintype m] (v : m → α) (M : matrix m n α) : n → α | j := v ⬝ᵥ (λ i, M i j) /-- Left multiplication by a matrix, as an `add_monoid_hom` from vectors to vectors. -/ @[simps] def mul_vec.add_monoid_hom_left [fintype n] (v : n → α) : matrix m n α →+ m → α := { to_fun := λ M, mul_vec M v, map_zero' := by ext; simp [mul_vec]; refl, map_add' := λ x y, by { ext m, apply add_dot_product } } lemma mul_vec_diagonal [fintype m] [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := diagonal_dot_product v w x lemma vec_mul_diagonal [fintype m] [decidable_eq m] (v w : m → α) (x : m) : vec_mul v (diagonal w) x = v x * w x := dot_product_diagonal' v w x /-- Associate the dot product of `mul_vec` to the left. -/ lemma dot_product_mul_vec [fintype n] [fintype m] [non_unital_semiring R] (v : m → R) (A : matrix m n R) (w : n → R) : v ⬝ᵥ mul_vec A w = vec_mul v A ⬝ᵥ w := by simp only [dot_product, vec_mul, mul_vec, finset.mul_sum, finset.sum_mul, mul_assoc]; exact finset.sum_comm @[simp] lemma mul_vec_zero [fintype n] (A : matrix m n α) : mul_vec A 0 = 0 := by { ext, simp [mul_vec] } @[simp] lemma zero_vec_mul [fintype m] (A : matrix m n α) : vec_mul 0 A = 0 := by { ext, simp [vec_mul] } @[simp] lemma zero_mul_vec [fintype n] (v : n → α) : mul_vec (0 : matrix m n α) v = 0 := by { ext, simp [mul_vec] } @[simp] lemma vec_mul_zero [fintype m] (v : m → α) : vec_mul v (0 : matrix m n α) = 0 := by { ext, simp [vec_mul] } lemma vec_mul_vec_eq (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by { ext i j, simp [vec_mul_vec, mul_apply], refl } lemma smul_mul_vec_assoc [fintype n] [monoid R] [distrib_mul_action R α] [is_scalar_tower R α α] (a : R) (A : matrix m n α) (b : n → α) : (a • A).mul_vec b = a • (A.mul_vec b) := by { ext, apply smul_dot_product, } lemma mul_vec_add [fintype n] (A : matrix m n α) (x y : n → α) : A.mul_vec (x + y) = A.mul_vec x + A.mul_vec y := by { ext, apply dot_product_add } lemma add_mul_vec [fintype n] (A B : matrix m n α) (x : n → α) : (A + B).mul_vec x = A.mul_vec x + B.mul_vec x := by { ext, apply add_dot_product } lemma vec_mul_add [fintype m] (A B : matrix m n α) (x : m → α) : vec_mul x (A + B) = vec_mul x A + vec_mul x B := by { ext, apply dot_product_add } lemma add_vec_mul [fintype m] (A : matrix m n α) (x y : m → α) : vec_mul (x + y) A = vec_mul x A + vec_mul y A := by { ext, apply add_dot_product } lemma vec_mul_smul [fintype n] [comm_semiring R] [semiring S] [algebra R S] (M : matrix n m S) (b : R) (v : n → S) : M.vec_mul (b • v) = b • M.vec_mul v := by { ext i, simp only [vec_mul, dot_product, finset.smul_sum, pi.smul_apply, smul_mul_assoc] } lemma mul_vec_smul [fintype n] [comm_semiring R] [semiring S] [algebra R S] (M : matrix m n S) (b : R) (v : n → S) : M.mul_vec (b • v) = b • M.mul_vec v := by { ext i, simp only [mul_vec, dot_product, finset.smul_sum, pi.smul_apply, mul_smul_comm] } end non_unital_non_assoc_semiring section non_unital_semiring variables [non_unital_semiring α] [fintype n] @[simp] lemma vec_mul_vec_mul [fintype m] (v : m → α) (M : matrix m n α) (N : matrix n o α) : vec_mul (vec_mul v M) N = vec_mul v (M ⬝ N) := by { ext, apply dot_product_assoc } @[simp] lemma mul_vec_mul_vec [fintype o] (v : o → α) (M : matrix m n α) (N : matrix n o α) : mul_vec M (mul_vec N v) = mul_vec (M ⬝ N) v := by { ext, symmetry, apply dot_product_assoc } end non_unital_semiring section non_assoc_semiring variables [fintype m] [decidable_eq m] [non_assoc_semiring α] @[simp] lemma one_mul_vec (v : m → α) : mul_vec 1 v = v := by { ext, rw [←diagonal_one, mul_vec_diagonal, one_mul] } @[simp] lemma vec_mul_one (v : m → α) : vec_mul v 1 = v := by { ext, rw [←diagonal_one, vec_mul_diagonal, mul_one] } end non_assoc_semiring section ring variables [ring α] lemma neg_vec_mul [fintype m] (v : m → α) (A : matrix m n α) : vec_mul (-v) A = - vec_mul v A := by { ext, apply neg_dot_product } lemma vec_mul_neg [fintype m] (v : m → α) (A : matrix m n α) : vec_mul v (-A) = - vec_mul v A := by { ext, apply dot_product_neg } lemma neg_mul_vec [fintype n] (v : n → α) (A : matrix m n α) : mul_vec (-A) v = - mul_vec A v := by { ext, apply neg_dot_product } lemma mul_vec_neg [fintype n] (v : n → α) (A : matrix m n α) : mul_vec A (-v) = - mul_vec A v := by { ext, apply dot_product_neg } end ring section comm_semiring variables [comm_semiring α] lemma mul_vec_smul_assoc [fintype n] (A : matrix m n α) (b : n → α) (a : α) : A.mul_vec (a • b) = a • (A.mul_vec b) := by { ext, apply dot_product_smul } lemma mul_vec_transpose [fintype m] (A : matrix m n α) (x : m → α) : mul_vec Aᵀ x = vec_mul x A := by { ext, apply dot_product_comm } lemma vec_mul_transpose [fintype n] (A : matrix m n α) (x : n → α) : vec_mul x Aᵀ = mul_vec A x := by { ext, apply dot_product_comm } end comm_semiring section transpose open_locale matrix /-- Tell `simp` what the entries are in a transposed matrix. Compare with `mul_apply`, `diagonal_apply_eq`, etc. -/ @[simp] lemma transpose_apply (M : matrix m n α) (i j) : M.transpose j i = M i j := rfl @[simp] lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α)ᵀ = 1 := begin ext i j, unfold has_one.one transpose, by_cases i = j, { simp only [h, diagonal_apply_eq] }, { simp only [diagonal_apply_ne h, diagonal_apply_ne (λ p, h (symm p))] } end @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := by { ext i j, simp } @[simp] lemma transpose_sub [has_sub α] (M : matrix m n α) (N : matrix m n α) : (M - N)ᵀ = Mᵀ - Nᵀ := by { ext i j, simp } @[simp] lemma transpose_mul [comm_semiring α] [fintype n] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, apply dot_product_comm end @[simp] lemma transpose_smul {R : Type*} [has_scalar R α] (c : R) (M : matrix m n α) : (c • M)ᵀ = c • Mᵀ := by { ext i j, refl } @[simp] lemma transpose_neg [has_neg α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl lemma transpose_map {f : α → β} {M : matrix m n α} : Mᵀ.map f = (M.map f)ᵀ := by { ext, refl } /-- `matrix.transpose` as an `add_equiv` -/ @[simps apply] def transpose_add_equiv [has_add α] : matrix m n α ≃+ matrix n m α := { to_fun := transpose, inv_fun := transpose, left_inv := transpose_transpose, right_inv := transpose_transpose, map_add' := transpose_add } @[simp] lemma transpose_add_equiv_symm [has_add α] : (transpose_add_equiv : matrix m n α ≃+ matrix n m α).symm = transpose_add_equiv := rfl lemma transpose_list_sum [add_monoid α] (l : list (matrix m n α)) : l.sumᵀ = (l.map transpose).sum := (transpose_add_equiv : matrix m n α ≃+ matrix n m α).to_add_monoid_hom.map_list_sum l lemma transpose_multiset_sum [add_comm_monoid α] (s : multiset (matrix m n α)) : s.sumᵀ = (s.map transpose).sum := (transpose_add_equiv : matrix m n α ≃+ matrix n m α).to_add_monoid_hom.map_multiset_sum s lemma transpose_sum [add_comm_monoid α] {ι : Type*} (s : finset ι) (M : ι → matrix m n α) : (∑ i in s, M i)ᵀ = ∑ i in s, (M i)ᵀ := (transpose_add_equiv : matrix m n α ≃+ matrix n m α).to_add_monoid_hom.map_sum _ s /-- `matrix.transpose` as a `ring_equiv` to the opposite ring -/ @[simps] def transpose_ring_equiv [comm_semiring α] [fintype m] : matrix m m α ≃+* (matrix m m α)ᵐᵒᵖ := { to_fun := λ M, mul_opposite.op (Mᵀ), inv_fun := λ M, M.unopᵀ, map_mul' := λ M N, (congr_arg mul_opposite.op (transpose_mul M N)).trans (mul_opposite.op_mul _ _), ..transpose_add_equiv.trans mul_opposite.op_add_equiv } lemma transpose_list_prod [comm_semiring α] [fintype m] [decidable_eq m] (l : list (matrix m m α)) : l.prodᵀ = (l.map transpose).reverse.prod := (transpose_ring_equiv : matrix m m α ≃+* (matrix m m α)ᵐᵒᵖ).unop_map_list_prod l end transpose section conj_transpose open_locale matrix /-- Tell `simp` what the entries are in a conjugate transposed matrix. Compare with `mul_apply`, `diagonal_apply_eq`, etc. -/ @[simp] lemma conj_transpose_apply [has_star α] (M : matrix m n α) (i j) : M.conj_transpose j i = star (M i j) := rfl @[simp] lemma conj_transpose_conj_transpose [has_involutive_star α] (M : matrix m n α) : Mᴴᴴ = M := by ext; simp @[simp] lemma conj_transpose_zero [semiring α] [star_ring α] : (0 : matrix m n α)ᴴ = 0 := by ext i j; simp @[simp] lemma conj_transpose_one [decidable_eq n] [semiring α] [star_ring α]: (1 : matrix n n α)ᴴ = 1 := by simp [conj_transpose] @[simp] lemma conj_transpose_add [add_monoid α] [star_add_monoid α] (M N : matrix m n α) : (M + N)ᴴ = Mᴴ + Nᴴ := by ext i j; simp @[simp] lemma conj_transpose_sub [add_group α] [star_add_monoid α] (M N : matrix m n α) : (M - N)ᴴ = Mᴴ - Nᴴ := by ext i j; simp @[simp] lemma conj_transpose_smul [comm_monoid α] [star_monoid α] (c : α) (M : matrix m n α) : (c • M)ᴴ = (star c) • Mᴴ := by ext i j; simp [mul_comm] @[simp] lemma conj_transpose_mul [fintype n] [semiring α] [star_ring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᴴ = Nᴴ ⬝ Mᴴ := by ext i j; simp [mul_apply] @[simp] lemma conj_transpose_neg [ring α] [star_ring α] (M : matrix m n α) : (- M)ᴴ = - Mᴴ := by ext i j; simp /-- `matrix.conj_transpose` as an `add_equiv` -/ @[simps apply] def conj_transpose_add_equiv [add_monoid α] [star_add_monoid α] : matrix m n α ≃+ matrix n m α := { to_fun := conj_transpose, inv_fun := conj_transpose, left_inv := conj_transpose_conj_transpose, right_inv := conj_transpose_conj_transpose, map_add' := conj_transpose_add } @[simp] lemma conj_transpose_add_equiv_symm [add_monoid α] [star_add_monoid α] : (conj_transpose_add_equiv : matrix m n α ≃+ matrix n m α).symm = conj_transpose_add_equiv := rfl lemma conj_transpose_list_sum [add_monoid α] [star_add_monoid α] (l : list (matrix m n α)) : l.sumᴴ = (l.map conj_transpose).sum := (conj_transpose_add_equiv : matrix m n α ≃+ matrix n m α).to_add_monoid_hom.map_list_sum l lemma conj_transpose_multiset_sum [add_comm_monoid α] [star_add_monoid α] (s : multiset (matrix m n α)) : s.sumᴴ = (s.map conj_transpose).sum := (conj_transpose_add_equiv : matrix m n α ≃+ matrix n m α).to_add_monoid_hom.map_multiset_sum s lemma conj_transpose_sum [add_comm_monoid α] [star_add_monoid α] {ι : Type*} (s : finset ι) (M : ι → matrix m n α) : (∑ i in s, M i)ᴴ = ∑ i in s, (M i)ᴴ := (conj_transpose_add_equiv : matrix m n α ≃+ matrix n m α).to_add_monoid_hom.map_sum _ s /-- `matrix.conj_transpose` as a `ring_equiv` to the opposite ring -/ @[simps] def conj_transpose_ring_equiv [comm_semiring α] [star_ring α] [fintype m] : matrix m m α ≃+* (matrix m m α)ᵐᵒᵖ := { to_fun := λ M, mul_opposite.op (Mᴴ), inv_fun := λ M, M.unopᴴ, map_mul' := λ M N, (congr_arg mul_opposite.op (conj_transpose_mul M N)).trans (mul_opposite.op_mul _ _), ..conj_transpose_add_equiv.trans mul_opposite.op_add_equiv } lemma conj_transpose_list_prod [comm_semiring α] [star_ring α] [fintype m] [decidable_eq m] (l : list (matrix m m α)) : l.prodᴴ = (l.map conj_transpose).reverse.prod := (conj_transpose_ring_equiv : matrix m m α ≃+* (matrix m m α)ᵐᵒᵖ).unop_map_list_prod l end conj_transpose section star /-- When `α` has a star operation, square matrices `matrix n n α` have a star operation equal to `matrix.conj_transpose`. -/ instance [has_star α] : has_star (matrix n n α) := {star := conj_transpose} lemma star_eq_conj_transpose [has_star α] (M : matrix m m α) : star M = Mᴴ := rfl @[simp] lemma star_apply [has_star α] (M : matrix n n α) (i j) : (star M) i j = star (M j i) := rfl instance [has_involutive_star α] : has_involutive_star (matrix n n α) := { star_involutive := conj_transpose_conj_transpose } /-- When `α` is a `*`-additive monoid, `matrix.has_star` is also a `*`-additive monoid. -/ instance [add_monoid α] [star_add_monoid α] : star_add_monoid (matrix n n α) := { star_add := conj_transpose_add } /-- When `α` is a `*`-(semi)ring, `matrix.has_star` is also a `*`-(semi)ring. -/ instance [fintype n] [decidable_eq n] [semiring α] [star_ring α] : star_ring (matrix n n α) := { star_add := conj_transpose_add, star_mul := conj_transpose_mul, } /-- A version of `star_mul` for `⬝` instead of `*`. -/ lemma star_mul [fintype n] [semiring α] [star_ring α] (M N : matrix n n α) : star (M ⬝ N) = star N ⬝ star M := conj_transpose_mul _ _ end star /-- Given maps `(r_reindex : l → m)` and `(c_reindex : o → n)` reindexing the rows and columns of a matrix `M : matrix m n α`, the matrix `M.minor r_reindex c_reindex : matrix l o α` is defined by `(M.minor r_reindex c_reindex) i j = M (r_reindex i) (c_reindex j)` for `(i,j) : l × o`. Note that the total number of row and columns does not have to be preserved. -/ def minor (A : matrix m n α) (r_reindex : l → m) (c_reindex : o → n) : matrix l o α := λ i j, A (r_reindex i) (c_reindex j) @[simp] lemma minor_apply (A : matrix m n α) (r_reindex : l → m) (c_reindex : o → n) (i j) : A.minor r_reindex c_reindex i j = A (r_reindex i) (c_reindex j) := rfl @[simp] lemma minor_id_id (A : matrix m n α) : A.minor id id = A := ext $ λ _ _, rfl @[simp] lemma minor_minor {l₂ o₂ : Type*} (A : matrix m n α) (r₁ : l → m) (c₁ : o → n) (r₂ : l₂ → l) (c₂ : o₂ → o) : (A.minor r₁ c₁).minor r₂ c₂ = A.minor (r₁ ∘ r₂) (c₁ ∘ c₂) := ext $ λ _ _, rfl @[simp] lemma transpose_minor (A : matrix m n α) (r_reindex : l → m) (c_reindex : o → n) : (A.minor r_reindex c_reindex)ᵀ = Aᵀ.minor c_reindex r_reindex := ext $ λ _ _, rfl @[simp] lemma conj_transpose_minor [has_star α] (A : matrix m n α) (r_reindex : l → m) (c_reindex : o → n) : (A.minor r_reindex c_reindex)ᴴ = Aᴴ.minor c_reindex r_reindex := ext $ λ _ _, rfl lemma minor_add [has_add α] (A B : matrix m n α) : ((A + B).minor : (l → m) → (o → n) → matrix l o α) = A.minor + B.minor := rfl lemma minor_neg [has_neg α] (A : matrix m n α) : ((-A).minor : (l → m) → (o → n) → matrix l o α) = -A.minor := rfl lemma minor_sub [has_sub α] (A B : matrix m n α) : ((A - B).minor : (l → m) → (o → n) → matrix l o α) = A.minor - B.minor := rfl @[simp] lemma minor_zero [has_zero α] : ((0 : matrix m n α).minor : (l → m) → (o → n) → matrix l o α) = 0 := rfl lemma minor_smul {R : Type*} [semiring R] [add_comm_monoid α] [module R α] (r : R) (A : matrix m n α) : ((r • A : matrix m n α).minor : (l → m) → (o → n) → matrix l o α) = r • A.minor := rfl lemma minor_map (f : α → β) (e₁ : l → m) (e₂ : o → n) (A : matrix m n α) : (A.map f).minor e₁ e₂ = (A.minor e₁ e₂).map f := rfl /-- Given a `(m × m)` diagonal matrix defined by a map `d : m → α`, if the reindexing map `e` is injective, then the resulting matrix is again diagonal. -/ lemma minor_diagonal [has_zero α] [decidable_eq m] [decidable_eq l] (d : m → α) (e : l → m) (he : function.injective e) : (diagonal d).minor e e = diagonal (d ∘ e) := ext $ λ i j, begin rw minor_apply, by_cases h : i = j, { rw [h, diagonal_apply_eq, diagonal_apply_eq], }, { rw [diagonal_apply_ne h, diagonal_apply_ne (he.ne h)], }, end lemma minor_one [has_zero α] [has_one α] [decidable_eq m] [decidable_eq l] (e : l → m) (he : function.injective e) : (1 : matrix m m α).minor e e = 1 := minor_diagonal _ e he lemma minor_mul [fintype n] [fintype o] [semiring α] {p q : Type*} (M : matrix m n α) (N : matrix n p α) (e₁ : l → m) (e₂ : o → n) (e₃ : q → p) (he₂ : function.bijective e₂) : (M ⬝ N).minor e₁ e₃ = (M.minor e₁ e₂) ⬝ (N.minor e₂ e₃) := ext $ λ _ _, (he₂.sum_comp _).symm /-! `simp` lemmas for `matrix.minor`s interaction with `matrix.diagonal`, `1`, and `matrix.mul` for when the mappings are bundled. -/ @[simp] lemma minor_diagonal_embedding [has_zero α] [decidable_eq m] [decidable_eq l] (d : m → α) (e : l ↪ m) : (diagonal d).minor e e = diagonal (d ∘ e) := minor_diagonal d e e.injective @[simp] lemma minor_diagonal_equiv [has_zero α] [decidable_eq m] [decidable_eq l] (d : m → α) (e : l ≃ m) : (diagonal d).minor e e = diagonal (d ∘ e) := minor_diagonal d e e.injective @[simp] lemma minor_one_embedding [has_zero α] [has_one α] [decidable_eq m] [decidable_eq l] (e : l ↪ m) : (1 : matrix m m α).minor e e = 1 := minor_one e e.injective @[simp] lemma minor_one_equiv [has_zero α] [has_one α] [decidable_eq m] [decidable_eq l] (e : l ≃ m) : (1 : matrix m m α).minor e e = 1 := minor_one e e.injective @[simp] lemma minor_mul_equiv [fintype n] [fintype o] [semiring α] {p q : Type*} (M : matrix m n α) (N : matrix n p α) (e₁ : l → m) (e₂ : o ≃ n) (e₃ : q → p) : (M.minor e₁ e₂) ⬝ (N.minor e₂ e₃) = (M ⬝ N).minor e₁ e₃ := (minor_mul M N e₁ e₂ e₃ e₂.bijective).symm lemma mul_minor_one [fintype n] [fintype o] [semiring α] [decidable_eq o] (e₁ : n ≃ o) (e₂ : l → o) (M : matrix m n α) : M ⬝ (1 : matrix o o α).minor e₁ e₂ = minor M id (e₁.symm ∘ e₂) := begin let A := M.minor id e₁.symm, have : M = A.minor id e₁, { simp only [minor_minor, function.comp.right_id, minor_id_id, equiv.symm_comp_self], }, rw [this, minor_mul_equiv], simp only [matrix.mul_one, minor_minor, function.comp.right_id, minor_id_id, equiv.symm_comp_self], end lemma one_minor_mul [fintype m] [fintype o] [semiring α] [decidable_eq o] (e₁ : l → o) (e₂ : m ≃ o) (M : matrix m n α) : ((1 : matrix o o α).minor e₁ e₂).mul M = minor M (e₂.symm ∘ e₁) id := begin let A := M.minor e₂.symm id, have : M = A.minor e₂ id, { simp only [minor_minor, function.comp.right_id, minor_id_id, equiv.symm_comp_self], }, rw [this, minor_mul_equiv], simp only [matrix.one_mul, minor_minor, function.comp.right_id, minor_id_id, equiv.symm_comp_self], end /-- The natural map that reindexes a matrix's rows and columns with equivalent types is an equivalence. -/ def reindex (eₘ : m ≃ l) (eₙ : n ≃ o) : matrix m n α ≃ matrix l o α := { to_fun := λ M, M.minor eₘ.symm eₙ.symm, inv_fun := λ M, M.minor eₘ eₙ, left_inv := λ M, by simp, right_inv := λ M, by simp, } @[simp] lemma reindex_apply (eₘ : m ≃ l) (eₙ : n ≃ o) (M : matrix m n α) : reindex eₘ eₙ M = M.minor eₘ.symm eₙ.symm := rfl @[simp] lemma reindex_refl_refl (A : matrix m n α) : reindex (equiv.refl _) (equiv.refl _) A = A := A.minor_id_id @[simp] lemma reindex_symm (eₘ : m ≃ l) (eₙ : n ≃ o) : (reindex eₘ eₙ).symm = (reindex eₘ.symm eₙ.symm : matrix l o α ≃ _) := rfl @[simp] lemma reindex_trans {l₂ o₂ : Type*} (eₘ : m ≃ l) (eₙ : n ≃ o) (eₘ₂ : l ≃ l₂) (eₙ₂ : o ≃ o₂) : (reindex eₘ eₙ).trans (reindex eₘ₂ eₙ₂) = (reindex (eₘ.trans eₘ₂) (eₙ.trans eₙ₂) : matrix m n α ≃ _) := equiv.ext $ λ A, (A.minor_minor eₘ.symm eₙ.symm eₘ₂.symm eₙ₂.symm : _) lemma transpose_reindex (eₘ : m ≃ l) (eₙ : n ≃ o) (M : matrix m n α) : (reindex eₘ eₙ M)ᵀ = (reindex eₙ eₘ Mᵀ) := rfl lemma conj_transpose_reindex [has_star α] (eₘ : m ≃ l) (eₙ : n ≃ o) (M : matrix m n α) : (reindex eₘ eₙ M)ᴴ = (reindex eₙ eₘ Mᴴ) := rfl @[simp] lemma minor_mul_transpose_minor [fintype n] [fintype m] [semiring α] (e : n ≃ m) (M : matrix n m α) : (M.minor id e) ⬝ (Mᵀ).minor e id = M ⬝ Mᵀ := by rw [minor_mul_equiv, minor_id_id] /-- The left `n × l` part of a `n × (l+r)` matrix. -/ @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id (fin.cast_add r) /-- The right `n × r` part of a `n × (l+r)` matrix. -/ @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id (fin.nat_add l) /-- The top `u × n` part of a `(u+d) × n` matrix. -/ @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (fin.cast_add d) id /-- The bottom `d × n` part of a `(u+d) × n` matrix. -/ @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (fin.nat_add u) id /-- The top-right `u × r` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) /-- The bottom-right `d × r` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) /-- The top-left `u × l` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) /-- The bottom-left `d × l` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) section row_col /-! ### `row_col` section Simplification lemmas for `matrix.row` and `matrix.col`. -/ open_locale matrix @[simp] lemma col_add [has_add α] (v w : m → α) : col (v + w) = col v + col w := by { ext, refl } @[simp] lemma col_smul [has_scalar R α] (x : R) (v : m → α) : col (x • v) = x • col v := by { ext, refl } @[simp] lemma row_add [has_add α] (v w : m → α) : row (v + w) = row v + row w := by { ext, refl } @[simp] lemma row_smul [has_scalar R α] (x : R) (v : m → α) : row (x • v) = x • row v := by { ext, refl } @[simp] lemma col_apply (v : m → α) (i j) : matrix.col v i j = v i := rfl @[simp] lemma row_apply (v : m → α) (i j) : matrix.row v i j = v j := rfl @[simp] lemma transpose_col (v : m → α) : (matrix.col v)ᵀ = matrix.row v := by { ext, refl } @[simp] lemma transpose_row (v : m → α) : (matrix.row v)ᵀ = matrix.col v := by { ext, refl } @[simp] lemma conj_transpose_col [has_star α] (v : m → α) : (col v)ᴴ = row (star v) := by { ext, refl } @[simp] lemma conj_transpose_row [has_star α] (v : m → α) : (row v)ᴴ = col (star v) := by { ext, refl } lemma row_vec_mul [fintype m] [semiring α] (M : matrix m n α) (v : m → α) : matrix.row (matrix.vec_mul v M) = matrix.row v ⬝ M := by {ext, refl} lemma col_vec_mul [fintype m] [semiring α] (M : matrix m n α) (v : m → α) : matrix.col (matrix.vec_mul v M) = (matrix.row v ⬝ M)ᵀ := by {ext, refl} lemma col_mul_vec [fintype n] [semiring α] (M : matrix m n α) (v : n → α) : matrix.col (matrix.mul_vec M v) = M ⬝ matrix.col v := by {ext, refl} lemma row_mul_vec [fintype n] [semiring α] (M : matrix m n α) (v : n → α) : matrix.row (matrix.mul_vec M v) = (M ⬝ matrix.col v)ᵀ := by {ext, refl} @[simp] lemma row_mul_col_apply [fintype m] [has_mul α] [add_comm_monoid α] (v w : m → α) (i j) : (row v ⬝ col w) i j = v ⬝ᵥ w := rfl end row_col section update /-- Update, i.e. replace the `i`th row of matrix `A` with the values in `b`. -/ def update_row [decidable_eq n] (M : matrix n m α) (i : n) (b : m → α) : matrix n m α := function.update M i b /-- Update, i.e. replace the `j`th column of matrix `A` with the values in `b`. -/ def update_column [decidable_eq m] (M : matrix n m α) (j : m) (b : n → α) : matrix n m α := λ i, function.update (M i) j (b i) variables {M : matrix n m α} {i : n} {j : m} {b : m → α} {c : n → α} @[simp] lemma update_row_self [decidable_eq n] : update_row M i b i = b := function.update_same i b M @[simp] lemma update_column_self [decidable_eq m] : update_column M j c i j = c i := function.update_same j (c i) (M i) @[simp] lemma update_row_ne [decidable_eq n] {i' : n} (i_ne : i' ≠ i) : update_row M i b i' = M i' := function.update_noteq i_ne b M @[simp] lemma update_column_ne [decidable_eq m] {j' : m} (j_ne : j' ≠ j) : update_column M j c i j' = M i j' := function.update_noteq j_ne (c i) (M i) lemma update_row_apply [decidable_eq n] {i' : n} : update_row M i b i' j = if i' = i then b j else M i' j := begin by_cases i' = i, { rw [h, update_row_self, if_pos rfl] }, { rwa [update_row_ne h, if_neg h] } end lemma update_column_apply [decidable_eq m] {j' : m} : update_column M j c i j' = if j' = j then c i else M i j' := begin by_cases j' = j, { rw [h, update_column_self, if_pos rfl] }, { rwa [update_column_ne h, if_neg h] } end @[simp] lemma update_column_subsingleton [subsingleton m] (A : matrix n m R) (i : m) (b : n → R) : A.update_column i b = (col b).minor id (function.const m ()) := begin ext x y, simp [update_column_apply, subsingleton.elim i y] end @[simp] lemma update_row_subsingleton [subsingleton n] (A : matrix n m R) (i : n) (b : m → R) : A.update_row i b = (row b).minor (function.const n ()) id := begin ext x y, simp [update_column_apply, subsingleton.elim i x] end lemma map_update_row [decidable_eq n] (f : α → β) : map (update_row M i b) f = update_row (M.map f) i (f ∘ b) := begin ext i' j', rw [update_row_apply, map_apply, map_apply, update_row_apply], exact apply_ite f _ _ _, end lemma map_update_column [decidable_eq m] (f : α → β) : map (update_column M j c) f = update_column (M.map f) j (f ∘ c) := begin ext i' j', rw [update_column_apply, map_apply, map_apply, update_column_apply], exact apply_ite f _ _ _, end lemma update_row_transpose [decidable_eq m] : update_row Mᵀ j c = (update_column M j c)ᵀ := begin ext i' j, rw [transpose_apply, update_row_apply, update_column_apply], refl end lemma update_column_transpose [decidable_eq n] : update_column Mᵀ i b = (update_row M i b)ᵀ := begin ext i' j, rw [transpose_apply, update_row_apply, update_column_apply], refl end lemma update_row_conj_transpose [decidable_eq m] [has_star α] : update_row Mᴴ j (star c) = (update_column M j c)ᴴ := begin rw [conj_transpose, conj_transpose, transpose_map, transpose_map, update_row_transpose, map_update_column], refl, end lemma update_column_conj_transpose [decidable_eq n] [has_star α] : update_column Mᴴ i (star b) = (update_row M i b)ᴴ := begin rw [conj_transpose, conj_transpose, transpose_map, transpose_map, update_column_transpose, map_update_row], refl, end @[simp] lemma update_row_eq_self [decidable_eq m] (A : matrix m n α) {i : m} : A.update_row i (A i) = A := function.update_eq_self i A @[simp] lemma update_column_eq_self [decidable_eq n] (A : matrix m n α) {i : n} : A.update_column i (λ j, A j i) = A := funext $ λ j, function.update_eq_self i (A j) end update end matrix namespace ring_hom variables [fintype n] [semiring α] [semiring β] lemma map_matrix_mul (M : matrix m n α) (N : matrix n o α) (i : m) (j : o) (f : α →+* β) : f (matrix.mul M N i j) = matrix.mul (λ i j, f (M i j)) (λ i j, f (N i j)) i j := by simp [matrix.mul_apply, ring_hom.map_sum] lemma map_dot_product [semiring R] [semiring S] (f : R →+* S) (v w : n → R) : f (v ⬝ᵥ w) = (f ∘ v) ⬝ᵥ (f ∘ w) := by simp only [matrix.dot_product, f.map_sum, f.map_mul] lemma map_vec_mul [semiring R] [semiring S] (f : R →+* S) (M : matrix n m R) (v : n → R) (i : m) : f (M.vec_mul v i) = ((M.map f).vec_mul (f ∘ v) i) := by simp only [matrix.vec_mul, matrix.map_apply, ring_hom.map_dot_product] lemma map_mul_vec [semiring R] [semiring S] (f : R →+* S) (M : matrix m n R) (v : n → R) (i : m) : f (M.mul_vec v i) = ((M.map f).mul_vec (f ∘ v) i) := by simp only [matrix.mul_vec, matrix.map_apply, ring_hom.map_dot_product] end ring_hom
2a0f38bf7584e60ec54444153aac0ef17e1cad60
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Elab/Binders.lean
1f8b3a56fe39e9da87f43681ee7fd6a35661275a
[ "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
24,680
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.Elab.Term import Lean.Parser.Term namespace Lean.Elab.Term open Meta open Lean.Parser.Term /-- Given syntax of the forms a) (`:` term)? b) `:` term return `term` if it is present, or a hole if not. -/ private def expandBinderType (ref : Syntax) (stx : Syntax) : Syntax := if stx.getNumArgs == 0 then mkHole ref else stx[1] /-- Given syntax of the form `ident <|> hole`, return `ident`. If `hole`, then we create a new anonymous name. -/ private def expandBinderIdent (stx : Syntax) : TermElabM Syntax := match stx with | `(_) => mkFreshIdent stx | _ => pure stx /-- Given syntax of the form `(ident >> " : ")?`, return `ident`, or a new instance name. -/ private def expandOptIdent (stx : Syntax) : TermElabM Syntax := do if stx.isNone then let id ← withFreshMacroScope <| MonadQuotation.addMacroScope `inst return mkIdentFrom stx id else return stx[0] structure BinderView where id : Syntax type : Syntax bi : BinderInfo partial def quoteAutoTactic : Syntax → TermElabM Syntax | stx@(Syntax.ident _ _ _ _) => throwErrorAt stx "invalid auto tactic, identifier is not allowed" | stx@(Syntax.node k args) => do if stx.isAntiquot then throwErrorAt stx "invalid auto tactic, antiquotation is not allowed" else let mut quotedArgs ← `(Array.empty) for arg in args do if k == nullKind && (arg.isAntiquotSuffixSplice || arg.isAntiquotSplice) then throwErrorAt arg "invalid auto tactic, antiquotation is not allowed" else let quotedArg ← quoteAutoTactic arg quotedArgs ← `(Array.push $quotedArgs $quotedArg) `(Syntax.node $(quote k) $quotedArgs) | Syntax.atom info val => `(mkAtom $(quote val)) | Syntax.missing => unreachable! def declareTacticSyntax (tactic : Syntax) : TermElabM Name := withFreshMacroScope do let name ← MonadQuotation.addMacroScope `_auto let type := Lean.mkConst `Lean.Syntax let tactic ← quoteAutoTactic tactic let val ← elabTerm tactic type let val ← instantiateMVars val trace[Elab.autoParam] val let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := val, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } addDecl decl compileDecl decl return name /- Expand `optional (binderTactic <|> binderDefault)` def binderTactic := leading_parser " := " >> " by " >> tacticParser def binderDefault := leading_parser " := " >> termParser -/ private def expandBinderModifier (type : Syntax) (optBinderModifier : Syntax) : TermElabM Syntax := do if optBinderModifier.isNone then return type else let modifier := optBinderModifier[0] let kind := modifier.getKind if kind == `Lean.Parser.Term.binderDefault then let defaultVal := modifier[1] `(optParam $type $defaultVal) else if kind == `Lean.Parser.Term.binderTactic then let tac := modifier[2] let name ← declareTacticSyntax tac `(autoParam $type $(mkIdentFrom tac name)) else throwUnsupportedSyntax private def getBinderIds (ids : Syntax) : TermElabM (Array Syntax) := ids.getArgs.mapM fun id => let k := id.getKind if k == identKind || k == `Lean.Parser.Term.hole then return id else throwErrorAt id "identifier or `_` expected" /- Recall that ``` def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec ``` -/ def expandOptType (ref : Syntax) (optType : Syntax) : Syntax := if optType.isNone then mkHole ref else optType[0][1] private def matchBinder (stx : Syntax) : TermElabM (Array BinderView) := do let k := stx.getKind if k == `Lean.Parser.Term.simpleBinder then -- binderIdent+ >> optType let ids ← getBinderIds stx[0] let type := expandOptType stx stx[1] ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.default } else if k == `Lean.Parser.Term.explicitBinder then -- `(` binderIdent+ binderType (binderDefault <|> binderTactic)? `)` let ids ← getBinderIds stx[1] let type := expandBinderType stx stx[2] let optModifier := stx[3] let type ← expandBinderModifier type optModifier ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.default } else if k == `Lean.Parser.Term.implicitBinder then -- `{` binderIdent+ binderType `}` let ids ← getBinderIds stx[1] let type := expandBinderType stx stx[2] ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.implicit } else if k == `Lean.Parser.Term.instBinder then -- `[` optIdent type `]` let id ← expandOptIdent stx[1] let type := stx[2] pure #[ { id := id, type := type, bi := BinderInfo.instImplicit } ] else throwUnsupportedSyntax private def registerFailedToInferBinderTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer binder type" private def addLocalVarInfoCore (lctx : LocalContext) (stx : Syntax) (fvar : Expr) : TermElabM Unit := do if (← getInfoState).enabled then pushInfoTree <| InfoTree.node (children := {}) <| Info.ofTermInfo { lctx := lctx, expr := fvar, stx := stx } private def addLocalVarInfo (stx : Syntax) (fvar : Expr) : TermElabM Unit := do addLocalVarInfoCore (← getLCtx) stx fvar private def ensureAtomicBinderName (binderView : BinderView) : TermElabM Unit := let n := binderView.id.getId.eraseMacroScopes unless n.isAtomic do throwErrorAt binderView.id "invalid binder name '{n}', it must be atomic" private partial def elabBinderViews {α} (binderViews : Array BinderView) (fvars : Array Expr) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α := do if h : i < binderViews.size then let binderView := binderViews.get ⟨i, h⟩ ensureAtomicBinderName binderView let type ← elabType binderView.type registerFailedToInferBinderTypeInfo type binderView.type withLocalDecl binderView.id.getId binderView.bi type fun fvar => do addLocalVarInfo binderView.id fvar loop (i+1) (fvars.push fvar) else k fvars loop 0 fvars private partial def elabBindersAux {α} (binders : Array Syntax) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α := do if h : i < binders.size then let binderViews ← matchBinder (binders.get ⟨i, h⟩) elabBinderViews binderViews fvars <| loop (i+1) else k fvars loop 0 #[] /-- Elaborate the given binders (i.e., `Syntax` objects for `simpleBinder <|> bracketedBinder`), update the local context, set of local instances, reset instance chache (if needed), and then execute `x` with the updated context. -/ def elabBinders {α} (binders : Array Syntax) (k : Array Expr → TermElabM α) : TermElabM α := withoutPostponingUniverseConstraints do if binders.isEmpty then k #[] else elabBindersAux binders k @[inline] def elabBinder {α} (binder : Syntax) (x : Expr → TermElabM α) : TermElabM α := elabBinders #[binder] fun fvars => x fvars[0] @[builtinTermElab «forall»] def elabForall : TermElab := fun stx _ => match stx with | `(forall $binders*, $term) => elabBinders binders fun xs => do let e ← elabType term mkForallFVars xs e | _ => throwUnsupportedSyntax @[builtinTermElab arrow] def elabArrow : TermElab := adaptExpander fun stx => match stx with | `($dom:term -> $rng) => `(forall (a : $dom), $rng) | _ => throwUnsupportedSyntax @[builtinTermElab depArrow] def elabDepArrow : TermElab := fun stx _ => -- bracketedBinder `->` term let binder := stx[0] let term := stx[2] elabBinders #[binder] fun xs => do mkForallFVars xs (← elabType term) /-- Auxiliary functions for converting `id_1 ... id_n` application into `#[id_1, ..., id_m]` It is used at `expandFunBinders`. -/ private partial def getFunBinderIds? (stx : Syntax) : OptionT TermElabM (Array Syntax) := let convertElem (stx : Syntax) : OptionT TermElabM Syntax := match stx with | `(_) => do let ident ← mkFreshIdent stx; pure ident | `($id:ident) => return id | _ => failure match stx with | `($f $args*) => do let mut acc := #[].push (← convertElem f) for arg in args do acc := acc.push (← convertElem arg) return acc | _ => return #[].push (← convertElem stx) /-- Auxiliary function for expanding `fun` notation binders. Recall that `fun` parser is defined as ``` def funBinder : Parser := implicitBinder <|> instBinder <|> termParser maxPrec leading_parser unicodeSymbol "λ" "fun" >> many1 funBinder >> "=>" >> termParser ``` to allow notation such as `fun (a, b) => a + b`, where `(a, b)` should be treated as a pattern. The result is a pair `(explicitBinders, newBody)`, where `explicitBinders` is syntax of the form ``` `(` ident `:` term `)` ``` which can be elaborated using `elabBinders`, and `newBody` is the updated `body` syntax. We update the `body` syntax when expanding the pattern notation. Example: `fun (a, b) => a + b` expands into `fun _a_1 => match _a_1 with | (a, b) => a + b`. See local function `processAsPattern` at `expandFunBindersAux`. The resulting `Bool` is true if a pattern was found. We use it "mark" a macro expansion. -/ partial def expandFunBinders (binders : Array Syntax) (body : Syntax) : TermElabM (Array Syntax × Syntax × Bool) := let rec loop (body : Syntax) (i : Nat) (newBinders : Array Syntax) := do if h : i < binders.size then let binder := binders.get ⟨i, h⟩ let processAsPattern : Unit → TermElabM (Array Syntax × Syntax × Bool) := fun _ => do let pattern := binder let major ← mkFreshIdent binder let (binders, newBody, _) ← loop body (i+1) (newBinders.push $ mkExplicitBinder major (mkHole binder)) let newBody ← `(match $major:ident with | $pattern => $newBody) pure (binders, newBody, true) match binder with | Syntax.node `Lean.Parser.Term.implicitBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.instBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.explicitBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.simpleBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.hole _ => let ident ← mkFreshIdent binder let type := binder loop body (i+1) (newBinders.push <| mkExplicitBinder ident type) | Syntax.node `Lean.Parser.Term.paren args => -- `(` (termParser >> parenSpecial)? `)` -- parenSpecial := (tupleTail <|> typeAscription)? let binderBody := binder[1] if binderBody.isNone then processAsPattern () else let idents := binderBody[0] let special := binderBody[1] if special.isNone then processAsPattern () else if special[0].getKind != `Lean.Parser.Term.typeAscription then processAsPattern () else -- typeAscription := `:` term let type := special[0][1] match (← getFunBinderIds? idents) with | some idents => loop body (i+1) (newBinders ++ idents.map (fun ident => mkExplicitBinder ident type)) | none => processAsPattern () | Syntax.ident .. => let type := mkHole binder loop body (i+1) (newBinders.push <| mkExplicitBinder binder type) | _ => processAsPattern () else pure (newBinders, body, false) loop body 0 #[] namespace FunBinders structure State where fvars : Array Expr := #[] lctx : LocalContext localInsts : LocalInstances expectedType? : Option Expr := none private def propagateExpectedType (fvar : Expr) (fvarType : Expr) (s : State) : TermElabM State := do match s.expectedType? with | none => pure s | some expectedType => let expectedType ← whnfForall expectedType match expectedType with | Expr.forallE _ d b _ => discard <| isDefEq fvarType d let b := b.instantiate1 fvar pure { s with expectedType? := some b } | _ => pure { s with expectedType? := none } private partial def elabFunBinderViews (binderViews : Array BinderView) (i : Nat) (s : State) : TermElabM State := do if h : i < binderViews.size then let binderView := binderViews.get ⟨i, h⟩ ensureAtomicBinderName binderView withRef binderView.type <| withLCtx s.lctx s.localInsts do let type ← elabType binderView.type registerFailedToInferBinderTypeInfo type binderView.type let fvarId ← mkFreshFVarId let fvar := mkFVar fvarId let s := { s with fvars := s.fvars.push fvar } -- dbgTrace (toString binderView.id.getId ++ " : " ++ toString type) /- We do **not** want to support default and auto arguments in lambda abstractions. Example: `fun (x : Nat := 10) => x+1`. We do not believe this is an useful feature, and it would complicate the logic here. -/ let lctx := s.lctx.mkLocalDecl fvarId binderView.id.getId type binderView.bi addLocalVarInfoCore lctx binderView.id fvar let s ← withRef binderView.id <| propagateExpectedType fvar type s let s := { s with lctx := lctx } match (← isClass? type) with | none => elabFunBinderViews binderViews (i+1) s | some className => resettingSynthInstanceCache do let localInsts := s.localInsts.push { className := className, fvar := mkFVar fvarId } elabFunBinderViews binderViews (i+1) { s with localInsts := localInsts } else pure s partial def elabFunBindersAux (binders : Array Syntax) (i : Nat) (s : State) : TermElabM State := do if h : i < binders.size then let binderViews ← matchBinder (binders.get ⟨i, h⟩) let s ← elabFunBinderViews binderViews 0 s elabFunBindersAux binders (i+1) s else pure s end FunBinders def elabFunBinders {α} (binders : Array Syntax) (expectedType? : Option Expr) (x : Array Expr → Option Expr → TermElabM α) : TermElabM α := if binders.isEmpty then x #[] expectedType? else do let lctx ← getLCtx let localInsts ← getLocalInstances let s ← FunBinders.elabFunBindersAux binders 0 { lctx := lctx, localInsts := localInsts, expectedType? := expectedType? } resettingSynthInstanceCacheWhen (s.localInsts.size > localInsts.size) <| withLCtx s.lctx s.localInsts <| x s.fvars s.expectedType? /- Helper function for `expandEqnsIntoMatch` -/ private def getMatchAltsNumPatterns (matchAlts : Syntax) : Nat := let alt0 := matchAlts[0][0] let pats := alt0[1].getSepArgs pats.size def expandWhereDecls (whereDecls : Syntax) (body : Syntax) : MacroM Syntax := match whereDecls with | `(whereDecls|where $[$decls:letRecDecl $[;]?]*) => `(let rec $decls:letRecDecl,*; $body) | _ => Macro.throwUnsupported def expandWhereDeclsOpt (whereDeclsOpt : Syntax) (body : Syntax) : MacroM Syntax := if whereDeclsOpt.isNone then body else expandWhereDecls whereDeclsOpt[0] body /- Helper function for `expandMatchAltsIntoMatch` -/ private def expandMatchAltsIntoMatchAux (matchAlts : Syntax) (matchTactic : Bool) : Nat → Array Syntax → MacroM Syntax | 0, discrs => do if matchTactic then `(tactic|match $[$discrs:term],* with $matchAlts:matchAlts) else `(match $[$discrs:term],* with $matchAlts:matchAlts) | n+1, discrs => withFreshMacroScope do let x ← `(x) let d ← `(@$x:ident) -- See comment below let body ← expandMatchAltsIntoMatchAux matchAlts matchTactic n (discrs.push d) if matchTactic then `(tactic| intro $x:term; $body:tactic) else `(@fun $x => $body) /-- Expand `matchAlts` syntax into a full `match`-expression. Example ``` | 0, true => alt_1 | i, _ => alt_2 ``` expands into (for tactic == false) ``` fun x_1 x_2 => match @x_1, @x_2 with | 0, true => alt_1 | i, _ => alt_2 ``` and (for tactic == true) ``` intro x_1; intro x_2; match @x_1, @x_2 with | 0, true => alt_1 | i, _ => alt_2 ``` Remark: we add `@` to make sure we don't consume implicit arguments, and to make the behavior consistent with `fun`. Example: ``` inductive T : Type 1 := | mkT : (forall {a : Type}, a -> a) -> T def makeT (f : forall {a : Type}, a -> a) : T := mkT f def makeT' : (forall {a : Type}, a -> a) -> T | f => mkT f ``` The two definitions should be elaborated without errors and be equivalent. -/ def expandMatchAltsIntoMatch (ref : Syntax) (matchAlts : Syntax) (tactic := false) : MacroM Syntax := withRef ref <| expandMatchAltsIntoMatchAux matchAlts tactic (getMatchAltsNumPatterns matchAlts) #[] def expandMatchAltsIntoMatchTactic (ref : Syntax) (matchAlts : Syntax) : MacroM Syntax := withRef ref <| expandMatchAltsIntoMatchAux matchAlts true (getMatchAltsNumPatterns matchAlts) #[] /-- Similar to `expandMatchAltsIntoMatch`, but supports an optional `where` clause. Expand `matchAltsWhereDecls` into `let rec` + `match`-expression. Example ``` | 0, true => ... f 0 ... | i, _ => ... f i + g i ... where f x := g x + 1 g : Nat → Nat | 0 => 1 | x+1 => f x ``` expands into ``` fux x_1 x_2 => let rec f x := g x + 1, g : Nat → Nat | 0 => 1 | x+1 => f x match x_1, x_2 with | 0, true => ... f 0 ... | i, _ => ... f i + g i ... ``` -/ def expandMatchAltsWhereDecls (matchAltsWhereDecls : Syntax) : MacroM Syntax := let matchAlts := matchAltsWhereDecls[0] let whereDeclsOpt := matchAltsWhereDecls[1] let rec loop (i : Nat) (discrs : Array Syntax) : MacroM Syntax := match i with | 0 => do let matchStx ← `(match $[$discrs:term],* with $matchAlts:matchAlts) if whereDeclsOpt.isNone then return matchStx else expandWhereDeclsOpt whereDeclsOpt matchStx | n+1 => withFreshMacroScope do let x ← `(x) let d ← `(@$x:ident) -- See comment at `expandMatchAltsIntoMatch` let body ← loop n (discrs.push d) `(@fun $x => $body) loop (getMatchAltsNumPatterns matchAlts) #[] @[builtinTermElab «fun»] partial def elabFun : TermElab := fun stx expectedType? => loop stx expectedType? where loop (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := match stx with | `(fun $binders* => $body) => do let (binders, body, expandedPattern) ← expandFunBinders binders body if expandedPattern then let newStx ← `(fun $binders* => $body) loop newStx expectedType? else elabFunBinders binders expectedType? fun xs expectedType? => do /- We ensure the expectedType here since it will force coercions to be applied if needed. If we just use `elabTerm`, then we will need to a coercion `Coe (α → β) (α → δ)` whenever there is a coercion `Coe β δ`, and another instance for the dependent version. -/ let e ← elabTermEnsuringType body expectedType? mkLambdaFVars xs e | `(fun $m:matchAlts) => do let stxNew ← liftMacroM $ expandMatchAltsIntoMatch stx m withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? | _ => throwUnsupportedSyntax /- If `useLetExpr` is true, then a kernel let-expression `let x : type := val; body` is created. Otherwise, we create a term of the form `(fun (x : type) => body) val` The default elaboration order is `binders`, `typeStx`, `valStx`, and `body`. If `elabBodyFirst == true`, then we use the order `binders`, `typeStx`, `body`, and `valStx`. -/ def elabLetDeclAux (id : Syntax) (binders : Array Syntax) (typeStx : Syntax) (valStx : Syntax) (body : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) : TermElabM Expr := do let (type, val, arity) ← elabBinders binders fun xs => do let type ← elabType typeStx registerCustomErrorIfMVar type typeStx "failed to infer 'let' declaration type" if elabBodyFirst then let type ← mkForallFVars xs type let val ← mkFreshExprMVar type pure (type, val, xs.size) else let val ← elabTermEnsuringType valStx type let type ← mkForallFVars xs type let val ← mkLambdaFVars xs val pure (type, val, xs.size) trace[Elab.let.decl] "{id.getId} : {type} := {val}" let result ← if useLetExpr then withLetDecl id.getId type val fun x => do addLocalVarInfo id x let body ← elabTerm body expectedType? let body ← instantiateMVars body mkLetFVars #[x] body else let f ← withLocalDecl id.getId BinderInfo.default type fun x => do addLocalVarInfo id x let body ← elabTerm body expectedType? let body ← instantiateMVars body mkLambdaFVars #[x] body pure <| mkApp f val if elabBodyFirst then forallBoundedTelescope type arity fun xs type => do let valResult ← elabTermEnsuringType valStx type let valResult ← mkLambdaFVars xs valResult unless (← isDefEq val valResult) do throwError "unexpected error when elaborating 'let'" pure result structure LetIdDeclView where id : Syntax binders : Array Syntax type : Syntax value : Syntax def mkLetIdDeclView (letIdDecl : Syntax) : LetIdDeclView := -- `letIdDecl` is of the form `ident >> many bracketedBinder >> optType >> " := " >> termParser let id := letIdDecl[0] let binders := letIdDecl[1].getArgs let optType := letIdDecl[2] let type := expandOptType letIdDecl optType let value := letIdDecl[4] { id := id, binders := binders, type := type, value := value } def expandLetEqnsDecl (letDecl : Syntax) : MacroM Syntax := do let ref := letDecl let matchAlts := letDecl[3] let val ← expandMatchAltsIntoMatch ref matchAlts return Syntax.node `Lean.Parser.Term.letIdDecl #[letDecl[0], letDecl[1], letDecl[2], mkAtomFrom ref " := ", val] def elabLetDeclCore (stx : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) : TermElabM Expr := do let ref := stx let letDecl := stx[1][0] let body := stx[3] if letDecl.getKind == `Lean.Parser.Term.letIdDecl then let { id := id, binders := binders, type := type, value := val } := mkLetIdDeclView letDecl elabLetDeclAux id binders type val body expectedType? useLetExpr elabBodyFirst else if letDecl.getKind == `Lean.Parser.Term.letPatDecl then -- node `Lean.Parser.Term.letPatDecl $ try (termParser >> pushNone >> optType >> " := ") >> termParser let pat := letDecl[0] let optType := letDecl[2] let type := expandOptType stx optType let val := letDecl[4] let stxNew ← `(let x : $type := $val; match x with | $pat => $body) let stxNew := match useLetExpr, elabBodyFirst with | true, false => stxNew | true, true => stxNew.setKind `Lean.Parser.Term.«let_delayed» | false, true => stxNew.setKind `Lean.Parser.Term.«let_fun» | false, false => unreachable! withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? else if letDecl.getKind == `Lean.Parser.Term.letEqnsDecl then let letDeclIdNew ← liftMacroM <| expandLetEqnsDecl letDecl let declNew := stx[1].setArg 0 letDeclIdNew let stxNew := stx.setArg 1 declNew withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? else throwUnsupportedSyntax @[builtinTermElab «let»] def elabLetDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? true false @[builtinTermElab «let_fun»] def elabLetFunDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? false false @[builtinTermElab «let_delayed»] def elabLetDelayedDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? true true builtin_initialize registerTraceClass `Elab.let end Lean.Elab.Term
556ca5e126671088647da0f9bf8c766736ae779d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/polynomial/homogeneous_auto.lean
1becd57854271bef084edee3775e96ba4d2e1467
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,604
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.mv_polynomial.default import Mathlib.data.fintype.card import Mathlib.PostPort universes u_1 u_3 u_2 namespace Mathlib /-! # Homogeneous polynomials A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. ## Main definitions/lemmas * `is_homogeneous φ n`: a predicate that asserts that `φ` is homogeneous of degree `n`. * `homogeneous_component n`: the additive morphism that projects polynomials onto their summand that is homogeneous of degree `n`. * `sum_homogeneous_component`: every polynomial is the sum of its homogeneous components -/ namespace mv_polynomial /- TODO * create definition for `∑ i in d.support, d i` * define graded rings, and show that mv_polynomial is an example -/ /-- A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. -/ def is_homogeneous {σ : Type u_1} {R : Type u_3} [comm_semiring R] (φ : mv_polynomial σ R) (n : ℕ) := ∀ {d : σ →₀ ℕ}, coeff d φ ≠ 0 → (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n theorem is_homogeneous_monomial {σ : Type u_1} {R : Type u_3} [comm_semiring R] (d : σ →₀ ℕ) (r : R) (n : ℕ) (hn : (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n) : is_homogeneous (monomial d r) n := sorry theorem is_homogeneous_C (σ : Type u_1) {R : Type u_3} [comm_semiring R] (r : R) : is_homogeneous (coe_fn C r) 0 := sorry theorem is_homogeneous_zero (σ : Type u_1) (R : Type u_3) [comm_semiring R] (n : ℕ) : is_homogeneous 0 n := fun (d : σ →₀ ℕ) (hd : coeff d 0 ≠ 0) => false.elim (hd (coeff_zero d)) theorem is_homogeneous_one (σ : Type u_1) (R : Type u_3) [comm_semiring R] : is_homogeneous 1 0 := is_homogeneous_C σ 1 theorem is_homogeneous_X {σ : Type u_1} (R : Type u_3) [comm_semiring R] (i : σ) : is_homogeneous (X i) 1 := sorry namespace is_homogeneous theorem coeff_eq_zero {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {n : ℕ} (hφ : is_homogeneous φ n) (d : σ →₀ ℕ) (hd : (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) ≠ n) : coeff d φ = 0 := eq.mp (Eq._oldrec (Eq.refl (¬coeff d φ ≠ 0)) (propext not_not)) (mt hφ hd) theorem inj_right {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {m : ℕ} {n : ℕ} (hm : is_homogeneous φ m) (hn : is_homogeneous φ n) (hφ : φ ≠ 0) : m = n := sorry theorem add {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {ψ : mv_polynomial σ R} {n : ℕ} (hφ : is_homogeneous φ n) (hψ : is_homogeneous ψ n) : is_homogeneous (φ + ψ) n := sorry theorem sum {σ : Type u_1} {R : Type u_3} [comm_semiring R] {ι : Type u_2} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ℕ) (h : ∀ (i : ι), i ∈ s → is_homogeneous (φ i) n) : is_homogeneous (finset.sum s fun (i : ι) => φ i) n := sorry theorem mul {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {ψ : mv_polynomial σ R} {m : ℕ} {n : ℕ} (hφ : is_homogeneous φ m) (hψ : is_homogeneous ψ n) : is_homogeneous (φ * ψ) (m + n) := sorry theorem prod {σ : Type u_1} {R : Type u_3} [comm_semiring R] {ι : Type u_2} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ι → ℕ) (h : ∀ (i : ι), i ∈ s → is_homogeneous (φ i) (n i)) : is_homogeneous (finset.prod s fun (i : ι) => φ i) (finset.sum s fun (i : ι) => n i) := sorry theorem total_degree {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {n : ℕ} (hφ : is_homogeneous φ n) (h : φ ≠ 0) : total_degree φ = n := sorry end is_homogeneous /-- `homogeneous_component n φ` is the part of `φ` that is homogeneous of degree `n`. See `sum_homogeneous_component` for the statement that `φ` is equal to the sum of all its homogeneous components. -/ def homogeneous_component {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) : linear_map R (mv_polynomial σ R) (mv_polynomial σ R) := linear_map.comp (submodule.subtype (finsupp.supported R R (set_of fun (d : σ →₀ ℕ) => (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n))) (finsupp.restrict_dom R R (set_of fun (d : σ →₀ ℕ) => (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n)) theorem coeff_homogeneous_component {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) (d : σ →₀ ℕ) : coeff d (coe_fn (homogeneous_component n) φ) = ite ((finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n) (coeff d φ) 0 := sorry theorem homogeneous_component_apply {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) : coe_fn (homogeneous_component n) φ = finset.sum (finset.filter (fun (d : σ →₀ ℕ) => (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n) (finsupp.support φ)) fun (d : σ →₀ ℕ) => monomial d (coeff d φ) := sorry theorem homogeneous_component_is_homogeneous {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) : is_homogeneous (coe_fn (homogeneous_component n) φ) n := sorry theorem homogeneous_component_zero {σ : Type u_1} {R : Type u_3} [comm_semiring R] (φ : mv_polynomial σ R) : coe_fn (homogeneous_component 0) φ = coe_fn C (coeff 0 φ) := sorry theorem homogeneous_component_eq_zero' {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) (h : ∀ (d : σ →₀ ℕ), d ∈ finsupp.support φ → (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) ≠ n) : coe_fn (homogeneous_component n) φ = 0 := sorry theorem homogeneous_component_eq_zero {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) (h : total_degree φ < n) : coe_fn (homogeneous_component n) φ = 0 := sorry theorem sum_homogeneous_component {σ : Type u_1} {R : Type u_3} [comm_semiring R] (φ : mv_polynomial σ R) : (finset.sum (finset.range (total_degree φ + 1)) fun (i : ℕ) => coe_fn (homogeneous_component i) φ) = φ := sorry end Mathlib
6f548cfbda36389ea0ea243c505f5220e7295a99
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/euclidean_domain.lean
3d7cddcfacd3fdafbdda701cd43cf14f27f6d562
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
14,079
lean
/- Copyright (c) 2018 Louis Carlin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Louis Carlin, Mario Carneiro Euclidean domains and Euclidean algorithm (extended to come) A lot is based on pre-existing code in mathlib for natural number gcds -/ import data.int.basic import algebra.field universe u section prio set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true @[protect_proj without mul_left_not_lt r_well_founded] class euclidean_domain (α : Type u) extends comm_ring α, nontrivial α := (quotient : α → α → α) (quotient_zero : ∀ a, quotient a 0 = 0) (remainder : α → α → α) -- This could be changed to the same order as int.mod_add_div. -- We normally write qb+r rather than r + qb though. (quotient_mul_add_remainder_eq : ∀ a b, b * quotient a b + remainder a b = a) (r : α → α → Prop) (r_well_founded : well_founded r) (remainder_lt : ∀ a {b}, b ≠ 0 → r (remainder a b) b) /- `val_le_mul_left` is often not a required in definitions of a euclidean domain since given the other properties we can show there is a (noncomputable) euclidean domain α with the property `val_le_mul_left`. So potentially this definition could be split into two different ones (euclidean_domain_weak and euclidean_domain_strong) with a noncomputable function from weak to strong. I've currently divided the lemmas into strong and weak depending on whether they require `val_le_mul_left` or not. -/ (mul_left_not_lt : ∀ a {b}, b ≠ 0 → ¬r (a * b) a) end prio namespace euclidean_domain variable {α : Type u} variables [euclidean_domain α] local infix ` ≺ `:50 := euclidean_domain.r @[priority 70] -- see Note [lower instance priority] instance : has_div α := ⟨euclidean_domain.quotient⟩ @[priority 70] -- see Note [lower instance priority] instance : has_mod α := ⟨euclidean_domain.remainder⟩ theorem div_add_mod (a b : α) : b * (a / b) + a % b = a := euclidean_domain.quotient_mul_add_remainder_eq _ _ lemma mod_eq_sub_mul_div {α : Type*} [euclidean_domain α] (a b : α) : a % b = a - b * (a / b) := calc a % b = b * (a / b) + a % b - b * (a / b) : (add_sub_cancel' _ _).symm ... = a - b * (a / b) : by rw div_add_mod theorem mod_lt : ∀ a {b : α}, b ≠ 0 → (a % b) ≺ b := euclidean_domain.remainder_lt theorem mul_right_not_lt {a : α} (b) (h : a ≠ 0) : ¬(a * b) ≺ b := by rw mul_comm; exact mul_left_not_lt b h lemma mul_div_cancel_left {a : α} (b) (a0 : a ≠ 0) : a * b / a = b := eq.symm $ eq_of_sub_eq_zero $ classical.by_contradiction $ λ h, begin have := mul_left_not_lt a h, rw [mul_sub, sub_eq_iff_eq_add'.2 (div_add_mod (a*b) a).symm] at this, exact this (mod_lt _ a0) end lemma mul_div_cancel (a) {b : α} (b0 : b ≠ 0) : a * b / b = a := by rw mul_comm; exact mul_div_cancel_left a b0 @[simp] lemma mod_zero (a : α) : a % 0 = a := by simpa only [zero_mul, zero_add] using div_add_mod a 0 @[simp] lemma mod_eq_zero {a b : α} : a % b = 0 ↔ b ∣ a := ⟨λ h, by rw [← div_add_mod a b, h, add_zero]; exact dvd_mul_right _ _, λ ⟨c, e⟩, begin rw [e, ← add_left_cancel_iff, div_add_mod, add_zero], haveI := classical.dec, by_cases b0 : b = 0, { simp only [b0, zero_mul] }, { rw [mul_div_cancel_left _ b0] } end⟩ @[simp] lemma mod_self (a : α) : a % a = 0 := mod_eq_zero.2 (dvd_refl _) lemma dvd_mod_iff {a b c : α} (h : c ∣ b) : c ∣ a % b ↔ c ∣ a := by rw [dvd_add_iff_right (dvd_mul_of_dvd_left h _), div_add_mod] lemma lt_one (a : α) : a ≺ (1:α) → a = 0 := by haveI := classical.dec; exact not_imp_not.1 (λ h, by simpa only [one_mul] using mul_left_not_lt 1 h) lemma val_dvd_le : ∀ a b : α, b ∣ a → a ≠ 0 → ¬a ≺ b | _ b ⟨d, rfl⟩ ha := mul_left_not_lt b (mt (by rintro rfl; exact mul_zero _) ha) @[simp] lemma mod_one (a : α) : a % 1 = 0 := mod_eq_zero.2 (one_dvd _) @[simp] lemma zero_mod (b : α) : 0 % b = 0 := mod_eq_zero.2 (dvd_zero _) @[simp] lemma div_zero (a : α) : a / 0 = 0 := euclidean_domain.quotient_zero a @[simp] lemma zero_div {a : α} : 0 / a = 0 := classical.by_cases (λ a0 : a = 0, a0.symm ▸ div_zero 0) (λ a0, by simpa only [zero_mul] using mul_div_cancel 0 a0) @[simp] lemma div_self {a : α} (a0 : a ≠ 0) : a / a = 1 := by simpa only [one_mul] using mul_div_cancel 1 a0 lemma eq_div_of_mul_eq_left {a b c : α} (hb : b ≠ 0) (h : a * b = c) : a = c / b := by rw [← h, mul_div_cancel _ hb] lemma eq_div_of_mul_eq_right {a b c : α} (ha : a ≠ 0) (h : a * b = c) : b = c / a := by rw [← h, mul_div_cancel_left _ ha] theorem mul_div_assoc (x : α) {y z : α} (h : z ∣ y) : x * y / z = x * (y / z) := begin classical, by_cases hz : z = 0, { subst hz, rw [div_zero, div_zero, mul_zero] }, rcases h with ⟨p, rfl⟩, rw [mul_div_cancel_left _ hz, mul_left_comm, mul_div_cancel_left _ hz] end section open_locale classical @[elab_as_eliminator] theorem gcd.induction {P : α → α → Prop} : ∀ a b : α, (∀ x, P 0 x) → (∀ a b, a ≠ 0 → P (b % a) a → P a b) → P a b | a := λ b H0 H1, if a0 : a = 0 then by rw [a0]; apply H0 else have h:_ := mod_lt b a0, H1 _ _ a0 (gcd.induction (b%a) a H0 H1) using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} end section gcd variable [decidable_eq α] def gcd : α → α → α | a := λ b, if a0 : a = 0 then b else have h:_ := mod_lt b a0, gcd (b%a) a using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} @[simp] theorem gcd_zero_left (a : α) : gcd 0 a = a := by rw gcd; exact if_pos rfl @[simp] theorem gcd_zero_right (a : α) : gcd a 0 = a := by rw gcd; split_ifs; simp only [h, zero_mod, gcd_zero_left] theorem gcd_val (a b : α) : gcd a b = gcd (b % a) a := by rw gcd; split_ifs; [simp only [h, mod_zero, gcd_zero_right], refl] theorem gcd_dvd (a b : α) : gcd a b ∣ a ∧ gcd a b ∣ b := gcd.induction a b (λ b, by rw [gcd_zero_left]; exact ⟨dvd_zero _, dvd_refl _⟩) (λ a b aneq ⟨IH₁, IH₂⟩, by rw gcd_val; exact ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩) theorem gcd_dvd_left (a b : α) : gcd a b ∣ a := (gcd_dvd a b).left theorem gcd_dvd_right (a b : α) : gcd a b ∣ b := (gcd_dvd a b).right protected theorem gcd_eq_zero_iff {a b : α} : gcd a b = 0 ↔ a = 0 ∧ b = 0 := ⟨λ h, by simpa [h] using gcd_dvd a b, by rintro ⟨rfl, rfl⟩; simp⟩ theorem dvd_gcd {a b c : α} : c ∣ a → c ∣ b → c ∣ gcd a b := gcd.induction a b (λ _ _ H, by simpa only [gcd_zero_left] using H) (λ a b a0 IH ca cb, by rw gcd_val; exact IH ((dvd_mod_iff ca).2 cb) ca) theorem gcd_eq_left {a b : α} : gcd a b = a ↔ a ∣ b := ⟨λ h, by rw ← h; apply gcd_dvd_right, λ h, by rw [gcd_val, mod_eq_zero.2 h, gcd_zero_left]⟩ @[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 := gcd_eq_left.2 (one_dvd _) @[simp] theorem gcd_self (a : α) : gcd a a = a := gcd_eq_left.2 (dvd_refl _) def xgcd_aux : α → α → α → α → α → α → α × α × α | r := λ s t r' s' t', if hr : r = 0 then (r', s', t') else have r' % r ≺ r, from mod_lt _ hr, let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} @[simp] theorem xgcd_zero_left {s t r' s' t' : α} : xgcd_aux 0 s t r' s' t' = (r', s', t') := by unfold xgcd_aux; exact if_pos rfl theorem xgcd_aux_rec {r s t r' s' t' : α} (h : r ≠ 0) : xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t := by conv {to_lhs, rw [xgcd_aux]}; exact if_neg h /-- Use the extended GCD algorithm to generate the `a` and `b` values satisfying `gcd x y = x * a + y * b`. -/ def xgcd (x y : α) : α × α := (xgcd_aux x 1 0 y 0 1).2 /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_a (x y : α) : α := (xgcd x y).1 /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_b (x y : α) : α := (xgcd x y).2 @[simp] theorem xgcd_aux_fst (x y : α) : ∀ s t s' t', (xgcd_aux x s t y s' t').1 = gcd x y := gcd.induction x y (by intros; rw [xgcd_zero_left, gcd_zero_left]) (λ x y h IH s t s' t', by simp only [xgcd_aux_rec h, if_neg h, IH]; rw ← gcd_val) 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, prod.mk.eta] theorem xgcd_val (x y : α) : xgcd x y = (gcd_a x y, gcd_b x y) := prod.mk.eta.symm private def P (a b : α) : α × α × α → Prop | (r, s, t) := (r : α) = a * s + b * t theorem xgcd_aux_P (a b : α) {r r' : α} : ∀ {s t s' t'}, P a b (r, s, t) → P a b (r', s', t') → P a b (xgcd_aux r s t r' s' t') := gcd.induction r r' (by intros; simpa only [xgcd_zero_left]) $ λ x y h IH s t s' t' p p', begin rw [xgcd_aux_rec h], refine IH _ p, unfold P at p p' ⊢, rw [mul_sub, mul_sub, add_sub, sub_add_eq_add_sub, ← p', sub_sub, mul_comm _ s, ← mul_assoc, mul_comm _ t, ← mul_assoc, ← add_mul, ← p, mod_eq_sub_mul_div] end theorem gcd_eq_gcd_ab (a b : α) : (gcd a b : α) = a * gcd_a a b + b * gcd_b a b := by have := @xgcd_aux_P _ _ _ a b a b 1 0 0 1 (by rw [P, mul_one, mul_zero, add_zero]) (by rw [P, mul_one, mul_zero, zero_add]); rwa [xgcd_aux_val, xgcd_val] at this @[priority 70] -- see Note [lower instance priority] instance (α : Type*) [e : euclidean_domain α] : integral_domain α := by haveI := classical.dec_eq α; exact { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, (or_iff_not_and_not.2 $ λ h0, h0.1 $ by rw [← mul_div_cancel a h0.2, h, zero_div]), zero := 0, add := (+), mul := (*), ..e } end gcd section lcm variables [decidable_eq α] def lcm (x y : α) : α := x * y / gcd x y theorem dvd_lcm_left (x y : α) : x ∣ lcm x y := classical.by_cases (assume hxy : gcd x y = 0, by rw [lcm, hxy, div_zero]; exact dvd_zero _) (λ hxy, let ⟨z, hz⟩ := (gcd_dvd x y).2 in ⟨z, eq.symm $ eq_div_of_mul_eq_left hxy $ by rw [mul_right_comm, mul_assoc, ← hz]⟩) theorem dvd_lcm_right (x y : α) : y ∣ lcm x y := classical.by_cases (assume hxy : gcd x y = 0, by rw [lcm, hxy, div_zero]; exact dvd_zero _) (λ hxy, let ⟨z, hz⟩ := (gcd_dvd x y).1 in ⟨z, eq.symm $ eq_div_of_mul_eq_right hxy $ by rw [← mul_assoc, mul_right_comm, ← hz]⟩) theorem lcm_dvd {x y z : α} (hxz : x ∣ z) (hyz : y ∣ z) : lcm x y ∣ z := begin rw lcm, by_cases hxy : gcd x y = 0, { rw [hxy, div_zero], rw euclidean_domain.gcd_eq_zero_iff at hxy, rwa hxy.1 at hxz }, rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, suffices : x * y ∣ z * gcd x y, { cases this with p hp, use p, generalize_hyp : gcd x y = g at hxy hs hp ⊢, subst hs, rw [mul_left_comm, mul_div_cancel_left _ hxy, ← mul_left_inj' hxy, hp], rw [← mul_assoc], simp only [mul_right_comm] }, rw [gcd_eq_gcd_ab, mul_add], apply dvd_add, { rw mul_left_comm, exact mul_dvd_mul_left _ (dvd_mul_of_dvd_left hyz _) }, { rw [mul_left_comm, mul_comm], exact mul_dvd_mul_left _ (dvd_mul_of_dvd_left hxz _) } end @[simp] lemma lcm_dvd_iff {x y z : α} : lcm x y ∣ z ↔ x ∣ z ∧ y ∣ z := ⟨λ hz, ⟨dvd_trans (dvd_lcm_left _ _) hz, dvd_trans (dvd_lcm_right _ _) hz⟩, λ ⟨hxz, hyz⟩, lcm_dvd hxz hyz⟩ @[simp] lemma lcm_zero_left (x : α) : lcm 0 x = 0 := by rw [lcm, zero_mul, zero_div] @[simp] lemma lcm_zero_right (x : α) : lcm x 0 = 0 := by rw [lcm, mul_zero, zero_div] @[simp] lemma lcm_eq_zero_iff {x y : α} : lcm x y = 0 ↔ x = 0 ∨ y = 0 := begin split, { intro hxy, rw [lcm, mul_div_assoc _ (gcd_dvd_right _ _), mul_eq_zero] at hxy, apply or_of_or_of_imp_right hxy, intro hy, by_cases hgxy : gcd x y = 0, { rw euclidean_domain.gcd_eq_zero_iff at hgxy, exact hgxy.2 }, { rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, generalize_hyp : gcd x y = g at hr hs hy hgxy ⊢, subst hs, rw [mul_div_cancel_left _ hgxy] at hy, rw [hy, mul_zero] } }, rintro (hx | hy), { rw [hx, lcm_zero_left] }, { rw [hy, lcm_zero_right] } end @[simp] lemma gcd_mul_lcm (x y : α) : gcd x y * lcm x y = x * y := begin rw lcm, by_cases h : gcd x y = 0, { rw [h, zero_mul], rw euclidean_domain.gcd_eq_zero_iff at h, rw [h.1, zero_mul] }, rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, generalize_hyp : gcd x y = g at h hr ⊢, subst hr, rw [mul_assoc, mul_div_cancel_left _ h] end end lcm end euclidean_domain instance int.euclidean_domain : euclidean_domain ℤ := { add := (+), mul := (*), one := 1, zero := 0, neg := has_neg.neg, quotient := (/), quotient_zero := int.div_zero, remainder := (%), quotient_mul_add_remainder_eq := λ a b, by rw add_comm; exact int.mod_add_div _ _, r := λ a b, a.nat_abs < b.nat_abs, r_well_founded := measure_wf (λ a, int.nat_abs a), remainder_lt := λ a b b0, int.coe_nat_lt.1 $ by rw [int.nat_abs_of_nonneg (int.mod_nonneg _ b0), ← int.abs_eq_nat_abs]; exact int.mod_lt _ b0, mul_left_not_lt := λ a b b0, not_lt_of_ge $ by rw [← mul_one a.nat_abs, int.nat_abs_mul]; exact mul_le_mul_of_nonneg_left (int.nat_abs_pos_of_ne_zero b0) (nat.zero_le _), .. int.comm_ring, .. int.nontrivial } @[priority 100] -- see Note [lower instance priority] instance field.to_euclidean_domain {K : Type u} [field K] : euclidean_domain K := { add := (+), mul := (*), one := 1, zero := 0, neg := has_neg.neg, quotient := (/), remainder := λ a b, a - a * b / b, quotient_zero := div_zero, quotient_mul_add_remainder_eq := λ a b, by classical; by_cases b = 0; simp [h, mul_div_cancel'], r := λ a b, a = 0 ∧ b ≠ 0, r_well_founded := well_founded.intro $ λ a, acc.intro _ $ λ b ⟨hb, hna⟩, acc.intro _ $ λ c ⟨hc, hnb⟩, false.elim $ hnb hb, remainder_lt := λ a b hnb, by simp [hnb], mul_left_not_lt := λ a b hnb ⟨hab, hna⟩, or.cases_on (mul_eq_zero.1 hab) hna hnb, .. ‹field K› }
2d4b0c3a24350954cf8e2545b2147d537c6c1dc2
b328e8ebb2ba923140e5137c83f09fa59516b793
/stage0/src/Lean/Meta/AppBuilder.lean
96c9f06c0f4b4bd0b62c1668bfd65d0263827890
[ "Apache-2.0" ]
permissive
DrMaxis/lean4
a781bcc095511687c56ab060e816fd948553e162
5a02c4facc0658aad627cfdcc3db203eac0cb544
refs/heads/master
1,677,051,517,055
1,611,876,226,000
1,611,876,226,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,438
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Structure import Lean.Util.Recognizers import Lean.Meta.SynthInstance import Lean.Meta.Check namespace Lean.Meta /-- Return `id e` -/ def mkId (e : Expr) : MetaM Expr := do let type ← inferType e let u ← getLevel type pure $ mkApp2 (mkConst ``id [u]) type e /-- Return `idRhs e` -/ def mkIdRhs (e : Expr) : MetaM Expr := do let type ← inferType e let u ← getLevel type pure $ mkApp2 (mkConst ``idRhs [u]) type e /-- Given `e` s.t. `inferType e` is definitionally equal to `expectedType`, return term `@id expectedType e`. -/ def mkExpectedTypeHint (e : Expr) (expectedType : Expr) : MetaM Expr := do let u ← getLevel expectedType pure $ mkApp2 (mkConst ``id [u]) expectedType e def mkEq (a b : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType pure $ mkApp3 (mkConst ``Eq [u]) aType a b def mkHEq (a b : Expr) : MetaM Expr := do let aType ← inferType a let bType ← inferType b let u ← getLevel aType pure $ mkApp4 (mkConst ``HEq [u]) aType a bType b def mkEqRefl (a : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType pure $ mkApp2 (mkConst ``Eq.refl [u]) aType a def mkHEqRefl (a : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType pure $ mkApp2 (mkConst ``HEq.refl [u]) aType a private def infer (h : Expr) : MetaM Expr := do let hType ← inferType h whnfD hType private def hasTypeMsg (e type : Expr) : MessageData := m!"{indentExpr e}\nhas type{indentExpr type}" private def throwAppBuilderException {α} (op : Name) (msg : MessageData) : MetaM α := throwError! "AppBuilder for '{op}', {msg}" def mkEqSymm (h : Expr) : MetaM Expr := if h.isAppOf ``Eq.refl then pure h else do let hType ← infer h match hType.eq? with | some (α, a, b) => do let u ← getLevel α; pure $ mkApp4 (mkConst ``Eq.symm [u]) α a b h | none => throwAppBuilderException ``Eq.symm ("equality proof expected" ++ hasTypeMsg h hType) def mkEqTrans (h₁ h₂ : Expr) : MetaM Expr := if h₁.isAppOf ``Eq.refl then pure h₂ else if h₂.isAppOf ``Eq.refl then pure h₁ else do let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.eq?, hType₂.eq? with | some (α, a, b), some (_, _, c) => do let u ← getLevel α; pure $ mkApp6 (mkConst ``Eq.trans [u]) α a b c h₁ h₂ | none, _ => throwAppBuilderException ``Eq.trans ("equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException ``Eq.trans ("equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkHEqSymm (h : Expr) : MetaM Expr := if h.isAppOf ``HEq.refl then pure h else do let hType ← infer h match hType.heq? with | some (α, a, β, b) => do let u ← getLevel α; pure $ mkApp5 (mkConst ``HEq.symm [u]) α β a b h | none => throwAppBuilderException ``HEq.symm ("heterogeneous equality proof expected" ++ hasTypeMsg h hType) def mkHEqTrans (h₁ h₂ : Expr) : MetaM Expr := do if h₁.isAppOf ``HEq.refl then pure h₂ else if h₂.isAppOf ``HEq.refl then pure h₁ else do let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.heq?, hType₂.heq? with | some (α, a, β, b), some (_, _, γ, c) => let u ← getLevel α; pure $ mkApp8 (mkConst ``HEq.trans [u]) α β γ a b c h₁ h₂ | none, _ => throwAppBuilderException ``HEq.trans ("heterogeneous equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException ``HEq.trans ("heterogeneous equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkEqOfHEq (h : Expr) : MetaM Expr := do let hType ← infer h match hType.heq? with | some (α, a, β, b) => unless (← isDefEq α β) do throwAppBuilderException ``eqOfHEq m!"heterogeneous equality types are not definitionally equal{indentExpr α}\nis not definitionally equal to{indentExpr β}" let u ← getLevel α pure $ mkApp4 (mkConst ``eqOfHEq [u]) α a b h | _ => throwAppBuilderException ``HEq.trans m!"heterogeneous equality proof expected{indentExpr h}" def mkCongrArg (f h : Expr) : MetaM Expr := do let hType ← infer h let fType ← infer f match fType.arrow?, hType.eq? with | some (α, β), some (_, a, b) => let u ← getLevel α; let v ← getLevel β; pure $ mkApp6 (mkConst ``congrArg [u, v]) α β a b f h | none, _ => throwAppBuilderException ``congrArg ("non-dependent function expected" ++ hasTypeMsg f fType) | _, none => throwAppBuilderException ``congrArg ("equality proof expected" ++ hasTypeMsg h hType) def mkCongrFun (h a : Expr) : MetaM Expr := do let hType ← infer h match hType.eq? with | some (ρ, f, g) => do let ρ ← whnfD ρ match ρ with | Expr.forallE n α β _ => do let β' := Lean.mkLambda n BinderInfo.default α β let u ← getLevel α let v ← getLevel (mkApp β' a) pure $ mkApp6 (mkConst ``congrFun [u, v]) α β' f g h a | _ => throwAppBuilderException ``congrFun ("equality proof between functions expected" ++ hasTypeMsg h hType) | _ => throwAppBuilderException ``congrFun ("equality proof expected" ++ hasTypeMsg h hType) def mkCongr (h₁ h₂ : Expr) : MetaM Expr := do let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.eq?, hType₂.eq? with | some (ρ, f, g), some (α, a, b) => do let ρ ← whnfD ρ match ρ.arrow? with | some (_, β) => do let u ← getLevel α let v ← getLevel β pure $ mkApp8 (mkConst ``congr [u, v]) α β f g a b h₁ h₂ | _ => throwAppBuilderException ``congr ("non-dependent function expected" ++ hasTypeMsg h₁ hType₁) | none, _ => throwAppBuilderException ``congr ("equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException ``congr ("equality proof expected" ++ hasTypeMsg h₂ hType₂) private def mkAppMFinal (methodName : Name) (f : Expr) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do instMVars.forM fun mvarId => do let mvarDecl ← getMVarDecl mvarId let mvarVal ← synthInstance mvarDecl.type assignExprMVar mvarId mvarVal let result ← instantiateMVars (mkAppN f args) if (← hasAssignableMVar result) then throwAppBuilderException methodName ("result contains metavariables" ++ indentExpr result) pure result private partial def mkAppMArgs (f : Expr) (fType : Expr) (xs : Array Expr) : MetaM Expr := let rec loop (type : Expr) (i : Nat) (j : Nat) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do if i >= xs.size then mkAppMFinal `mkAppM f args instMVars else match type with | Expr.forallE n d b c => let d := d.instantiateRevRange j args.size args match c.binderInfo with | BinderInfo.implicit => let mvar ← mkFreshExprMVar d MetavarKind.natural n loop b i j (args.push mvar) instMVars | BinderInfo.instImplicit => let mvar ← mkFreshExprMVar d MetavarKind.synthetic n loop b i j (args.push mvar) (instMVars.push mvar.mvarId!) | _ => let x := xs[i] let xType ← inferType x if (← isDefEq d xType) then loop b (i+1) j (args.push x) instMVars else throwAppTypeMismatch (mkAppN f args) x | type => let type := type.instantiateRevRange j args.size args let type ← whnfD type if type.isForall then loop type i args.size args instMVars else throwAppBuilderException `mkAppM m!"too many explicit arguments provided to{indentExpr f}\narguments{indentD xs}" loop fType 0 0 #[] #[] private def mkFun (constName : Name) : MetaM (Expr × Expr) := do let cinfo ← getConstInfo constName let us ← cinfo.lparams.mapM fun _ => mkFreshLevelMVar let f := mkConst constName us let fType := cinfo.instantiateTypeLevelParams us pure (f, fType) /-- Return the application `constName xs`. It tries to fill the implicit arguments before the last element in `xs`. Remark: ``mkAppM `arbitrary #[α]`` returns `@arbitrary.{u} α` without synthesizing the implicit argument occurring after `α`. Given a `x : (([Decidable p] → Bool) × Nat`, ``mkAppM `Prod.fst #[x]`` returns `@Prod.fst ([Decidable p] → Bool) Nat x` -/ def mkAppM (constName : Name) (xs : Array Expr) : MetaM Expr := do traceCtx `Meta.appBuilder $ withNewMCtxDepth do let (f, fType) ← mkFun constName let r ← mkAppMArgs f fType xs trace[Meta.appBuilder]! "constName: {constName}, xs: {xs}, result: {r}" pure r private partial def mkAppOptMAux (f : Expr) (xs : Array (Option Expr)) : Nat → Array Expr → Nat → Array MVarId → Expr → MetaM Expr | i, args, j, instMVars, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args if h : i < xs.size then match xs.get ⟨i, h⟩ with | none => match c.binderInfo with | BinderInfo.instImplicit => do let mvar ← mkFreshExprMVar d MetavarKind.synthetic n mkAppOptMAux f xs (i+1) (args.push mvar) j (instMVars.push mvar.mvarId!) b | _ => do let mvar ← mkFreshExprMVar d MetavarKind.natural n mkAppOptMAux f xs (i+1) (args.push mvar) j instMVars b | some x => let xType ← inferType x if (← isDefEq d xType) then mkAppOptMAux f xs (i+1) (args.push x) j instMVars b else throwAppTypeMismatch (mkAppN f args) x else mkAppMFinal `mkAppOptM f args instMVars | i, args, j, instMVars, type => do let type := type.instantiateRevRange j args.size args let type ← whnfD type if type.isForall then mkAppOptMAux f xs i args args.size instMVars type else if i == xs.size then mkAppMFinal `mkAppOptM f args instMVars else do let xs : Array Expr := xs.foldl (fun r x? => match x? with | none => r | some x => r.push x) #[] throwAppBuilderException `mkAppOptM ("too many arguments provided to" ++ indentExpr f ++ Format.line ++ "arguments" ++ xs) /-- Similar to `mkAppM`, but it allows us to specify which arguments are provided explicitly using `Option` type. Example: Given `Pure.pure {m : Type u → Type v} [Pure m] {α : Type u} (a : α) : m α`, ``` mkAppOptM `Pure.pure #[m, none, none, a] ``` returns a `Pure.pure` application if the instance `Pure m` can be synthesized, and the universes match. Note that, ``` mkAppM `Pure.pure #[a] ``` fails because the only explicit argument `(a : α)` is not sufficient for inferring the remaining arguments, we would need the expected type. -/ def mkAppOptM (constName : Name) (xs : Array (Option Expr)) : MetaM Expr := do traceCtx `Meta.appBuilder $ withNewMCtxDepth do let (f, fType) ← mkFun constName mkAppOptMAux f xs 0 #[] 0 #[] fType def mkEqNDRec (motive h1 h2 : Expr) : MetaM Expr := do if h2.isAppOf ``Eq.refl then pure h1 else let h2Type ← infer h2 match h2Type.eq? with | none => throwAppBuilderException ``Eq.ndrec ("equality proof expected" ++ hasTypeMsg h2 h2Type) | some (α, a, b) => let u2 ← getLevel α let motiveType ← infer motive match motiveType with | Expr.forallE _ _ (Expr.sort u1 _) _ => pure $ mkAppN (mkConst ``Eq.ndrec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwAppBuilderException ``Eq.ndrec ("invalid motive" ++ indentExpr motive) def mkEqRec (motive h1 h2 : Expr) : MetaM Expr := do if h2.isAppOf ``Eq.refl then pure h1 else let h2Type ← infer h2 match h2Type.eq? with | none => throwAppBuilderException ``Eq.rec ("equality proof expected" ++ indentExpr h2) | some (α, a, b) => let u2 ← getLevel α let motiveType ← infer motive match motiveType with | Expr.forallE _ _ (Expr.forallE _ _ (Expr.sort u1 _) _) _ => pure $ mkAppN (mkConst ``Eq.rec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwAppBuilderException ``Eq.rec ("invalid motive" ++ indentExpr motive) def mkEqMP (eqProof pr : Expr) : MetaM Expr := mkAppM ``Eq.mp #[eqProof, pr] def mkEqMPR (eqProof pr : Expr) : MetaM Expr := mkAppM ``Eq.mpr #[eqProof, pr] def mkNoConfusion (target : Expr) (h : Expr) : MetaM Expr := do let type ← inferType h let type ← whnf type match type.eq? with | none => throwAppBuilderException `noConfusion ("equality expected" ++ hasTypeMsg h type) | some (α, a, b) => let α ← whnf α matchConstInduct α.getAppFn (fun _ => throwAppBuilderException `noConfusion ("inductive type expected" ++ indentExpr α)) fun v us => do let u ← getLevel target pure $ mkAppN (mkConst (Name.mkStr v.name "noConfusion") (u :: us)) (α.getAppArgs ++ #[target, a, b, h]) def mkPure (monad : Expr) (e : Expr) : MetaM Expr := mkAppOptM ``Pure.pure #[monad, none, none, e] /-- `mkProjection s fieldName` return an expression for accessing field `fieldName` of the structure `s`. Remark: `fieldName` may be a subfield of `s`. -/ partial def mkProjection : Expr → Name → MetaM Expr | s, fieldName => do let type ← inferType s let type ← whnf type match type.getAppFn with | Expr.const structName us _ => let env ← getEnv unless isStructureLike env structName do throwAppBuilderException `mkProjection ("structure expected" ++ hasTypeMsg s type) match getProjFnForField? env structName fieldName with | some projFn => let params := type.getAppArgs pure $ mkApp (mkAppN (mkConst projFn us) params) s | none => do let fields := getStructureFields env structName let r? ← fields.findSomeM? fun fieldName' => do match isSubobjectField? env structName fieldName' with | none => pure none | some _ => let parent ← mkProjection s fieldName' (do let r ← mkProjection parent fieldName; pure $ some r) <|> pure none match r? with | some r => pure r | none => throwAppBuilderException `mkProjectionn ("invalid field name '" ++ toString fieldName ++ "' for" ++ hasTypeMsg s type) | _ => throwAppBuilderException `mkProjectionn ("structure expected" ++ hasTypeMsg s type) private def mkListLitAux (nil : Expr) (cons : Expr) : List Expr → Expr | [] => nil | x::xs => mkApp (mkApp cons x) (mkListLitAux nil cons xs) def mkListLit (type : Expr) (xs : List Expr) : MetaM Expr := do let u ← getDecLevel type let nil := mkApp (mkConst ``List.nil [u]) type match xs with | [] => pure nil | _ => let cons := mkApp (mkConst ``List.cons [u]) type pure $ mkListLitAux nil cons xs def mkArrayLit (type : Expr) (xs : List Expr) : MetaM Expr := do let u ← getDecLevel type let listLit ← mkListLit type xs pure (mkApp (mkApp (mkConst ``List.toArray [u]) type) listLit) def mkSorry (type : Expr) (synthetic : Bool) : MetaM Expr := do let u ← getLevel type pure $ mkApp2 (mkConst ``sorryAx [u]) type (toExpr synthetic) /-- Return `Decidable.decide p` -/ def mkDecide (p : Expr) : MetaM Expr := mkAppOptM ``Decidable.decide #[p, none] /-- Return a proof for `p : Prop` using `decide p` -/ def mkDecideProof (p : Expr) : MetaM Expr := do let decP ← mkDecide p let decEqTrue ← mkEq decP (mkConst ``Bool.true) let h ← mkEqRefl (mkConst ``Bool.true) let h ← mkExpectedTypeHint h decEqTrue mkAppM ``ofDecideEqTrue #[h] /-- Return `a < b` -/ def mkLt (a b : Expr) : MetaM Expr := mkAppM ``HasLess.Less #[a, b] /-- Return `a <= b` -/ def mkLe (a b : Expr) : MetaM Expr := mkAppM ``HasLessEq.LessEq #[a, b] /-- Return `arbitrary α` -/ def mkArbitrary (α : Expr) : MetaM Expr := mkAppOptM ``arbitrary #[α, none] /-- Return `sorryAx type` -/ def mkSyntheticSorry (type : Expr) : MetaM Expr := return mkApp2 (mkConst ``sorryAx [← getLevel type]) type (mkConst ``Bool.true) /-- Return `funext h` -/ def mkFunExt (h : Expr) : MetaM Expr := mkAppM ``funext #[h] /-- Return `propext h` -/ def mkPropExt (h : Expr) : MetaM Expr := mkAppM ``propext #[h] /-- Return `eqTrue h` -/ def mkEqTrue (h : Expr) : MetaM Expr := mkAppM ``eqTrue #[h] /-- Return `eqFalse h` -/ def mkEqFalse (h : Expr) : MetaM Expr := mkAppM ``eqFalse #[h] def mkImpCongr (h₁ h₂ : Expr) : MetaM Expr := mkAppM ``impCongr #[h₁, h₂] def mkImpCongrCtx (h₁ h₂ : Expr) : MetaM Expr := mkAppM ``impCongrCtx #[h₁, h₂] def mkForallCongr (h : Expr) : MetaM Expr := mkAppM ``forallCongr #[h] /-- Return `(n : type)`, a numeric literal of type `type`. The method fails if we don't have an instance `OfNat type n` -/ def mkNumeral (type : Expr) (n : Nat) : MetaM Expr := do let u ← getDecLevel type let inst ← synthInstance (mkApp2 (mkConst ``OfNat [u]) type (mkNatLit n)) return mkApp3 (mkConst ``OfNat.ofNat [u]) type (mkNatLit n) inst /-- Return `a op b`, where `op` has name `opName` and is implemented using the typeclass `className`. This method assumes `a` and `b` have the same type, and typeclass `className` is heterogeneous. Examples of supported clases: `HAdd`, `HSub`, `HMul`. We use heterogeneous operators to ensure we have a uniform representation. -/ private def mkBinaryOp (className : Name) (opName : Name) (a b : Expr) : MetaM Expr := do let aType ← inferType a let u ← getDecLevel aType let inst ← synthInstance (mkApp3 (mkConst className [u, u, u]) aType aType aType) return mkApp6 (mkConst opName [u, u, u]) aType aType aType inst a b /-- Return `a + b` using a heterogeneous `+`. This method assumes `a` and `b` have the same type. -/ def mkAdd (a b : Expr) : MetaM Expr := mkBinaryOp ``HAdd ``HAdd.hAdd a b /-- Return `a - b` using a heterogeneous `-`. This method assumes `a` and `b` have the same type. -/ def mkSub (a b : Expr) : MetaM Expr := mkBinaryOp ``HSub ``HSub.hSub a b /-- Return `a * b` using a heterogeneous `*`. This method assumes `a` and `b` have the same type. -/ def mkMul (a b : Expr) : MetaM Expr := mkBinaryOp ``HMul ``HMul.hMul a b builtin_initialize registerTraceClass `Meta.appBuilder end Lean.Meta
7b876b88fe252a7b01934d21945b2ac6782c619a
43390109ab88557e6090f3245c47479c123ee500
/src/xenalib/keji_lemma.lean
b82efd1723e212f3af87e92e31c2b2a690ab26d4
[ "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
6,603
lean
import data.finset import algebra.big_operators import data.fintype open finset lemma disjoint_equiv_classes (α : Type*) [fintype α] [h : setoid α] [decidable_rel h.r] [decidable_eq α]: ∀ x ∈ @finset.univ (quotient h) _, ∀ y ∈ @finset.univ (quotient h) _, x ≠ y → (finset.filter (λ b : α, ⟦b⟧ = x) finset.univ) ∩ (finset.filter (λ b : α, ⟦b⟧ = y) finset.univ) = ∅ := begin intros x hx y hx hxy, rw ←filter_and, rw ←filter_false, congr,funext, suffices : ⟦a⟧ = x ∧ ⟦a⟧ = y → false, simp [this], intro H,cases H with Hx Hy, rw Hx at Hy,apply hxy,exact Hy, intro x,show decidable false, refine is_false id end lemma sum_equiv_classes {α β : Type*} [add_comm_monoid α] [fintype β] (f : β → α) (h : setoid β) [decidable_rel h.r] [decidable_eq β] : finset.sum (@finset.univ β _) f = finset.sum finset.univ (λ (x : quotient h), finset.sum (filter (λ b : β, ⟦b⟧ = x) finset.univ) f) := begin rw ←finset.sum_bind (disjoint_equiv_classes β), congr,symmetry, rw eq_univ_iff_forall, intro b, rw mem_bind, existsi ⟦b⟧, existsi (mem_univ ⟦b⟧), rw mem_filter, split,exact mem_univ b,refl end -- now let's define the equivalence relation on s by a is related to a and g(a) (and that's it) definition gbar {β : Type*} {s : finset β} (g : Π a ∈ s, β) (h₄ : ∀ a ha, g a ha ∈ s) : (↑s : set β) → (↑s : set β) := --λ ⟨a,ha⟩,⟨g a ha,h₄ a ha⟩ λ x,⟨g x.val x.property, h₄ x.val x.property⟩ definition gbar_involution {β : Type*} {s : finset β} (g : Π a ∈ s, β) (h₄ : ∀ a ha, g a ha ∈ s) (h₅ : ∀ a ha, g (g a ha) (h₄ a ha) = a) : let gb := gbar g h₄ in ∀ x, gb (gb x) = x := begin intros gb x, apply subtype.eq, have H := h₅ x.val x.property, rw ←H,refl, end private definition eqv {β : Type*} {s : finset β} (g : Π a ∈ s, β) (h₄ : ∀ a ha, g a ha ∈ s) (h₅ : ∀ a ha, g (g a ha) (h₄ a ha) = a) (a₁ a₂ : (↑s : set β)) : Prop := let gb := gbar g h₄ in a₁ = a₂ ∨ a₁ = gb a₂ private theorem eqv.refl {β : Type*} {s : finset β} (g : Π a ∈ s, β) (h₄ : ∀ a ha, g a ha ∈ s) (h₅ : ∀ a ha, g (g a ha) (h₄ a ha) = a) : ∀ a : (↑s : set β), eqv g h₄ h₅ a a := λ a, or.inl rfl private theorem eqv.symm {β : Type*} {s : finset β} (g : Π a ∈ s, β) (h₄ : ∀ a ha, g a ha ∈ s) (h₅ : ∀ a ha, g (g a ha) (h₄ a ha) = a) : ∀ a₁ a₂ : (↑s : set β), eqv g h₄ h₅ a₁ a₂ → eqv g h₄ h₅ a₂ a₁ | a₁ a₂ (or.inl h) := or.inl h.symm | a₁ a₂ (or.inr h) := or.inr (by rw h;exact (gbar_involution g h₄ h₅ a₂).symm) private theorem eqv.trans {β : Type*} {s : finset β} (g : Π a ∈ s, β) (h₄ : ∀ a ha, g a ha ∈ s) (h₅ : ∀ a ha, g (g a ha) (h₄ a ha) = a) : ∀ a₁ a₂ a₃: (↑s : set β), eqv g h₄ h₅ a₁ a₂ → eqv g h₄ h₅ a₂ a₃ → eqv g h₄ h₅ a₁ a₃ | a₁ a₂ a₃ (or.inl h12) (or.inl h23) := or.inl (eq.trans h12 h23) | a₁ a₂ a₃ (or.inl h12) (or.inr h23) := or.inr (h12.symm ▸ h23) | a₁ a₂ a₃ (or.inr h12) (or.inl h23) := or.inr (h23 ▸ h12) | a₁ a₂ a₃ (or.inr h12) (or.inr h23) := or.inl (by rw [h12,h23];exact (gbar_involution g h₄ h₅ a₃)) private theorem is_equivalence {β : Type*} {s : finset β} (g : Π a ∈ s, β) (h₄ : ∀ a ha, g a ha ∈ s) (h₅ : ∀ a ha, g (g a ha) (h₄ a ha) = a) : equivalence (eqv g h₄ h₅) := ⟨eqv.refl g h₄ h₅,eqv.symm g h₄ h₅,eqv.trans g h₄ h₅⟩ instance {β : Type*} [decidable_eq β] {s : finset β} (g : Π a ∈ s, β) (h₄ : ∀ a ha, g a ha ∈ s) (h₅ : ∀ a ha, g (g a ha) (h₄ a ha) = a) : decidable_rel (eqv g h₄ h₅) := begin intros a₁ a₂, by_cases H12 : a₁ = a₂, refine is_true (or.inl H12), by_cases H12g : a₁ = gbar g h₄ a₂, refine is_true (or.inr H12g), refine is_false _, intro H,cases H, apply H12,exact H, apply H12g,exact H, end lemma sum_keji {α β : Type*} [add_comm_monoid α] [decidable_eq β] {f : β → α} {s : finset β} (g : Π a ∈ s, β) (h₀ : ∀ a ha, f a + f (g a ha) = 0) (h₁ : ∀ a ha, g a ha ≠ a) (h₂ : ∀ a₁ a₂ ha₁ ha₂, g a₁ ha₁ = g a₂ ha₂ → a₁ = a₂) (h₃ : ∀ a ∈ s, ∃ b hb, g b hb = a) (h₄ : ∀ a ha, g a ha ∈ s) (h₅ : ∀ a ha, g (g a ha) (h₄ a ha) = a ) : s.sum f = 0 := begin let gb := gbar g h₄, let β' := ↥(↑s : set β), letI fβ' : fintype β' := by apply_instance, let inst_2 : fintype β' := by apply_instance, let f' : β' → α := λ b,f b, let h : setoid β' := {r := eqv g h₄ h₅,iseqv := is_equivalence g h₄ h₅}, let inst_4 : decidable_eq β' := by apply_instance, let inst_3 : decidable_rel h.r := by apply_instance, have H : s.sum f = sum univ f', { let g' : β' → β := λ x, x.val, let s' : finset β' := finset.univ, have Hinj : ∀ x ∈ s', ∀ y ∈ s', g' x = g' y → x = y, { intros x Hx y Hy,exact subtype.eq, }, have H2 := @sum_image β α β' f _ _ _ s' g' Hinj, have H3 : image g' s' = s, { ext,split, { rw finset.mem_image, intro Ha, cases Ha with b Hb, cases Hb with Hb Hg', rw ←Hg', exact b.property, }, intro Ha, rw finset.mem_image, existsi (⟨a,Ha⟩ : β'), existsi (mem_univ _),refl }, rw ←H3, rw H2, refl }, rw H, -- now finally rewrite sum_equiv_classes rw @sum_equiv_classes α β' _ fβ' f' h _ _, rw ←sum_const_zero, congr,funext, let b := quotient.out x, suffices : (filter (λ (b : β'), ⟦b⟧ = x) univ) = insert b (finset.singleton (gb b)), { rw this, have H2 : b ∉ finset.singleton (gb b), rw mem_singleton, intro H3,replace H3 := H3.symm, apply h₁ b.val b.property, have H4 : (gb b).val = b.val := by rw H3, exact H4, rw finset.sum_insert H2, rw finset.sum_singleton, show f b.val + f (g b.val b.property) = 0, exact h₀ b.val b.property }, clear H, have H : ∀ c : β', ⟦c⟧ = x ↔ c = b ∨ c = gb b, { intro c,split,swap, intro H2,cases H2,rw H2,simp, rw H2, suffices : ⟦gb b⟧ = ⟦b⟧, by simp [this], rw quotient.eq, exact or.inr rfl, have H : x = ⟦b⟧ := by simp, rw H,rw quotient.eq, intro H2, cases H2,left,exact H2, right,exact H2, }, ext, have H2 : a ∈ insert b (finset.singleton (gb b)) ↔ a = b ∨ a = gb b := by simp, rw H2, rw ←H a, simp, end
da37d62050be1dad498a6ae0377463a0f84e7d13
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/algebra/module.lean
b3787bbfea5f8769d7afe5252a1a46669fa28741
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
26,170
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 -/ import algebra.ring algebra.big_operators group_theory.subgroup group_theory.group_action /-! # Modules over a ring In this file we define * `semimodule R M` : an additive commutative monoid `M` is a `semimodule` over a `semiring` `R` if for `r : R` and `x : M` their "scalar multiplication `r • x : M` is defined, and the operation `•` satisfies some natural associativity and distributivity axioms similar to those on a ring. * `module R M` : same as `semimodule R M` but assumes that `R` is a `ring` and `M` is an additive commutative group. * `vector_space k M` : same as `semimodule k M` and `module k M` but assumes that `k` is a `field` and `M` is an additive commutative group. * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`module`s. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. * `submodule R M` : a subset of `M` that contains zero and is closed with respect to addition and scalar multiplication. * `subspace k M` : an abbreviation for `submodule` assuming that `k` is a `field`. ## Implementation notes * `vector_space` is an abbreviation for `module R M` while the latter `extends semimodule R M`. There were several attempts to make `module` an abbreviation of `semimodule` but this makes class instance search too hard for Lean 3. ## TODO * `submodule R M` was written before bundled `submonoid`s, so it does not extend it. ## Tags semimodule, module, vector space, submodule, subspace, linear map -/ open function universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} section prio set_option default_priority 100 -- see Note [default priority] /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `R` and an additive monoid of "vectors" `M`, connected by a "scalar multiplication" operation `r • x : M` (where `r : R` and `x : M`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class semimodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] extends distrib_mul_action R M := (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (zero_smul : ∀x : M, (0 : R) • x = 0) end prio section semimodule variables [semiring R] [add_comm_monoid M] [semimodule R M] (r s : R) (x y : M) theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x variables (R) @[simp] theorem zero_smul : (0 : R) • x = 0 := semimodule.zero_smul x variable {R} lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : x = 0 := by rw [←one_smul R x, ←zero_eq_one, zero_smul] instance smul.is_add_monoid_hom (x : M) : is_add_monoid_hom (λ r:R, r • x) := { map_zero := zero_smul _ x, map_add := λ r₁ r₂, add_smul r₁ r₂ x } lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := show (λ r, r • x) l.sum = (l.map (λ r, r • x)).sum, from (list.sum_hom _ _).symm lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := show (λ r, r • x) l.sum = (l.map (λ r, r • x)).sum, from (multiset.sum_hom _ _).symm lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} : s.sum f • x = s.sum (λ r, (f r) • x) := show (λ r, r • x) (s.sum f) = s.sum (λ r, (f r) • x), from (finset.sum_hom _ _).symm end semimodule section prio set_option default_priority 100 -- see Note [default priority] /-- A module is a generalization of vector spaces to a scalar ring. It consists of a scalar ring `R` and an additive group of "vectors" `M`, connected by a "scalar multiplication" operation `r • x : M` (where `r : R` and `x : M`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class module (R : Type u) (M : Type v) [ring R] [add_comm_group M] extends semimodule R M end prio /-- To prove two module structures on a fixed `add_comm_group` agree, it suffices to check the scalar multiplications agree. -/ -- We'll later use this to show `module ℤ M` is a subsingleton. @[ext] lemma module_ext {R : Type*} [ring R] {M : Type*} [add_comm_group M] (P Q : module R M) (w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) : P = Q := begin resetI, rcases P with ⟨⟨⟨⟨⟨P⟩⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨⟨Q⟩⟩⟩⟩⟩, congr, funext r m, exact w r m, all_goals { apply proof_irrel_heq }, end /-- An auxiliary `structure` that is used to define `module`s without verifying `zero_smul` and `smul_zero`. -/ structure module.core (R M) [ring R] [add_comm_group M] extends has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀x : M, (1 : R) • x = x) /-- Define `module` without proving `zero_smul` and `smul_zero` by using an auxiliary structure `module.core`. -/ def module.of_core [ring R] [add_comm_group M] (Mc : module.core R M) : module R M := by letI := Mc.to_has_scalar; exact { zero_smul := λ x, (add_monoid_hom.mk' (λ r : R, r • x) (λ r s, Mc.add_smul r s x)).map_zero, smul_zero := λ r, (add_monoid_hom.mk' ((•) r) (Mc.smul_add r)).map_zero, ..Mc } section module variables [ring R] [add_comm_group M] [module R M] (r s : R) (x y : M) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (R) theorem neg_one_smul (x : M) : (-1 : R) • x = -x := by simp variables {R} @[simp] theorem smul_neg : r • (-x) = -(r • x) := by rw [← neg_one_smul R, ← mul_smul, mul_neg_one, neg_smul] theorem smul_sub (r : R) (x y : M) : r • (x - y) = r • x - r • y := by simp [smul_add, sub_eq_add_neg]; rw smul_neg theorem sub_smul (r s : R) (y : M) : (r - s) • y = r • y - s • y := by simp [add_smul, sub_eq_add_neg] theorem smul_eq_zero {R E : Type*} [division_ring R] [add_comm_group E] [module R E] {c : R} {x : E} : c • x = 0 ↔ c = 0 ∨ x = 0 := ⟨λ h, classical.by_cases or.inl (λ hc, or.inr $ by rw [← one_smul R x, ← inv_mul_cancel hc, mul_smul, h, smul_zero]), λ h, h.elim (λ hc, hc.symm ▸ zero_smul R x) (λ hx, hx.symm ▸ smul_zero c)⟩ end module instance semiring.to_semimodule [semiring R] : semimodule R R := { 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 } @[simp] lemma smul_eq_mul [semiring R] {a a' : R} : a • a' = a * a' := rfl instance ring.to_module [ring R] : module R R := { to_semimodule := semiring.to_semimodule } /-- A ring homomorphism `f : R →+* S` defines a semimodule structure by `r • x = f r * x`. -/ def ring_hom.to_semimodule [semiring R] [semiring S] (f : R →+* S) : semimodule R S := { smul := λ r x, f r * x, smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add], add_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_add, add_mul], mul_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_mul, mul_assoc], one_smul := λ x, show f 1 * x = _, by rw [f.map_one, one_mul], zero_smul := λ x, show f 0 * x = 0, by rw [f.map_zero, zero_mul], smul_zero := λ r, mul_zero (f r) } /-- A ring homomorphism `f : R →+* S` defines a module structure by `r • x = f r * x`. -/ def ring_hom.to_module [ring R] [ring S] (f : R →+* S) : module R S := { to_semimodule := f.to_semimodule } /-- A class saying that `f` is an `R` linear map. Though it is a class, it is used as an explicit argument in most lemmas. -/ class is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] (f : M → M₂) : Prop := (add [] : ∀ x y, f (x + y) = f x + f y) (smul [] : ∀ (c : R) x, f (c • x) = c • f x) /-- A bundled `R`-linear map from `M` to `M₂`. -/ structure linear_map (R : Type u) (M : Type v) (M₂ : Type w) [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] := (to_fun : M → M₂) (add : ∀x y, to_fun (x + y) = to_fun x + to_fun y) (smul : ∀(c : R) x, to_fun (c • x) = c • to_fun x) infixr ` →ₗ `:25 := linear_map _ notation β ` →ₗ[`:25 α:25 `] `:0 γ:0 := linear_map α β γ namespace linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] section variables [module R M] [module R M₂] variables (f g : M →ₗ[R] M₂) instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩ @[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl end -- We can infer the module structure implicitly from the linear maps, -- rather than via typeclass resolution. variables {module_M : module R M} {module_M₂ : module R M₂} variables (f g : M →ₗ[R] M₂) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R f := {..f} variables {f g} @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl } , ext⟩ variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.add x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.smul c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul R, map_smul f 0 0, zero_smul] instance : is_add_group_hom f := { map_add := map_add f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : ((f.to_add_monoid_hom) : M → M₂) = f := rfl @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y @[simp] lemma map_sum {t : finset ι} {g : ι → M} : f (t.sum g) = t.sum (λi, f (g i)) := f.to_add_monoid_hom.map_sum _ _ end linear_map namespace linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] variables [add_comm_group M₃] variables {module_M : module R M} {module_M₂ : module R M₂} {module_M₃ : module R M₃} variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂) /-- Composition of two linear maps is a linear map -/ def comp : M →ₗ[R] M₃ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl /-- Identity map as a `linear_map` -/ def id {R} {M} [ring R] [add_comm_group M] [module R M] : M →ₗ[R] M := ⟨id, λ _ _, rfl, λ _ _, rfl⟩ @[simp] lemma id_apply {R} {M} [ring R] [add_comm_group M] [module R M] (x : M) : @id R M _ _ _ x = x := rfl end linear_map namespace is_linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] variables [module R M] [module R M₂] /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := {to_fun := f, ..H} @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) lemma is_linear_map_smul {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end --TODO: move lemma is_linear_map_smul' (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero lemma map_add : ∀ x y, f (x + y) = f x + f y := lin.add lemma map_neg (x) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := (lin.mk' f).map_smul c x end is_linear_map /-- Ring of linear endomorphismsms of a module. -/ abbreviation module.End (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] := M →ₗ[R] M /-- 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 (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] : Type v := (carrier : set M) (zero : (0:M) ∈ carrier) (add : ∀ {x y}, x ∈ carrier → y ∈ carrier → x + y ∈ carrier) (smul : ∀ (c:R) {x}, x ∈ carrier → c • x ∈ carrier) namespace submodule variables [ring R] [add_comm_group M] [add_comm_group M₂] section variables [module R M] instance : has_coe (submodule R M) (set M) := ⟨submodule.carrier⟩ instance : has_mem M (submodule R M) := ⟨λ x p, x ∈ (p : set M)⟩ end -- We can infer the module structure implicitly from the bundled submodule, -- rather than via typeclass resolution. variables {module_M : module R M} variables {p q : submodule R M} variables {r : R} {x y : M} theorem ext' (h : (p : set M) = q) : p = q := by cases p; cases q; congr' protected theorem ext'_iff : (p : set M) = q ↔ p = q := ⟨ext', λ h, h ▸ rfl⟩ @[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := ext' $ set.ext h variables (p) @[simp] theorem mem_coe : x ∈ (p : set M) ↔ x ∈ p := iff.rfl @[simp] lemma zero_mem : (0 : M) ∈ p := p.zero lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add h₁ h₂ lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul r h lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul R; 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 {t : finset ι} {f : ι → M} : (∀c∈t, f c ∈ p) → t.sum f ∈ p := begin classical, exact finset.induction_on t (by simp [p.zero_mem]) (by simp [p.add_mem] {contextual := tt}) end lemma smul_mem_iff' (u : units R) : (u:R) • x ∈ p ↔ x ∈ p := ⟨λ h, by simpa only [smul_smul, u.inv_mul, one_smul] using p.smul_mem ↑u⁻¹ h, p.smul_mem u⟩ instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : inhabited p := ⟨0⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ instance : has_scalar R p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩ variables {p} @[simp, norm_cast] lemma coe_add (x y : p) : (↑(x + y) : M) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : p) : M) = 0 := rfl @[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl @[simp, norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl @[simp] protected lemma eta (x : p) (hx : (x : M) ∈ p) : (⟨x, hx⟩ : p) = x := subtype.eta x hx instance : add_comm_group p := by refine {add := (+), zero := 0, neg := has_neg.neg, ..}; { intros, apply set_coe.ext, simp [add_comm, add_left_comm] } instance submodule_is_add_subgroup : is_add_subgroup (p : set M) := { zero_mem := p.zero, add_mem := p.add, neg_mem := λ _, p.neg_mem } @[simp, norm_cast] lemma coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := rfl variables (p) instance : module R p := by refine {smul := (•), ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } /-- Embedding of a submodule `p` to the ambient space `M`. -/ protected def subtype : p →ₗ[R] M := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val : ((submodule.subtype p) : p → M) = subtype.val := rfl end submodule -- TODO: Do we want one-sided ideals? /-- Ideal in a commutative ring is an additive subgroup `s` such that `a * b ∈ s` whenever `b ∈ s`. We define `ideal R` as `submodule R R`. -/ @[reducible] def ideal (R : Type u) [comm_ring R] := submodule R R namespace ideal variables [comm_ring R] (I : ideal R) {a b : R} protected lemma zero_mem : (0 : R) ∈ 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 /-- Vector spaces are defined as an `abbreviation` for modules, if the base ring is a field. (A previous definition made `vector_space` a structure defined to be `module`.) This has as advantage that vector spaces are completely transparent for type class inference, which means that all instances for modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend vector spaces an sich, in definitions such as `normed_space`. The solution is to extend `module` instead. -/ library_note "vector space definition" /-- 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. -/ abbreviation vector_space (k : Type u) (M : Type v) [field k] [add_comm_group M] := module k M instance field.to_vector_space {k : Type*} [field k] : vector_space k k := ring.to_module /-- Subspace of a vector space. Defined to equal `submodule`. -/ @[reducible] def subspace (k : Type u) (M : Type v) [field k] [add_comm_group M] [vector_space k M] : Type v := submodule k M instance subspace.vector_space {k M} {f : field k} [add_comm_group M] [vector_space k M] (p : subspace k M) : vector_space k p := p.module namespace submodule variables [division_ring R] [add_comm_group M] [module R M] variables (p : submodule R M) {r : R} {x y : M} theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p := p.smul_mem_iff' (units.mk0 r r0) end submodule namespace add_comm_monoid open add_monoid variables [add_comm_monoid M] /-- The natural ℕ-semimodule structure on any `add_comm_monoid`. -/ -- We don't make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℕ`. def nat_semimodule : semimodule ℕ M := { smul := smul, smul_add := λ _ _ _, smul_add _ _ _, add_smul := λ _ _ _, add_smul _ _ _, mul_smul := λ _ _ _, mul_smul _ _ _, one_smul := one_smul, zero_smul := zero_smul, smul_zero := smul_zero } end add_comm_monoid namespace add_comm_group variables [add_comm_group M] /-- The natural ℤ-module structure on any `add_comm_group`. -/ -- We don't immediately make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℤ`. -- We do turn it into a global instance, but only at the end of this file, -- and I remain dubious whether this is a good idea. def int_module : module ℤ M := { smul := gsmul, smul_add := λ _ _ _, gsmul_add _ _ _, add_smul := λ _ _ _, add_gsmul _ _ _, mul_smul := λ _ _ _, gsmul_mul _ _ _, one_smul := one_gsmul, zero_smul := zero_gsmul, smul_zero := gsmul_zero } instance : subsingleton (module ℤ M) := begin split, intros P Q, ext, -- isn't that lovely: `r • m = r • m` have one_smul : by { haveI := P, exact (1 : ℤ) • m } = by { haveI := Q, exact (1 : ℤ) • m }, begin rw [@one_smul ℤ _ _ (by { haveI := P, apply_instance, }) m], rw [@one_smul ℤ _ _ (by { haveI := Q, apply_instance, }) m], end, have nat_smul : ∀ n : ℕ, by { haveI := P, exact (n : ℤ) • m } = by { haveI := Q, exact (n : ℤ) • m }, begin intro n, induction n with n ih, { erw [zero_smul, zero_smul], }, { rw [int.coe_nat_succ, add_smul, add_smul], erw ih, rw [one_smul], } end, cases r, { rw [int.of_nat_eq_coe, nat_smul], }, { rw [int.neg_succ_of_nat_coe, neg_smul, neg_smul, nat_smul], } end end add_comm_group section local attribute [instance] add_comm_monoid.nat_semimodule lemma semimodule.smul_eq_smul (R : Type*) [semiring R] {M : Type*} [add_comm_monoid M] [semimodule R M] (n : ℕ) (b : M) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { change (n + 1) • b = (n + 1 : R) • b, rw [add_smul, add_smul, one_smul, ih, one_smul] } end lemma semimodule.add_monoid_smul_eq_smul (R : Type*) [semiring R] {M : Type*} [add_comm_monoid M] [semimodule R M] (n : ℕ) (b : M) : add_monoid.smul n b = (n : R) • b := semimodule.smul_eq_smul R n b lemma nat.smul_def {M : Type*} [add_comm_monoid M] (n : ℕ) (x : M) : n • x = add_monoid.smul n x := rfl end section local attribute [instance] add_comm_group.int_module lemma gsmul_eq_smul {M : Type*} [add_comm_group M] (n : ℤ) (x : M) : gsmul n x = n • x := rfl lemma module.gsmul_eq_smul_cast (R : Type*) [ring R] {β : Type*} [add_comm_group β] [module R β] (n : ℤ) (b : β) : gsmul n b = (n : R) • b := begin cases n, { apply semimodule.add_monoid_smul_eq_smul, }, { dsimp, rw semimodule.add_monoid_smul_eq_smul R, push_cast, rw neg_smul, } end lemma module.gsmul_eq_smul {M : Type*} [add_comm_group M] [module ℤ M] (n : ℤ) (b : M) : gsmul n b = n • b := by rw [module.gsmul_eq_smul_cast ℤ, int.cast_id] end -- We prove this without using the `add_comm_group.int_module` instance, so the `•`s here -- come from whatever the local `module ℤ` structure actually is. lemma add_monoid_hom.map_int_module_smul [add_comm_group M] [add_comm_group M₂] [module ℤ M] [module ℤ M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f (x • a) = x • f a := by simp only [← module.gsmul_eq_smul, f.map_gsmul] lemma add_monoid_hom.map_int_cast_smul [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [← module.gsmul_eq_smul_cast, f.map_gsmul] lemma add_monoid_hom.map_nat_cast_smul [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M →+ M₂) (x : ℕ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [← semimodule.add_monoid_smul_eq_smul, f.map_smul] lemma add_monoid_hom.map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] (f : E →+ F) (c : ℚ) (x : E) : f ((c : R) • x) = (c : R) • f x := begin have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x, { intros x n hn, replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn), conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] }, rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat, inv_mul_cancel hn, one_smul] }, refine c.num_denom_cases_on (λ m n hn hmn, _), rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul, rat.cast_coe_int, f.map_int_cast_smul, this _ n hn] end lemma add_monoid_hom.map_rat_module_smul {E : Type*} [add_comm_group E] [vector_space ℚ E] {F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) : f (c • x) = c • f x := rat.cast_id c ▸ f.map_rat_cast_smul c x -- We finally turn on these instances globally: attribute [instance] add_comm_monoid.nat_semimodule add_comm_group.int_module /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := ⟨f, f.map_add, f.map_int_module_smul⟩ /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [vector_space ℚ M] [add_comm_group M₂] [vector_space ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := ⟨f, f.map_add, f.map_rat_module_smul⟩ namespace finset variable (R) lemma sum_const' [semiring R] [add_comm_monoid M] [semimodule R M] {s : finset ι} (b : M) : finset.sum s (λ (i : ι), b) = (finset.card s : R) • b := by rw [finset.sum_const, ← semimodule.smul_eq_smul]; refl variables {R} [decidable_linear_ordered_cancel_add_comm_monoid M] {s : finset ι} (f : ι → M) theorem exists_card_smul_le_sum (hs : s.nonempty) : ∃ i ∈ s, s.card • f i ≤ s.sum f := exists_le_of_sum_le hs $ by rw [sum_const, ← nat.smul_def, smul_sum] theorem exists_card_smul_ge_sum (hs : s.nonempty) : ∃ i ∈ s, s.sum f ≤ s.card • f i := exists_le_of_sum_le hs $ by rw [sum_const, ← nat.smul_def, smul_sum] end finset
57bf2f65a0b089a15fcc90c2bfacd453fe125e94
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/box_integral/partition/subbox_induction.lean
e171fc752b88eeace6279c16ea5c3c27dbb3cc11
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
10,553
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.box.subbox_induction import analysis.box_integral.partition.tagged /-! # Induction on subboxes In this file we prove (see `box_integral.tagged_partition.exists_is_Henstock_is_subordinate_homothetic`) that for every box `I` in `ℝⁿ` and a function `r : ℝⁿ → ℝ` positive on `I` there exists a tagged partition `π` of `I` such that * `π` is a Henstock partition; * `π` is subordinate to `r`; * each box in `π` is homothetic to `I` with coefficient of the form `1 / 2 ^ n`. Later we will use this lemma to prove that the Henstock filter is nontrivial, hence the Henstock integral is well-defined. ## Tags partition, tagged partition, Henstock integral -/ namespace box_integral open set metric open_locale classical topological_space noncomputable theory variables {ι : Type*} [fintype ι] {I J : box ι} namespace prepartition /-- Split a box in `ℝⁿ` into `2 ^ n` boxes by hyperplanes passing through its center. -/ def split_center (I : box ι) : prepartition I := { boxes := finset.univ.map (box.split_center_box_emb I), le_of_mem' := by simp [I.split_center_box_le], pairwise_disjoint := begin rw [finset.coe_map, finset.coe_univ, image_univ], rintro _ ⟨s, rfl⟩ _ ⟨t, rfl⟩ Hne, exact I.disjoint_split_center_box (mt (congr_arg _) Hne) end } @[simp] lemma mem_split_center : J ∈ split_center I ↔ ∃ s, I.split_center_box s = J := by simp [split_center] lemma is_partition_split_center (I : box ι) : is_partition (split_center I) := λ x hx, by simp [hx] lemma upper_sub_lower_of_mem_split_center (h : J ∈ split_center I) (i : ι) : J.upper i - J.lower i = (I.upper i - I.lower i) / 2 := let ⟨s, hs⟩ := mem_split_center.1 h in hs ▸ I.upper_sub_lower_split_center_box s i end prepartition namespace box open prepartition tagged_prepartition /-- Let `p` be a predicate on `box ι`, let `I` be a box. Suppose that the following two properties hold true. * Consider a smaller box `J ≤ I`. The hyperplanes passing through the center of `J` split it into `2 ^ n` boxes. If `p` holds true on each of these boxes, then it true on `J`. * For each `z` in the closed box `I.Icc` there exists a neighborhood `U` of `z` within `I.Icc` such that for every box `J ≤ I` such that `z ∈ J.Icc ⊆ U`, if `J` is homothetic to `I` with a coefficient of the form `1 / 2 ^ m`, then `p` is true on `J`. Then `p I` is true. See also `box_integral.box.subbox_induction_on'` for a version using `box_integral.box.split_center_box` instead of `box_integral.prepartition.split_center`. -/ @[elab_as_eliminator] lemma subbox_induction_on {p : box ι → Prop} (I : box ι) (H_ind : ∀ J ≤ I, (∀ J' ∈ split_center J, p J') → p J) (H_nhds : ∀ z ∈ I.Icc, ∃ (U ∈ 𝓝[I.Icc] z), ∀ (J ≤ I) (m : ℕ), z ∈ J.Icc → J.Icc ⊆ U → (∀ i, J.upper i - J.lower i = (I.upper i - I.lower i) / 2 ^ m) → p J) : p I := begin refine subbox_induction_on' I (λ J hle hs, H_ind J hle $ λ J' h', _) H_nhds, rcases mem_split_center.1 h' with ⟨s, rfl⟩, exact hs s end /-- Given a box `I` in `ℝⁿ` and a function `r : ℝⁿ → (0, ∞)`, there exists a tagged partition `π` of `I` such that * `π` is a Henstock partition; * `π` is subordinate to `r`; * each box in `π` is homothetic to `I` with coefficient of the form `1 / 2 ^ m`. This lemma implies that the Henstock filter is nontrivial, hence the Henstock integral is well-defined. -/ lemma exists_tagged_partition_is_Henstock_is_subordinate_homothetic (I : box ι) (r : (ι → ℝ) → Ioi (0 : ℝ)) : ∃ π : tagged_prepartition I, π.is_partition ∧ π.is_Henstock ∧ π.is_subordinate r ∧ (∀ J ∈ π, ∃ m : ℕ, ∀ i, (J : _).upper i - J.lower i = (I.upper i - I.lower i) / 2 ^ m) ∧ π.distortion = I.distortion := begin refine subbox_induction_on I (λ J hle hJ, _) (λ z hz, _), { choose! πi hP hHen hr Hn Hd using hJ, choose! n hn using Hn, have hP : ((split_center J).bUnion_tagged πi).is_partition, from (is_partition_split_center _).bUnion_tagged hP, have hsub : ∀ (J' ∈ (split_center J).bUnion_tagged πi), ∃ n : ℕ, ∀ i, (J' : _).upper i - J'.lower i = (J.upper i - J.lower i) / 2 ^ n, { intros J' hJ', rcases (split_center J).mem_bUnion_tagged.1 hJ' with ⟨J₁, h₁, h₂⟩, refine ⟨n J₁ J' + 1, λ i, _⟩, simp only [hn J₁ h₁ J' h₂, upper_sub_lower_of_mem_split_center h₁, pow_succ, div_div] }, refine ⟨_, hP, is_Henstock_bUnion_tagged.2 hHen, is_subordinate_bUnion_tagged.2 hr, hsub, _⟩, refine tagged_prepartition.distortion_of_const _ hP.nonempty_boxes (λ J' h', _), rcases hsub J' h' with ⟨n, hn⟩, exact box.distortion_eq_of_sub_eq_div hn }, { refine ⟨I.Icc ∩ closed_ball z (r z), inter_mem_nhds_within _ (closed_ball_mem_nhds _ (r z).coe_prop), _⟩, intros J Hle n Hmem HIcc Hsub, rw set.subset_inter_iff at HIcc, refine ⟨single _ _ le_rfl _ Hmem, is_partition_single _, is_Henstock_single _, (is_subordinate_single _ _).2 HIcc.2, _, distortion_single _ _⟩, simp only [tagged_prepartition.mem_single, forall_eq], refine ⟨0, λ i, _⟩, simp } end end box namespace prepartition open tagged_prepartition finset function /-- Given a box `I` in `ℝⁿ`, a function `r : ℝⁿ → (0, ∞)`, and a prepartition `π` of `I`, there exists a tagged prepartition `π'` of `I` such that * each box of `π'` is included in some box of `π`; * `π'` is a Henstock partition; * `π'` is subordinate to `r`; * `π'` covers exactly the same part of `I` as `π`; * the distortion of `π'` is equal to the distortion of `π`. -/ lemma exists_tagged_le_is_Henstock_is_subordinate_Union_eq {I : box ι} (r : (ι → ℝ) → Ioi (0 : ℝ)) (π : prepartition I) : ∃ π' : tagged_prepartition I, π'.to_prepartition ≤ π ∧ π'.is_Henstock ∧ π'.is_subordinate r ∧ π'.distortion = π.distortion ∧ π'.Union = π.Union := begin have := λ J, box.exists_tagged_partition_is_Henstock_is_subordinate_homothetic J r, choose! πi πip πiH πir hsub πid, clear hsub, refine ⟨π.bUnion_tagged πi, bUnion_le _ _, is_Henstock_bUnion_tagged.2 (λ J _, πiH J), is_subordinate_bUnion_tagged.2 (λ J _, πir J), _, π.Union_bUnion_partition (λ J _, πip J)⟩, rw [distortion_bUnion_tagged], exact sup_congr rfl (λ J _, πid J) end /-- Given a prepartition `π` of a box `I` and a function `r : ℝⁿ → (0, ∞)`, `π.to_subordinate r` is a tagged partition `π'` such that * each box of `π'` is included in some box of `π`; * `π'` is a Henstock partition; * `π'` is subordinate to `r`; * `π'` covers exactly the same part of `I` as `π`; * the distortion of `π'` is equal to the distortion of `π`. -/ def to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : tagged_prepartition I := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some lemma to_subordinate_to_prepartition_le (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).to_prepartition ≤ π := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.1 lemma is_Henstock_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).is_Henstock := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.1 lemma is_subordinate_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).is_subordinate r := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.1 @[simp] lemma distortion_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).distortion = π.distortion := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.2.1 @[simp] lemma Union_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).Union = π.Union := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.2.2 end prepartition namespace tagged_prepartition /-- Given a tagged prepartition `π₁`, a prepartition `π₂` that covers exactly `I \ π₁.Union`, and a function `r : ℝⁿ → (0, ∞)`, returns the union of `π₁` and `π₂.to_subordinate r`. This partition `π` has the following properties: * `π` is a partition, i.e. it covers the whole `I`; * `π₁.boxes ⊆ π.boxes`; * `π.tag J = π₁.tag J` whenever `J ∈ π₁`; * `π` is Henstock outside of `π₁`: `π.tag J ∈ J.Icc` whenever `J ∈ π`, `J ∉ π₁`; * `π` is subordinate to `r` outside of `π₁`; * the distortion of `π` is equal to the maximum of the distortions of `π₁` and `π₂`. -/ def union_compl_to_subordinate (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : tagged_prepartition I := π₁.disj_union (π₂.to_subordinate r) (((π₂.Union_to_subordinate r).trans hU).symm ▸ disjoint_sdiff_self_right) lemma is_partition_union_compl_to_subordinate (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : is_partition (π₁.union_compl_to_subordinate π₂ hU r) := prepartition.is_partition_disj_union_of_eq_diff ((π₂.Union_to_subordinate r).trans hU) @[simp] lemma union_compl_to_subordinate_boxes (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π₁.union_compl_to_subordinate π₂ hU r).boxes = π₁.boxes ∪ (π₂.to_subordinate r).boxes := rfl @[simp] lemma Union_union_compl_to_subordinate_boxes (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π₁.union_compl_to_subordinate π₂ hU r).Union = I := (is_partition_union_compl_to_subordinate _ _ _ _).Union_eq @[simp] lemma distortion_union_compl_to_subordinate (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π₁.union_compl_to_subordinate π₂ hU r).distortion = max π₁.distortion π₂.distortion := by simp [union_compl_to_subordinate] end tagged_prepartition end box_integral
740b4a0972aa54900ece34eee2bcc71f079c4dab
92b50235facfbc08dfe7f334827d47281471333b
/library/data/list/set.lean
9ed84b4b5b24e359bde741ba37c294907eb96ab3
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
37,082
lean
/- Copyright (c) 2015 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Set-like operations on lists -/ import data.list.basic data.list.comb open nat function decidable helper_tactics eq.ops namespace list section erase variable {A : Type} variable [H : decidable_eq A] include H definition erase (a : A) : list A → list A | [] := [] | (b::l) := match H a b with | inl e := l | inr n := b :: erase l end lemma erase_nil (a : A) : erase a [] = [] := rfl lemma erase_cons_head (a : A) (l : list A) : erase a (a :: l) = l := show match H a a with | inl e := l | inr n := a :: erase a l end = l, by rewrite decidable_eq_inl_refl lemma erase_cons_tail {a b : A} (l : list A) : a ≠ b → erase a (b::l) = b :: erase a l := assume h : a ≠ b, show match H a b with | inl e := l | inr n₁ := b :: erase a l end = b :: erase a l, by rewrite (decidable_eq_inr_neg h) lemma length_erase_of_mem {a : A} : ∀ {l}, a ∈ l → length (erase a l) = pred (length l) | [] h := rfl | [x] h := by rewrite [mem_singleton h, erase_cons_head] | (x::y::xs) h := by_cases (λ aeqx : a = x, by rewrite [aeqx, erase_cons_head]) (λ anex : a ≠ x, assert ainyxs : a ∈ y::xs, from or_resolve_right h anex, by rewrite [erase_cons_tail _ anex, *length_cons, length_erase_of_mem ainyxs]) lemma length_erase_of_not_mem {a : A} : ∀ {l}, a ∉ l → length (erase a l) = length l | [] h := rfl | (x::xs) h := assert anex : a ≠ x, from λ aeqx : a = x, absurd (or.inl aeqx) h, assert aninxs : a ∉ xs, from λ ainxs : a ∈ xs, absurd (or.inr ainxs) h, by rewrite [erase_cons_tail _ anex, length_cons, length_erase_of_not_mem aninxs] lemma erase_append_left {a : A} : ∀ {l₁} (l₂), a ∈ l₁ → erase a (l₁++l₂) = erase a l₁ ++ l₂ | [] l₂ h := absurd h !not_mem_nil | (x::xs) l₂ h := by_cases (λ aeqx : a = x, by rewrite [aeqx, append_cons, *erase_cons_head]) (λ anex : a ≠ x, assert ainxs : a ∈ xs, from mem_of_ne_of_mem anex h, by rewrite [append_cons, *erase_cons_tail _ anex, erase_append_left l₂ ainxs]) lemma erase_append_right {a : A} : ∀ {l₁} (l₂), a ∉ l₁ → erase a (l₁++l₂) = l₁ ++ erase a l₂ | [] l₂ h := rfl | (x::xs) l₂ h := by_cases (λ aeqx : a = x, by rewrite aeqx at h; exact (absurd !mem_cons h)) (λ anex : a ≠ x, assert nainxs : a ∉ xs, from not_mem_of_not_mem_cons h, by rewrite [append_cons, *erase_cons_tail _ anex, erase_append_right l₂ nainxs]) lemma erase_sub (a : A) : ∀ l, erase a l ⊆ l | [] := λ x xine, xine | (x::xs) := λ y xine, by_cases (λ aeqx : a = x, by rewrite [aeqx at xine, erase_cons_head at xine]; exact (or.inr xine)) (λ anex : a ≠ x, assert yinxe : y ∈ x :: erase a xs, by rewrite [erase_cons_tail _ anex at xine]; exact xine, assert subxs : erase a xs ⊆ xs, from erase_sub xs, by_cases (λ yeqx : y = x, by rewrite yeqx; apply mem_cons) (λ ynex : y ≠ x, assert yine : y ∈ erase a xs, from mem_of_ne_of_mem ynex yinxe, assert yinxs : y ∈ xs, from subxs yine, or.inr yinxs)) theorem mem_erase_of_ne_of_mem {a b : A} : ∀ {l : list A}, a ≠ b → a ∈ l → a ∈ erase b l | [] n i := absurd i !not_mem_nil | (c::l) n i := by_cases (λ beqc : b = c, assert ainl : a ∈ l, from or.elim (eq_or_mem_of_mem_cons i) (λ aeqc : a = c, absurd aeqc (beqc ▸ n)) (λ ainl : a ∈ l, ainl), by rewrite [beqc, erase_cons_head]; exact ainl) (λ bnec : b ≠ c, by_cases (λ aeqc : a = c, assert aux : a ∈ c :: erase b l, by rewrite [aeqc]; exact !mem_cons, by rewrite [erase_cons_tail _ bnec]; exact aux) (λ anec : a ≠ c, have ainl : a ∈ l, from mem_of_ne_of_mem anec i, have ainel : a ∈ erase b l, from mem_erase_of_ne_of_mem n ainl, assert aux : a ∈ c :: erase b l, from mem_cons_of_mem _ ainel, by rewrite [erase_cons_tail _ bnec]; exact aux)) -- theorem mem_of_mem_erase {a b : A} : ∀ {l}, a ∈ erase b l → a ∈ l | [] i := absurd i !not_mem_nil | (c::l) i := by_cases (λ beqc : b = c, by rewrite [beqc at i, erase_cons_head at i]; exact (mem_cons_of_mem _ i)) (λ bnec : b ≠ c, have i₁ : a ∈ c :: erase b l, by rewrite [erase_cons_tail _ bnec at i]; exact i, or.elim (eq_or_mem_of_mem_cons i₁) (λ aeqc : a = c, by rewrite [aeqc]; exact !mem_cons) (λ ainel : a ∈ erase b l, have ainl : a ∈ l, from mem_of_mem_erase ainel, mem_cons_of_mem _ ainl)) theorem all_erase_of_all {p : A → Prop} (a : A) : ∀ {l}, all l p → all (erase a l) p | [] h := by rewrite [erase_nil]; exact h | (b::l) h := assert h₁ : all l p, from all_of_all_cons h, have h₂ : all (erase a l) p, from all_erase_of_all h₁, have pb : p b, from of_all_cons h, assert h₃ : all (b :: erase a l) p, from all_cons_of_all pb h₂, by_cases (λ aeqb : a = b, by rewrite [aeqb, erase_cons_head]; exact h₁) (λ aneb : a ≠ b, by rewrite [erase_cons_tail _ aneb]; exact h₃) end erase /- disjoint -/ section disjoint variable {A : Type} definition disjoint (l₁ l₂ : list A) : Prop := ∀ ⦃a⦄, (a ∈ l₁ → a ∈ l₂ → false) lemma disjoint_left {l₁ l₂ : list A} : disjoint l₁ l₂ → ∀ {a}, a ∈ l₁ → a ∉ l₂ := λ d a, d a lemma disjoint_right {l₁ l₂ : list A} : disjoint l₁ l₂ → ∀ {a}, a ∈ l₂ → a ∉ l₁ := λ d a i₂ i₁, d a i₁ i₂ lemma disjoint.comm {l₁ l₂ : list A} : disjoint l₁ l₂ → disjoint l₂ l₁ := λ d a i₂ i₁, d a i₁ i₂ lemma disjoint_of_disjoint_cons_left {a : A} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := λ d x xinl₁, disjoint_left d (or.inr xinl₁) lemma disjoint_of_disjoint_cons_right {a : A} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := λ d, disjoint.comm (disjoint_of_disjoint_cons_left (disjoint.comm d)) lemma disjoint_nil_left (l : list A) : disjoint [] l := λ a ab, absurd ab !not_mem_nil lemma disjoint_nil_right (l : list A) : disjoint l [] := disjoint.comm (disjoint_nil_left l) lemma disjoint_cons_of_not_mem_of_disjoint {a : A} {l₁ l₂} : a ∉ l₂ → disjoint l₁ l₂ → disjoint (a::l₁) l₂ := λ nainl₂ d x (xinal₁ : x ∈ a::l₁), or.elim (eq_or_mem_of_mem_cons xinal₁) (λ xeqa : x = a, xeqa⁻¹ ▸ nainl₂) (λ xinl₁ : x ∈ l₁, disjoint_left d xinl₁) lemma disjoint_of_disjoint_append_left_left : ∀ {l₁ l₂ l : list A}, disjoint (l₁++l₂) l → disjoint l₁ l | [] l₂ l d := disjoint_nil_left l | (x::xs) l₂ l d := have nxinl : x ∉ l, from disjoint_left d !mem_cons, have d₁ : disjoint (xs++l₂) l, from disjoint_of_disjoint_cons_left d, have d₂ : disjoint xs l, from disjoint_of_disjoint_append_left_left d₁, disjoint_cons_of_not_mem_of_disjoint nxinl d₂ lemma disjoint_of_disjoint_append_left_right : ∀ {l₁ l₂ l : list A}, disjoint (l₁++l₂) l → disjoint l₂ l | [] l₂ l d := d | (x::xs) l₂ l d := have d₁ : disjoint (xs++l₂) l, from disjoint_of_disjoint_cons_left d, disjoint_of_disjoint_append_left_right d₁ lemma disjoint_of_disjoint_append_right_left : ∀ {l₁ l₂ l : list A}, disjoint l (l₁++l₂) → disjoint l l₁ := λ l₁ l₂ l d, disjoint.comm (disjoint_of_disjoint_append_left_left (disjoint.comm d)) lemma disjoint_of_disjoint_append_right_right : ∀ {l₁ l₂ l : list A}, disjoint l (l₁++l₂) → disjoint l l₂ := λ l₁ l₂ l d, disjoint.comm (disjoint_of_disjoint_append_left_right (disjoint.comm d)) end disjoint /- no duplicates predicate -/ inductive nodup {A : Type} : list A → Prop := | ndnil : nodup [] | ndcons : ∀ {a l}, a ∉ l → nodup l → nodup (a::l) section nodup open nodup variables {A B : Type} theorem nodup_nil : @nodup A [] := ndnil theorem nodup_cons {a : A} {l : list A} : a ∉ l → nodup l → nodup (a::l) := λ i n, ndcons i n theorem nodup_singleton (a : A) : nodup [a] := nodup_cons !not_mem_nil nodup_nil theorem nodup_of_nodup_cons : ∀ {a : A} {l : list A}, nodup (a::l) → nodup l | a xs (ndcons i n) := n theorem not_mem_of_nodup_cons : ∀ {a : A} {l : list A}, nodup (a::l) → a ∉ l | a xs (ndcons i n) := i theorem not_nodup_cons_of_mem {a : A} {l : list A} : a ∈ l → ¬ nodup (a :: l) := λ ainl d, absurd ainl (not_mem_of_nodup_cons d) theorem not_nodup_cons_of_not_nodup {a : A} {l : list A} : ¬ nodup l → ¬ nodup (a :: l) := λ nd d, absurd (nodup_of_nodup_cons d) nd theorem nodup_of_nodup_append_left : ∀ {l₁ l₂ : list A}, nodup (l₁++l₂) → nodup l₁ | [] l₂ n := nodup_nil | (x::xs) l₂ n := have ndxs : nodup xs, from nodup_of_nodup_append_left (nodup_of_nodup_cons n), have nxinxsl₂ : x ∉ xs++l₂, from not_mem_of_nodup_cons n, have nxinxs : x ∉ xs, from not_mem_of_not_mem_append_left nxinxsl₂, nodup_cons nxinxs ndxs theorem nodup_of_nodup_append_right : ∀ {l₁ l₂ : list A}, nodup (l₁++l₂) → nodup l₂ | [] l₂ n := n | (x::xs) l₂ n := nodup_of_nodup_append_right (nodup_of_nodup_cons n) theorem disjoint_of_nodup_append : ∀ {l₁ l₂ : list A}, nodup (l₁++l₂) → disjoint l₁ l₂ | [] l₂ d := disjoint_nil_left l₂ | (x::xs) l₂ d := have d₁ : nodup (x::(xs++l₂)), from d, have d₂ : nodup (xs++l₂), from nodup_of_nodup_cons d₁, have nxin : x ∉ xs++l₂, from not_mem_of_nodup_cons d₁, have nxinl₂ : x ∉ l₂, from not_mem_of_not_mem_append_right nxin, have dsj : disjoint xs l₂, from disjoint_of_nodup_append d₂, λ a (ainxxs : a ∈ x::xs), or.elim (eq_or_mem_of_mem_cons ainxxs) (λ aeqx : a = x, aeqx⁻¹ ▸ nxinl₂) (λ ainxs : a ∈ xs, disjoint_left dsj ainxs) theorem nodup_append_of_nodup_of_nodup_of_disjoint : ∀ {l₁ l₂ : list A}, nodup l₁ → nodup l₂ → disjoint l₁ l₂ → nodup (l₁++l₂) | [] l₂ d₁ d₂ dsj := by rewrite [append_nil_left]; exact d₂ | (x::xs) l₂ d₁ d₂ dsj := have dsj₁ : disjoint xs l₂, from disjoint_of_disjoint_cons_left dsj, have ndxs : nodup xs, from nodup_of_nodup_cons d₁, have ndxsl₂ : nodup (xs++l₂), from nodup_append_of_nodup_of_nodup_of_disjoint ndxs d₂ dsj₁, have nxinxs : x ∉ xs, from not_mem_of_nodup_cons d₁, have nxinl₂ : x ∉ l₂, from disjoint_left dsj !mem_cons, have nxinxsl₂ : x ∉ xs++l₂, from not_mem_append nxinxs nxinl₂, nodup_cons nxinxsl₂ ndxsl₂ theorem nodup_app_comm {l₁ l₂ : list A} (d : nodup (l₁++l₂)) : nodup (l₂++l₁) := have d₁ : nodup l₁, from nodup_of_nodup_append_left d, have d₂ : nodup l₂, from nodup_of_nodup_append_right d, have dsj : disjoint l₁ l₂, from disjoint_of_nodup_append d, nodup_append_of_nodup_of_nodup_of_disjoint d₂ d₁ (disjoint.comm dsj) theorem nodup_head {a : A} {l₁ l₂ : list A} (d : nodup (l₁++(a::l₂))) : nodup (a::(l₁++l₂)) := have d₁ : nodup (a::(l₂++l₁)), from nodup_app_comm d, have d₂ : nodup (l₂++l₁), from nodup_of_nodup_cons d₁, have d₃ : nodup (l₁++l₂), from nodup_app_comm d₂, have nain : a ∉ l₂++l₁, from not_mem_of_nodup_cons d₁, have nain₂ : a ∉ l₂, from not_mem_of_not_mem_append_left nain, have nain₁ : a ∉ l₁, from not_mem_of_not_mem_append_right nain, nodup_cons (not_mem_append nain₁ nain₂) d₃ theorem nodup_middle {a : A} {l₁ l₂ : list A} (d : nodup (a::(l₁++l₂))) : nodup (l₁++(a::l₂)) := have d₁ : nodup (l₁++l₂), from nodup_of_nodup_cons d, have nain : a ∉ l₁++l₂, from not_mem_of_nodup_cons d, have disj : disjoint l₁ l₂, from disjoint_of_nodup_append d₁, have d₂ : nodup l₁, from nodup_of_nodup_append_left d₁, have d₃ : nodup l₂, from nodup_of_nodup_append_right d₁, have nain₂ : a ∉ l₂, from not_mem_of_not_mem_append_right nain, have nain₁ : a ∉ l₁, from not_mem_of_not_mem_append_left nain, have d₄ : nodup (a::l₂), from nodup_cons nain₂ d₃, have disj₂ : disjoint l₁ (a::l₂), from disjoint.comm (disjoint_cons_of_not_mem_of_disjoint nain₁ (disjoint.comm disj)), nodup_append_of_nodup_of_nodup_of_disjoint d₂ d₄ disj₂ theorem nodup_map {f : A → B} (inj : injective f) : ∀ {l : list A}, nodup l → nodup (map f l) | [] n := begin rewrite [map_nil], apply nodup_nil end | (x::xs) n := assert nxinxs : x ∉ xs, from not_mem_of_nodup_cons n, assert ndxs : nodup xs, from nodup_of_nodup_cons n, assert ndmfxs : nodup (map f xs), from nodup_map ndxs, assert nfxinm : f x ∉ map f xs, from λ ab : f x ∈ map f xs, obtain (y : A) (yinxs : y ∈ xs) (fyfx : f y = f x), from exists_of_mem_map ab, assert yeqx : y = x, from inj fyfx, by subst y; contradiction, nodup_cons nfxinm ndmfxs theorem nodup_erase_of_nodup [h : decidable_eq A] (a : A) : ∀ {l}, nodup l → nodup (erase a l) | [] n := nodup_nil | (b::l) n := by_cases (λ aeqb : a = b, by rewrite [aeqb, erase_cons_head]; exact (nodup_of_nodup_cons n)) (λ aneb : a ≠ b, have nbinl : b ∉ l, from not_mem_of_nodup_cons n, have ndl : nodup l, from nodup_of_nodup_cons n, have ndeal : nodup (erase a l), from nodup_erase_of_nodup ndl, have nbineal : b ∉ erase a l, from λ i, absurd (erase_sub _ _ i) nbinl, assert aux : nodup (b :: erase a l), from nodup_cons nbineal ndeal, by rewrite [erase_cons_tail _ aneb]; exact aux) theorem mem_erase_of_nodup [h : decidable_eq A] (a : A) : ∀ {l}, nodup l → a ∉ erase a l | [] n := !not_mem_nil | (b::l) n := have ndl : nodup l, from nodup_of_nodup_cons n, have naineal : a ∉ erase a l, from mem_erase_of_nodup ndl, assert nbinl : b ∉ l, from not_mem_of_nodup_cons n, by_cases (λ aeqb : a = b, by rewrite [aeqb, erase_cons_head]; exact nbinl) (λ aneb : a ≠ b, assert aux : a ∉ b :: erase a l, from assume ainbeal : a ∈ b :: erase a l, or.elim (eq_or_mem_of_mem_cons ainbeal) (λ aeqb : a = b, absurd aeqb aneb) (λ aineal : a ∈ erase a l, absurd aineal naineal), by rewrite [erase_cons_tail _ aneb]; exact aux) definition erase_dup [H : decidable_eq A] : list A → list A | [] := [] | (x :: xs) := if x ∈ xs then erase_dup xs else x :: erase_dup xs theorem erase_dup_nil [H : decidable_eq A] : erase_dup [] = ([] : list A) theorem erase_dup_cons_of_mem [H : decidable_eq A] {a : A} {l : list A} : a ∈ l → erase_dup (a::l) = erase_dup l := assume ainl, calc erase_dup (a::l) = if a ∈ l then erase_dup l else a :: erase_dup l : rfl ... = erase_dup l : if_pos ainl theorem erase_dup_cons_of_not_mem [H : decidable_eq A] {a : A} {l : list A} : a ∉ l → erase_dup (a::l) = a :: erase_dup l := assume nainl, calc erase_dup (a::l) = if a ∈ l then erase_dup l else a :: erase_dup l : rfl ... = a :: erase_dup l : if_neg nainl theorem mem_erase_dup [H : decidable_eq A] {a : A} : ∀ {l}, a ∈ l → a ∈ erase_dup l | [] h := absurd h !not_mem_nil | (b::l) h := by_cases (λ binl : b ∈ l, or.elim (eq_or_mem_of_mem_cons h) (λ aeqb : a = b, by rewrite [erase_dup_cons_of_mem binl, -aeqb at binl]; exact (mem_erase_dup binl)) (λ ainl : a ∈ l, by rewrite [erase_dup_cons_of_mem binl]; exact (mem_erase_dup ainl))) (λ nbinl : b ∉ l, or.elim (eq_or_mem_of_mem_cons h) (λ aeqb : a = b, by rewrite [erase_dup_cons_of_not_mem nbinl, aeqb]; exact !mem_cons) (λ ainl : a ∈ l, by rewrite [erase_dup_cons_of_not_mem nbinl]; exact (or.inr (mem_erase_dup ainl)))) theorem mem_of_mem_erase_dup [H : decidable_eq A] {a : A} : ∀ {l}, a ∈ erase_dup l → a ∈ l | [] h := by rewrite [erase_dup_nil at h]; exact h | (b::l) h := by_cases (λ binl : b ∈ l, have h₁ : a ∈ erase_dup l, by rewrite [erase_dup_cons_of_mem binl at h]; exact h, or.inr (mem_of_mem_erase_dup h₁)) (λ nbinl : b ∉ l, have h₁ : a ∈ b :: erase_dup l, by rewrite [erase_dup_cons_of_not_mem nbinl at h]; exact h, or.elim (eq_or_mem_of_mem_cons h₁) (λ aeqb : a = b, by rewrite aeqb; exact !mem_cons) (λ ainel : a ∈ erase_dup l, or.inr (mem_of_mem_erase_dup ainel))) theorem erase_dup_sub [H : decidable_eq A] (l : list A) : erase_dup l ⊆ l := λ a i, mem_of_mem_erase_dup i theorem sub_erase_dup [H : decidable_eq A] (l : list A) : l ⊆ erase_dup l := λ a i, mem_erase_dup i theorem nodup_erase_dup [H : decidable_eq A] : ∀ l : list A, nodup (erase_dup l) | [] := by rewrite erase_dup_nil; exact nodup_nil | (a::l) := by_cases (λ ainl : a ∈ l, by rewrite [erase_dup_cons_of_mem ainl]; exact (nodup_erase_dup l)) (λ nainl : a ∉ l, assert r : nodup (erase_dup l), from nodup_erase_dup l, assert nin : a ∉ erase_dup l, from assume ab : a ∈ erase_dup l, absurd (mem_of_mem_erase_dup ab) nainl, by rewrite [erase_dup_cons_of_not_mem nainl]; exact (nodup_cons nin r)) theorem erase_dup_eq_of_nodup [H : decidable_eq A] : ∀ {l : list A}, nodup l → erase_dup l = l | [] d := rfl | (a::l) d := assert nainl : a ∉ l, from not_mem_of_nodup_cons d, assert dl : nodup l, from nodup_of_nodup_cons d, by rewrite [erase_dup_cons_of_not_mem nainl, erase_dup_eq_of_nodup dl] definition decidable_nodup [instance] [h : decidable_eq A] : ∀ (l : list A), decidable (nodup l) | [] := inl nodup_nil | (a::l) := match decidable_mem a l with | inl p := inr (not_nodup_cons_of_mem p) | inr n := match decidable_nodup l with | inl nd := inl (nodup_cons n nd) | inr d := inr (not_nodup_cons_of_not_nodup d) end end theorem nodup_product : ∀ {l₁ : list A} {l₂ : list B}, nodup l₁ → nodup l₂ → nodup (product l₁ l₂) | [] l₂ n₁ n₂ := nodup_nil | (a::l₁) l₂ n₁ n₂ := have nainl₁ : a ∉ l₁, from not_mem_of_nodup_cons n₁, have n₃ : nodup l₁, from nodup_of_nodup_cons n₁, have n₄ : nodup (product l₁ l₂), from nodup_product n₃ n₂, have dgen : ∀ l, nodup l → nodup (map (λ b, (a, b)) l) | [] h := nodup_nil | (x::l) h := have dl : nodup l, from nodup_of_nodup_cons h, have dm : nodup (map (λ b, (a, b)) l), from dgen l dl, have nxin : x ∉ l, from not_mem_of_nodup_cons h, have npin : (a, x) ∉ map (λ b, (a, b)) l, from assume pin, absurd (mem_of_mem_map_pair₁ pin) nxin, nodup_cons npin dm, have dm : nodup (map (λ b, (a, b)) l₂), from dgen l₂ n₂, have dsj : disjoint (map (λ b, (a, b)) l₂) (product l₁ l₂), from λ p, match p with | (a₁, b₁) := λ (i₁ : (a₁, b₁) ∈ map (λ b, (a, b)) l₂) (i₂ : (a₁, b₁) ∈ product l₁ l₂), have a₁inl₁ : a₁ ∈ l₁, from mem_of_mem_product_left i₂, have a₁eqa : a₁ = a, from eq_of_mem_map_pair₁ i₁, absurd (a₁eqa ▸ a₁inl₁) nainl₁ end, nodup_append_of_nodup_of_nodup_of_disjoint dm n₄ dsj theorem nodup_filter (p : A → Prop) [h : decidable_pred p] : ∀ {l : list A}, nodup l → nodup (filter p l) | [] nd := nodup_nil | (a::l) nd := have nainl : a ∉ l, from not_mem_of_nodup_cons nd, have ndl : nodup l, from nodup_of_nodup_cons nd, assert ndf : nodup (filter p l), from nodup_filter ndl, assert nainf : a ∉ filter p l, from assume ainf, absurd (mem_of_mem_filter ainf) nainl, by_cases (λ pa : p a, by rewrite [filter_cons_of_pos _ pa]; exact (nodup_cons nainf ndf)) (λ npa : ¬ p a, by rewrite [filter_cons_of_neg _ npa]; exact ndf) lemma dmap_nodup_of_dinj {p : A → Prop} [h : decidable_pred p] {f : Π a, p a → B} (Pdi : dinj p f): ∀ {l : list A}, nodup l → nodup (dmap p f l) | [] := take P, nodup.ndnil | (a::l) := take Pnodup, decidable.rec_on (h a) (λ Pa, begin rewrite [dmap_cons_of_pos Pa], apply nodup_cons, apply (not_mem_dmap_of_dinj_of_not_mem Pdi Pa), exact not_mem_of_nodup_cons Pnodup, exact dmap_nodup_of_dinj (nodup_of_nodup_cons Pnodup) end) (λ nPa, begin rewrite [dmap_cons_of_neg nPa], exact dmap_nodup_of_dinj (nodup_of_nodup_cons Pnodup) end) end nodup /- upto -/ definition upto : nat → list nat | 0 := [] | (n+1) := n :: upto n theorem upto_nil : upto 0 = nil theorem upto_succ (n : nat) : upto (succ n) = n :: upto n theorem length_upto : ∀ n, length (upto n) = n | 0 := rfl | (succ n) := by rewrite [upto_succ, length_cons, length_upto] theorem upto_less : ∀ n, all (upto n) (λ i, i < n) | 0 := trivial | (succ n) := have alln : all (upto n) (λ i, i < n), from upto_less n, all_cons_of_all (lt.base n) (all_implies alln (λ x h, lt.step h)) theorem nodup_upto : ∀ n, nodup (upto n) | 0 := nodup_nil | (n+1) := have d : nodup (upto n), from nodup_upto n, have n : n ∉ upto n, from assume i : n ∈ upto n, absurd (of_mem_of_all i (upto_less n)) (lt.irrefl n), nodup_cons n d theorem lt_of_mem_upto {n i : nat} : i ∈ upto n → i < n := assume i, of_mem_of_all i (upto_less n) theorem mem_upto_succ_of_mem_upto {n i : nat} : i ∈ upto n → i ∈ upto (succ n) := assume i, mem_cons_of_mem _ i theorem mem_upto_of_lt : ∀ {n i : nat}, i < n → i ∈ upto n | 0 i h := absurd h !not_lt_zero | (succ n) i h := begin cases h with m h', { rewrite upto_succ, apply mem_cons}, { exact mem_upto_succ_of_mem_upto (mem_upto_of_lt h')} end lemma upto_step : ∀ {n : nat}, upto (succ n) = (map succ (upto n))++[0] | 0 := rfl | (succ n) := begin rewrite [upto_succ n, map_cons, append_cons, -upto_step] end /- union -/ section union variable {A : Type} variable [H : decidable_eq A] include H definition union : list A → list A → list A | [] l₂ := l₂ | (a::l₁) l₂ := if a ∈ l₂ then union l₁ l₂ else a :: union l₁ l₂ theorem nil_union (l : list A) : union [] l = l theorem union_cons_of_mem {a : A} {l₂} : ∀ (l₁), a ∈ l₂ → union (a::l₁) l₂ = union l₁ l₂ := take l₁, assume ainl₂, calc union (a::l₁) l₂ = if a ∈ l₂ then union l₁ l₂ else a :: union l₁ l₂ : rfl ... = union l₁ l₂ : if_pos ainl₂ theorem union_cons_of_not_mem {a : A} {l₂} : ∀ (l₁), a ∉ l₂ → union (a::l₁) l₂ = a :: union l₁ l₂ := take l₁, assume nainl₂, calc union (a::l₁) l₂ = if a ∈ l₂ then union l₁ l₂ else a :: union l₁ l₂ : rfl ... = a :: union l₁ l₂ : if_neg nainl₂ theorem union_nil : ∀ (l : list A), union l [] = l | [] := !nil_union | (a::l) := by rewrite [union_cons_of_not_mem _ !not_mem_nil, union_nil] theorem mem_or_mem_of_mem_union : ∀ {l₁ l₂} {a : A}, a ∈ union l₁ l₂ → a ∈ l₁ ∨ a ∈ l₂ | [] l₂ a ainl₂ := by rewrite nil_union at ainl₂; exact (or.inr (ainl₂)) | (b::l₁) l₂ a ainbl₁l₂ := by_cases (λ binl₂ : b ∈ l₂, have ainl₁l₂ : a ∈ union l₁ l₂, by rewrite [union_cons_of_mem l₁ binl₂ at ainbl₁l₂]; exact ainbl₁l₂, or.elim (mem_or_mem_of_mem_union ainl₁l₂) (λ ainl₁, or.inl (mem_cons_of_mem _ ainl₁)) (λ ainl₂, or.inr ainl₂)) (λ nbinl₂ : b ∉ l₂, have ainb_l₁l₂ : a ∈ b :: union l₁ l₂, by rewrite [union_cons_of_not_mem l₁ nbinl₂ at ainbl₁l₂]; exact ainbl₁l₂, or.elim (eq_or_mem_of_mem_cons ainb_l₁l₂) (λ aeqb, by rewrite aeqb; exact (or.inl !mem_cons)) (λ ainl₁l₂, or.elim (mem_or_mem_of_mem_union ainl₁l₂) (λ ainl₁, or.inl (mem_cons_of_mem _ ainl₁)) (λ ainl₂, or.inr ainl₂))) theorem mem_union_right {a : A} : ∀ (l₁) {l₂}, a ∈ l₂ → a ∈ union l₁ l₂ | [] l₂ h := by rewrite nil_union; exact h | (b::l₁) l₂ h := by_cases (λ binl₂ : b ∈ l₂, by rewrite [union_cons_of_mem _ binl₂]; exact (mem_union_right _ h)) (λ nbinl₂ : b ∉ l₂, by rewrite [union_cons_of_not_mem _ nbinl₂]; exact (mem_cons_of_mem _ (mem_union_right _ h))) theorem mem_union_left {a : A} : ∀ {l₁} (l₂), a ∈ l₁ → a ∈ union l₁ l₂ | [] l₂ h := absurd h !not_mem_nil | (b::l₁) l₂ h := by_cases (λ binl₂ : b ∈ l₂, or.elim (eq_or_mem_of_mem_cons h) (λ aeqb : a = b, by rewrite [union_cons_of_mem l₁ binl₂, -aeqb at binl₂]; exact (mem_union_right _ binl₂)) (λ ainl₁ : a ∈ l₁, by rewrite [union_cons_of_mem l₁ binl₂]; exact (mem_union_left _ ainl₁))) (λ nbinl₂ : b ∉ l₂, or.elim (eq_or_mem_of_mem_cons h) (λ aeqb : a = b, by rewrite [union_cons_of_not_mem l₁ nbinl₂, aeqb]; exact !mem_cons) (λ ainl₁ : a ∈ l₁, by rewrite [union_cons_of_not_mem l₁ nbinl₂]; exact (mem_cons_of_mem _ (mem_union_left _ ainl₁)))) theorem mem_union_cons (a : A) (l₁ : list A) (l₂ : list A) : a ∈ union (a::l₁) l₂ := by_cases (λ ainl₂ : a ∈ l₂, mem_union_right _ ainl₂) (λ nainl₂ : a ∉ l₂, by rewrite [union_cons_of_not_mem _ nainl₂]; exact !mem_cons) theorem nodup_union_of_nodup_of_nodup : ∀ {l₁ l₂ : list A}, nodup l₁ → nodup l₂ → nodup (union l₁ l₂) | [] l₂ n₁ nl₂ := by rewrite nil_union; exact nl₂ | (a::l₁) l₂ nal₁ nl₂ := assert nl₁ : nodup l₁, from nodup_of_nodup_cons nal₁, assert nl₁l₂ : nodup (union l₁ l₂), from nodup_union_of_nodup_of_nodup nl₁ nl₂, by_cases (λ ainl₂ : a ∈ l₂, by rewrite [union_cons_of_mem l₁ ainl₂]; exact nl₁l₂) (λ nainl₂ : a ∉ l₂, have nainl₁ : a ∉ l₁, from not_mem_of_nodup_cons nal₁, assert nainl₁l₂ : a ∉ union l₁ l₂, from assume ainl₁l₂ : a ∈ union l₁ l₂, or.elim (mem_or_mem_of_mem_union ainl₁l₂) (λ ainl₁, absurd ainl₁ nainl₁) (λ ainl₂, absurd ainl₂ nainl₂), by rewrite [union_cons_of_not_mem l₁ nainl₂]; exact (nodup_cons nainl₁l₂ nl₁l₂)) theorem union_eq_append : ∀ {l₁ l₂ : list A}, disjoint l₁ l₂ → union l₁ l₂ = append l₁ l₂ | [] l₂ d := rfl | (a::l₁) l₂ d := assert nainl₂ : a ∉ l₂, from disjoint_left d !mem_cons, assert d₁ : disjoint l₁ l₂, from disjoint_of_disjoint_cons_left d, by rewrite [union_cons_of_not_mem _ nainl₂, append_cons, union_eq_append d₁] theorem all_union {p : A → Prop} : ∀ {l₁ l₂ : list A}, all l₁ p → all l₂ p → all (union l₁ l₂) p | [] l₂ h₁ h₂ := h₂ | (a::l₁) l₂ h₁ h₂ := have h₁' : all l₁ p, from all_of_all_cons h₁, have pa : p a, from of_all_cons h₁, assert au : all (union l₁ l₂) p, from all_union h₁' h₂, assert au' : all (a :: union l₁ l₂) p, from all_cons_of_all pa au, by_cases (λ ainl₂ : a ∈ l₂, by rewrite [union_cons_of_mem _ ainl₂]; exact au) (λ nainl₂ : a ∉ l₂, by rewrite [union_cons_of_not_mem _ nainl₂]; exact au') theorem all_of_all_union_left {p : A → Prop} : ∀ {l₁ l₂ : list A}, all (union l₁ l₂) p → all l₁ p | [] l₂ h := trivial | (a::l₁) l₂ h := have ain : a ∈ union (a::l₁) l₂, from !mem_union_cons, have pa : p a, from of_mem_of_all ain h, by_cases (λ ainl₂ : a ∈ l₂, have al₁l₂ : all (union l₁ l₂) p, by rewrite [union_cons_of_mem _ ainl₂ at h]; exact h, have al₁ : all l₁ p, from all_of_all_union_left al₁l₂, all_cons_of_all pa al₁) (λ nainl₂ : a ∉ l₂, have aal₁l₂ : all (a::union l₁ l₂) p, by rewrite [union_cons_of_not_mem _ nainl₂ at h]; exact h, have al₁l₂ : all (union l₁ l₂) p, from all_of_all_cons aal₁l₂, have al₁ : all l₁ p, from all_of_all_union_left al₁l₂, all_cons_of_all pa al₁) theorem all_of_all_union_right {p : A → Prop} : ∀ {l₁ l₂ : list A}, all (union l₁ l₂) p → all l₂ p | [] l₂ h := by rewrite [nil_union at h]; exact h | (a::l₁) l₂ h := by_cases (λ ainl₂ : a ∈ l₂, by rewrite [union_cons_of_mem _ ainl₂ at h]; exact (all_of_all_union_right h)) (λ nainl₂ : a ∉ l₂, have h₁ : all (a :: union l₁ l₂) p, by rewrite [union_cons_of_not_mem _ nainl₂ at h]; exact h, all_of_all_union_right (all_of_all_cons h₁)) variable {B : Type} theorem foldl_union_of_disjoint (f : B → A → B) (b : B) {l₁ l₂ : list A} (d : disjoint l₁ l₂) : foldl f b (union l₁ l₂) = foldl f (foldl f b l₁) l₂ := by rewrite [union_eq_append d, foldl_append] theorem foldr_union_of_dijoint (f : A → B → B) (b : B) {l₁ l₂ : list A} (d : disjoint l₁ l₂) : foldr f b (union l₁ l₂) = foldr f (foldr f b l₂) l₁ := by rewrite [union_eq_append d, foldr_append] end union /- insert -/ section insert variable {A : Type} variable [H : decidable_eq A] include H definition insert (a : A) (l : list A) : list A := if a ∈ l then l else a::l theorem insert_eq_of_mem {a : A} {l : list A} : a ∈ l → insert a l = l := assume ainl, if_pos ainl theorem insert_eq_of_not_mem {a : A} {l : list A} : a ∉ l → insert a l = a::l := assume nainl, if_neg nainl theorem mem_insert (a : A) (l : list A) : a ∈ insert a l := by_cases (λ ainl : a ∈ l, by rewrite [insert_eq_of_mem ainl]; exact ainl) (λ nainl : a ∉ l, by rewrite [insert_eq_of_not_mem nainl]; exact !mem_cons) theorem mem_insert_of_mem {a : A} (b : A) {l : list A} : a ∈ l → a ∈ insert b l := assume ainl, by_cases (λ binl : b ∈ l, by rewrite [insert_eq_of_mem binl]; exact ainl) (λ nbinl : b ∉ l, by rewrite [insert_eq_of_not_mem nbinl]; exact (mem_cons_of_mem _ ainl)) theorem eq_or_mem_of_mem_insert {x a : A} {l : list A} (H : x ∈ insert a l) : x = a ∨ x ∈ l := decidable.by_cases (assume H3: a ∈ l, or.inr (insert_eq_of_mem H3 ▸ H)) (assume H3: a ∉ l, have H4: x ∈ a :: l, from insert_eq_of_not_mem H3 ▸ H, iff.mp !mem_cons_iff H4) theorem mem_insert_iff (x a : A) (l : list A) : x ∈ insert a l ↔ x = a ∨ x ∈ l := iff.intro (!eq_or_mem_of_mem_insert) (assume H, or.elim H (assume H' : x = a, H'⁻¹ ▸ !mem_insert) (assume H' : x ∈ l, !mem_insert_of_mem H')) theorem nodup_insert (a : A) {l : list A} : nodup l → nodup (insert a l) := assume n, by_cases (λ ainl : a ∈ l, by rewrite [insert_eq_of_mem ainl]; exact n) (λ nainl : a ∉ l, by rewrite [insert_eq_of_not_mem nainl]; exact (nodup_cons nainl n)) theorem length_insert_of_mem {a : A} {l : list A} : a ∈ l → length (insert a l) = length l := assume ainl, by rewrite [insert_eq_of_mem ainl] theorem length_insert_of_not_mem {a : A} {l : list A} : a ∉ l → length (insert a l) = length l + 1 := assume nainl, by rewrite [insert_eq_of_not_mem nainl] theorem all_insert_of_all {p : A → Prop} {a : A} {l} : p a → all l p → all (insert a l) p := assume h₁ h₂, by_cases (λ ainl : a ∈ l, by rewrite [insert_eq_of_mem ainl]; exact h₂) (λ nainl : a ∉ l, by rewrite [insert_eq_of_not_mem nainl]; exact (all_cons_of_all h₁ h₂)) end insert /- inter -/ section inter variable {A : Type} variable [H : decidable_eq A] include H definition inter : list A → list A → list A | [] l₂ := [] | (a::l₁) l₂ := if a ∈ l₂ then a :: inter l₁ l₂ else inter l₁ l₂ theorem inter_nil (l : list A) : inter [] l = [] theorem inter_cons_of_mem {a : A} (l₁ : list A) {l₂} : a ∈ l₂ → inter (a::l₁) l₂ = a :: inter l₁ l₂ := assume i, if_pos i theorem inter_cons_of_not_mem {a : A} (l₁ : list A) {l₂} : a ∉ l₂ → inter (a::l₁) l₂ = inter l₁ l₂ := assume i, if_neg i theorem mem_of_mem_inter_left : ∀ {l₁ l₂} {a : A}, a ∈ inter l₁ l₂ → a ∈ l₁ | [] l₂ a i := absurd i !not_mem_nil | (b::l₁) l₂ a i := by_cases (λ binl₂ : b ∈ l₂, have aux : a ∈ b :: inter l₁ l₂, by rewrite [inter_cons_of_mem _ binl₂ at i]; exact i, or.elim (eq_or_mem_of_mem_cons aux) (λ aeqb : a = b, by rewrite [aeqb]; exact !mem_cons) (λ aini, mem_cons_of_mem _ (mem_of_mem_inter_left aini))) (λ nbinl₂ : b ∉ l₂, have ainl₁ : a ∈ l₁, by rewrite [inter_cons_of_not_mem _ nbinl₂ at i]; exact (mem_of_mem_inter_left i), mem_cons_of_mem _ ainl₁) theorem mem_of_mem_inter_right : ∀ {l₁ l₂} {a : A}, a ∈ inter l₁ l₂ → a ∈ l₂ | [] l₂ a i := absurd i !not_mem_nil | (b::l₁) l₂ a i := by_cases (λ binl₂ : b ∈ l₂, have aux : a ∈ b :: inter l₁ l₂, by rewrite [inter_cons_of_mem _ binl₂ at i]; exact i, or.elim (eq_or_mem_of_mem_cons aux) (λ aeqb : a = b, by rewrite [aeqb]; exact binl₂) (λ aini : a ∈ inter l₁ l₂, mem_of_mem_inter_right aini)) (λ nbinl₂ : b ∉ l₂, by rewrite [inter_cons_of_not_mem _ nbinl₂ at i]; exact (mem_of_mem_inter_right i)) theorem mem_inter_of_mem_of_mem : ∀ {l₁ l₂} {a : A}, a ∈ l₁ → a ∈ l₂ → a ∈ inter l₁ l₂ | [] l₂ a i₁ i₂ := absurd i₁ !not_mem_nil | (b::l₁) l₂ a i₁ i₂ := by_cases (λ binl₂ : b ∈ l₂, or.elim (eq_or_mem_of_mem_cons i₁) (λ aeqb : a = b, by rewrite [inter_cons_of_mem _ binl₂, aeqb]; exact !mem_cons) (λ ainl₁ : a ∈ l₁, by rewrite [inter_cons_of_mem _ binl₂]; apply mem_cons_of_mem; exact (mem_inter_of_mem_of_mem ainl₁ i₂))) (λ nbinl₂ : b ∉ l₂, or.elim (eq_or_mem_of_mem_cons i₁) (λ aeqb : a = b, absurd (aeqb ▸ i₂) nbinl₂) (λ ainl₁ : a ∈ l₁, by rewrite [inter_cons_of_not_mem _ nbinl₂]; exact (mem_inter_of_mem_of_mem ainl₁ i₂))) theorem nodup_inter_of_nodup : ∀ {l₁ : list A} (l₂), nodup l₁ → nodup (inter l₁ l₂) | [] l₂ d := nodup_nil | (a::l₁) l₂ d := have d₁ : nodup l₁, from nodup_of_nodup_cons d, assert d₂ : nodup (inter l₁ l₂), from nodup_inter_of_nodup _ d₁, have nainl₁ : a ∉ l₁, from not_mem_of_nodup_cons d, assert naini : a ∉ inter l₁ l₂, from λ i, absurd (mem_of_mem_inter_left i) nainl₁, by_cases (λ ainl₂ : a ∈ l₂, by rewrite [inter_cons_of_mem _ ainl₂]; exact (nodup_cons naini d₂)) (λ nainl₂ : a ∉ l₂, by rewrite [inter_cons_of_not_mem _ nainl₂]; exact d₂) theorem inter_eq_nil_of_disjoint : ∀ {l₁ l₂ : list A}, disjoint l₁ l₂ → inter l₁ l₂ = [] | [] l₂ d := rfl | (a::l₁) l₂ d := assert aux_eq : inter l₁ l₂ = [], from inter_eq_nil_of_disjoint (disjoint_of_disjoint_cons_left d), assert nainl₂ : a ∉ l₂, from disjoint_left d !mem_cons, by rewrite [inter_cons_of_not_mem _ nainl₂, aux_eq] theorem all_inter_of_all_left {p : A → Prop} : ∀ {l₁} (l₂), all l₁ p → all (inter l₁ l₂) p | [] l₂ h := trivial | (a::l₁) l₂ h := have h₁ : all l₁ p, from all_of_all_cons h, assert h₂ : all (inter l₁ l₂) p, from all_inter_of_all_left _ h₁, have pa : p a, from of_all_cons h, assert h₃ : all (a :: inter l₁ l₂) p, from all_cons_of_all pa h₂, by_cases (λ ainl₂ : a ∈ l₂, by rewrite [inter_cons_of_mem _ ainl₂]; exact h₃) (λ nainl₂ : a ∉ l₂, by rewrite [inter_cons_of_not_mem _ nainl₂]; exact h₂) theorem all_inter_of_all_right {p : A → Prop} : ∀ (l₁) {l₂}, all l₂ p → all (inter l₁ l₂) p | [] l₂ h := trivial | (a::l₁) l₂ h := assert h₁ : all (inter l₁ l₂) p, from all_inter_of_all_right _ h, by_cases (λ ainl₂ : a ∈ l₂, have pa : p a, from of_mem_of_all ainl₂ h, assert h₂ : all (a :: inter l₁ l₂) p, from all_cons_of_all pa h₁, by rewrite [inter_cons_of_mem _ ainl₂]; exact h₂) (λ nainl₂ : a ∉ l₂, by rewrite [inter_cons_of_not_mem _ nainl₂]; exact h₁) end inter end list
6062689c16d70ca2292da05afac1162227c27315
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/imp.lean
2da67e149a002c90cdb6174fc41653916cc53b1f
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
3,758
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Yury Kudryashov -/ import order.symm_diff import tactic.monotonicity.basic /-! # Implication and equivalence as operations on a boolean algebra In this file we define `lattice.imp` (notation: `a ⇒ₒ b`) and `lattice.biimp` (notation: `a ⇔ₒ b`) to be the implication and equivalence as operations on a boolean algebra. More precisely, we put `a ⇒ₒ b = aᶜ ⊔ b` and `a ⇔ₒ b = (a ⇒ₒ b) ⊓ (b ⇒ₒ a)`. Equivalently, `a ⇒ₒ b = (a \ b)ᶜ` and `a ⇔ₒ b = (a Δ b)ᶜ`. For propositions these operations are equal to the usual implication and `iff`. -/ variables {α β : Type*} namespace lattice /-- Implication as a binary operation on a boolean algebra. -/ def imp [has_compl α] [has_sup α] (a b : α) : α := aᶜ ⊔ b infix ` ⇒ₒ `:65 := lattice.imp /-- Equivalence as a binary operation on a boolean algebra. -/ def biimp [has_compl α] [has_sup α] [has_inf α] (a b : α) : α := (a ⇒ₒ b) ⊓ (b ⇒ₒ a) infix ` ⇔ₒ `:60 := lattice.biimp @[simp] lemma imp_eq_arrow (p q : Prop) : p ⇒ₒ q = (p → q) := propext imp_iff_not_or.symm @[simp] lemma biimp_eq_iff (p q : Prop) : p ⇔ₒ q = (p ↔ q) := by simp [biimp, ← iff_def] variables [boolean_algebra α] {a b c d : α} @[simp] lemma compl_imp (a b : α) : (a ⇒ₒ b)ᶜ = a \ b := by simp [imp, sdiff_eq] lemma compl_sdiff (a b : α) : (a \ b)ᶜ = a ⇒ₒ b := by rw [← compl_imp, compl_compl] @[mono] lemma imp_mono (h₁ : a ≤ b) (h₂ : c ≤ d) : b ⇒ₒ c ≤ a ⇒ₒ d := sup_le_sup (compl_le_compl h₁) h₂ lemma inf_imp_eq (a b c : α) : a ⊓ (b ⇒ₒ c) = (a ⇒ₒ b) ⇒ₒ (a ⊓ c) := by unfold imp; simp [inf_sup_left] @[simp] lemma imp_eq_top_iff : (a ⇒ₒ b = ⊤) ↔ a ≤ b := by rw [← compl_sdiff, compl_eq_top, sdiff_eq_bot_iff] @[simp] lemma imp_eq_bot_iff : (a ⇒ₒ b = ⊥) ↔ (a = ⊤ ∧ b = ⊥) := by simp [imp] @[simp] lemma imp_bot (a : α) : a ⇒ₒ ⊥ = aᶜ := sup_bot_eq @[simp] lemma top_imp (a : α) : ⊤ ⇒ₒ a = a := by simp [imp] @[simp] lemma bot_imp (a : α) : ⊥ ⇒ₒ a = ⊤ := imp_eq_top_iff.2 bot_le @[simp] lemma imp_top (a : α) : a ⇒ₒ ⊤ = ⊤ := imp_eq_top_iff.2 le_top @[simp] lemma imp_self (a : α) : a ⇒ₒ a = ⊤ := compl_sup_eq_top @[simp] lemma compl_imp_compl (a b : α) : aᶜ ⇒ₒ bᶜ = b ⇒ₒ a := by simp [imp, sup_comm] lemma imp_inf_le {α : Type*} [boolean_algebra α] (a b : α) : (a ⇒ₒ b) ⊓ a ≤ b := by { unfold imp, rw [inf_sup_right], simp } lemma inf_imp_eq_imp_imp (a b c : α) : ((a ⊓ b) ⇒ₒ c) = (a ⇒ₒ (b ⇒ₒ c)) := by simp [imp, sup_assoc] lemma le_imp_iff : a ≤ (b ⇒ₒ c) ↔ a ⊓ b ≤ c := by rw [imp, sup_comm, is_compl_compl.le_sup_right_iff_inf_left_le] lemma biimp_mp (a b : α) : (a ⇔ₒ b) ≤ (a ⇒ₒ b) := inf_le_left lemma biimp_mpr (a b : α) : (a ⇔ₒ b) ≤ (b ⇒ₒ a) := inf_le_right lemma biimp_comm (a b : α) : (a ⇔ₒ b) = (b ⇔ₒ a) := by {unfold lattice.biimp, rw inf_comm} @[simp] lemma biimp_eq_top_iff : a ⇔ₒ b = ⊤ ↔ a = b := by simp [biimp, ← le_antisymm_iff] @[simp] lemma biimp_self (a : α) : a ⇔ₒ a = ⊤ := biimp_eq_top_iff.2 rfl lemma biimp_symm : a ≤ (b ⇔ₒ c) ↔ a ≤ (c ⇔ₒ b) := by rw biimp_comm lemma compl_symm_diff (a b : α) : (a Δ b)ᶜ = a ⇔ₒ b := by simp only [biimp, imp, symm_diff, sdiff_eq, compl_sup, compl_inf, compl_compl] lemma compl_biimp (a b : α) : (a ⇔ₒ b)ᶜ = a Δ b := by rw [← compl_symm_diff, compl_compl] @[simp] lemma compl_biimp_compl : aᶜ ⇔ₒ bᶜ = a ⇔ₒ b := by simp [biimp, inf_comm] end lattice
06a4d1690e73487932f93324e539cf698194be40
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/geometry/manifold/instances/units_of_normed_algebra.lean
a7b7b50267a7176c4b9fdfcd7298de6318556221
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,585
lean
/- Copyright © 2021 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Heather Macbeth -/ import geometry.manifold.smooth_manifold_with_corners import analysis.normed_space.units /-! # Units of a normed algebra > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file is a stub, containing a construction of the charted space structure on the group of units of a complete normed ring `R`, and of the smooth manifold structure on the group of units of a complete normed `𝕜`-algebra `R`. This manifold is actually a Lie group, which eventually should be the main result of this file. An important special case of this construction is the general linear group. For a normed space `V` over a field `𝕜`, the `𝕜`-linear endomorphisms of `V` are a normed `𝕜`-algebra (see `continuous_linear_map.to_normed_algebra`), so this construction provides a Lie group structure on its group of units, the general linear group GL(`𝕜`, `V`). ## TODO The Lie group instance requires the following fields: ``` instance : lie_group 𝓘(𝕜, R) Rˣ := { smooth_mul := sorry, smooth_inv := sorry, ..units.smooth_manifold_with_corners } ``` The ingredients needed for the construction are * smoothness of multiplication and inversion in the charts, i.e. as functions on the normed `𝕜`-space `R`: see `cont_diff_at_ring_inverse` for the inversion result, and `cont_diff_mul` (needs to be generalized from field to algebra) for the multiplication result * for an open embedding `f`, whose domain is equipped with the induced manifold structure `f.singleton_smooth_manifold_with_corners`, characterization of smoothness of functions to/from this manifold in terms of smoothness in the target space. See the pair of lemmas `cont_mdiff_coe_sphere` and `cont_mdiff.cod_restrict_sphere` for a model. None of this should be particularly difficult. -/ noncomputable theory open_locale manifold namespace units variables {R : Type*} [normed_ring R] [complete_space R] instance : charted_space R Rˣ := open_embedding_coe.singleton_charted_space lemma chart_at_apply {a : Rˣ} {b : Rˣ} : chart_at R a b = b := rfl lemma chart_at_source {a : Rˣ} : (chart_at R a).source = set.univ := rfl variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] [normed_algebra 𝕜 R] instance : smooth_manifold_with_corners 𝓘(𝕜, R) Rˣ := open_embedding_coe.singleton_smooth_manifold_with_corners 𝓘(𝕜, R) end units
e8fd9eb042b2a2ffca960a202512721e993b8f0d
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/data/real/basic.lean
b961a8ea7f937553bb5a8ce261381c45ffb691fa
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,901
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn The (classical) real numbers ℝ. This is a direct construction from Cauchy sequences. -/ import order.conditionally_complete_lattice import data.real.cau_seq_completion import algebra.archimedean import algebra.star.basic /-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational numbers. -/ structure real := of_cauchy :: (cauchy : @cau_seq.completion.Cauchy ℚ _ _ _ abs _) notation `ℝ` := real attribute [pp_using_anonymous_constructor] real namespace real open cau_seq cau_seq.completion variables {x y : ℝ} lemma ext_cauchy_iff : ∀ {x y : real}, x = y ↔ x.cauchy = y.cauchy | ⟨a⟩ ⟨b⟩ := by split; cc lemma ext_cauchy {x y : real} : x.cauchy = y.cauchy → x = y := ext_cauchy_iff.2 /-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/ def equiv_Cauchy : ℝ ≃ cau_seq.completion.Cauchy := ⟨real.cauchy, real.of_cauchy, λ ⟨_⟩, rfl, λ _, rfl⟩ -- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511 @[irreducible] private def zero : ℝ := ⟨0⟩ @[irreducible] private def one : ℝ := ⟨1⟩ @[irreducible] private def add : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩ @[irreducible] private def neg : ℝ → ℝ | ⟨a⟩ := ⟨-a⟩ @[irreducible] private def mul : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩ instance : has_zero ℝ := ⟨zero⟩ instance : has_one ℝ := ⟨one⟩ instance : has_add ℝ := ⟨add⟩ instance : has_neg ℝ := ⟨neg⟩ instance : has_mul ℝ := ⟨mul⟩ lemma zero_cauchy : (⟨0⟩ : ℝ) = 0 := show _ = zero, by rw zero lemma one_cauchy : (⟨1⟩ : ℝ) = 1 := show _ = one, by rw one lemma add_cauchy {a b} : (⟨a⟩ + ⟨b⟩ : ℝ) = ⟨a + b⟩ := show add _ _ = _, by rw add lemma neg_cauchy {a} : (-⟨a⟩ : ℝ) = ⟨-a⟩ := show neg _ = _, by rw neg lemma mul_cauchy {a b} : (⟨a⟩ * ⟨b⟩ : ℝ) = ⟨a * b⟩ := show mul _ _ = _, by rw mul instance : comm_ring ℝ := begin refine_struct { zero := 0, one := 1, mul := (*), add := (+), neg := @has_neg.neg ℝ _, sub := λ a b, a + (-b), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨@has_neg.neg ℝ _⟩ }; repeat { rintro ⟨_⟩, }; try { refl }; simp [← zero_cauchy, ← one_cauchy, add_cauchy, neg_cauchy, mul_cauchy]; apply add_assoc <|> apply add_comm <|> apply mul_assoc <|> apply mul_comm <|> apply left_distrib <|> apply right_distrib <|> apply sub_eq_add_neg <|> skip end /- Extra instances to short-circuit type class resolution -/ instance : ring ℝ := by apply_instance instance : comm_semiring ℝ := by apply_instance instance : semiring ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_left_cancel_semigroup ℝ := by apply_instance instance : add_right_cancel_semigroup ℝ := by apply_instance instance : add_comm_semigroup ℝ := by apply_instance instance : add_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : semigroup ℝ := by apply_instance instance : has_sub ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ /-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/ instance : star_ring ℝ := star_ring_of_comm /-- Coercion `ℚ` → `ℝ` as a `ring_hom`. Note that this is `cau_seq.completion.of_rat`, not `rat.cast`. -/ def of_rat : ℚ →+* ℝ := by refine_struct { to_fun := of_cauchy ∘ of_rat }; simp [of_rat_one, of_rat_zero, of_rat_mul, of_rat_add, one_cauchy, zero_cauchy, ← mul_cauchy, ← add_cauchy] lemma of_rat_apply (x : ℚ) : of_rat x = of_cauchy (cau_seq.completion.of_rat x) := rfl /-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/ def mk (x : cau_seq ℚ abs) : ℝ := ⟨cau_seq.completion.mk x⟩ theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := ext_cauchy_iff.trans mk_eq @[irreducible] private def lt : ℝ → ℝ → Prop | ⟨x⟩ ⟨y⟩ := quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩ instance : has_lt ℝ := ⟨lt⟩ lemma lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _, by rw lt; refl @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := lt_cauchy lemma mk_zero : mk 0 = 0 := by rw ← zero_cauchy; refl lemma mk_one : mk 1 = 1 := by rw ← one_cauchy; refl lemma mk_add {f g : cau_seq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, add_cauchy] lemma mk_mul {f g : cau_seq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, mul_cauchy] lemma mk_neg {f : cau_seq ℚ abs} : mk (-f) = -mk f := by simp [mk, neg_cauchy] @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := by rw [← mk_zero, mk_lt]; exact iff_of_eq (congr_arg pos (sub_zero f)) @[irreducible] private def le (x y : ℝ) : Prop := x < y ∨ x = y instance : has_le ℝ := ⟨le⟩ private lemma le_def {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := show le _ _ ↔ _, by rw le @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := by simp [le_def, mk_eq]; refl @[elab_as_eliminator] protected lemma ind_mk {C : real → Prop} (x : real) (h : ∀ y, C (mk y)) : C x := begin cases x with x, induction x using quot.induction_on with x, exact h x end theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := begin induction a using real.ind_mk, induction b using real.ind_mk, induction c using real.ind_mk, simp only [mk_lt, ← mk_add], show pos _ ↔ pos _, rw add_sub_add_left_eq_sub end instance : partial_order ℝ := { le := (≤), lt := (<), lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_refl := λ a, a.ind_mk (by intro a; rw mk_le), le_trans := λ a b c, real.ind_mk a $ λ a, real.ind_mk b $ λ b, real.ind_mk c $ λ c, by simpa using le_trans, lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_antisymm := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ a b } instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := begin rw [mk_lt] {md := tactic.transparency.semireducible}, exact const_lt end protected theorem zero_lt_one : (0 : ℝ) < 1 := by convert of_rat_lt.2 zero_lt_one; simp protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := begin induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa only [mk_lt, mk_pos, ← mk_mul] using cau_seq.mul_pos end instance : ordered_ring ℝ := { add_le_add_left := begin simp only [le_iff_eq_or_lt], rintros a b ⟨rfl, h⟩, { simp }, { exact λ c, or.inr ((add_lt_add_iff_left c).2 ‹_›) } end, zero_le_one := le_of_lt real.zero_lt_one, mul_pos := @real.mul_pos, .. real.comm_ring, .. real.partial_order, .. real.semiring } instance : ordered_semiring ℝ := by apply_instance instance : ordered_add_comm_group ℝ := by apply_instance instance : ordered_cancel_add_comm_monoid ℝ := by apply_instance instance : ordered_add_comm_monoid ℝ := by apply_instance instance : nontrivial ℝ := ⟨⟨0, 1, ne_of_lt real.zero_lt_one⟩⟩ open_locale classical noncomputable instance : linear_order ℝ := { le_total := begin intros a b, induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa using le_total a b, end, decidable_le := by apply_instance, .. real.partial_order } noncomputable instance : linear_ordered_comm_ring ℝ := { .. real.nontrivial, .. real.ordered_ring, .. real.comm_ring, .. real.linear_order } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_ring ℝ := by apply_instance noncomputable instance : linear_ordered_semiring ℝ := by apply_instance instance : domain ℝ := { .. real.nontrivial, .. real.comm_ring, .. linear_ordered_ring.to_domain } /-- The real numbers are an ordered `*`-ring, with the trivial `*`-structure. -/ instance : star_ordered_ring ℝ := { star_mul_self_nonneg := λ r, mul_self_nonneg r, } @[irreducible] private noncomputable def inv' : ℝ → ℝ | ⟨a⟩ := ⟨a⁻¹⟩ noncomputable instance : has_inv ℝ := ⟨inv'⟩ lemma inv_cauchy {f} : (⟨f⟩ : ℝ)⁻¹ = ⟨f⁻¹⟩ := show inv' _ = _, by rw inv' noncomputable instance : linear_ordered_field ℝ := { inv := has_inv.inv, mul_inv_cancel := begin rintros ⟨a⟩ h, rw mul_comm, simp only [inv_cauchy, mul_cauchy, ← one_cauchy, ← zero_cauchy, ne.def] at *, exact cau_seq.completion.inv_mul_cancel h, end, inv_zero := by simp [← zero_cauchy, inv_cauchy], ..real.linear_ordered_comm_ring, ..real.domain } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_add_comm_group ℝ := by apply_instance noncomputable instance field : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance noncomputable instance : integral_domain ℝ := by apply_instance noncomputable instance : distrib_lattice ℝ := by apply_instance noncomputable instance : lattice ℝ := by apply_instance noncomputable instance : semilattice_inf ℝ := by apply_instance noncomputable instance : semilattice_sup ℝ := by apply_instance noncomputable instance : has_inf ℝ := by apply_instance noncomputable instance : has_sup ℝ := by apply_instance noncomputable instance decidable_lt (a b : ℝ) : decidable (a < b) := by apply_instance noncomputable instance decidable_le (a b : ℝ) : decidable (a ≤ b) := by apply_instance noncomputable instance decidable_eq (a b : ℝ) : decidable (a = b) := by apply_instance open rat @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := of_rat.eq_rat_cast theorem le_mk_of_forall_le {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := begin intro h, induction x using real.ind_mk with x, apply le_of_not_lt, rw mk_lt, rintro ⟨K, K0, hK⟩, obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0)), apply not_lt_of_le (H _ (le_refl _)).1, rw ← of_rat_eq_cast, rw [mk_lt] {md := tactic.transparency.semireducible}, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} (h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x := begin cases h with i H, rw [← neg_le_neg_iff, ← mk_neg], exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ end theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, real.ind_mk x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) : ∃ h', real.mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) → ∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y | ⟨L, hL⟩ ⟨U, hU⟩ := begin choose f hf using begin refine λ d : ℕ, @int.exists_greatest_of_bdd (λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _, { cases exists_int_gt U with k hk, refine ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (le_trans hy _), simp, exact mul_le_mul_of_nonneg_right (le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) }, { exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ } end, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := lt_of_lt_of_le (sub_one_lt_floor _) (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 xz) hK), refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS), rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ }, intros ε ε0, suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩, rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij }, intros j k ij ik, replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ij), have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) end noncomputable instance : has_Sup ℝ := ⟨λ S, if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0⟩ lemma Sup_def (S : set ℝ) : Sup S = if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0 := rfl theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y := by simp [Sup_def, h₁, h₂]; exact classical.some_spec (exists_sup S h₁ h₂) y theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : y < Sup S ↔ ∃ z ∈ S, y < z := by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y) theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S := (Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub := (Sup_le S h₁ ⟨_, h₂⟩).2 h₂ protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) : is_lub s (Sup s) := ⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs, λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩ noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup {x | -x ∈ S}⟩ lemma Inf_def (S : set ℝ) : Inf S = -Sup {x | -x ∈ S} := rfl theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z := begin refine le_neg.trans ((Sup_le _ _ _).trans _), { cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ }, { cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ }, split; intros H z hz, { exact neg_le_neg_iff.1 (H _ $ by simp [hz]) }, { exact le_neg.2 (H _ hz) } end section -- this proof times out without this local attribute [instance, priority 1000] classical.prop_decidable theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : Inf S < y ↔ ∃ z ∈ S, z < y := by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y) end theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x := (le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S := (le_Inf S h₁ ⟨_, h₂⟩).2 h₂ noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := has_Sup.Sup, Inf := has_Inf.Inf, le_cSup := assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s), show a ≤ Sup s, from le_Sup s ‹bdd_above s› ‹a ∈ s›, cSup_le := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, b ≤ a), show Sup s ≤ a, from Sup_le_ub s ‹s.nonempty› H, cInf_le := assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s), show Inf s ≤ a, from Inf_le s ‹bdd_below s› ‹a ∈ s›, le_cInf := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, a ≤ b), show a ≤ Inf s, from lb_le_Inf s ‹s.nonempty› H, ..real.linear_order, ..real.lattice} theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 := dif_neg $ assume h, hs h.2 theorem Sup_univ : Sup (@set.univ ℝ) = 0 := real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _) theorem Inf_empty : Inf (∅ : set ℝ) = 0 := by simp [Inf_def, Sup_empty] theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 := have bdd_above {x | -x ∈ s} → bdd_below s, from assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb $ by simp [hxs]⟩, have ¬ bdd_above {x | -x ∈ s}, from mt this hs, neg_eq_zero.2 $ Sup_of_not_bdd_above $ this /-- As `0` is the default value for `real.Sup` of the empty set or sets which are not bounded above, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Sup_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Sup S := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { simp [Sup_empty] }, { apply dite _ (λ h, le_cSup_of_le h hy $ hS y hy) (λ h, (Sup_of_not_bdd_above h).ge) } end /-- As `0` is the default value for `real.Sup` of the empty set, it suffices to show that `S` is bounded above by `0` to show that `Sup S ≤ 0`. -/ lemma Sup_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Sup S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, { simp [Sup_empty] }, { apply Sup_le_ub _ hS₂ hS, } end /-- As `0` is the default value for `real.Inf` of the empty set, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Inf_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Inf S := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, { simp [Inf_empty] }, { apply lb_le_Inf S hS₂ hS } end /-- As `0` is the default value for `real.Inf` of the empty set or sets which are not bounded below, it suffices to show that `S` is bounded above by `0` to show that `Inf S ≤ 0`. -/ lemma Inf_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Inf S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { simp [Inf_empty] }, { apply dite _ (λ h, cInf_le_of_le h hy $ hS y hy) (λ h, (Inf_of_not_bdd_below h).le) } end theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (Sup_le_ub S lb (ub' _ _)) (sub_lt_self _ (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (le_Sup S ub _) ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩ end real
4c0cb6fd115bc1cd9135ef0a7dce55f224d1deda
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/induction_auto.lean
9a60158ef74a06a5a3a5981d6a27160fded169d7
[]
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
10,959
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jannis Limperg -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.dependencies import Mathlib.tactic.fresh_names import Mathlib.tactic.generalizes import Mathlib.tactic.has_variable_names import Mathlib.tactic.unify_equations import Mathlib.PostPort universes l namespace Mathlib /-! # A better tactic for induction and case analysis This module defines the tactics `tactic.interactive.induction'` and `tactic.interactive.cases'`, which are variations on Lean's builtin `induction` and `cases`. The primed variants feature various improvements over the builtin tactics; in particular, they generate more human-friendly names and `induction'` deals much better with indexed inductive types. See the tactics' documentation for more details. We also provide corresponding non-interactive induction tactics `tactic.eliminate_hyp` and `tactic.eliminate_expr`. The design and implementation of these tactics is described in a [draft paper](https://limperg.de/paper/cpp2021-induction/). -/ namespace tactic namespace eliminate /-! ## Tracing We set up two tracing functions to be used by `eliminate_hyp` and its supporting tactics. Their output is enabled by setting `trace.eliminate_hyp` to `true`. -/ /-- `trace_eliminate_hyp msg` traces `msg` if the option `trace.eliminate_hyp` is `true`. -/ /-- `trace_state_eliminate_hyp msg` traces `msg` followed by the tactic state if the option `trace.eliminate_hyp` is `true`. -/ /-! ## Information Gathering We define data structures for information relevant to the induction, and functions to collect this information for a specific goal. -/ /-- Information about a constructor argument. E.g. given the declaration ``` induction ℕ : Type | zero : ℕ | suc (n : ℕ) : ℕ ``` the `zero` constructor has no arguments and the `suc` constructor has one argument, `n`. We record the following information: - `aname`: the argument's name. If the argument was not explicitly named in the declaration, the elaborator generates a name for it. - `type` : the argument's type. - `dependent`: whether the argument is dependent, i.e. whether it occurs in the remainder of the constructor type. - `index_occurrences`: the index arguments of the constructor's return type in which this argument occurs. If the constructor return type is `I i₀ ... iₙ` and the argument under consideration is `a`, and `a` occurs in `i₁` and `i₂`, then the `index_occurrences` are `1, 2`. As an additional requirement, for `iⱼ` to be considered an index occurrences, the type of `iⱼ` must match that of `a` according to `index_occurrence_type_match`. - `is_recursive`: whether this is a recursive constructor argument. -/ /-- Information about a constructor. Contains: - `cname`: the constructor's name. - `non_param_args`: information about the arguments of the constructor, excluding the arguments induced by the parameters of the inductive type. - `num_non_param_args`: the length of `non_param_args`. - `rec_args`: the subset of `non_param_args` which are recursive constructor arguments. - `num_rec_args`: the length of `rec_args`. For example, take the constructor ``` list.cons : ∀ {α} (x : α) (xs : list α), list α ``` `α` is a parameter of `list`, so `non_param_args` contains information about `x` and `xs`. `rec_args` contains information about `xs`. -/ /-- When we construct the goal for the minor premise of a given constructor, this is the number of hypotheses we must name. -/ /-- Information about an inductive type. Contains: - `iname`: the type's name. - `constructors`: information about the type's constructors. - `num_constructors`: the length of `constructors`. - `type`: the type's type. - `num_param`: the type's number of parameters. - `num_indices`: the type's number of indices. -/ /-- Information about a major premise (i.e. the hypothesis on which we are performing induction). Contains: - `mpname`: the major premise's name. - `mpexpr`: the major premise itself. - `type`: the type of `mpexpr`. - `args`: the arguments of the major premise. The major premise has type `I x₀ ... xₙ`, where `I` is an inductive type. `args` is the map `[0 → x₀, ..., n → xₙ]`. -/ /-- `index_occurrence_type_match t s` is true iff `t` and `s` are definitionally equal. -/ -- We could extend this check to be more permissive. E.g. if a constructor -- argument has type `list α` and the index has type `list β`, we may want to -- consider these types sufficiently similar to inherit the name. Same (but even -- more obvious) with `vec α n` and `vec α (n + 1)`. /-- From the return type of a constructor `C` of an inductive type `I`, determine the index occurrences of the constructor arguments of `C`. Input: - `num_params:` the number of parameters of `I`. - `ret_type`: the return type of `C`. `e` must be of the form `I x₁ ... xₙ`. Output: A map associating each local constant `c` that appears in any of the `xᵢ` with the set of indexes `j` such that `c` appears in `xⱼ` and `xⱼ`'s type matches that of `c` according to `tactic.index_occurrence_type_match`. -/ /-- Returns true iff `arg_type` is the local constant named `type_name` (possibly applied to some arguments). If `arg_type` is the type of an argument of one of `type_name`'s constructors and this function returns true, then the constructor argument is a recursive occurrence. -/ /-- Get information about the arguments of a constructor `C` of an inductive type `I`. Input: - `inductive_name`: the name of `I`. - `num_params`: the number of parameters of `I`. - `T`: the type of `C`. Output: a `constructor_argument_info` structure for each argument of `C`. -/ /-- Get information about a constructor `C` of an inductive type `I`. Input: - `iname`: the name of `I`. - `num_params`: the number of parameters of `I`. - `c` : the name of `C`. Output: A `constructor_info` structure for `C`. -/ /-- Get information about an inductive type `I`, given `I`'s name. -/ /-- Get information about a major premise. The given `expr` must be a local hypothesis. -/ /-! ## Constructor Argument Naming We define the algorithm for naming constructor arguments (which is a remarkably big part of the tactic). -/ /-- Information used when naming a constructor argument. -/ /-- A constructor argument naming rule takes a `constructor_argument_naming_info` structure and returns a list of suitable names for the argument. If the rule is not applicable to the given constructor argument, the returned list is empty. -/ /-- Naming rule for recursive constructor arguments. -/ /-- Naming rule for constructor arguments associated with an index. -/ /- Right now, this rule only triggers if the major premise arg is exactly a local const. We could consider a more permissive rule where the major premise arg can be an arbitrary term as long as that term *contains* only a single local const. -/ /-- Naming rule for constructor arguments which are named in the constructor declaration. -/ /-- Naming rule for constructor arguments whose type is associated with a list of typical variable names. See `tactic.typical_variable_names`. -/ /-- Naming rule for constructor arguments whose type is in `Prop`. -/ /-- Fallback constructor argument naming rule. This rule never fails. -/ /-- `apply_constructor_argument_naming_rules info rules` applies the constructor argument naming rules in `rules` to the constructor argument given by `info`. Returns the result of the first applicable rule. Fails if no rule is applicable. -/ /-- Get possible names for a constructor argument. This tactic applies all the previously defined rules in order. It cannot fail and always returns a nonempty list. -/ /-- `intron_fresh n` introduces `n` hypotheses with names generated by `tactic.mk_fresh_name`. -/ /-- Introduce the new hypotheses generated by the minor premise for a given constructor. The new hypotheses are given fresh (unique, non-human-friendly) names. They are later renamed by `constructor_renames`. We delay the generation of the human-friendly names because when `constructor_renames` is called, more names may have become unused. Input: - `generate_induction_hyps`: whether we generate induction hypotheses (i.e. whether `eliminate_hyp` is in `induction` or `cases` mode). - `cinfo`: information about the constructor. Output: - For each constructor argument, the pretty name of the newly introduced hypothesis corresponding to the argument and its `constructor_argument_info`. - For each newly introduced induction hypothesis, its pretty name and the name of the recursive constructor argument from which it was derived. -/ /-- `ih_name arg_name` is the name `ih_<arg_name>`. -/ /-- Rename the new hypotheses in the goal for a minor premise. Input: - `generate_induction_hyps`: whether we generate induction hypotheses (i.e. whether `eliminate_hyp` is in `induction` or `cases` mode). - `mpinfo`: information about the major premise. - `iinfo`: information about the inductive type. - `cinfo`: information about the constructor whose minor premise we are processing. - `with_names`: a list of names given by the user. These are used to name constructor arguments and induction hypotheses. Our own naming logic only kicks in if this list does not contain enough names. - `args` and `ihs`: the output of `constructor_intros`. Output: - The newly introduced hypotheses corresponding to constructor arguments. - The newly introduced induction hypotheses. -/ /-! ## Generalisation `induction'` can generalise the goal before performing an induction, which gives us a more general induction hypothesis. We call this 'auto-generalisation'. -/ /-- A value of `generalization_mode` describes the behaviour of the auto-generalisation functionality: - `generalize_all_except hs` means that the `hs` remain fixed and all other hypotheses are generalised. However, there are three exceptions: * Hypotheses depending on any `h` in `hs` also remain fixed. If we were to generalise them, we would have to generalise `h` as well. * Hypotheses which do not occur in the target and which do not mention the major premise or its dependencies are never generalised. Generalising them would not lead to a more general induction hypothesis. * Frozen local instances and their dependencies are never generalised. - `generalize_only hs` means that only the `hs` are generalised. Exception: hypotheses which depend on the major premise are generalised even if they do not appear in `hs`. -/ inductive generalization_mode where | generalize_all_except : List name → generalization_mode | generalize_only : List name → generalization_mode protected instance generalization_mode.inhabited : Inhabited generalization_mode := { default := generalization_mode.generalize_all_except [] } end Mathlib
021016761cc48d2e4f08a8cf1d9385f58bf36546
a7602958ab456501ff85db8cf5553f7bcab201d7
/Notes/Theorem_Proving_in_Lean/Chapter2/2.4.lean
ed2ff4e77052c9aede10576657eab74feb60c490
[]
no_license
enlauren/math-logic
081e2e737c8afb28dbb337968df95ead47321ba0
086b6935543d1841f1db92d0e49add1124054c37
refs/heads/master
1,594,506,621,950
1,558,634,976,000
1,558,634,976,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,188
lean
-- 2.4 Introducing Definitions -- To define a new "object", we use the `def` keyword. This allows -- us to create something, with a type, that we can reference later -- via some name, and prove things about. def foo: ℕ → ℕ := fun (x: ℕ), x + 2 -- Basic check. #check foo -- Going to be the type that we defined just before "foo". -- Basic reductions. constant x: ℕ #reduce foo x -- Going to carry out all of the abstract computations -- necessary/warranted by the expressed logic. #reduce foo 2 -- Alternate syntax of the above function: def foo' (x: ℕ): ℕ := x + 2 -- ^___^ -- ℕ → ℕ (this is really manifested in the above form). -- More examples (some of which employ the new cool-kid syntax we learned). def double (x: ℕ): ℕ := x + x #reduce double 10 -- 20 :) def square (x: ℕ): ℕ := x * x #reduce square 10 -- 100 :) def do_twice (f: ℕ → ℕ) (x: ℕ): ℕ := f (f x) def do_twice_longhand: (ℕ → ℕ) → ℕ → ℕ := fun (f: ℕ → ℕ) (x: ℕ), f x -- Another example of the short- and long-hand definitions: section def f (x : ℕ) : ℕ := x + 7 def f': ℕ → ℕ := fun (a: ℕ), a + 7 def f'' (x: ℕ) (y: ℕ ): ℕ := x + y #check f #check f' #check f'' #reduce f 4 #reduce f' 4 end -- Examples #reduce do_twice double #reduce do_twice double 2 #reduce do_twice square #reduce do_twice square 2 def square_twice (x: ℕ): ℕ := do_twice square x #reduce square_twice 4 constant a: ℕ def do_once (outer: (ℕ → ℕ) → ℕ → ℕ) (inner: ℕ → ℕ) := outer inner -- Checks and reduces. #check do_once #check do_once do_twice #check do_twice -- Same as above. #reduce ((do_once do_twice) double) a #reduce do_once do_twice double 2 -- Exercise: "We encourage you to try defining a function": -- Do_Twice: ((ℕ → ℕ) → (ℕ → ℕ)) → (ℕ → ℕ) → (ℕ → ℕ) def Do_Twice: ((ℕ → ℕ) → (ℕ → ℕ)) → (ℕ → ℕ) → (ℕ → ℕ) := fun (outer: (ℕ → ℕ) → ℕ → ℕ) (inner: (ℕ → ℕ)), outer (outer inner) #reduce Do_Twice do_twice double 2 -- See assignment for the curry/uncurry exercise of this section.
8ab80cc4d70ef81c96d27c54deae719af85f0c41
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world10/level04.lean
0ebb0249d4e3079e9b8b2272d1c2ad85fba26598
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
92
lean
lemma zero_le (a : mynat) : 0 ≤ a := begin rw le_iff_exists_add, use a, rwa zero_add, end
c4a17afc35250d296917ef51357a7b24c94e525e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/match2.lean
1c1d824299773957f4e7fd0a1fdbe1a30b4ac8d5
[ "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
252
lean
inductive imf (f : nat → nat) : nat → Type | mk1 : ∀ (a : nat), imf (f a) | mk2 : imf (f 0 + 1) definition inv_2 (f : nat → nat) : ∀ (b : nat), imf f b → {x : nat // x > b} → nat | _ (imf.mk1 a) x := a | _ imf.mk2 x := subtype.val x
84631b84e8c569bbe36c70c0156bde9104e25016
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/eisenstein_criterion.lean
6b0ea20da2a46c98d5c3c9ed3ae2a251fcd43501
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
5,543
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import ring_theory.prime import ring_theory.polynomial.content /-! # Eisenstein's criterion A proof of a slight generalisation of Eisenstein's criterion for the irreducibility of a polynomial over an integral domain. -/ open polynomial ideal.quotient variables {R : Type*} [integral_domain R] namespace polynomial namespace eisenstein_criterion_aux /- Section for auxiliary lemmas used in the proof of `irreducible_of_eisenstein_criterion`-/ lemma map_eq_C_mul_X_pow_of_forall_coeff_mem {f : polynomial R} {P : ideal R} (hfP : ∀ (n : ℕ), ↑n < f.degree → f.coeff n ∈ P) (hf0 : f ≠ 0) : map (mk P) f = C ((mk P) f.leading_coeff) * X ^ f.nat_degree := polynomial.ext (λ n, begin rcases lt_trichotomy ↑n (degree f) with h | h | h, { erw [coeff_map, eq_zero_iff_mem.2 (hfP n h), coeff_C_mul, coeff_X_pow, if_neg, mul_zero], rintro rfl, exact not_lt_of_ge degree_le_nat_degree h }, { have : nat_degree f = n, from nat_degree_eq_of_degree_eq_some h.symm, rw [coeff_C_mul, coeff_X_pow, if_pos this.symm, mul_one, leading_coeff, this, coeff_map] }, { rw [coeff_eq_zero_of_degree_lt, coeff_eq_zero_of_degree_lt], { refine lt_of_le_of_lt (degree_C_mul_X_pow_le _ _) _, rwa ← degree_eq_nat_degree hf0 }, { exact lt_of_le_of_lt (degree_map_le _ _) h } } end) lemma le_nat_degree_of_map_eq_mul_X_pow {n : ℕ} {P : ideal R} (hP : P.is_prime) {q : polynomial R} {c : polynomial P.quotient} (hq : map (mk P) q = c * X ^ n) (hc0 : c.degree = 0) : n ≤ q.nat_degree := with_bot.coe_le_coe.1 (calc ↑n = degree (q.map (mk P)) : by rw [hq, degree_mul, hc0, zero_add, degree_pow, degree_X, nsmul_one, nat.cast_with_bot] ... ≤ degree q : degree_map_le _ _ ... ≤ nat_degree q : degree_le_nat_degree) lemma eval_zero_mem_ideal_of_eq_mul_X_pow {n : ℕ} {P : ideal R} {q : polynomial R} {c : polynomial P.quotient} (hq : map (mk P) q = c * X ^ n) (hn0 : 0 < n) : eval 0 q ∈ P := by rw [← coeff_zero_eq_eval_zero, ← eq_zero_iff_mem, ← coeff_map, coeff_zero_eq_eval_zero, hq, eval_mul, eval_pow, eval_X, zero_pow hn0, mul_zero] lemma is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit {p q : polynomial R} (hu : ∀ (x : R), C x ∣ p * q → is_unit x) (hpm : p.nat_degree = 0) : is_unit p := begin rw [eq_C_of_degree_le_zero (nat_degree_eq_zero_iff_degree_le_zero.1 hpm), is_unit_C], refine hu _ _, rw [← eq_C_of_degree_le_zero (nat_degree_eq_zero_iff_degree_le_zero.1 hpm)], exact dvd_mul_right _ _ end end eisenstein_criterion_aux open eisenstein_criterion_aux /-- If `f` is a non constant polynomial with coefficients in `R`, and `P` is a prime ideal in `R`, then if every coefficient in `R` except the leading coefficient is in `P`, and the trailing coefficient is not in `P^2` and no non units in `R` divide `f`, then `f` is irreducible. -/ theorem irreducible_of_eisenstein_criterion {f : polynomial R} {P : ideal R} (hP : P.is_prime) (hfl : f.leading_coeff ∉ P) (hfP : ∀ n : ℕ, ↑n < degree f → f.coeff n ∈ P) (hfd0 : 0 < degree f) (h0 : f.coeff 0 ∉ P^2) (hu : f.is_primitive) : irreducible f := have hf0 : f ≠ 0, from λ _, by simp only [*, not_true, submodule.zero_mem, coeff_zero] at *, have hf : f.map (mk P) = C (mk P (leading_coeff f)) * X ^ nat_degree f, from map_eq_C_mul_X_pow_of_forall_coeff_mem hfP hf0, have hfd0 : 0 < f.nat_degree, from with_bot.coe_lt_coe.1 (lt_of_lt_of_le hfd0 degree_le_nat_degree), ⟨mt degree_eq_zero_of_is_unit (λ h, by simp only [*, lt_irrefl] at *), begin rintros p q rfl, rw [map_mul] at hf, rcases mul_eq_mul_prime_pow (show prime (X : polynomial (ideal.quotient P)), from prime_of_degree_eq_one_of_monic degree_X monic_X) hf with ⟨m, n, b, c, hmnd, hbc, hp, hq⟩, have hmn : 0 < m → 0 < n → false, { assume hm0 hn0, refine h0 _, rw [coeff_zero_eq_eval_zero, eval_mul, sq], exact ideal.mul_mem_mul (eval_zero_mem_ideal_of_eq_mul_X_pow hp hm0) (eval_zero_mem_ideal_of_eq_mul_X_pow hq hn0) }, have hpql0 : (mk P) (p * q).leading_coeff ≠ 0, { rwa [ne.def, eq_zero_iff_mem] }, have hp0 : p ≠ 0, from λ h, by simp only [*, zero_mul, eq_self_iff_true, not_true, ne.def] at *, have hq0 : q ≠ 0, from λ h, by simp only [*, eq_self_iff_true, not_true, ne.def, mul_zero] at *, have hbc0 : degree b = 0 ∧ degree c = 0, { apply_fun degree at hbc, rwa [degree_C hpql0, degree_mul, eq_comm, nat.with_bot.add_eq_zero_iff] at hbc }, have hmp : m ≤ nat_degree p, from le_nat_degree_of_map_eq_mul_X_pow hP hp hbc0.1, have hnq : n ≤ nat_degree q, from le_nat_degree_of_map_eq_mul_X_pow hP hq hbc0.2, have hpmqn : p.nat_degree = m ∧ q.nat_degree = n, { rw [nat_degree_mul hp0 hq0] at hmnd, clear_except hmnd hmp hnq, contrapose hmnd, apply ne_of_lt, rw not_and_distrib at hmnd, cases hmnd, { exact add_lt_add_of_lt_of_le (lt_of_le_of_ne hmp (ne.symm hmnd)) hnq }, { exact add_lt_add_of_le_of_lt hmp (lt_of_le_of_ne hnq (ne.symm hmnd)) } }, obtain rfl | rfl : m = 0 ∨ n = 0, { rwa [pos_iff_ne_zero, pos_iff_ne_zero, imp_false, not_not, ← or_iff_not_imp_left] at hmn }, { exact or.inl (is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit hu hpmqn.1) }, { exact or.inr (is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit (by simpa only [mul_comm] using hu) hpmqn.2) } end⟩ end polynomial
bc8b1a884c9dfdc15a4bc5b456efcff09fa29b7a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/category/Group/preadditive.lean
f6002036a76f09c51f88a37723ccfae63c250368
[ "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
719
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import algebra.category.Group.basic import category_theory.preadditive.basic /-! # The category of additive commutative groups is preadditive. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open category_theory universe u namespace AddCommGroup instance : preadditive AddCommGroup := { add_comp' := λ P Q R f f' g, show (f + f') ≫ g = f ≫ g + f' ≫ g, by { ext, simp }, comp_add' := λ P Q R f g g', show f ≫ (g + g') = f ≫ g + f ≫ g', by { ext, simp } } end AddCommGroup
73657b60f63b1762a030e543865d4a77c31ca64c
bdb33f8b7ea65f7705fc342a178508e2722eb851
/meta/expr.lean
a6d644b2056bd87c5acca23ac1236e7ff287d473
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
1,302
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Traversal for Lean expressions -/ universes u v section expr open expr variables {m : Type → Type u} [monad m] variables {elab elab' : bool} variables f : expr elab → m (expr elab') /- only traverses the direct descendents -/ meta def expr.traverse : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> mmap f es meta def expr.list_local_const (e : expr) : list expr := e.fold [] (λ e' _ es, if expr.is_local_constant e' ∧ ¬ e' ∈ es then e' :: es else es) end expr namespace tactic open expr meta def pis : list expr → expr → tactic expr | (e@(local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ pi pp info t (abstract_local f' uniq) | _ f := pure f end tactic
e472cfe82335a030532553917906292ac3f8bfbf
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/free_product.lean
e2affe73cfd853d4eb5349c4a918d03affecc12b
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,374
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import algebra.free_monoid import group_theory.congruence import data.list.chain /-! # The free product of groups or monoids Given an `ι`-indexed family `M` of monoids, we define their free product (categorical coproduct) `free_product M`. When `ι` and all `M i` have decidable equality, the free product bijects with the type `word M` of reduced words. This bijection is constructed by defining an action of `free_product M` on `word M`. When `M i` are all groups, `free_product M` is also a group (and the coproduct in the category of groups). ## Main definitions - `free_product M`: the free product, defined as a quotient of a free monoid. - `free_product.of {i} : M i →* free_product M`. - `free_product.lift : (Π {i}, M i →* N) ≃ (free_product M →* N)`: the universal property. - `free_product.word M`: the type of reduced words. - `free_product.word.equiv M : free_product M ≃ word M`. ## Remarks There are many answers to the question "what is the free product of a family `M` of monoids?", and they are all equivalent but not obviously equivalent. We provide two answers. The first, almost tautological answer is given by `free_product M`, which is a quotient of the type of words in the alphabet `Σ i, M i`. It's straightforward to define and easy to prove its universal property. But this answer is not completely satisfactory, because it's difficult to tell when two elements `x y : free_product M` are distinct since `free_product M` is defined as a quotient. The second, maximally efficient answer is given by `word M`. An element of `word M` is a word in the alphabet `Σ i, M i`, where the letter `⟨i, 1⟩` doesn't occur and no adjacent letters share an index `i`. Since we only work with reduced words, there is no need for quotienting, and it is easy to tell when two elements are distinct. However it's not obvious that this is even a monoid! We prove that every element of `free_product M` can be represented by a unique reduced word, i.e. `free_product M` and `word M` are equivalent types. This means that `word M` can be given a monoid structure, and it lets us tell when two elements of `free_product M` are distinct. There is also a completely tautological, maximally inefficient answer given by `algebra.category.Mon.colimits`. Whereas `free_product M` at least ensures that (any instance of) associativity holds by reflexivity, in this answer associativity holds because of quotienting. Yet another answer, which is constructively more satisfying, could be obtained by showing that `free_product.rel` is confluent. ## References [van der Waerden, *Free products of groups*][MR25465] -/ variables {ι : Type*} (M : Π i : ι, Type*) [Π i, monoid (M i)] /-- A relation on the free monoid on alphabet `Σ i, M i`, relating `⟨i, 1⟩` with `1` and `⟨i, x⟩ * ⟨i, y⟩` with `⟨i, x * y⟩`. -/ inductive free_product.rel : free_monoid (Σ i, M i) → free_monoid (Σ i, M i) → Prop | of_one (i : ι) : free_product.rel (free_monoid.of ⟨i, 1⟩) 1 | of_mul {i : ι} (x y : M i) : free_product.rel (free_monoid.of ⟨i, x⟩ * free_monoid.of ⟨i, y⟩) (free_monoid.of ⟨i, x * y⟩) /-- The free product (categorical coproduct) of an indexed family of monoids. -/ @[derive [monoid, inhabited]] def free_product : Type* := (con_gen (free_product.rel M)).quotient namespace free_product /-- The type of reduced words. A reduced word cannot contain a letter `1`, and no two adjacent letters can come from the same summand. -/ @[ext] structure word := (to_list : list (Σ i, M i)) (ne_one : ∀ l ∈ to_list, sigma.snd l ≠ 1) (chain_ne : to_list.chain' (λ l l', sigma.fst l ≠ sigma.fst l')) variable {M} /-- The inclusion of a summand into the free product. -/ def of {i : ι} : M i →* free_product M := { to_fun := λ x, con.mk' _ (free_monoid.of $ sigma.mk i x), map_one' := (con.eq _).mpr (con_gen.rel.of _ _ (free_product.rel.of_one i)), map_mul' := λ x y, eq.symm $ (con.eq _).mpr (con_gen.rel.of _ _ (free_product.rel.of_mul x y)) } lemma of_apply {i} (m : M i) : of m = con.mk' _ (free_monoid.of $ sigma.mk i m) := rfl variables {N : Type*} [monoid N] /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma ext_hom (f g : free_product M →* N) (h : ∀ i, f.comp (of : M i →* _) = g.comp of) : f = g := (monoid_hom.cancel_right con.mk'_surjective).mp $ free_monoid.hom_eq $ λ ⟨i, x⟩, by rw [monoid_hom.comp_apply, monoid_hom.comp_apply, ←of_apply, ←monoid_hom.comp_apply, ←monoid_hom.comp_apply, h] /-- A map out of the free product corresponds to a family of maps out of the summands. This is the universal property of the free product, charaterizing it as a categorical coproduct. -/ @[simps symm_apply] def lift : (Π i, M i →* N) ≃ (free_product M →* N) := { to_fun := λ fi, con.lift _ (free_monoid.lift $ λ p : Σ i, M i, fi p.fst p.snd) $ con.con_gen_le begin simp_rw [con.rel_eq_coe, con.ker_rel], rintros _ _ (i | ⟨i, x, y⟩), { change free_monoid.lift _ (free_monoid.of _) = free_monoid.lift _ 1, simp only [monoid_hom.map_one, free_monoid.lift_eval_of], }, { change free_monoid.lift _ (free_monoid.of _ * free_monoid.of _) = free_monoid.lift _ (free_monoid.of _), simp only [monoid_hom.map_mul, free_monoid.lift_eval_of], } end, inv_fun := λ f i, f.comp of, left_inv := by { intro fi, ext i x, rw [monoid_hom.comp_apply, of_apply, con.lift_mk', free_monoid.lift_eval_of], }, right_inv := by { intro f, ext i x, simp only [monoid_hom.comp_apply, of_apply, con.lift_mk', free_monoid.lift_eval_of], } } @[simp] lemma lift_of {N} [monoid N] (fi : Π i, M i →* N) {i} (m : M i) : lift fi (of m) = fi i m := by conv_rhs { rw [←lift.symm_apply_apply fi, lift_symm_apply, monoid_hom.comp_apply] } @[elab_as_eliminator] lemma induction_on {C : free_product M → Prop} (m : free_product M) (h_one : C 1) (h_of : ∀ (i) (m : M i), C (of m)) (h_mul : ∀ (x y), C x → C y → C (x * y)) : C m := begin let S : submonoid (free_product M) := ⟨set_of C, h_one, h_mul⟩, convert subtype.prop (lift (λ i, of.cod_mrestrict S (h_of i)) m), change monoid_hom.id _ m = S.subtype.comp _ m, congr, ext, simp [monoid_hom.cod_mrestrict], end lemma of_left_inverse [decidable_eq ι] (i : ι) : function.left_inverse (lift $ function.update 1 i (monoid_hom.id (M i))) of := λ x, by simp only [lift_of, function.update_same, monoid_hom.id_apply] lemma of_injective (i : ι) : function.injective ⇑(of : M i →* _) := by { classical, exact (of_left_inverse i).injective } section group variables (G : ι → Type*) [Π i, group (G i)] instance : has_inv (free_product G) := { inv := opposite.unop ∘ lift (λ i, (of : G i →* _).op.comp (mul_equiv.inv' (G i)).to_monoid_hom) } lemma inv_def (x : free_product G) : x⁻¹ = opposite.unop (lift (λ i, (of : G i →* _).op.comp (mul_equiv.inv' (G i)).to_monoid_hom) x) := rfl instance : group (free_product G) := { mul_left_inv := begin intro m, rw inv_def, apply m.induction_on, { rw [monoid_hom.map_one, opposite.unop_one, one_mul], }, { intros i m, change of m⁻¹ * of m = 1, rw [←of.map_mul, mul_left_inv, of.map_one], }, { intros x y hx hy, rw [monoid_hom.map_mul, opposite.unop_mul, mul_assoc, ←mul_assoc _ x y, hx, one_mul, hy], }, end, ..free_product.has_inv G, ..free_product.monoid G } end group namespace word /-- The empty reduced word. -/ def empty : word M := { to_list := [], ne_one := λ _, false.elim, chain_ne := list.chain'_nil } instance : inhabited (word M) := ⟨empty⟩ /-- A reduced word determines an element of the free product, given by multiplication. -/ def prod (w : word M) : free_product M := list.prod (w.to_list.map $ λ l, of l.snd) @[simp] lemma prod_nil : prod (empty : word M) = 1 := rfl /-- `fst_idx w` is `some i` if the first letter of `w` is `⟨i, m⟩` with `m : M i`. If `w` is empty then it's `none`. -/ def fst_idx (w : word M) : option ι := w.to_list.head'.map sigma.fst lemma fst_idx_ne_iff {w : word M} {i} : fst_idx w ≠ some i ↔ ∀ l ∈ w.to_list.head', i ≠ sigma.fst l := not_iff_not.mp $ by simp [fst_idx] variable (M) /-- Given an index `i : ι`, `pair M i` is the type of pairs `(head, tail)` where `head : M i` and `tail : word M`, subject to the constraint that first letter of `tail` can't be `⟨i, m⟩`. By prepending `head` to `tail`, one obtains a new word. We'll show that any word can be uniquely obtained in this way. -/ @[ext] structure pair (i : ι) := (head : M i) (tail : word M) (fst_idx_ne : fst_idx tail ≠ some i) instance (i : ι) : inhabited (pair M i) := ⟨⟨1, empty, by tauto⟩⟩ variable {M} variables [∀ i, decidable_eq (M i)] /-- Given a pair `(head, tail)`, we can form a word by prepending `head` to `tail`, except if `head` is `1 : M i` then we have to just return `word` since we need the result to be reduced. -/ def rcons {i} (p : pair M i) : word M := if h : p.head = 1 then p.tail else { to_list := ⟨i, p.head⟩ :: p.tail.to_list, ne_one := by { rintros l (rfl | hl), exact h, exact p.tail.ne_one l hl }, chain_ne := p.tail.chain_ne.cons' (fst_idx_ne_iff.mp p.fst_idx_ne) } /-- Given a word of the form `⟨l :: ls, h1, h2⟩`, we can form a word of the form `⟨ls, _, _⟩`, dropping the first letter. -/ private def mk_aux {l} (ls : list (Σ i, M i)) (h1 : ∀ l' ∈ l :: ls, sigma.snd l' ≠ 1) (h2 : (l :: ls).chain' _) : word M := ⟨ls, λ l' hl, h1 _ (list.mem_cons_of_mem _ hl), h2.tail⟩ lemma cons_eq_rcons {i} {m : M i} {ls h1 h2} : word.mk (⟨i, m⟩ :: ls) h1 h2 = rcons ⟨m, mk_aux ls h1 h2, fst_idx_ne_iff.mpr h2.rel_head'⟩ := by { rw [rcons, dif_neg], refl, exact h1 ⟨i, m⟩ (ls.mem_cons_self _) } @[simp] lemma prod_rcons {i} (p : pair M i) : prod (rcons p) = of p.head * prod p.tail := if hm : p.head = 1 then by rw [rcons, dif_pos hm, hm, monoid_hom.map_one, one_mul] else by rw [rcons, dif_neg hm, prod, list.map_cons, list.prod_cons, prod] lemma rcons_inj {i} : function.injective (rcons : pair M i → word M) := begin rintros ⟨m, w, h⟩ ⟨m', w', h'⟩ he, by_cases hm : m = 1; by_cases hm' : m' = 1, { simp only [rcons, dif_pos hm, dif_pos hm'] at he, cc, }, { exfalso, simp only [rcons, dif_pos hm, dif_neg hm'] at he, rw he at h, exact h rfl }, { exfalso, simp only [rcons, dif_pos hm', dif_neg hm] at he, rw ←he at h', exact h' rfl, }, { have : m = m' ∧ w.to_list = w'.to_list, { simpa only [rcons, dif_neg hm, dif_neg hm', true_and, eq_self_iff_true, subtype.mk_eq_mk, heq_iff_eq, ←subtype.ext_iff_val] using he }, rcases this with ⟨rfl, h⟩, congr, exact word.ext _ _ h, } end variable [decidable_eq ι] /-- Given `i : ι`, any reduced word can be decomposed into a pair `p` such that `w = rcons p`. -/ -- This definition is computable but not very nice to look at. Thankfully we don't have to inspect -- it, since `rcons` is known to be injective. private def equiv_pair_aux (i) : Π w : word M, { p : pair M i // rcons p = w } | w@⟨[], _, _⟩ := ⟨⟨1, w, by rintro ⟨⟩⟩, dif_pos rfl⟩ | w@⟨⟨j, m⟩ :: ls, h1, h2⟩ := if ij : i = j then { val := { head := ij.symm.rec m, tail := mk_aux ls h1 h2, fst_idx_ne := by cases ij; exact fst_idx_ne_iff.mpr h2.rel_head' }, property := by cases ij; exact cons_eq_rcons.symm } else ⟨⟨1, w, (option.some_injective _).ne (ne.symm ij)⟩, dif_pos rfl⟩ /-- The equivalence between words and pairs. Given a word, it decomposes it as a pair by removing the first letter if it comes from `M i`. Given a pair, it prepends the head to the tail. -/ def equiv_pair (i) : word M ≃ pair M i := { to_fun := λ w, (equiv_pair_aux i w).val, inv_fun := rcons, left_inv := λ w, (equiv_pair_aux i w).property, right_inv := λ p, rcons_inj (equiv_pair_aux i _).property } lemma equiv_pair_symm (i) (p : pair M i) : (equiv_pair i).symm p = rcons p := rfl lemma equiv_pair_eq_of_fst_idx_ne {i} {w : word M} (h : fst_idx w ≠ some i) : equiv_pair i w = ⟨1, w, h⟩ := (equiv_pair i).apply_eq_iff_eq_symm_apply.mpr $ eq.symm (dif_pos rfl) instance summand_action (i) : mul_action (M i) (word M) := { smul := λ m w, rcons { head := m * (equiv_pair i w).head, ..equiv_pair i w }, one_smul := λ w, by { simp_rw [one_mul], apply (equiv_pair i).symm_apply_eq.mpr, ext; refl }, mul_smul := λ m m' w, by simp only [mul_assoc, ←equiv_pair_symm, equiv.apply_symm_apply], } instance : mul_action (free_product M) (word M) := mul_action.of_End_hom (lift (λ i, mul_action.to_End_hom)) lemma of_smul_def (i) (w : word M) (m : M i) : of m • w = rcons { head := m * (equiv_pair i w).head, ..equiv_pair i w } := rfl lemma cons_eq_smul {i} {m : M i} {ls h1 h2} : word.mk (⟨i, m⟩ :: ls) h1 h2 = of m • mk_aux ls h1 h2 := by rw [cons_eq_rcons, of_smul_def, equiv_pair_eq_of_fst_idx_ne _]; simp only [mul_one] lemma smul_induction {C : word M → Prop} (h_empty : C empty) (h_smul : ∀ i (m : M i) w, C w → C (of m • w)) (w : word M) : C w := begin cases w with ls h1 h2, induction ls with l ls ih, { exact h_empty }, cases l with i m, rw cons_eq_smul, exact h_smul _ _ _ (ih _ _), end @[simp] lemma prod_smul (m) : ∀ w : word M, prod (m • w) = m * prod w := begin apply m.induction_on, { intro, rw [one_smul, one_mul] }, { intros, rw [of_smul_def, prod_rcons, of.map_mul, mul_assoc, ←prod_rcons, ←equiv_pair_symm, equiv.symm_apply_apply] }, { intros x y hx hy w, rw [mul_smul, hx, hy, mul_assoc] }, end /-- Each element of the free product corresponds to a unique reduced word. -/ def equiv : free_product M ≃ word M := { to_fun := λ m, m • empty, inv_fun := λ w, prod w, left_inv := λ m, by dsimp only; rw [prod_smul, prod_nil, mul_one], right_inv := begin apply smul_induction, { dsimp only, rw [prod_nil, one_smul], }, { dsimp only, intros i m w ih, rw [prod_smul, mul_smul, ih], }, end } instance : decidable_eq (word M) := function.injective.decidable_eq word.ext instance : decidable_eq (free_product M) := word.equiv.decidable_eq end word end free_product
8f9d0aae14039d7dac75f519b88c56c8ae46e109
e0b0b1648286e442507eb62344760d5cd8d13f2d
/stage0/src/Lean/PrettyPrinter/Formatter.lean
56508c7337781a7bdec6a478ce89acd849392d2a
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,851
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ /-! The formatter turns a `Syntax` tree into a `Format` object, inserting both mandatory whitespace (to separate adjacent tokens) as well as "pretty" optional whitespace. The basic approach works much like the parenthesizer: A right-to-left traversal over the syntax tree, driven by parser-specific handlers registered via attributes. The traversal is right-to-left so that when emitting a token, we already know the text following it and can decide whether or not whitespace between the two is necessary. -/ import Lean.CoreM import Lean.Parser.Extension import Lean.KeyedDeclsAttribute import Lean.ParserCompiler.Attribute import Lean.PrettyPrinter.Basic namespace Lean namespace PrettyPrinter namespace Formatter structure Context where options : Options table : Parser.TokenTable structure State where stxTrav : Syntax.Traverser -- Textual content of `stack` up to the first whitespace (not enclosed in an escaped ident). We assume that the textual -- content of `stack` is modified only by `pushText` and `pushLine`, so `leadWord` is adjusted there accordingly. leadWord : String := "" -- Stack of generated Format objects, analogous to the Syntax stack in the parser. -- Note, however, that the stack is reversed because of the right-to-left traversal. stack : Array Format := #[] end Formatter abbrev FormatterM := ReaderT Formatter.Context $ StateRefT Formatter.State CoreM @[inline] def FormatterM.orelse {α} (p₁ p₂ : FormatterM α) : FormatterM α := do let s ← get catchInternalId backtrackExceptionId p₁ (fun _ => do set s; p₂) instance {α} : OrElse (FormatterM α) := ⟨FormatterM.orelse⟩ abbrev Formatter := FormatterM Unit unsafe def mkFormatterAttribute : IO (KeyedDeclsAttribute Formatter) := KeyedDeclsAttribute.init { builtinName := `builtinFormatter, name := `formatter, descr := "Register a formatter for a parser. [formatter k] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `SyntaxNodeKind` `k`.", valueTypeName := `Lean.PrettyPrinter.Formatter, evalKey := fun builtin stx => do let env ← getEnv let id ← Attribute.Builtin.getId stx -- `isValidSyntaxNodeKind` is updated only in the next stage for new `[builtin*Parser]`s, but we try to -- synthesize a formatter for it immediately, so we just check for a declaration in this case if (builtin && (env.find? id).isSome) || Parser.isValidSyntaxNodeKind env id then pure id else throwError "invalid [formatter] argument, unknown syntax kind '{id}'" } `Lean.PrettyPrinter.formatterAttribute @[builtinInit mkFormatterAttribute] constant formatterAttribute : KeyedDeclsAttribute Formatter unsafe def mkCombinatorFormatterAttribute : IO ParserCompiler.CombinatorAttribute := ParserCompiler.registerCombinatorAttribute `combinatorFormatter "Register a formatter for a parser combinator. [combinatorFormatter c] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `Parser` declaration `c`. Note that, unlike with [formatter], this is not a node kind since combinators usually do not introduce their own node kinds. The tagged declaration may optionally accept parameters corresponding to (a prefix of) those of `c`, where `Parser` is replaced with `Formatter` in the parameter types." @[builtinInit mkCombinatorFormatterAttribute] constant combinatorFormatterAttribute : ParserCompiler.CombinatorAttribute namespace Formatter open Lean.Core open Lean.Parser def throwBacktrack {α} : FormatterM α := throw $ Exception.internal backtrackExceptionId instance : Syntax.MonadTraverser FormatterM := ⟨{ get := State.stxTrav <$> get, set := fun t => modify (fun st => { st with stxTrav := t }), modifyGet := fun f => modifyGet (fun st => let (a, t) := f st.stxTrav; (a, { st with stxTrav := t })) }⟩ open Syntax.MonadTraverser def getStack : FormatterM (Array Format) := do let st ← get pure st.stack def getStackSize : FormatterM Nat := do let stack ← getStack; pure stack.size def setStack (stack : Array Format) : FormatterM Unit := modify fun st => { st with stack := stack } def push (f : Format) : FormatterM Unit := modify fun st => { st with stack := st.stack.push f } def pushLine : FormatterM Unit := do push Format.line; modify fun st => { st with leadWord := "" } /-- Execute `x` at the right-most child of the current node, if any, then advance to the left. -/ def visitArgs (x : FormatterM Unit) : FormatterM Unit := do let stx ← getCur if stx.getArgs.size > 0 then goDown (stx.getArgs.size - 1) *> x <* goUp goLeft /-- Execute `x`, pass array of generated Format objects to `fn`, and push result. -/ def fold (fn : Array Format → Format) (x : FormatterM Unit) : FormatterM Unit := do let sp ← getStackSize x let stack ← getStack let f := fn $ stack.extract sp stack.size setStack $ (stack.shrink sp).push f /-- Execute `x` and concatenate generated Format objects. -/ def concat (x : FormatterM Unit) : FormatterM Unit := do fold (Array.foldl (fun acc f => if acc.isNil then f else f ++ acc) Format.nil) x def indent (x : Formatter) (indent : Option Int := none) : Formatter := do concat x let ctx ← read let indent := indent.getD $ Std.Format.getIndent ctx.options modify fun st => { st with stack := st.stack.pop.push (Format.nest indent st.stack.back) } def group (x : Formatter) : Formatter := do concat x modify fun st => { st with stack := st.stack.pop.push (Format.fill st.stack.back) } @[combinatorFormatter Lean.Parser.orelse] def orelse.formatter (p1 p2 : Formatter) : Formatter := -- HACK: We have no (immediate) information on which side of the orelse could have produced the current node, so try -- them in turn. Uses the syntax traverser non-linearly! p1 <|> p2 -- `mkAntiquot` is quite complex, so we'd rather have its formatter synthesized below the actual parser definition. -- Note that there is a mutual recursion -- `categoryParser -> mkAntiquot -> termParser -> categoryParser`, so we need to introduce an indirection somewhere -- anyway. @[extern "lean_mk_antiquot_formatter"] constant mkAntiquot.formatter' (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Formatter -- break up big mutual recursion @[extern "lean_pretty_printer_formatter_interpret_parser_descr"] constant interpretParserDescr' : ParserDescr → CoreM Formatter unsafe def formatterForKindUnsafe (k : SyntaxNodeKind) : Formatter := do if k == `missing then push "<missing>" goLeft else let f ← runForNodeKind formatterAttribute k interpretParserDescr' f @[implementedBy formatterForKindUnsafe] constant formatterForKind (k : SyntaxNodeKind) : Formatter @[combinatorFormatter Lean.Parser.withAntiquot] def withAntiquot.formatter (antiP p : Formatter) : Formatter := -- TODO: could be optimized using `isAntiquot` (which would have to be moved), but I'd rather -- fix the backtracking hack outright. orelse.formatter antiP p @[combinatorFormatter Lean.Parser.withAntiquotSuffixSplice] def withAntiquotSuffixSplice.formatter (k : SyntaxNodeKind) (p suffix : Formatter) : Formatter := do if (← getCur).isAntiquotSuffixSplice then visitArgs <| suffix *> p else p @[combinatorFormatter Lean.Parser.tokenWithAntiquot] def tokenWithAntiquot.formatter (p : Formatter) : Formatter := do if (← getCur).isTokenAntiquot then visitArgs p else p @[combinatorFormatter Lean.Parser.categoryParser] def categoryParser.formatter (cat : Name) : Formatter := group $ indent do let stx ← getCur trace[PrettyPrinter.format] "formatting {indentD (fmt stx)}" if stx.getKind == `choice then visitArgs do -- format only last choice -- TODO: We could use elaborator data here to format the chosen child when available formatterForKind (← getCur).getKind else withAntiquot.formatter (mkAntiquot.formatter' cat.toString none) (formatterForKind stx.getKind) @[combinatorFormatter Lean.Parser.categoryParserOfStack] def categoryParserOfStack.formatter (offset : Nat) : Formatter := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) categoryParser.formatter stx.getId @[combinatorFormatter Lean.Parser.parserOfStack] def parserOfStack.formatter (offset : Nat) (prec : Nat := 0) : Formatter := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) formatterForKind stx.getKind @[combinatorFormatter Lean.Parser.error] def error.formatter (msg : String) : Formatter := pure () @[combinatorFormatter Lean.Parser.errorAtSavedPos] def errorAtSavedPos.formatter (msg : String) (delta : Bool) : Formatter := pure () @[combinatorFormatter Lean.Parser.atomic] def atomic.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.lookahead] def lookahead.formatter (p : Formatter) : Formatter := pure () @[combinatorFormatter Lean.Parser.notFollowedBy] def notFollowedBy.formatter (p : Formatter) : Formatter := pure () @[combinatorFormatter Lean.Parser.andthen] def andthen.formatter (p1 p2 : Formatter) : Formatter := p2 *> p1 def checkKind (k : SyntaxNodeKind) : FormatterM Unit := do let stx ← getCur if k != stx.getKind then trace[PrettyPrinter.format.backtrack] "unexpected node kind '{stx.getKind}', expected '{k}'" throwBacktrack @[combinatorFormatter Lean.Parser.node] def node.formatter (k : SyntaxNodeKind) (p : Formatter) : Formatter := do checkKind k; visitArgs p @[combinatorFormatter Lean.Parser.trailingNode] def trailingNode.formatter (k : SyntaxNodeKind) (_ _ : Nat) (p : Formatter) : Formatter := do checkKind k visitArgs do p; -- leading term, not actually produced by `p` categoryParser.formatter `foo def parseToken (s : String) : FormatterM ParserState := do Parser.tokenFn [] { input := s, fileName := "", fileMap := FileMap.ofString "", prec := 0, env := ← getEnv, options := ← getOptions, tokens := (← read).table } (Parser.mkParserState s) def pushTokenCore (tk : String) : FormatterM Unit := do if tk.toSubstring.dropRightWhile (fun s => s == ' ') == tk.toSubstring then push tk else pushLine push tk.trimRight def pushToken (info : SourceInfo) (tk : String) : FormatterM Unit := do match info with | SourceInfo.original _ _ ss => -- preserve non-whitespace content (i.e. comments) let ss' := ss.trim if !ss'.isEmpty then let ws := { ss with startPos := ss'.stopPos } if ws.contains '\n' then push s!"\n{ss'}" else push s!" {ss'}" modify fun st => { st with leadWord := "" } | _ => pure () let st ← get -- If there is no space between `tk` and the next word, see if we would parse more than `tk` as a single token if st.leadWord != "" && tk.trimRight == tk then let tk' := tk.trimLeft let t ← parseToken $ tk' ++ st.leadWord if t.pos <= tk'.bsize then -- stopped within `tk` => use it as is, extend `leadWord` if not prefixed by whitespace pushTokenCore tk modify fun st => { st with leadWord := if tk.trimLeft == tk then tk ++ st.leadWord else "" } else -- stopped after `tk` => add space pushTokenCore $ tk ++ " " modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" } else -- already separated => use `tk` as is pushTokenCore tk modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" } match info with | SourceInfo.original ss _ _ => -- preserve non-whitespace content (i.e. comments) let ss' := ss.trim if !ss'.isEmpty then let ws := { ss with startPos := ss'.stopPos } if ws.contains '\n' then do -- Indentation is automatically increased when entering a category, but comments should be aligned -- with the actual token, so dedent indent (push s!"{ss'}\n") (some ((0:Int) - Std.Format.getIndent (← getOptions))) else push s!"{ss'} " modify fun st => { st with leadWord := "" } | _ => pure () @[combinatorFormatter Lean.Parser.symbolNoAntiquot] def symbolNoAntiquot.formatter (sym : String) : Formatter := do let stx ← getCur if stx.isToken sym then do let (Syntax.atom info _) ← pure stx | unreachable! pushToken info sym goLeft else do trace[PrettyPrinter.format.backtrack] "unexpected syntax '{fmt stx}', expected symbol '{sym}'" throwBacktrack @[combinatorFormatter Lean.Parser.nonReservedSymbolNoAntiquot] def nonReservedSymbolNoAntiquot.formatter := symbolNoAntiquot.formatter @[combinatorFormatter Lean.Parser.unicodeSymbolNoAntiquot] def unicodeSymbolNoAntiquot.formatter (sym asciiSym : String) : Formatter := do let Syntax.atom info val ← getCur | throwError m!"not an atom: {← getCur}" if val == sym.trim then pushToken info sym else pushToken info asciiSym; goLeft @[combinatorFormatter Lean.Parser.identNoAntiquot] def identNoAntiquot.formatter : Formatter := do checkKind identKind; let Syntax.ident info _ id _ ← getCur | throwError m!"not an ident: {← getCur}" let id := id.simpMacroScopes let s := id.toString; if id.isAnonymous then pushToken info "[anonymous]" else if isInaccessibleUserName id || id.components.any Name.isNum || -- loose bvar "#".isPrefixOf s then -- not parsable anyway, output as-is pushToken info s else -- try to parse `s` as-is; if it fails, escape let pst ← parseToken s if pst.pos == s.bsize then pushToken info s else -- TODO: do something better than escaping all parts let id := (id.components.map fun c => "«" ++ toString c ++ "»").foldl Name.mkStr Name.anonymous pushToken info id.toString goLeft @[combinatorFormatter Lean.Parser.rawIdentNoAntiquot] def rawIdentNoAntiquot.formatter : Formatter := do checkKind identKind let Syntax.ident info _ id _ ← getCur | throwError m!"not an ident: {← getCur}" pushToken info id.toString goLeft @[combinatorFormatter Lean.Parser.identEq] def identEq.formatter (id : Name) := rawIdentNoAntiquot.formatter def visitAtom (k : SyntaxNodeKind) : Formatter := do let stx ← getCur if k != Name.anonymous then checkKind k let Syntax.atom info val ← pure $ stx.ifNode (fun n => n.getArg 0) (fun _ => stx) | throwError m!"not an atom: {stx}" pushToken info val goLeft @[combinatorFormatter Lean.Parser.charLitNoAntiquot] def charLitNoAntiquot.formatter := visitAtom charLitKind @[combinatorFormatter Lean.Parser.strLitNoAntiquot] def strLitNoAntiquot.formatter := visitAtom strLitKind @[combinatorFormatter Lean.Parser.nameLitNoAntiquot] def nameLitNoAntiquot.formatter := visitAtom nameLitKind @[combinatorFormatter Lean.Parser.numLitNoAntiquot] def numLitNoAntiquot.formatter := visitAtom numLitKind @[combinatorFormatter Lean.Parser.scientificLitNoAntiquot] def scientificLitNoAntiquot.formatter := visitAtom scientificLitKind @[combinatorFormatter Lean.Parser.fieldIdx] def fieldIdx.formatter := visitAtom fieldIdxKind @[combinatorFormatter Lean.Parser.manyNoAntiquot] def manyNoAntiquot.formatter (p : Formatter) : Formatter := do let stx ← getCur visitArgs $ stx.getArgs.size.forM fun _ => p @[combinatorFormatter Lean.Parser.many1NoAntiquot] def many1NoAntiquot.formatter (p : Formatter) : Formatter := manyNoAntiquot.formatter p @[combinatorFormatter Lean.Parser.optionalNoAntiquot] def optionalNoAntiquot.formatter (p : Formatter) : Formatter := visitArgs p @[combinatorFormatter Lean.Parser.many1Unbox] def many1Unbox.formatter (p : Formatter) : Formatter := do let stx ← getCur if stx.getKind == nullKind then do manyNoAntiquot.formatter p else p @[combinatorFormatter Lean.Parser.sepByNoAntiquot] def sepByNoAntiquot.formatter (p pSep : Formatter) : Formatter := do let stx ← getCur visitArgs $ (List.range stx.getArgs.size).reverse.forM $ fun i => if i % 2 == 0 then p else pSep @[combinatorFormatter Lean.Parser.sepBy1NoAntiquot] def sepBy1NoAntiquot.formatter := sepByNoAntiquot.formatter @[combinatorFormatter Lean.Parser.withPosition] def withPosition.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutPosition] def withoutPosition.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withForbidden] def withForbidden.formatter (tk : Token) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutForbidden] def withoutForbidden.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutInfo] def withoutInfo.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.setExpected] def setExpected.formatter (expected : List String) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.incQuotDepth] def incQuotDepth.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.decQuotDepth] def decQuotDepth.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.suppressInsideQuot] def suppressInsideQuot.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.evalInsideQuot] def evalInsideQuot.formatter (declName : Name) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.checkWsBefore] def checkWsBefore.formatter : Formatter := do let st ← get if st.leadWord != "" then pushLine @[combinatorFormatter Lean.Parser.checkPrec] def checkPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkLhsPrec] def checkLhsPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.setLhsPrec] def setLhsPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkStackTop] def checkStackTop.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkNoWsBefore] def checkNoWsBefore.formatter : Formatter := -- prevent automatic whitespace insertion modify fun st => { st with leadWord := "" } @[combinatorFormatter Lean.Parser.checkLinebreakBefore] def checkLinebreakBefore.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkTailWs] def checkTailWs.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkColGe] def checkColGe.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkColGt] def checkColGt.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkLineEq] def checkLineEq.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.eoi] def eoi.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.notFollowedByCategoryToken] def notFollowedByCategoryToken.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkNoImmediateColon] def checkNoImmediateColon.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkInsideQuot] def checkInsideQuot.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkOutsideQuot] def checkOutsideQuot.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.skip] def skip.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.pushNone] def pushNone.formatter : Formatter := goLeft @[combinatorFormatter Lean.Parser.interpolatedStr] def interpolatedStr.formatter (p : Formatter) : Formatter := do visitArgs $ (← getCur).getArgs.reverse.forM fun chunk => match chunk.isLit? interpolatedStrLitKind with | some str => push str *> goLeft | none => p @[combinatorFormatter Lean.Parser.dbgTraceState] def dbgTraceState.formatter (label : String) (p : Formatter) : Formatter := p @[combinatorFormatter ite, macroInline] def ite {α : Type} (c : Prop) [h : Decidable c] (t e : Formatter) : Formatter := if c then t else e abbrev FormatterAliasValue := AliasValue Formatter builtin_initialize formatterAliasesRef : IO.Ref (NameMap FormatterAliasValue) ← IO.mkRef {} def registerAlias (aliasName : Name) (v : FormatterAliasValue) : IO Unit := do Parser.registerAliasCore formatterAliasesRef aliasName v instance : Coe Formatter FormatterAliasValue := { coe := AliasValue.const } instance : Coe (Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.unary } instance : Coe (Formatter → Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.binary } builtin_initialize registerAlias "ws" checkWsBefore.formatter registerAlias "noWs" checkNoWsBefore.formatter registerAlias "linebreak" checkLinebreakBefore.formatter registerAlias "colGt" checkColGt.formatter registerAlias "colGe" checkColGe.formatter registerAlias "lookahead" lookahead.formatter registerAlias "atomic" atomic.formatter registerAlias "notFollowedBy" notFollowedBy.formatter registerAlias "withPosition" withPosition.formatter registerAlias "interpolatedStr" interpolatedStr.formatter registerAlias "orelse" orelse.formatter registerAlias "andthen" andthen.formatter end Formatter open Formatter def format (formatter : Formatter) (stx : Syntax) : CoreM Format := do trace[PrettyPrinter.format.input] "{fmt stx}" let options ← getOptions let table ← Parser.builtinTokenTable.get catchInternalId backtrackExceptionId (do let (_, st) ← (concat formatter { table := table, options := options }).run { stxTrav := Syntax.Traverser.fromSyntax stx }; pure $ Format.fill $ st.stack.get! 0) (fun _ => throwError "format: uncaught backtrack exception") def formatTerm := format $ categoryParser.formatter `term def formatCommand := format $ categoryParser.formatter `command builtin_initialize registerTraceClass `PrettyPrinter.format; end PrettyPrinter end Lean
196fcc7181c74e06f63d4a53abbdf74ad6acf954
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/exists2.lean
aa6ad409cff4761d5f63c1d427338805c48a6cda
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
831
lean
import Int. variable a : Int variable P : Int -> Int -> Bool variable f : Int -> Int -> Int variable g : Int -> Int axiom H1 : P (f a (g a)) (f a (g a)) axiom H2 : P (f (g a) (g a)) (f (g a) (g a)) axiom H3 : P (f (g a) (g a)) (g a) theorem T1 : exists x y : Int, P (f y x) (f y x) := exists_intro _ (exists_intro _ H1) theorem T2 : exists x : Int, P (f x (g x)) (f x (g x)) := exists_intro _ H1 theorem T3 : exists x : Int, P (f x x) (f x x) := exists_intro _ H2 theorem T4 : exists x : Int, P (f (g a) x) (f x x) := exists_intro _ H2 theorem T5 : exists x : Int, P x x := exists_intro _ H2 theorem T6 : exists x y : Int, P x y := exists_intro _ (exists_intro _ H3) theorem T7 : exists x : Int, P (f x x) x := exists_intro _ H3 theorem T8 : exists x y : Int, P (f x x) y := exists_intro _ (exists_intro _ H3) print environment 8.
54884c46d78f51980af3ebd199d1fec2499d9623
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/lie/of_associative.lean
8398a14d00de1952779fbe254195459b8ab9263c
[ "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
10,449
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.basic import algebra.lie.subalgebra import algebra.lie.submodule import algebra.algebra.subalgebra.basic /-! # Lie algebras of associative algebras This file defines the Lie algebra structure that arises on an associative algebra via the ring commutator. Since the linear endomorphisms of a Lie algebra form an associative algebra, one can define the adjoint action as a morphism of Lie algebras from a Lie algebra to its linear endomorphisms. We make such a definition in this file. ## Main definitions * `lie_algebra.of_associative_algebra` * `lie_algebra.of_associative_algebra_hom` * `lie_module.to_endomorphism` * `lie_algebra.ad` * `linear_equiv.lie_conj` * `alg_equiv.to_lie_equiv` ## Tags lie algebra, ring commutator, adjoint action -/ universes u v w w₁ w₂ section of_associative variables {A : Type v} [ring A] namespace ring /-- The bracket operation for rings is the ring commutator, which captures the extent to which a ring is commutative. It is identically zero exactly when the ring is commutative. -/ @[priority 100] instance : has_bracket A A := ⟨λ x y, x*y - y*x⟩ lemma lie_def (x y : A) : ⁅x, y⁆ = x*y - y*x := rfl end ring namespace lie_ring /-- An associative ring gives rise to a Lie ring by taking the bracket to be the ring commutator. -/ @[priority 100] instance of_associative_ring : lie_ring A := { add_lie := by simp only [ring.lie_def, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm, forall_const, eq_self_iff_true, neg_add_rev], lie_add := by simp only [ring.lie_def, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm, forall_const, eq_self_iff_true, neg_add_rev], lie_self := by simp only [ring.lie_def, forall_const, sub_self], leibniz_lie := λ x y z, by { repeat { rw ring.lie_def, }, noncomm_ring, } } lemma of_associative_ring_bracket (x y : A) : ⁅x, y⁆ = x*y - y*x := rfl @[simp] lemma lie_apply {α : Type*} (f g : α → A) (a : α) : ⁅f, g⁆ a = ⁅f a, g a⁆ := rfl end lie_ring section associative_module variables {M : Type w} [add_comm_group M] [module A M] /-- We can regard a module over an associative ring `A` as a Lie ring module over `A` with Lie bracket equal to its ring commutator. Note that this cannot be a global instance because it would create a diamond when `M = A`, specifically we can build two mathematically-different `has_bracket A A`s: 1. `@ring.has_bracket A _` which says `⁅a, b⁆ = a * b - b * a` 2. `(@lie_ring_module.of_associative_module A _ A _ _).to_has_bracket` which says `⁅a, b⁆ = a • b` (and thus `⁅a, b⁆ = a * b`) See note [reducible non-instances] -/ @[reducible] def lie_ring_module.of_associative_module : lie_ring_module A M := { bracket := (•), add_lie := add_smul, lie_add := smul_add, leibniz_lie := by simp [lie_ring.of_associative_ring_bracket, sub_smul, mul_smul, sub_add_cancel], } local attribute [instance] lie_ring_module.of_associative_module lemma lie_eq_smul (a : A) (m : M) : ⁅a, m⁆ = a • m := rfl end associative_module section lie_algebra variables {R : Type u} [comm_ring R] [algebra R A] /-- An associative algebra gives rise to a Lie algebra by taking the bracket to be the ring commutator. -/ @[priority 100] instance lie_algebra.of_associative_algebra : lie_algebra R A := { lie_smul := λ t x y, by rw [lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket, algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_sub], } local attribute [instance] lie_ring_module.of_associative_module section associative_representation variables {M : Type w} [add_comm_group M] [module R M] [module A M] [is_scalar_tower R A M] /-- A representation of an associative algebra `A` is also a representation of `A`, regarded as a Lie algebra via the ring commutator. See the comment at `lie_ring_module.of_associative_module` for why the possibility `M = A` means this cannot be a global instance. -/ def lie_module.of_associative_module : lie_module R A M := { smul_lie := smul_assoc, lie_smul := smul_algebra_smul_comm } instance module.End.lie_ring_module : lie_ring_module (module.End R M) M := lie_ring_module.of_associative_module instance module.End.lie_module : lie_module R (module.End R M) M := lie_module.of_associative_module end associative_representation namespace alg_hom variables {B : Type w} {C : Type w₁} [ring B] [ring C] [algebra R B] [algebra R C] variables (f : A →ₐ[R] B) (g : B →ₐ[R] C) /-- The map `of_associative_algebra` associating a Lie algebra to an associative algebra is functorial. -/ def to_lie_hom : A →ₗ⁅R⁆ B := { map_lie' := λ x y, show f ⁅x,y⁆ = ⁅f x,f y⁆, by simp only [lie_ring.of_associative_ring_bracket, alg_hom.map_sub, alg_hom.map_mul], ..f.to_linear_map, } instance : has_coe (A →ₐ[R] B) (A →ₗ⁅R⁆ B) := ⟨to_lie_hom⟩ @[simp] lemma to_lie_hom_coe : f.to_lie_hom = ↑f := rfl @[simp] lemma coe_to_lie_hom : ((f : A →ₗ⁅R⁆ B) : A → B) = f := rfl lemma to_lie_hom_apply (x : A) : f.to_lie_hom x = f x := rfl @[simp] lemma to_lie_hom_id : (alg_hom.id R A : A →ₗ⁅R⁆ A) = lie_hom.id := rfl @[simp] lemma to_lie_hom_comp : (g.comp f : A →ₗ⁅R⁆ C) = (g : B →ₗ⁅R⁆ C).comp (f : A →ₗ⁅R⁆ B) := rfl lemma to_lie_hom_injective {f g : A →ₐ[R] B} (h : (f : A →ₗ⁅R⁆ B) = (g : A →ₗ⁅R⁆ B)) : f = g := by { ext a, exact lie_hom.congr_fun h a, } end alg_hom end lie_algebra end of_associative section adjoint_action variables (R : Type u) (L : Type v) (M : Type w) variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] /-- A Lie module yields a Lie algebra morphism into the linear endomorphisms of the module. See also `lie_module.to_module_hom`. -/ @[simps] def lie_module.to_endomorphism : L →ₗ⁅R⁆ module.End R M := { to_fun := λ x, { to_fun := λ m, ⁅x, m⁆, map_add' := lie_add x, map_smul' := λ t, lie_smul t x, }, map_add' := λ x y, by { ext m, apply add_lie, }, map_smul' := λ t x, by { ext m, apply smul_lie, }, map_lie' := λ x y, by { ext m, apply lie_lie, }, } /-- The adjoint action of a Lie algebra on itself. -/ def lie_algebra.ad : L →ₗ⁅R⁆ module.End R L := lie_module.to_endomorphism R L L @[simp] lemma lie_algebra.ad_apply (x y : L) : lie_algebra.ad R L x y = ⁅x, y⁆ := rfl @[simp] lemma lie_module.to_endomorphism_module_End : lie_module.to_endomorphism R (module.End R M) M = lie_hom.id := by { ext g m, simp [lie_eq_smul], } lemma lie_subalgebra.to_endomorphism_eq (K : lie_subalgebra R L) {x : K} : lie_module.to_endomorphism R K M x = lie_module.to_endomorphism R L M x := rfl @[simp] lemma lie_subalgebra.to_endomorphism_mk (K : lie_subalgebra R L) {x : L} (hx : x ∈ K) : lie_module.to_endomorphism R K M ⟨x, hx⟩ = lie_module.to_endomorphism R L M x := rfl variables {R L M} namespace lie_submodule open lie_module variables {N : lie_submodule R L M} {x : L} lemma coe_map_to_endomorphism_le : (N : submodule R M).map (lie_module.to_endomorphism R L M x) ≤ N := begin rintros n ⟨m, hm, rfl⟩, exact N.lie_mem hm, end variables (N x) lemma to_endomorphism_comp_subtype_mem (m : M) (hm : m ∈ N) : (to_endomorphism R L M x).comp (N : submodule R M).subtype ⟨m, hm⟩ ∈ N := by simpa using N.lie_mem hm @[simp] lemma to_endomorphism_restrict_eq_to_endomorphism (h := N.to_endomorphism_comp_subtype_mem x) : ((to_endomorphism R L M x).restrict h : N →ₗ[R] N) = to_endomorphism R L N x := by { ext, simp [linear_map.restrict_apply], } end lie_submodule open lie_algebra lemma lie_algebra.ad_eq_lmul_left_sub_lmul_right (A : Type v) [ring A] [algebra R A] : (ad R A : A → module.End R A) = algebra.lmul_left R - algebra.lmul_right R := by { ext a b, simp [lie_ring.of_associative_ring_bracket], } lemma lie_subalgebra.ad_comp_incl_eq (K : lie_subalgebra R L) (x : K) : (ad R L ↑x).comp (K.incl : K →ₗ[R] L) = (K.incl : K →ₗ[R] L).comp (ad R K x) := begin ext y, simp only [ad_apply, lie_hom.coe_to_linear_map, lie_subalgebra.coe_incl, linear_map.coe_comp, lie_subalgebra.coe_bracket, function.comp_app], end end adjoint_action /-- A subalgebra of an associative algebra is a Lie subalgebra of the associated Lie algebra. -/ def lie_subalgebra_of_subalgebra (R : Type u) [comm_ring R] (A : Type v) [ring A] [algebra R A] (A' : subalgebra R A) : lie_subalgebra R A := { lie_mem' := λ x y hx hy, by { change ⁅x, y⁆ ∈ A', change x ∈ A' at hx, change y ∈ A' at hy, rw lie_ring.of_associative_ring_bracket, have hxy := A'.mul_mem hx hy, have hyx := A'.mul_mem hy hx, exact submodule.sub_mem A'.to_submodule hxy hyx, }, ..A'.to_submodule } namespace linear_equiv variables {R : Type u} {M₁ : Type v} {M₂ : Type w} variables [comm_ring R] [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] variables (e : M₁ ≃ₗ[R] M₂) /-- A linear equivalence of two modules induces a Lie algebra equivalence of their endomorphisms. -/ def lie_conj : module.End R M₁ ≃ₗ⁅R⁆ module.End R M₂ := { map_lie' := λ f g, show e.conj ⁅f, g⁆ = ⁅e.conj f, e.conj g⁆, by simp only [lie_ring.of_associative_ring_bracket, linear_map.mul_eq_comp, e.conj_comp, linear_equiv.map_sub], ..e.conj } @[simp] lemma lie_conj_apply (f : module.End R M₁) : e.lie_conj f = e.conj f := rfl @[simp] lemma lie_conj_symm : e.lie_conj.symm = e.symm.lie_conj := rfl end linear_equiv namespace alg_equiv variables {R : Type u} {A₁ : Type v} {A₂ : Type w} variables [comm_ring R] [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] variables (e : A₁ ≃ₐ[R] A₂) /-- An equivalence of associative algebras is an equivalence of associated Lie algebras. -/ def to_lie_equiv : A₁ ≃ₗ⁅R⁆ A₂ := { to_fun := e.to_fun, map_lie' := λ x y, by simp [lie_ring.of_associative_ring_bracket], ..e.to_linear_equiv } @[simp] lemma to_lie_equiv_apply (x : A₁) : e.to_lie_equiv x = e x := rfl @[simp] lemma to_lie_equiv_symm_apply (x : A₂) : e.to_lie_equiv.symm x = e.symm x := rfl end alg_equiv
e7c8ae0044a1406da6fcde724abced132227b487
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/ring_theory/adjoin_root.lean
a7e85752940feb880e0e5c1cf66b76f5a9167af0
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
3,771
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes Adjoining roots of polynomials -/ import data.polynomial ring_theory.principal_ideal_domain universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace adjoin_root open polynomial ideal section comm_ring variables [comm_ring α] [decidable_eq α] (f : polynomial α) def adjoin_root (f : polynomial α) : Type u := ideal.quotient (span {f} : ideal (polynomial α)) instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _ noncomputable instance : decidable_eq (adjoin_root f) := classical.dec_eq _ variable {f} def mk : polynomial α → adjoin_root f := ideal.quotient.mk _ def root : adjoin_root f := mk X def of (x : α) : adjoin_root f := mk (C x) instance adjoin_root.has_coe_t : has_coe_t α (adjoin_root f) := ⟨of⟩ instance mk.is_ring_hom : is_ring_hom (mk : polynomial α → adjoin_root f) := ideal.quotient.is_ring_hom_mk _ @[simp] lemma mk_self : (mk f : adjoin_root f) = 0 := quotient.sound' (mem_span_singleton.2 $ by simp) instance : is_ring_hom (coe : α → adjoin_root f) := @is_ring_hom.comp _ _ _ _ C _ _ _ mk mk.is_ring_hom lemma eval₂_root (f : polynomial α) : f.eval₂ coe (root : adjoin_root f) = 0 := quotient.induction_on' (root : adjoin_root f) (λ (g : polynomial α) (hg : mk g = mk X), show finsupp.sum f (λ (e : ℕ) (a : α), mk (C a) * mk g ^ e) = 0, by simp only [hg, (is_semiring_hom.map_pow (mk : polynomial α → adjoin_root f) _ _).symm, (is_ring_hom.map_mul (mk : polynomial α → adjoin_root f)).symm]; rw [finsupp.sum, finset.sum_hom (mk : polynomial α → adjoin_root f), show finset.sum _ _ = _, from sum_C_mul_X_eq _, mk_self]) (show (root : adjoin_root f) = mk X, from rfl) lemma is_root_root (f : polynomial α) : is_root (f.map coe) (root : adjoin_root f) := by rw [is_root, eval_map, eval₂_root] variables [comm_ring β] def lift (i : α → β) [is_ring_hom i] (x : β) (h : f.eval₂ i x = 0) : (adjoin_root f) → β := ideal.quotient.lift _ (eval₂ i x) $ λ g H, begin simp [mem_span_singleton] at H, cases H with y H, dsimp at H, rw [H, eval₂_mul], simp [h] end variables {i : α → β} [is_ring_hom i] {a : β} {h : f.eval₂ i a = 0} @[simp] lemma lift_mk {g : polynomial α} : lift i a h (mk g) = g.eval₂ i a := ideal.quotient.lift_mk @[simp] lemma lift_root : lift i a h root = a := by simp [root, h] @[simp] lemma lift_of {x : α} : lift i a h x = i x := by show lift i a h (ideal.quotient.mk _ (C x)) = i x; convert ideal.quotient.lift_mk; simp instance is_ring_hom_lift : is_ring_hom (lift i a h) := by unfold lift; apply_instance end comm_ring variables [discrete_field α] {f : polynomial α} [irreducible f] instance is_maximal_span : is_maximal (span {f} : ideal (polynomial α)) := principal_ideal_domain.is_maximal_of_irreducible ‹irreducible f› noncomputable instance field : discrete_field (adjoin_root f) := { has_decidable_eq := by apply_instance, inv_zero := by convert dif_pos rfl, ..adjoin_root.comm_ring f, ..ideal.quotient.field (span {f} : ideal (polynomial α)) } instance : is_field_hom (coe : α → adjoin_root f) := by apply_instance instance lift_is_field_hom [field β] {i : α → β} [is_ring_hom i] {a : β} {h : f.eval₂ i a = 0} : is_field_hom (lift i a h) := by apply_instance lemma coe_injective : function.injective (coe : α → adjoin_root f) := is_field_hom.injective _ lemma mul_div_root_cancel (f : polynomial α) [irreducible f] : (X - C (root : adjoin_root f)) * (f.map coe / (X - C root)) = f.map coe := mul_div_eq_iff_is_root.2 $ is_root_root _ end adjoin_root
9018e943c1263c302eea92452fc02d9ccfb58a84
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/set/function.lean
7580ac6908cc7b34170c94152f3b0890bce23328
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,851
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu, Yury Kudryashov -/ import data.set.basic import logic.function.conjugate /-! # Functions over sets ## Main definitions ### Predicate * `set.eq_on f₁ f₂ s` : functions `f₁` and `f₂` are equal at every point of `s`; * `set.maps_to f s t` : `f` sends every point of `s` to a point of `t`; * `set.inj_on f s` : restriction of `f` to `s` is injective; * `set.surj_on f s t` : every point in `s` has a preimage in `s`; * `set.bij_on f s t` : `f` is a bijection between `s` and `t`; * `set.left_inv_on f' f s` : for every `x ∈ s` we have `f' (f x) = x`; * `set.right_inv_on f' f t` : for every `y ∈ t` we have `f (f' y) = y`; * `set.inv_on f' f s t` : `f'` is a two-side inverse of `f` on `s` and `t`, i.e. we have `set.left_inv_on f' f s` and `set.right_inv_on f' f t`. ### Functions * `set.restrict f s` : restrict the domain of `f` to the set `s`; * `set.cod_restrict f s h` : given `h : ∀ x, f x ∈ s`, restrict the codomain of `f` to the set `s`; * `set.maps_to.restrict f s t h`: given `h : maps_to f s t`, restrict the domain of `f` to `s` and the codomain to `t`. -/ universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} open function namespace set /-! ### Restrict -/ /-- Restrict domain of a function `f` to a set `s`. Same as `subtype.restrict` but this version takes an argument `↥s` instead of `subtype s`. -/ def restrict (f : α → β) (s : set α) : s → β := λ x, f x lemma restrict_eq (f : α → β) (s : set α) : s.restrict f = f ∘ coe := rfl @[simp] lemma restrict_apply (f : α → β) (s : set α) (x : s) : restrict f s x = f x := rfl @[simp] lemma range_restrict (f : α → β) (s : set α) : set.range (restrict f s) = f '' s := (range_comp _ _).trans $ congr_arg (('') f) subtype.range_coe lemma image_restrict (f : α → β) (s t : set α) : s.restrict f '' (coe ⁻¹' t) = f '' (t ∩ s) := by rw [restrict, image_comp, image_preimage_eq_inter_range, subtype.range_coe] /-- Restrict codomain of a function `f` to a set `s`. Same as `subtype.coind` but this version has codomain `↥s` instead of `subtype s`. -/ def cod_restrict (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) : α → s := λ x, ⟨f x, h x⟩ @[simp] lemma coe_cod_restrict_apply (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) (x : α) : (cod_restrict f s h x : β) = f x := rfl variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {p : set γ} {f f₁ f₂ f₃ : α → β} {g : β → γ} {f' f₁' f₂' : β → α} {g' : γ → β} @[simp] lemma injective_cod_restrict (h : ∀ x, f x ∈ t) : injective (cod_restrict f t h) ↔ injective f := by simp only [injective, subtype.ext_iff, coe_cod_restrict_apply] alias injective_cod_restrict ↔ _ function.injective.cod_restrict /-! ### Equality on a set -/ /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ def eq_on (f₁ f₂ : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f₁ x = f₂ x @[simp] lemma eq_on_empty (f₁ f₂ : α → β) : eq_on f₁ f₂ ∅ := λ x, false.elim @[symm] lemma eq_on.symm (h : eq_on f₁ f₂ s) : eq_on f₂ f₁ s := λ x hx, (h hx).symm lemma eq_on_comm : eq_on f₁ f₂ s ↔ eq_on f₂ f₁ s := ⟨eq_on.symm, eq_on.symm⟩ @[refl] lemma eq_on_refl (f : α → β) (s : set α) : eq_on f f s := λ _ _, rfl @[trans] lemma eq_on.trans (h₁ : eq_on f₁ f₂ s) (h₂ : eq_on f₂ f₃ s) : eq_on f₁ f₃ s := λ x hx, (h₁ hx).trans (h₂ hx) theorem eq_on.image_eq (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq theorem eq_on.inter_preimage_eq (heq : eq_on f₁ f₂ s) (t : set β) : s ∩ f₁ ⁻¹' t = s ∩ f₂ ⁻¹' t := ext $ λ x, and.congr_right_iff.2 $ λ hx, by rw [mem_preimage, mem_preimage, heq hx] lemma eq_on.mono (hs : s₁ ⊆ s₂) (hf : eq_on f₁ f₂ s₂) : eq_on f₁ f₂ s₁ := λ x hx, hf (hs hx) lemma comp_eq_of_eq_on_range {ι : Sort*} {f : ι → α} {g₁ g₂ : α → β} (h : eq_on g₁ g₂ (range f)) : g₁ ∘ f = g₂ ∘ f := funext $ λ x, h $ mem_range_self _ /-! ### maps to -/ /-- `maps_to f a b` means that the image of `a` is contained in `b`. -/ @[reducible] def maps_to (f : α → β) (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ s → f x ∈ t /-- Given a map `f` sending `s : set α` into `t : set β`, restrict domain of `f` to `s` and the codomain to `t`. Same as `subtype.map`. -/ def maps_to.restrict (f : α → β) (s : set α) (t : set β) (h : maps_to f s t) : s → t := subtype.map f h @[simp] lemma maps_to.coe_restrict_apply (h : maps_to f s t) (x : s) : (h.restrict f s t x : β) = f x := rfl lemma maps_to_iff_exists_map_subtype : maps_to f s t ↔ ∃ g : s → t, ∀ x : s, f x = g x := ⟨λ h, ⟨h.restrict f s t, λ _, rfl⟩, λ ⟨g, hg⟩ x hx, by { erw [hg ⟨x, hx⟩], apply subtype.coe_prop }⟩ theorem maps_to' : maps_to f s t ↔ f '' s ⊆ t := image_subset_iff.symm @[simp] theorem maps_to_singleton {x : α} : maps_to f {x} t ↔ f x ∈ t := singleton_subset_iff theorem maps_to_empty (f : α → β) (t : set β) : maps_to f ∅ t := empty_subset _ theorem maps_to.image_subset (h : maps_to f s t) : f '' s ⊆ t := maps_to'.1 h theorem maps_to.congr (h₁ : maps_to f₁ s t) (h : eq_on f₁ f₂ s) : maps_to f₂ s t := λ x hx, h hx ▸ h₁ hx theorem eq_on.maps_to_iff (H : eq_on f₁ f₂ s) : maps_to f₁ s t ↔ maps_to f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem maps_to.comp (h₁ : maps_to g t p) (h₂ : maps_to f s t) : maps_to (g ∘ f) s p := λ x h, h₁ (h₂ h) theorem maps_to_id (s : set α) : maps_to id s s := λ x, id theorem maps_to.iterate {f : α → α} {s : set α} (h : maps_to f s s) : ∀ n, maps_to (f^[n]) s s | 0 := λ _, id | (n+1) := (maps_to.iterate n).comp h theorem maps_to.iterate_restrict {f : α → α} {s : set α} (h : maps_to f s s) (n : ℕ) : (h.restrict f s s^[n]) = (h.iterate n).restrict _ _ _ := begin funext x, rw [subtype.ext_iff, maps_to.coe_restrict_apply], induction n with n ihn generalizing x, { refl }, { simp [nat.iterate, ihn] } end theorem maps_to.mono (hs : s₂ ⊆ s₁) (ht : t₁ ⊆ t₂) (hf : maps_to f s₁ t₁) : maps_to f s₂ t₂ := λ x hx, ht (hf $ hs hx) theorem maps_to.union_union (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) : maps_to f (s₁ ∪ s₂) (t₁ ∪ t₂) := λ x hx, hx.elim (λ hx, or.inl $ h₁ hx) (λ hx, or.inr $ h₂ hx) theorem maps_to.union (h₁ : maps_to f s₁ t) (h₂ : maps_to f s₂ t) : maps_to f (s₁ ∪ s₂) t := union_self t ▸ h₁.union_union h₂ @[simp] theorem maps_to_union : maps_to f (s₁ ∪ s₂) t ↔ maps_to f s₁ t ∧ maps_to f s₂ t := ⟨λ h, ⟨h.mono (subset_union_left s₁ s₂) (subset.refl t), h.mono (subset_union_right s₁ s₂) (subset.refl t)⟩, λ h, h.1.union h.2⟩ theorem maps_to.inter (h₁ : maps_to f s t₁) (h₂ : maps_to f s t₂) : maps_to f s (t₁ ∩ t₂) := λ x hx, ⟨h₁ hx, h₂ hx⟩ theorem maps_to.inter_inter (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) : maps_to f (s₁ ∩ s₂) (t₁ ∩ t₂) := λ x hx, ⟨h₁ hx.1, h₂ hx.2⟩ @[simp] theorem maps_to_inter : maps_to f s (t₁ ∩ t₂) ↔ maps_to f s t₁ ∧ maps_to f s t₂ := ⟨λ h, ⟨h.mono (subset.refl s) (inter_subset_left t₁ t₂), h.mono (subset.refl s) (inter_subset_right t₁ t₂)⟩, λ h, h.1.inter h.2⟩ theorem maps_to_univ (f : α → β) (s : set α) : maps_to f s univ := λ x h, trivial theorem maps_to_image (f : α → β) (s : set α) : maps_to f s (f '' s) := by rw maps_to' theorem maps_to_preimage (f : α → β) (t : set β) : maps_to f (f ⁻¹' t) t := subset.refl _ theorem maps_to_range (f : α → β) (s : set α) : maps_to f s (range f) := (maps_to_image f s).mono (subset.refl s) (image_subset_range _ _) @[simp] lemma maps_image_to (f : α → β) (g : γ → α) (s : set γ) (t : set β) : maps_to f (g '' s) t ↔ maps_to (f ∘ g) s t := ⟨λ h c hc, h ⟨c, hc, rfl⟩, λ h d ⟨c, hc⟩, hc.2 ▸ h hc.1⟩ @[simp] lemma maps_univ_to (f : α → β) (s : set β) : maps_to f univ s ↔ ∀ a, f a ∈ s := ⟨λ h a, h (mem_univ _), λ h x _, h x⟩ @[simp] lemma maps_range_to (f : α → β) (g : γ → α) (s : set β) : maps_to f (range g) s ↔ maps_to (f ∘ g) univ s := by rw [←image_univ, maps_image_to] theorem surjective_maps_to_image_restrict (f : α → β) (s : set α) : surjective ((maps_to_image f s).restrict f s (f '' s)) := λ ⟨y, x, hs, hxy⟩, ⟨⟨x, hs⟩, subtype.ext hxy⟩ theorem maps_to.mem_iff (h : maps_to f s t) (hc : maps_to f sᶜ tᶜ) {x} : f x ∈ t ↔ x ∈ s := ⟨λ ht, by_contra $ λ hs, hc hs ht, λ hx, h hx⟩ /-! ### Injectivity on a set -/ /-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/ @[reducible] def inj_on (f : α → β) (s : set α) : Prop := ∀ ⦃x₁ : α⦄, x₁ ∈ s → ∀ ⦃x₂ : α⦄, x₂ ∈ s → f x₁ = f x₂ → x₁ = x₂ theorem subsingleton.inj_on (hs : s.subsingleton) (f : α → β) : inj_on f s := λ x hx y hy h, hs hx hy @[simp] theorem inj_on_empty (f : α → β) : inj_on f ∅ := subsingleton_empty.inj_on f @[simp] theorem inj_on_singleton (f : α → β) (a : α) : inj_on f {a} := subsingleton_singleton.inj_on f theorem inj_on.eq_iff {x y} (h : inj_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x = f y ↔ x = y := ⟨h hx hy, λ h, h ▸ rfl⟩ theorem inj_on.congr (h₁ : inj_on f₁ s) (h : eq_on f₁ f₂ s) : inj_on f₂ s := λ x hx y hy, h hx ▸ h hy ▸ h₁ hx hy theorem eq_on.inj_on_iff (H : eq_on f₁ f₂ s) : inj_on f₁ s ↔ inj_on f₂ s := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem inj_on.mono (h : s₁ ⊆ s₂) (ht : inj_on f s₂) : inj_on f s₁ := λ x hx y hy H, ht (h hx) (h hy) H theorem inj_on_union (h : disjoint s₁ s₂) : inj_on f (s₁ ∪ s₂) ↔ inj_on f s₁ ∧ inj_on f s₂ ∧ ∀ (x ∈ s₁) (y ∈ s₂), f x ≠ f y := begin refine ⟨λ H, ⟨H.mono $ subset_union_left _ _, H.mono $ subset_union_right _ _, _⟩, _⟩, { intros x hx y hy hxy, obtain rfl : x = y, from H (or.inl hx) (or.inr hy) hxy, exact h ⟨hx, hy⟩ }, { rintro ⟨h₁, h₂, h₁₂⟩, rintro x (hx|hx) y (hy|hy) hxy, exacts [h₁ hx hy hxy, (h₁₂ _ hx _ hy hxy).elim, (h₁₂ _ hy _ hx hxy.symm).elim, h₂ hx hy hxy] } end theorem inj_on_insert {f : α → β} {s : set α} {a : α} (has : a ∉ s) : set.inj_on f (insert a s) ↔ set.inj_on f s ∧ f a ∉ f '' s := have disjoint s {a}, from λ x ⟨hxs, (hxa : x = a)⟩, has (hxa ▸ hxs), by { rw [← union_singleton, inj_on_union this], simp } lemma injective_iff_inj_on_univ : injective f ↔ inj_on f univ := ⟨λ h x hx y hy hxy, h hxy, λ h _ _ heq, h trivial trivial heq⟩ lemma inj_on_of_injective (h : injective f) (s : set α) : inj_on f s := λ x hx y hy hxy, h hxy alias inj_on_of_injective ← function.injective.inj_on theorem inj_on.comp (hg : inj_on g t) (hf: inj_on f s) (h : maps_to f s t) : inj_on (g ∘ f) s := λ x hx y hy heq, hf hx hy $ hg (h hx) (h hy) heq lemma inj_on_iff_injective : inj_on f s ↔ injective (restrict f s) := ⟨λ H a b h, subtype.eq $ H a.2 b.2 h, λ H a as b bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩ lemma inj_on_preimage {B : set (set β)} (hB : B ⊆ 𝒫 (range f)) : inj_on (preimage f) B := λ s hs t ht hst, (preimage_eq_preimage' (hB hs) (hB ht)).1 hst lemma inj_on.mem_of_mem_image {x} (hf : inj_on f s) (hs : s₁ ⊆ s) (h : x ∈ s) (h₁ : f x ∈ f '' s₁) : x ∈ s₁ := let ⟨x', h', eq⟩ := h₁ in hf (hs h') h eq ▸ h' lemma inj_on.mem_image_iff {x} (hf : inj_on f s) (hs : s₁ ⊆ s) (hx : x ∈ s) : f x ∈ f '' s₁ ↔ x ∈ s₁ := ⟨hf.mem_of_mem_image hs hx, mem_image_of_mem f⟩ lemma inj_on.preimage_image_inter (hf : inj_on f s) (hs : s₁ ⊆ s) : f ⁻¹' (f '' s₁) ∩ s = s₁ := ext $ λ x, ⟨λ ⟨h₁, h₂⟩, hf.mem_of_mem_image hs h₂ h₁, λ h, ⟨mem_image_of_mem _ h, hs h⟩⟩ lemma inj_on.pairwise_on_image (h : inj_on f s) {r : β → β → Prop} : pairwise_on (f '' s) r ↔ pairwise_on s (λ x y, r (f x) (f y)) := by simp [h.eq_iff, pairwise_on] {contextual := tt} /-! ### Surjectivity on a set -/ /-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/ @[reducible] def surj_on (f : α → β) (s : set α) (t : set β) : Prop := t ⊆ f '' s theorem surj_on.subset_range (h : surj_on f s t) : t ⊆ range f := subset.trans h $ image_subset_range f s lemma surj_on_iff_exists_map_subtype : surj_on f s t ↔ ∃ (t' : set β) (g : s → t'), t ⊆ t' ∧ surjective g ∧ ∀ x : s, f x = g x := ⟨λ h, ⟨_, (maps_to_image f s).restrict f s _, h, surjective_maps_to_image_restrict _ _, λ _, rfl⟩, λ ⟨t', g, htt', hg, hfg⟩ y hy, let ⟨x, hx⟩ := hg ⟨y, htt' hy⟩ in ⟨x, x.2, by rw [hfg, hx, subtype.coe_mk]⟩⟩ theorem surj_on_empty (f : α → β) (s : set α) : surj_on f s ∅ := empty_subset _ theorem surj_on_image (f : α → β) (s : set α) : surj_on f s (f '' s) := subset.rfl theorem surj_on.comap_nonempty (h : surj_on f s t) (ht : t.nonempty) : s.nonempty := (ht.mono h).of_image theorem surj_on.congr (h : surj_on f₁ s t) (H : eq_on f₁ f₂ s) : surj_on f₂ s t := by rwa [surj_on, ← H.image_eq] theorem eq_on.surj_on_iff (h : eq_on f₁ f₂ s) : surj_on f₁ s t ↔ surj_on f₂ s t := ⟨λ H, H.congr h, λ H, H.congr h.symm⟩ theorem surj_on.mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (hf : surj_on f s₁ t₂) : surj_on f s₂ t₁ := subset.trans ht $ subset.trans hf $ image_subset _ hs theorem surj_on.union (h₁ : surj_on f s t₁) (h₂ : surj_on f s t₂) : surj_on f s (t₁ ∪ t₂) := λ x hx, hx.elim (λ hx, h₁ hx) (λ hx, h₂ hx) theorem surj_on.union_union (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) : surj_on f (s₁ ∪ s₂) (t₁ ∪ t₂) := (h₁.mono (subset_union_left _ _) (subset.refl _)).union (h₂.mono (subset_union_right _ _) (subset.refl _)) theorem surj_on.inter_inter (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : surj_on f (s₁ ∩ s₂) (t₁ ∩ t₂) := begin intros y hy, rcases h₁ hy.1 with ⟨x₁, hx₁, rfl⟩, rcases h₂ hy.2 with ⟨x₂, hx₂, heq⟩, have : x₁ = x₂, from h (or.inl hx₁) (or.inr hx₂) heq.symm, subst x₂, exact mem_image_of_mem f ⟨hx₁, hx₂⟩ end theorem surj_on.inter (h₁ : surj_on f s₁ t) (h₂ : surj_on f s₂ t) (h : inj_on f (s₁ ∪ s₂)) : surj_on f (s₁ ∩ s₂) t := inter_self t ▸ h₁.inter_inter h₂ h theorem surj_on.comp (hg : surj_on g t p) (hf : surj_on f s t) : surj_on (g ∘ f) s p := subset.trans hg $ subset.trans (image_subset g hf) $ (image_comp g f s) ▸ subset.refl _ lemma surjective_iff_surj_on_univ : surjective f ↔ surj_on f univ univ := by simp [surjective, surj_on, subset_def] lemma surj_on_iff_surjective : surj_on f s univ ↔ surjective (restrict f s) := ⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩, λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩ lemma surj_on.image_eq_of_maps_to (h₁ : surj_on f s t) (h₂ : maps_to f s t) : f '' s = t := eq_of_subset_of_subset h₂.image_subset h₁ lemma surj_on.maps_to_compl (h : surj_on f s t) (h' : injective f) : maps_to f sᶜ tᶜ := λ x hs ht, let ⟨x', hx', heq⟩ := h ht in hs $ h' heq ▸ hx' lemma maps_to.surj_on_compl (h : maps_to f s t) (h' : surjective f) : surj_on f sᶜ tᶜ := h'.forall.2 $ λ x ht, mem_image_of_mem _ $ λ hs, ht (h hs) /-! ### Bijectivity -/ /-- `f` is bijective from `s` to `t` if `f` is injective on `s` and `f '' s = t`. -/ @[reducible] def bij_on (f : α → β) (s : set α) (t : set β) : Prop := maps_to f s t ∧ inj_on f s ∧ surj_on f s t lemma bij_on.maps_to (h : bij_on f s t) : maps_to f s t := h.left lemma bij_on.inj_on (h : bij_on f s t) : inj_on f s := h.right.left lemma bij_on.surj_on (h : bij_on f s t) : surj_on f s t := h.right.right lemma bij_on.mk (h₁ : maps_to f s t) (h₂ : inj_on f s) (h₃ : surj_on f s t) : bij_on f s t := ⟨h₁, h₂, h₃⟩ lemma bij_on_empty (f : α → β) : bij_on f ∅ ∅ := ⟨maps_to_empty f ∅, inj_on_empty f, surj_on_empty f ∅⟩ lemma bij_on.inter (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : bij_on f (s₁ ∩ s₂) (t₁ ∩ t₂) := ⟨h₁.maps_to.inter_inter h₂.maps_to, h₁.inj_on.mono $ inter_subset_left _ _, h₁.surj_on.inter_inter h₂.surj_on h⟩ lemma bij_on.union (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : bij_on f (s₁ ∪ s₂) (t₁ ∪ t₂) := ⟨h₁.maps_to.union_union h₂.maps_to, h, h₁.surj_on.union_union h₂.surj_on⟩ theorem bij_on.subset_range (h : bij_on f s t) : t ⊆ range f := h.surj_on.subset_range lemma inj_on.bij_on_image (h : inj_on f s) : bij_on f s (f '' s) := bij_on.mk (maps_to_image f s) h (subset.refl _) theorem bij_on.congr (h₁ : bij_on f₁ s t) (h : eq_on f₁ f₂ s) : bij_on f₂ s t := bij_on.mk (h₁.maps_to.congr h) (h₁.inj_on.congr h) (h₁.surj_on.congr h) theorem eq_on.bij_on_iff (H : eq_on f₁ f₂ s) : bij_on f₁ s t ↔ bij_on f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ lemma bij_on.image_eq (h : bij_on f s t) : f '' s = t := h.surj_on.image_eq_of_maps_to h.maps_to theorem bij_on.comp (hg : bij_on g t p) (hf : bij_on f s t) : bij_on (g ∘ f) s p := bij_on.mk (hg.maps_to.comp hf.maps_to) (hg.inj_on.comp hf.inj_on hf.maps_to) (hg.surj_on.comp hf.surj_on) theorem bij_on.bijective (h : bij_on f s t) : bijective (t.cod_restrict (s.restrict f) $ λ x, h.maps_to x.val_prop) := ⟨λ x y h', subtype.ext $ h.inj_on x.2 y.2 $ subtype.ext_iff.1 h', λ ⟨y, hy⟩, let ⟨x, hx, hxy⟩ := h.surj_on hy in ⟨⟨x, hx⟩, subtype.eq hxy⟩⟩ lemma bijective_iff_bij_on_univ : bijective f ↔ bij_on f univ univ := iff.intro (λ h, let ⟨inj, surj⟩ := h in ⟨maps_to_univ f _, inj.inj_on _, iff.mp surjective_iff_surj_on_univ surj⟩) (λ h, let ⟨map, inj, surj⟩ := h in ⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩) lemma bij_on.compl (hst : bij_on f s t) (hf : bijective f) : bij_on f sᶜ tᶜ := ⟨hst.surj_on.maps_to_compl hf.1, hf.1.inj_on _, hst.maps_to.surj_on_compl hf.2⟩ /-! ### left inverse -/ /-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/ @[reducible] def left_inv_on (f' : β → α) (f : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f' (f x) = x lemma left_inv_on.eq_on (h : left_inv_on f' f s) : eq_on (f' ∘ f) id s := h lemma left_inv_on.eq (h : left_inv_on f' f s) {x} (hx : x ∈ s) : f' (f x) = x := h hx lemma left_inv_on.congr_left (h₁ : left_inv_on f₁' f s) {t : set β} (h₁' : maps_to f s t) (heq : eq_on f₁' f₂' t) : left_inv_on f₂' f s := λ x hx, heq (h₁' hx) ▸ h₁ hx theorem left_inv_on.congr_right (h₁ : left_inv_on f₁' f₁ s) (heq : eq_on f₁ f₂ s) : left_inv_on f₁' f₂ s := λ x hx, heq hx ▸ h₁ hx theorem left_inv_on.inj_on (h : left_inv_on f₁' f s) : inj_on f s := λ x₁ h₁ x₂ h₂ heq, calc x₁ = f₁' (f x₁) : eq.symm $ h h₁ ... = f₁' (f x₂) : congr_arg f₁' heq ... = x₂ : h h₂ theorem left_inv_on.surj_on (h : left_inv_on f' f s) (hf : maps_to f s t) : surj_on f' t s := λ x hx, ⟨f x, hf hx, h hx⟩ theorem left_inv_on.maps_to (h : left_inv_on f' f s) (hf : surj_on f s t) : maps_to f' t s := λ y hy, let ⟨x, hs, hx⟩ := hf hy in by rwa [← hx, h hs] theorem left_inv_on.comp (hf' : left_inv_on f' f s) (hg' : left_inv_on g' g t) (hf : maps_to f s t) : left_inv_on (f' ∘ g') (g ∘ f) s := λ x h, calc (f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (hg' (hf h)) ... = x : hf' h theorem left_inv_on.mono (hf : left_inv_on f' f s) (ht : s₁ ⊆ s) : left_inv_on f' f s₁ := λ x hx, hf (ht hx) theorem left_inv_on.image_inter' (hf : left_inv_on f' f s) : f '' (s₁ ∩ s) = f' ⁻¹' s₁ ∩ f '' s := begin apply subset.antisymm, { rintro _ ⟨x, ⟨h₁, h⟩, rfl⟩, exact ⟨by rwa [mem_preimage, hf h], mem_image_of_mem _ h⟩ }, { rintro _ ⟨h₁, ⟨x, h, rfl⟩⟩, exact mem_image_of_mem _ ⟨by rwa ← hf h, h⟩ } end theorem left_inv_on.image_inter (hf : left_inv_on f' f s) : f '' (s₁ ∩ s) = f' ⁻¹' (s₁ ∩ s) ∩ f '' s := begin rw hf.image_inter', refine subset.antisymm _ (inter_subset_inter_left _ (preimage_mono $ inter_subset_left _ _)), rintro _ ⟨h₁, x, hx, rfl⟩, exact ⟨⟨h₁, by rwa hf hx⟩, mem_image_of_mem _ hx⟩ end theorem left_inv_on.image_image (hf : left_inv_on f' f s) : f' '' (f '' s) = s := by rw [image_image, image_congr hf, image_id'] theorem left_inv_on.image_image' (hf : left_inv_on f' f s) (hs : s₁ ⊆ s) : f' '' (f '' s₁) = s₁ := (hf.mono hs).image_image /-! ### Right inverse -/ /-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/ @[reducible] def right_inv_on (f' : β → α) (f : α → β) (t : set β) : Prop := left_inv_on f f' t lemma right_inv_on.eq_on (h : right_inv_on f' f t) : eq_on (f ∘ f') id t := h lemma right_inv_on.eq (h : right_inv_on f' f t) {y} (hy : y ∈ t) : f (f' y) = y := h hy lemma left_inv_on.right_inv_on_image (h : left_inv_on f' f s) : right_inv_on f' f (f '' s) := λ y ⟨x, hx, eq⟩, eq ▸ congr_arg f $ h.eq hx theorem right_inv_on.congr_left (h₁ : right_inv_on f₁' f t) (heq : eq_on f₁' f₂' t) : right_inv_on f₂' f t := h₁.congr_right heq theorem right_inv_on.congr_right (h₁ : right_inv_on f' f₁ t) (hg : maps_to f' t s) (heq : eq_on f₁ f₂ s) : right_inv_on f' f₂ t := left_inv_on.congr_left h₁ hg heq theorem right_inv_on.surj_on (hf : right_inv_on f' f t) (hf' : maps_to f' t s) : surj_on f s t := hf.surj_on hf' theorem right_inv_on.maps_to (h : right_inv_on f' f t) (hf : surj_on f' t s) : maps_to f s t := h.maps_to hf theorem right_inv_on.comp (hf : right_inv_on f' f t) (hg : right_inv_on g' g p) (g'pt : maps_to g' p t) : right_inv_on (f' ∘ g') (g ∘ f) p := hg.comp hf g'pt theorem right_inv_on.mono (hf : right_inv_on f' f t) (ht : t₁ ⊆ t) : right_inv_on f' f t₁ := hf.mono ht theorem inj_on.right_inv_on_of_left_inv_on (hf : inj_on f s) (hf' : left_inv_on f f' t) (h₁ : maps_to f s t) (h₂ : maps_to f' t s) : right_inv_on f f' s := λ x h, hf (h₂ $ h₁ h) h (hf' (h₁ h)) theorem eq_on_of_left_inv_on_of_right_inv_on (h₁ : left_inv_on f₁' f s) (h₂ : right_inv_on f₂' f t) (h : maps_to f₂' t s) : eq_on f₁' f₂' t := λ y hy, calc f₁' y = (f₁' ∘ f ∘ f₂') y : congr_arg f₁' (h₂ hy).symm ... = f₂' y : h₁ (h hy) theorem surj_on.left_inv_on_of_right_inv_on (hf : surj_on f s t) (hf' : right_inv_on f f' s) : left_inv_on f f' t := λ y hy, let ⟨x, hx, heq⟩ := hf hy in by rw [← heq, hf' hx] /-! ### Two-side inverses -/ /-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/ @[reducible] def inv_on (g : β → α) (f : α → β) (s : set α) (t : set β) : Prop := left_inv_on g f s ∧ right_inv_on g f t lemma inv_on.symm (h : inv_on f' f s t) : inv_on f f' t s := ⟨h.right, h.left⟩ lemma inv_on.mono (h : inv_on f' f s t) (hs : s₁ ⊆ s) (ht : t₁ ⊆ t) : inv_on f' f s₁ t₁ := ⟨h.1.mono hs, h.2.mono ht⟩ /-- If functions `f'` and `f` are inverse on `s` and `t`, `f` maps `s` into `t`, and `f'` maps `t` into `s`, then `f` is a bijection between `s` and `t`. The `maps_to` arguments can be deduced from `surj_on` statements using `left_inv_on.maps_to` and `right_inv_on.maps_to`. -/ theorem inv_on.bij_on (h : inv_on f' f s t) (hf : maps_to f s t) (hf' : maps_to f' t s) : bij_on f s t := ⟨hf, h.left.inj_on, h.right.surj_on hf'⟩ /-! ### `inv_fun_on` is a left/right inverse -/ theorem inj_on.left_inv_on_inv_fun_on [nonempty α] (h : inj_on f s) : left_inv_on (inv_fun_on f s) f s := λ x hx, inv_fun_on_eq' h hx lemma inj_on.inv_fun_on_image [nonempty α] (h : inj_on f s₂) (ht : s₁ ⊆ s₂) : (inv_fun_on f s₂) '' (f '' s₁) = s₁ := h.left_inv_on_inv_fun_on.image_image' ht theorem surj_on.right_inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : right_inv_on (inv_fun_on f s) f t := λ y hy, inv_fun_on_eq $ mem_image_iff_bex.1 $ h hy theorem bij_on.inv_on_inv_fun_on [nonempty α] (h : bij_on f s t) : inv_on (inv_fun_on f s) f s t := ⟨h.inj_on.left_inv_on_inv_fun_on, h.surj_on.right_inv_on_inv_fun_on⟩ theorem surj_on.inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : inv_on (inv_fun_on f s) f (inv_fun_on f s '' t) t := begin refine ⟨_, h.right_inv_on_inv_fun_on⟩, rintros _ ⟨y, hy, rfl⟩, rw [h.right_inv_on_inv_fun_on hy] end theorem surj_on.maps_to_inv_fun_on [nonempty α] (h : surj_on f s t) : maps_to (inv_fun_on f s) t s := λ y hy, mem_preimage.2 $ inv_fun_on_mem $ mem_image_iff_bex.1 $ h hy theorem surj_on.bij_on_subset [nonempty α] (h : surj_on f s t) : bij_on f (inv_fun_on f s '' t) t := begin refine h.inv_on_inv_fun_on.bij_on _ (maps_to_image _ _), rintros _ ⟨y, hy, rfl⟩, rwa [h.right_inv_on_inv_fun_on hy] end theorem surj_on_iff_exists_bij_on_subset : surj_on f s t ↔ ∃ s' ⊆ s, bij_on f s' t := begin split, { rcases eq_empty_or_nonempty t with rfl|ht, { exact λ _, ⟨∅, empty_subset _, bij_on_empty f⟩ }, { assume h, haveI : nonempty α := ⟨classical.some (h.comap_nonempty ht)⟩, exact ⟨_, h.maps_to_inv_fun_on.image_subset, h.bij_on_subset⟩ }}, { rintros ⟨s', hs', hfs'⟩, exact hfs'.surj_on.mono hs' (subset.refl _) } end lemma preimage_inv_fun_of_mem [n : nonempty α] {f : α → β} (hf : injective f) {s : set α} (h : classical.choice n ∈ s) : inv_fun f ⁻¹' s = f '' s ∪ (range f)ᶜ := begin ext x, rcases em (x ∈ range f) with ⟨a, rfl⟩|hx, { simp [left_inverse_inv_fun hf _, hf.mem_set_image] }, { simp [mem_preimage, inv_fun_neg hx, h, hx] } end lemma preimage_inv_fun_of_not_mem [n : nonempty α] {f : α → β} (hf : injective f) {s : set α} (h : classical.choice n ∉ s) : inv_fun f ⁻¹' s = f '' s := begin ext x, rcases em (x ∈ range f) with ⟨a, rfl⟩|hx, { rw [mem_preimage, left_inverse_inv_fun hf, hf.mem_set_image] }, { have : x ∉ f '' s, from λ h', hx (image_subset_range _ _ h'), simp only [mem_preimage, inv_fun_neg hx, h, this] }, end end set /-! ### Monotone -/ namespace monotone variables [preorder α] [preorder β] {f : α → β} protected lemma restrict (h : monotone f) (s : set α) : monotone (s.restrict f) := λ x y hxy, h hxy protected lemma cod_restrict (h : monotone f) {s : set β} (hs : ∀ x, f x ∈ s) : monotone (s.cod_restrict f hs) := h protected lemma range_factorization (h : monotone f) : monotone (set.range_factorization f) := h end monotone /-! ### Piecewise defined function -/ namespace set variables {δ : α → Sort y} (s : set α) (f g : Πi, δ i) @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : set α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (set.univ : set α))] : piecewise set.univ f g = f := by { ext i, simp [piecewise] } @[simp] lemma piecewise_insert_self {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] variable [∀j, decidable (j ∈ s)] instance compl.decidable_mem (j : α) : decidable (j ∈ sᶜ) := not.decidable lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) := begin simp [piecewise], ext i, by_cases h : i = j, { rw h, simp }, { by_cases h' : i ∈ s; simp [h, h'] } end @[simp, priority 990] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := if_pos hi @[simp, priority 990] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := if_neg hi lemma piecewise_singleton (x : α) [Π y, decidable (y ∈ ({x} : set α))] [decidable_eq α] (f g : α → β) : piecewise {x} f g = function.update g x (f x) := by { ext y, by_cases hy : y = x, { subst y, simp }, { simp [hy] } } lemma piecewise_eq_on (f g : α → β) : eq_on (s.piecewise f g) f s := λ _, piecewise_eq_of_mem _ _ _ lemma piecewise_eq_on_compl (f g : α → β) : eq_on (s.piecewise f g) g sᶜ := λ _, piecewise_eq_of_not_mem _ _ _ lemma piecewise_le {δ : α → Type*} [Π i, preorder (δ i)] {s : set α} [Π j, decidable (j ∈ s)] {f₁ f₂ g : Π i, δ i} (h₁ : ∀ i ∈ s, f₁ i ≤ g i) (h₂ : ∀ i ∉ s, f₂ i ≤ g i) : s.piecewise f₁ f₂ ≤ g := λ i, if h : i ∈ s then by simp * else by simp * lemma le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {s : set α} [Π j, decidable (j ∈ s)] {f₁ f₂ g : Π i, δ i} (h₁ : ∀ i ∈ s, g i ≤ f₁ i) (h₂ : ∀ i ∉ s, g i ≤ f₂ i) : g ≤ s.piecewise f₁ f₂ := @piecewise_le α (λ i, order_dual (δ i)) _ s _ _ _ _ h₁ h₂ lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {s : set α} [Π j, decidable (j ∈ s)] {f₁ f₂ g₁ g₂ : Π i, δ i} (h₁ : ∀ i ∈ s, f₁ i ≤ g₁ i) (h₂ : ∀ i ∉ s, f₂ i ≤ g₂ i) : s.piecewise f₁ f₂ ≤ s.piecewise g₁ g₂ := by apply piecewise_le; intros; simp * @[simp, priority 990] lemma piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] @[simp] lemma piecewise_compl [∀ i, decidable (i ∈ sᶜ)] : sᶜ.piecewise f g = s.piecewise g f := funext $ λ x, if hx : x ∈ s then by simp [hx] else by simp [hx] @[simp] lemma piecewise_range_comp {ι : Sort*} (f : ι → α) [Π j, decidable (j ∈ range f)] (g₁ g₂ : α → β) : (range f).piecewise g₁ g₂ ∘ f = g₁ ∘ f := comp_eq_of_eq_on_range $ piecewise_eq_on _ _ _ theorem maps_to.piecewise_ite {s s₁ s₂ : set α} {t t₁ t₂ : set β} {f₁ f₂ : α → β} [∀ i, decidable (i ∈ s)] (h₁ : maps_to f₁ (s₁ ∩ s) (t₁ ∩ t)) (h₂ : maps_to f₂ (s₂ ∩ sᶜ) (t₂ ∩ tᶜ)) : maps_to (s.piecewise f₁ f₂) (s.ite s₁ s₂) (t.ite t₁ t₂) := begin refine (h₁.congr _).union_union (h₂.congr _), exacts [(piecewise_eq_on s f₁ f₂).symm.mono (inter_subset_right _ _), (piecewise_eq_on_compl s f₁ f₂).symm.mono (inter_subset_right _ _)] end theorem eq_on_piecewise {f f' g : α → β} {t} : eq_on (s.piecewise f f') g t ↔ eq_on f g (t ∩ s) ∧ eq_on f' g (t ∩ sᶜ) := begin simp only [eq_on, ← forall_and_distrib], refine forall_congr (λ a, _), by_cases a ∈ s; simp * end theorem eq_on.piecewise_ite' {f f' g : α → β} {t t'} (h : eq_on f g (t ∩ s)) (h' : eq_on f' g (t' ∩ sᶜ)) : eq_on (s.piecewise f f') g (s.ite t t') := by simp [eq_on_piecewise, *] theorem eq_on.piecewise_ite {f f' g : α → β} {t t'} (h : eq_on f g t) (h' : eq_on f' g t') : eq_on (s.piecewise f f') g (s.ite t t') := (h.mono (inter_subset_left _ _)).piecewise_ite' s (h'.mono (inter_subset_left _ _)) lemma piecewise_preimage (f g : α → β) (t) : s.piecewise f g ⁻¹' t = s.ite (f ⁻¹' t) (g ⁻¹' t) := ext $ λ x, by by_cases x ∈ s; simp [*, set.ite] lemma apply_piecewise {δ' : α → Sort*} (h : Π i, δ i → δ' i) {x : α} : h x (s.piecewise f g x) = s.piecewise (λ x, h x (f x)) (λ x, h x (g x)) x := by by_cases hx : x ∈ s; simp [hx] lemma apply_piecewise₂ {δ' δ'' : α → Sort*} (f' g' : Π i, δ' i) (h : Π i, δ i → δ' i → δ'' i) {x : α} : h x (s.piecewise f g x) (s.piecewise f' g' x) = s.piecewise (λ x, h x (f x) (f' x)) (λ x, h x (g x) (g' x)) x := by by_cases hx : x ∈ s; simp [hx] lemma piecewise_op {δ' : α → Sort*} (h : Π i, δ i → δ' i) : s.piecewise (λ x, h x (f x)) (λ x, h x (g x)) = λ x, h x (s.piecewise f g x) := funext $ λ x, (apply_piecewise _ _ _ _).symm lemma piecewise_op₂ {δ' δ'' : α → Sort*} (f' g' : Π i, δ' i) (h : Π i, δ i → δ' i → δ'' i) : s.piecewise (λ x, h x (f x) (f' x)) (λ x, h x (g x) (g' x)) = λ x, h x (s.piecewise f g x) (s.piecewise f' g' x) := funext $ λ x, (apply_piecewise₂ _ _ _ _ _ _).symm @[simp] lemma piecewise_same : s.piecewise f f = f := by { ext x, by_cases hx : x ∈ s; simp [hx] } lemma range_piecewise (f g : α → β) : range (s.piecewise f g) = f '' s ∪ g '' sᶜ := begin ext y, split, { rintro ⟨x, rfl⟩, by_cases h : x ∈ s;[left, right]; use x; simp [h] }, { rintro (⟨x, hx, rfl⟩|⟨x, hx, rfl⟩); use x; simp * at * } end lemma injective_piecewise_iff {f g : α → β} : injective (s.piecewise f g) ↔ inj_on f s ∧ inj_on g sᶜ ∧ (∀ (x ∈ s) (y ∉ s), f x ≠ g y) := begin rw [injective_iff_inj_on_univ, ← union_compl_self s, inj_on_union (@disjoint_compl_right _ s _), (piecewise_eq_on s f g).inj_on_iff, (piecewise_eq_on_compl s f g).inj_on_iff], refine and_congr iff.rfl (and_congr iff.rfl $ forall_congr $ λ x, forall_congr $ λ hx, forall_congr $ λ y, forall_congr $ λ hy, _), rw [piecewise_eq_of_mem s f g hx, piecewise_eq_of_not_mem s f g hy] end lemma piecewise_mem_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)} {f g} (hf : f ∈ pi t t') (hg : g ∈ pi t t') : s.piecewise f g ∈ pi t t' := by { intros i ht, by_cases hs : i ∈ s; simp [hf i ht, hg i ht, hs] } @[simp] lemma pi_piecewise {ι : Type*} {α : ι → Type*} (s s' : set ι) (t t' : Π i, set (α i)) [Π x, decidable (x ∈ s')] : pi s (s'.piecewise t t') = pi (s ∩ s') t ∩ pi (s \ s') t' := begin ext x, simp only [mem_pi, mem_inter_eq, ← forall_and_distrib], refine forall_congr (λ i, _), by_cases hi : i ∈ s'; simp * end lemma univ_pi_piecewise {ι : Type*} {α : ι → Type*} (s : set ι) (t : Π i, set (α i)) [Π x, decidable (x ∈ s)] : pi univ (s.piecewise t (λ _, univ)) = pi s t := by simp end set lemma strict_mono_on.inj_on [linear_order α] [preorder β] {f : α → β} {s : set α} (H : strict_mono_on f s) : s.inj_on f := λ x hx y hy hxy, show ordering.eq.compares x y, from (H.compares hx hy).1 hxy lemma strict_anti_on.inj_on [linear_order α] [preorder β] {f : α → β} {s : set α} (H : strict_anti_on f s) : s.inj_on f := @strict_mono_on.inj_on α (order_dual β) _ _ f s H lemma strict_mono_on.comp [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_mono_on g t) (hf : strict_mono_on f s) (hs : set.maps_to f s t) : strict_mono_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hx) (hs hy) $ hf hx hy hxy lemma strict_mono_on.comp_strict_anti_on [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_mono_on g t) (hf : strict_anti_on f s) (hs : set.maps_to f s t) : strict_anti_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hy) (hs hx) $ hf hx hy hxy lemma strict_anti_on.comp [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_anti_on g t) (hf : strict_anti_on f s) (hs : set.maps_to f s t) : strict_mono_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hy) (hs hx) $ hf hx hy hxy lemma strict_anti_on.comp_strict_mono_on [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_anti_on g t) (hf : strict_mono_on f s) (hs : set.maps_to f s t) : strict_anti_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hx) (hs hy) $ hf hx hy hxy lemma strict_mono.cod_restrict [preorder α] [preorder β] {f : α → β} (hf : strict_mono f) {s : set β} (hs : ∀ x, f x ∈ s) : strict_mono (set.cod_restrict f s hs) := hf namespace function open set variables {fa : α → α} {fb : β → β} {f : α → β} {g : β → γ} {s t : set α} lemma injective.comp_inj_on (hg : injective g) (hf : s.inj_on f) : s.inj_on (g ∘ f) := (hg.inj_on univ).comp hf (maps_to_univ _ _) lemma surjective.surj_on (hf : surjective f) (s : set β) : surj_on f univ s := (surjective_iff_surj_on_univ.1 hf).mono (subset.refl _) (subset_univ _) lemma left_inverse.left_inv_on {g : β → α} (h : left_inverse f g) (s : set β) : left_inv_on f g s := λ x hx, h x lemma right_inverse.right_inv_on {g : β → α} (h : right_inverse f g) (s : set α) : right_inv_on f g s := λ x hx, h x lemma left_inverse.right_inv_on_range {g : β → α} (h : left_inverse f g) : right_inv_on f g (range g) := forall_range_iff.2 $ λ i, congr_arg g (h i) namespace semiconj lemma maps_to_image (h : semiconj f fa fb) (ha : maps_to fa s t) : maps_to fb (f '' s) (f '' t) := λ y ⟨x, hx, hy⟩, hy ▸ ⟨fa x, ha hx, h x⟩ lemma maps_to_range (h : semiconj f fa fb) : maps_to fb (range f) (range f) := λ y ⟨x, hy⟩, hy ▸ ⟨fa x, h x⟩ lemma surj_on_image (h : semiconj f fa fb) (ha : surj_on fa s t) : surj_on fb (f '' s) (f '' t) := begin rintros y ⟨x, hxt, rfl⟩, rcases ha hxt with ⟨x, hxs, rfl⟩, rw [h x], exact mem_image_of_mem _ (mem_image_of_mem _ hxs) end lemma surj_on_range (h : semiconj f fa fb) (ha : surjective fa) : surj_on fb (range f) (range f) := by { rw ← image_univ, exact h.surj_on_image (ha.surj_on univ) } lemma inj_on_image (h : semiconj f fa fb) (ha : inj_on fa s) (hf : inj_on f (fa '' s)) : inj_on fb (f '' s) := begin rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ H, simp only [← h.eq] at H, exact congr_arg f (ha hx hy $ hf (mem_image_of_mem fa hx) (mem_image_of_mem fa hy) H) end lemma inj_on_range (h : semiconj f fa fb) (ha : injective fa) (hf : inj_on f (range fa)) : inj_on fb (range f) := by { rw ← image_univ at *, exact h.inj_on_image (ha.inj_on univ) hf } lemma bij_on_image (h : semiconj f fa fb) (ha : bij_on fa s t) (hf : inj_on f t) : bij_on fb (f '' s) (f '' t) := ⟨h.maps_to_image ha.maps_to, h.inj_on_image ha.inj_on (ha.image_eq.symm ▸ hf), h.surj_on_image ha.surj_on⟩ lemma bij_on_range (h : semiconj f fa fb) (ha : bijective fa) (hf : injective f) : bij_on fb (range f) (range f) := begin rw [← image_univ], exact h.bij_on_image (bijective_iff_bij_on_univ.1 ha) (hf.inj_on univ) end lemma maps_to_preimage (h : semiconj f fa fb) {s t : set β} (hb : maps_to fb s t) : maps_to fa (f ⁻¹' s) (f ⁻¹' t) := λ x hx, by simp only [mem_preimage, h x, hb hx] lemma inj_on_preimage (h : semiconj f fa fb) {s : set β} (hb : inj_on fb s) (hf : inj_on f (f ⁻¹' s)) : inj_on fa (f ⁻¹' s) := begin intros x hx y hy H, have := congr_arg f H, rw [h.eq, h.eq] at this, exact hf hx hy (hb hx hy this) end end semiconj lemma update_comp_eq_of_not_mem_range' {α β : Sort*} {γ : β → Sort*} [decidable_eq β] (g : Π b, γ b) {f : α → β} {i : β} (a : γ i) (h : i ∉ set.range f) : (λ j, (function.update g i a) (f j)) = (λ j, g (f j)) := update_comp_eq_of_forall_ne' _ _ $ λ x hx, h ⟨x, hx⟩ /-- Non-dependent version of `function.update_comp_eq_of_not_mem_range'` -/ lemma update_comp_eq_of_not_mem_range {α β γ : Sort*} [decidable_eq β] (g : β → γ) {f : α → β} {i : β} (a : γ) (h : i ∉ set.range f) : (function.update g i a) ∘ f = g ∘ f := update_comp_eq_of_not_mem_range' g a h end function
4ffb81b3e06c17827c2d330bb7ec509b9c1bc882
46125763b4dbf50619e8846a1371029346f4c3db
/src/analysis/calculus/deriv.lean
8a0a6d3fc10fb28f90d533181be3563db0d23445
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
54,733
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.lean). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. -/ universes u v w noncomputable theory open_locale classical topological_space open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) set_option class.instance_max_depth 100 variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right 1 f' : 𝕜 →L[𝕜] F) x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (nhds_within x s) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := (fderiv_within 𝕜 f s x : 𝕜 →L[𝕜] F) 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := (fderiv 𝕜 f x : 𝕜 →L[𝕜] F) 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := by simp [has_deriv_within_at, has_deriv_at_filter, has_fderiv_within_at] /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := iff.rfl /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := by simp [has_deriv_at, has_deriv_at_filter, has_fderiv_at] /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x := iff.rfl lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ principal (-{x})) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), rw mem_inf_principal, refine univ_mem_sets' (λ z hz, _), have : z ≠ x, by simpa [function.comp] using hz, simp only [mem_set_of_eq], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 this), one_smul] end lemma has_deriv_within_at_iff_tendsto_slope {x : 𝕜} {s : set 𝕜} : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (s \ {x})) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, lattice.inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' {x : 𝕜} {s : set 𝕜} (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x s) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope {x : 𝕜} : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (-{x})) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at_unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ has_fderiv_at_unique h₀ h₁ lemma has_deriv_within_at_inter' (h : t ∈ nhds_within x s) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := begin simp only [has_deriv_within_at, nhds_within_union], exact hs.join ht, end lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] } lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] } lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := has_deriv_at_unique h.differentiable_at.has_deriv_at h lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right 1 (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right 1 (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } section congr /-! ### Congruence properties of derivatives -/ theorem has_deriv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : ∀ᶠ x in L, f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := has_fderiv_at_filter_congr_of_mem_sets hx h₀ (by simp [h₁]) lemma has_deriv_at_filter.congr_of_mem_sets (h : has_deriv_at_filter f f' x L) (hL : ∀ᶠ x in L, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa has_deriv_at_filter_congr_of_mem_sets hx hL rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_mem_nhds_within (h : has_deriv_within_at f f' s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_mem_sets h h₁ hx lemma has_deriv_at.congr_of_mem_nhds (h : has_deriv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f₁ y = f y) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma deriv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr_of_mem_nhds_within hs hL hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma deriv_congr_of_mem_nhds (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : deriv f₁ x = deriv f x := by { unfold deriv, rwa fderiv_congr_of_mem_nhds } end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (is_o_zero _ _).congr_left $ by simp theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := by { unfold deriv_within, rw fderiv_within_id, simp, assumption } end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (is_o_zero _ _).congr_left $ λ _, by simp [continuous_linear_map.zero_apply, sub_self] theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := by { rw (differentiable_at_const _).deriv_within hxs, apply deriv_const } end const section is_linear_map /-! ### Derivative of linear maps -/ variables (s x L) [is_linear_map 𝕜 f] lemma is_linear_map.has_deriv_at_filter : has_deriv_at_filter f (f 1) x L := (is_o_zero _ _).congr_left begin intro y, simp [sub_smul], rw ← is_linear_map.smul f x, rw ← is_linear_map.smul f y, simp end lemma is_linear_map.has_deriv_within_at : has_deriv_within_at f (f 1) s x := is_linear_map.has_deriv_at_filter _ _ lemma is_linear_map.has_deriv_at : has_deriv_at f (f 1) x := is_linear_map.has_deriv_at_filter _ _ lemma is_linear_map.differentiable_at : differentiable_at 𝕜 f x := (is_linear_map.has_deriv_at _).differentiable_at lemma is_linear_map.differentiable_within_at : differentiable_within_at 𝕜 f s x := (is_linear_map.differentiable_at _).differentiable_within_at @[simp] lemma is_linear_map.deriv : deriv f x = f 1 := has_deriv_at.deriv (is_linear_map.has_deriv_at _) lemma is_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f 1 := begin rw differentiable_at.deriv_within (is_linear_map.differentiable_at _) hxs, apply is_linear_map.deriv, assumption end lemma is_linear_map.differentiable : differentiable 𝕜 f := λ x, is_linear_map.differentiable_at _ lemma is_linear_map.differentiable_on : differentiable_on 𝕜 f s := is_linear_map.differentiable.differentiable_on end is_linear_map section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ by simp [add_smul, smul_add] theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := (hf.has_deriv_within_at.add_const c).deriv_within hxs lemma deriv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : deriv (λy, f y + c) x = deriv f x := (hf.has_deriv_at.add_const c).deriv theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c + f y) s x = deriv_within f s x := (hf.has_deriv_within_at.const_add c).deriv_within hxs lemma deriv_const_add (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λy, c + f y) x = deriv f x := (hf.has_deriv_at.const_add c).deriv end add section mul_vector /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {c : 𝕜 → 𝕜} {c' : 𝕜} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := begin show has_fderiv_within_at _ _ _ _, convert has_fderiv_within_at.smul hc hf, ext, simp [smul_add, (mul_smul _ _ _).symm, mul_comm] end theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv theorem has_deriv_within_at.const_smul (c : 𝕜) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := begin convert (has_deriv_within_at_const x s c).smul hf, rw [zero_smul, add_zero] end theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := begin rw [← has_deriv_within_at_univ] at *, exact hf.const_smul c end lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end mul_vector section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := h.neg.congr (by simp) (by simp) theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := h.has_deriv_within_at.neg.deriv_within hxs lemma deriv_neg : deriv (λy, -f y) x = - deriv f x := if h : differentiable_at 𝕜 f x then h.has_deriv_at.neg.deriv else have ¬differentiable_at 𝕜 (λ y, -f y) x, from λ h', by simpa only [neg_neg] using h'.neg, by simp only [deriv_zero_of_not_differentiable_at h, deriv_zero_of_not_differentiable_at this, neg_zero] @[simp] lemma deriv_neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv_neg end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := (hf.has_deriv_within_at.sub_const c).deriv_within hxs lemma deriv_sub_const (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, f y - c) x = deriv f x := (hf.has_deriv_at.sub_const c).deriv theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c - f y) s x = -deriv_within f s x := (hf.has_deriv_within_at.const_sub c).deriv_within hxs lemma deriv_const_sub (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c - f y) x = -deriv f x := (hf.has_deriv_at.const_sub c).deriv end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := has_fderiv_at_filter.tendsto_nhds hL h theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds lattice.inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds (le_refl _) h end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := show has_fderiv_at_filter _ _ _ _, by convert has_fderiv_at_filter.prod hf₁ hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector valued function and a scalar function -/ variables {h : 𝕜 → 𝕜} {h' : 𝕜} /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_deriv_at_filter.comp (hg : has_deriv_at_filter g g' (h x) (L.map h)) (hh : has_deriv_at_filter h h' x L) : has_deriv_at_filter (g ∘ h) (h' • g') x L := have (smul_right 1 g' : 𝕜 →L[𝕜] _).comp (smul_right 1 h' : 𝕜 →L[𝕜] _) = smul_right 1 (h' • g'), by { ext, simp [mul_smul] }, begin unfold has_deriv_at_filter, rw ← this, exact has_fderiv_at_filter.comp x hg hh, end theorem has_deriv_within_at.comp {t : set 𝕜} (hg : has_deriv_within_at g g' t (h x)) (hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin apply has_deriv_at_filter.comp _ (has_deriv_at_filter.mono hg _) hh, calc map h (nhds_within x s) ≤ nhds_within (h x) (h '' s) : hh.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (h x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_deriv_at.comp (hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g ∘ h) (h' • g') x := (hg.mono hh.continuous_at).comp x hh theorem has_deriv_at.comp_has_deriv_within_at (hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin rw ← has_deriv_within_at_univ at hg, exact has_deriv_within_at.comp x hg hh subset_preimage_univ end lemma deriv_within.comp (hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.comp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.comp (hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g ∘ h) x = deriv h x • deriv g (h x) := begin apply has_deriv_at.deriv, exact has_deriv_at.comp x hg.has_deriv_at hh.has_deriv_at end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and of a function defined on `𝕜` -/ variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw has_deriv_within_at_iff_has_fderiv_within_at, convert has_fderiv_within_at.comp x hl hf hst, ext, simp end /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' (f')) x := begin rw has_deriv_at_iff_has_fderiv_at, convert has_fderiv_at.comp x hl hf, ext, simp end theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw ← has_fderiv_within_at_univ at hl, exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ end lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs end lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := begin apply has_deriv_at.deriv _, exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at) end end composition_vector section mul /-! ### Derivative of the multiplication of two scalar functions -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ lemma has_deriv_at_inv_one : has_deriv_at (λx, x⁻¹) (-1) (1 : 𝕜) := begin rw has_deriv_at_iff_is_o_nhds_zero, have : is_o (λ (h : 𝕜), h^2 * (1 + h)⁻¹) (λ (h : 𝕜), h * 1) (𝓝 0), { have : tendsto (λ (h : 𝕜), (1 + h)⁻¹) (𝓝 0) (𝓝 (1 + 0)⁻¹) := ((tendsto_const_nhds).add tendsto_id).inv' (by norm_num), exact is_o.mul_is_O (is_o_pow_id one_lt_two) (is_O_one_of_tendsto _ this) }, apply this.congr' _ _, { have : metric.ball (0 : 𝕜) 1 ∈ 𝓝 (0 : 𝕜), from metric.ball_mem_nhds 0 zero_lt_one, filter_upwards [this], assume h hx, have : 0 < ∥1 + h∥ := calc 0 < ∥(1:𝕜)∥ - ∥-h∥ : by rwa [norm_neg, sub_pos, ← dist_zero_right h, normed_field.norm_one] ... ≤ ∥1 - -h∥ : norm_sub_norm_le _ _ ... = ∥1 + h∥ : by simp, have : 1 + h ≠ 0 := norm_pos_iff.mp this, simp, rw ← eq_div_iff_mul_eq _ _ (inv_ne_zero this), field_simp, simp [right_distrib, sub_mul, (show (1 + h)⁻¹ * (1 + h) = 1, by rw mul_comm; exact field.mul_inv_cancel this)], ring }, { exact univ_mem_sets' mul_one } end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := begin have A : has_deriv_at (λy, y⁻¹) (-1) (x⁻¹ * x : 𝕜), by { simp only [inv_mul_cancel x_ne_zero, has_deriv_at_inv_one] }, have B : has_deriv_at (λy, x⁻¹ * y) (x⁻¹) x, by simpa only [mul_one] using (has_deriv_at_id x).const_mul x⁻¹, convert (A.comp x B : _).const_mul x⁻¹, { ext y, rw [function.comp_apply, mul_inv', inv_inv', mul_comm, mul_assoc, mul_inv_cancel x_ne_zero, mul_one] }, { rw [pow_two, mul_inv', smul_eq_mul, mul_neg_one, neg_mul_eq_mul_neg] } end theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv (x_ne_zero : x ≠ 0) : differentiable_at 𝕜 (λx, x⁻¹) x := (has_deriv_at_inv x_ne_zero).differentiable_at lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv (x_ne_zero : x ≠ 0) : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := (has_deriv_at_inv x_ne_zero).deriv lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs, exact deriv_inv x_ne_zero end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv (x_ne_zero : x ≠ 0) : fderiv 𝕜 (λx, x⁻¹) x = smul_right 1 (-(x^2)⁻¹) := (has_fderiv_at_inv x_ne_zero).fderiv lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right 1 (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs, exact fderiv_inv x_ne_zero end end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin have A : (d x)⁻¹ * (d x)⁻¹ * (c' * d x) = (d x)⁻¹ * c', by rw [← mul_assoc, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel hx, one_mul], convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), simp [div_eq_inv_mul, pow_two, mul_inv', mul_add, A, sub_eq_add_neg], ring end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv end division end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : polynomial 𝕜) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma continuous : continuous (λx, p.eval x) := p.differentiable.continuous protected lemma continuous_on : continuous_on (λx, p.eval x) s := p.continuous.continuous_on protected lemma continuous_at : continuous_at (λx, p.eval x) x := p.continuous.continuous_at protected lemma continuous_within_at : continuous_within_at (λx, p.eval x) s x := p.continuous_at.continuous_within_at protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) x := by simpa [has_deriv_at_iff_has_fderiv_at] using p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right 1 (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right 1 (p.derivative.eval x) := begin rw differentiable_at.fderiv_within p.differentiable_at hxs, exact p.fderiv end end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} variable {n : ℕ } lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C 1 * (polynomial.X)^n).has_deriv_at x, { simp }, { rw [polynomial.derivative_monomial], simp } end theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := differentiable_at_pow.differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λx, differentiable_at_pow lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := differentiable_pow.differentiable_on lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma iter_deriv_pow' {k : ℕ} : deriv^[k] (λx:𝕜, x^n) = λ x, ((finset.range k).prod (λ i, n - i):ℕ) * x^(n-k) := begin induction k with k ihk, { simp only [one_mul, finset.prod_range_zero, nat.iterate_zero, nat.sub_zero, nat.cast_one] }, { simp only [nat.iterate_succ', ihk, finset.prod_range_succ], ext x, rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_left_comm, mul_assoc, nat.succ_eq_add_one, nat.sub_sub] } end lemma iter_deriv_pow {k : ℕ} : deriv^[k] (λx:𝕜, x^n) x = ((finset.range k).prod (λ i, n - i):ℕ) * x^(n-k) := congr_fun iter_deriv_pow' x end pow section fpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} variable {m : ℤ} lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [fpow_of_nat, int.cast_coe_nat], convert has_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, fpow_of_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have := (has_deriv_at_inv _).comp _ (this (-m) (neg_pos.2 hm)); [skip, exact fpow_ne_zero_of_ne_zero hx _], simp only [(∘), fpow_neg, one_div_eq_inv, inv_inv', smul_eq_mul] at this, convert this using 1, rw [pow_two, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg, ← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel }, { simp only [hm, fpow_zero, int.cast_zero, zero_mul, has_deriv_at_const] }, { exact this m hm } end theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_fpow m hx).has_deriv_within_at lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x := (has_deriv_at_fpow m hx).differentiable_at lemma differentiable_within_at_fpow (hx : x ≠ 0) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_fpow hx).differentiable_within_at lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs) -- TODO : this is true at `x=0` as well lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) := (has_deriv_at_fpow m hx).deriv lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_fpow m hx s).deriv_within hxs lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) : deriv^[k] (λx:𝕜, x^m) x = ((finset.range k).prod (λ i, m - i):ℤ) * x^(m-k) := begin induction k with k ihk generalizing x hx, { simp only [one_mul, finset.prod_range_zero, nat.iterate_zero, int.coe_nat_zero, sub_zero, int.cast_one] }, { rw [nat.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, mul_left_comm, int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv], apply deriv_congr_of_mem_nhds, apply eventually.mono _ @ihk, exact mem_nhds_sets (is_open_neg $ is_closed_eq continuous_id continuous_const) hx } end end fpow /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in nhds_within x (s \ {x}), (z - x)⁻¹ * (f z - f x) < r := has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in nhds_within x s, (z - x)⁻¹ * (f z - f x) < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : f' < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r := (hf.limsup_slope_le' (lt_irrefl x) hr).frequently (nhds_within_Ioi_self_ne_bot x) end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in nhds_within x (s \ {x}), ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr), have B : ∀ᶠ z in nhds_within x {x}, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_sets_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup_sets.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C, filter_upwards [C.1], simp only [mem_set_of_eq, norm_smul, mem_Iio, normed_field.norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.limsup_norm_slope_le hr).frequently (nhds_within_Ioi_self_ne_bot x) /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.limsup_slope_norm_le hr).frequently (nhds_within_Ioi_self_ne_bot x), refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
c4e1109643901814f38280520393676aee982544
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/topology/algebra/infinite_sum.lean
a5ee14875b32cfe4209bbda27452e9edefc98e45
[ "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
43,109
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 algebra.big_operators.intervals import topology.instances.real import topology.algebra.module import data.indicator_function import data.equiv.encodable.lattice import order.filter.at_top_bot /-! # Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ noncomputable theory open finset filter function classical open_locale topological_space classical big_operators nnreal variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is invariant under reordering. In particular, the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a sum for this definition, but a series which is absolutely convergent will have the correct sum. This is based on Mario Carneiro's [infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html). For the definition or many statements, `α` does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/ @[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0 -- see Note [operator precedence of big operators] notation `∑'` binders `, ` r:(scoped:67 f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : ∑'b, f b = 0 := by simp [tsum, h] lemma has_sum.has_sum_of_sum_eq {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (hf : has_sum g a) : has_sum f a := le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf lemma has_sum_iff_has_sum {g : γ → α} (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) : has_sum f a ↔ has_sum g a := ⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩ lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf] lemma function.injective.summable_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr $ λ _, hg.has_sum_iff hf lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) : has_sum (f ∘ coe : s → α) a ↔ has_sum f a := subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf lemma has_sum_subtype_iff_indicator {s : set β} : has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a := by rw [← set.indicator_range_comp, subtype.range_coe, has_sum_subtype_iff_of_support_subset set.support_indicator] @[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset $ set.subset.refl _ lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) := order_top.tendsto_at_top_nhds _ protected lemma finset.has_sum (s : finset β) (f : β → α) : has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) := by { rw ← sum_attach, exact has_sum_fintype _ } protected lemma finset.summable (s : finset β) (f : β → α) : summable (f ∘ coe : (↑s : set β) → α) := (s.has_sum f).summable protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) : summable (f ∘ coe : s → α) := by convert hs.to_finset.summable f; simp only [hs.coe_to_finset] /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) := (has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := (has_sum_sum_of_ne_finset_zero hf).summable lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : has_sum f (f b) := suffices has_sum f (∑ b' in {b}, f b'), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : β) (a : α) : has_sum (λb', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma equiv.has_sum_iff (e : γ ≃ β) : has_sum (f ∘ e) a ↔ has_sum f a := e.injective.has_sum_iff $ by simp lemma equiv.summable_iff (e : γ ≃ β) : summable (f ∘ e) ↔ summable f := exists_congr $ λ a, e.has_sum_iff lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) := (equiv.prod_comm γ β).summable_iff.2 hf lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : has_sum f a ↔ has_sum g a := have (g ∘ coe) ∘ e = f ∘ coe, from funext he, by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support] lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : has_sum f a ↔ has_sum g a := iff.symm $ equiv.has_sum_iff_of_support (equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩) ⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h, λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩) hfg lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : summable f ↔ summable g := exists_congr $ λ _, e.has_sum_iff_of_support he protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a) (g : α →+ γ) (hg : continuous g) : has_sum (g ∘ f) (g a) := have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)), from funext $ g.map_sum _, show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)), from this ▸ (hg.tendsto a).comp hf protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f) (g : α →+ γ) (hg : continuous g) : summable (g ∘ f) := (hf.has_sum.map g hg).summable /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := h.comp tendsto_finset_range lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := begin refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩, rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat, exact hf.has_sum end lemma equiv.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) {f : β → α} {g : γ → α'} (he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : summable f ↔ summable g := ⟨λ ⟨a, ha⟩, ⟨e.symm a, he.1 $ by rwa [e.apply_symm_apply]⟩, λ ⟨a, ha⟩, ⟨e a, he.2 ha⟩⟩ variable [has_continuous_add α] lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp only [has_sum, sum_add_distrib]; exact hf.add hg lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := (hf.has_sum.add hg.has_sum).summable lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) := finset.induction_on s (by simp only [has_sum_zero, sum_empty, forall_true_iff]) (by simp only [has_sum.add, sum_insert, mem_insert, forall_eq_or_imp, forall_2_true_iff, not_false_iff, forall_true_iff] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, ∑ i in s, f i b) := (has_sum_sum $ assume i hi, (hf i hi).has_sum).summable lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : sᶜ → α) b) : has_sum f (a + b) := by simpa using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : summable f := (hs.has_sum.add_compl hsc.has_sum).summable lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a) (hb : has_sum (f ∘ coe : s → α) b) : has_sum f (a + b) := by simpa using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α)) (hsc : summable (f ∘ coe : s → α)) : summable f := (hs.has_sum.compl_add hsc.has_sum).summable lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a := begin refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _, rintros s ⟨hs, hsc⟩, rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩, use [u.image sigma.fst, trivial], intros bs hbs, simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu, have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p) at_top (𝓝 $ ∑ b in bs, g b), { simp only [← sigma_preimage_mk, sum_sigma], refine tendsto_finset_sum _ (λ b hb, _), change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)), exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) }, refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩), exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩ end /-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ` has sum `g b`, then the series `g` has sum `a`. -/ lemma has_sum.prod_fiberwise [regular_space α] {f : β × γ → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) : has_sum g a := has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) : summable (λb, ∑'c, f ⟨b, c⟩) := (ha.has_sum.sigma (assume b, (hf b).has_sum)).summable lemma has_sum.sigma_of_has_sum [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a := by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum end has_sum section tsum variables [add_comm_monoid α] [topological_space α] [t2_space α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.tsum_eq (ha : has_sum f a) : ∑'b, f b = a := (summable.has_sum ⟨a, ha⟩).unique ha lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ ∑'b, f b = a := iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum) @[simp] lemma tsum_zero : ∑'b:β, (0:α) = 0 := has_sum_zero.tsum_eq lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : ∑' b, f b = ∑ b in s, f b := (has_sum_sum_of_ne_finset_zero hf).tsum_eq lemma tsum_fintype [fintype β] (f : β → α) : ∑'b, f b = ∑ b, f b := (has_sum_fintype f).tsum_eq @[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) : ∑' x : {x // x ∈ s}, f x = ∑ x in s, f x := (s.has_sum f).tsum_eq @[simp] lemma finset.tsum_subtype' (s : finset β) (f : β → α) : ∑' x : (s : set β), f x = ∑ x in s, f x := s.tsum_subtype f lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : ∑'b, f b = f b := (has_sum_single b hf).tsum_eq @[simp] lemma tsum_ite_eq (b : β) (a : α) : ∑'b', (if b' = b then a else 0) = a := (has_sum_ite_eq b a).tsum_eq lemma equiv.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) (h0 : e 0 = 0) {f : β → α} {g : γ → α'} (h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : ∑' b, f b = e (∑' c, g c) := by_cases (assume : summable g, (h.mpr this.has_sum).tsum_eq) (assume hg : ¬ summable g, have hf : ¬ summable f, from mt (e.summable_iff_of_has_sum_iff @h).1 hg, by simp [tsum, hf, hg, h0]) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : ∑'b, f b = ∑'c, g c := (equiv.refl α).tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : ∑'c, f (j c) = ∑'b, f b := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g) (he : ∀ x, g (e x) = f x) : (∑' x, f x) = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : ∑' x, f x = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg lemma tsum_subtype (s : set β) (f : β → α) : ∑' x:s, f x = ∑' x, s.indicator f x := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator section has_continuous_add variable [has_continuous_add α] lemma tsum_add (hf : summable f) (hg : summable g) : ∑'b, (f b + g b) = (∑'b, f b) + (∑'b, g b) := (hf.has_sum.add hg.has_sum).tsum_eq lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : ∑'b, ∑ i in s, f i b = ∑ i in s, ∑'b, f i b := (has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq lemma tsum_sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := (h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_prod' [regular_space α] {f : β × γ → α} (h : summable f) (h₁ : ∀b, summable (λc, f (b, c))) : ∑'p, f p = ∑'b c, f (b, c) := (h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_comm' [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) (h₁ : ∀b, summable (f b)) (h₂ : ∀ c, summable (λ b, f b c)) : ∑' c b, f b c = ∑' b c, f b c := begin erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm β γ).tsum_eq], refl, assumption end end has_continuous_add section encodable open encodable variable [encodable γ] /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode2 [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (s : γ → β) : ∑' i : ℕ, m (⨆ b ∈ decode2 γ i, s b) = ∑' b : γ, m (s b) := begin have H : ∀ n, m (⨆ b ∈ decode2 γ n, s b) ≠ 0 → (decode2 γ n).is_some, { intros n h, cases decode2 γ n with b, { refine (h $ by simp [m0]).elim }, { exact rfl } }, symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _, { rintros ⟨m, hm⟩ ⟨n, hn⟩ e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨⟨encode b, _⟩, _⟩, { simp only [mem_support, encodek2] at h ⊢, convert h, simp [set.ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { rintros ⟨n, h⟩, dsimp only [subtype.coe_mk], transitivity, swap, rw [show decode2 γ n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end /-- `tsum_supr_decode2` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode2 (m : set β → α) (m0 : m ∅ = 0) (s : γ → set β) : ∑' i, m (⋃ b ∈ decode2 γ i, s b) = ∑' b, m (s b) := tsum_supr_decode2 m m0 s /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≤)` in all applications. -/ /-- If a function is countably sub-additive then it is sub-additive on encodable types -/ theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) ∑' i, m (s i)) (s : γ → β) : R (m (⨆ b : γ, s b)) ∑' b : γ, m (s b) := by { rw [← supr_decode2, ← tsum_supr_decode2 _ m0 s], exact m_supr _ } /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s : δ → β) (t : finset δ) : R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) := by { cases t.nonempty_encodable, rw [supr_subtype'], convert rel_supr_tsum m m0 R m_supr _, rw [← finset.tsum_subtype], assumption } /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) := begin convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂), { simp only [supr_bool_eq, cond] }, { rw [tsum_fintype, fintype.sum_bool, cond, cond] } end end encodable end tsum section pi variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)] lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} : has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) := by simp [has_sum, tendsto_pi] lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) := by simp [summable, pi.has_sum, classical.skolem] lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) : (∑' i, f i) x = ∑' i, f i x := (pi.has_sum.mp hf.has_sum x).tsum_eq.symm end pi section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} -- `by simpa using` speeds up elaboration. Why? lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) := by simpa only using h.map (-add_monoid_hom.id α) continuous_neg lemma summable.neg (hf : summable f) : summable (λb, - f b) := hf.has_sum.neg.summable lemma summable.of_neg (hf : summable (λb, - f b)) : summable f := by simpa only [neg_neg] using hf.neg lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f := ⟨summable.of_neg, summable.neg⟩ lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by { simp [sub_eq_add_neg], exact hf.add hg.neg } lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := (hf.has_sum.sub hg.has_sum).summable lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) := begin refine ⟨λ h, hf.add_compl h, λ h, _⟩, rw [has_sum_subtype_iff_indicator] at hf ⊢, rw [set.indicator_compl], simpa only [add_sub_cancel'] using h.sub hf end lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) := iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right] lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) : summable (f ∘ coe : sᶜ → α) ↔ summable f := ⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable, λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩ protected lemma finset.has_sum_compl_iff (s : finset β) : has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) := (s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm] protected lemma finset.has_sum_iff_compl (s : finset β) : has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) := (s.has_sum f).has_sum_iff_compl protected lemma finset.summable_compl_iff (s : finset β) : summable (λ x : {x // x ∉ s}, f x) ↔ summable f := (s.summable f).summable_compl_iff lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) : summable (f ∘ coe : sᶜ → α) ↔ summable f := (hs.summable f).summable_compl_iff section tsum variables [t2_space α] lemma tsum_neg (hf : summable f) : ∑'b, - f b = - ∑'b, f b := hf.has_sum.neg.tsum_eq lemma tsum_sub (hf : summable f) (hg : summable g) : ∑'b, (f b - g b) = ∑'b, f b - ∑'b, g b := (hf.has_sum.sub hg.has_sum).tsum_eq lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : (∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x := (hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm lemma sum_add_tsum_compl {s : finset β} (hf : summable f) : (∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x := ((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm end tsum /-! ### Sums on subtypes If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype `univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`. -/ section subtype lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := begin refine iff.trans _ ((range k).has_sum_compl_iff), rw [← (not_mem_range_equiv k).symm.has_sum_iff], refl end lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f := iff.symm $ (equiv.add_right (∑ i in range k, f i)).summable_iff_of_has_sum_iff $ λ a, (has_sum_nat_add_iff k).symm lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a := by simp [has_sum_nat_add_iff] lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) : (∑ i in range k, f i) + (∑' i, f (i + k)) = ∑' i, f i := by simpa [add_comm] using ((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) : ∑'b, f b = f 0 + ∑'b, f (b + 1) := by simpa only [sum_range_one] using (sum_add_tsum_nat_add 1 hf).symm /-- For `f : ℕ → α`, 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 [t2_space α] (f : ℕ → α) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin by_cases hf : summable f, { have h₀ : (λ i, (∑' i, f i) - ∑ j in range i, f j) = λ i, ∑' (k : ℕ), f (k + i), { ext1 i, rw [sub_eq_iff_eq_add, add_comm, sum_add_tsum_nat_add i hf] }, have h₁ : tendsto (λ i : ℕ, ∑' i, f i) at_top (𝓝 (∑' i, f i)) := tendsto_const_nhds, simpa only [h₀, sub_self] using tendsto.sub h₁ hf.has_sum.tendsto_sum_nat }, { convert tendsto_const_nhds, ext1 i, rw ← summable_nat_add_iff i at hf, { exact tsum_eq_zero_of_not_summable hf }, { apply_instance } } end end subtype end topological_group section topological_semiring variables [semiring α] [topological_space α] [topological_semiring α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.mul_left (a₂) (h : has_sum f a₁) : has_sum (λb, a₂ * f b) (a₂ * a₁) := by simpa only using h.map (add_monoid_hom.mul_left a₂) (continuous_const.mul continuous_id) lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) := by simpa only using hf.map (add_monoid_hom.mul_right a₂) (continuous_id.mul continuous_const) lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) := (hf.has_sum.mul_left _).summable lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) := (hf.has_sum.mul_right _).summable section tsum variables [t2_space α] lemma summable.tsum_mul_left (a) (hf : summable f) : ∑'b, a * f b = a * ∑'b, f b := (hf.has_sum.mul_left _).tsum_eq lemma summable.tsum_mul_right (a) (hf : summable f) : (∑'b, f b * a) = (∑'b, f b) * a := (hf.has_sum.mul_right _).tsum_eq end tsum end topological_semiring section topological_semimodule variables {R : Type*} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [semimodule R α] [topological_semimodule R α] {f : β → α} lemma has_sum.smul {a : α} {r : R} (hf : has_sum f a) : has_sum (λ z, r • f z) (r • a) := hf.map (const_smul_hom α r) (continuous_const.smul continuous_id) lemma summable.smul {r : R} (hf : summable f) : summable (λ z, r • f z) := hf.has_sum.smul.summable lemma tsum_smul [t2_space α] {r : R} (hf : summable f) : ∑' z, r • f z = r • ∑' z, f z := hf.has_sum.smul.tsum_eq end topological_semimodule section division_ring variables [division_ring α] [topological_space α] [topological_semiring α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum.div_const (h : has_sum f a) (b : α) : has_sum (λ x, f x / b) (a / b) := by simp only [div_eq_mul_inv, h.mul_right b⁻¹] lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) := ⟨has_sum.mul_left _, λ H, by simpa only [inv_mul_cancel_left' h] using H.mul_left a₂⁻¹⟩ lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) := ⟨has_sum.mul_right _, λ H, by simpa only [mul_inv_cancel_right' h] using H.mul_right a₂⁻¹⟩ lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) := ⟨λ H, H.mul_left _, λ H, by simpa only [inv_mul_cancel_left' h] using H.mul_left a⁻¹⟩ lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) := ⟨λ H, H.mul_right _, λ H, by simpa only [mul_inv_cancel_right' h] using H.mul_right a⁻¹⟩ lemma tsum_mul_left [t2_space α] : (∑' x, a * f x) = a * ∑' x, f x := if hf : summable f then hf.tsum_mul_left a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_left_iff ha).2 hf), mul_zero] lemma tsum_mul_right [t2_space α] : (∑' x, f x * a) = (∑' x, f x) * a := if hf : summable f then hf.tsum_mul_right a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_right_iff ha).2 hf), zero_mul] end division_ring section order_topology variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' hf hg $ assume s, sum_le_sum $ assume b _, h b lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (i ∘ coe) _ _ _).2 hf, { exact assume c₁ c₂ eq, hi eq }, { intros c hc, rw [mem_support] at hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨⟨b, hc⟩, eq⟩ } }, { assume c, simp [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj i hi hs h hf.has_sum hg.has_sum lemma sum_le_has_sum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) : ∑ b in s, f b ≤ a := ge_of_tendsto hf (eventually_at_top.2 ⟨s, λ t hst, sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩) lemma le_has_sum (hf : has_sum f a) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ a := calc f b = ∑ b in {b}, f b : finset.sum_singleton.symm ... ≤ a : sum_le_has_sum _ (by { convert hb, simp }) hf lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) : ∑ b in s, f b ≤ tsum f := sum_le_has_sum s hs hf.has_sum lemma le_tsum (hf : summable f) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ ∑' b, f b := le_has_sum (summable.has_sum hf) b hb lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : ∑'b, f b ≤ ∑'b, g b := has_sum_le h hf.has_sum hg.has_sum lemma has_sum.nonneg (h : ∀ b, 0 ≤ g b) (ha : has_sum g a) : 0 ≤ a := has_sum_le h has_sum_zero ha lemma has_sum.nonpos (h : ∀ b, g b ≤ 0) (ha : has_sum g a) : a ≤ 0 := has_sum_le h ha has_sum_zero lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ ∑'b, g b := begin by_cases hg : summable g, { exact hg.has_sum.nonneg h }, { simp [tsum_eq_zero_of_not_summable hg] } end lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : ∑'b, f b ≤ 0 := begin by_cases hf : summable f, { exact hf.has_sum.nonpos h }, { simp [tsum_eq_zero_of_not_summable hf] } end end order_topology section canonically_ordered variables [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] variables {f : β → α} {a : α} lemma le_has_sum' (hf : has_sum f a) (b : β) : f b ≤ a := le_has_sum hf b $ λ _ _, zero_le _ lemma le_tsum' (hf : summable f) (b : β) : f b ≤ ∑' b, f b := le_tsum hf b $ λ _ _, zero_le _ lemma has_sum_zero_iff : has_sum f 0 ↔ ∀ x, f x = 0 := begin refine ⟨_, λ h, _⟩, { contrapose!, exact λ ⟨x, hx⟩ h, irrefl _ (lt_of_lt_of_le (pos_iff_ne_zero.2 hx) (le_has_sum' h x)) }, { convert has_sum_zero, exact funext h } end lemma tsum_eq_zero_iff (hf : summable f) : ∑' i, f i = 0 ↔ ∀ x, f x = 0 := by rw [←has_sum_zero_iff, hf.has_sum_iff] end canonically_ordered section uniform_group variables [add_comm_group α] [uniform_space α] lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} : summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) := cauchy_map_iff_exists_tendsto.symm variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α} lemma cauchy_seq_finset_iff_vanishing : cauchy_seq (λ (s : finset β), ∑ b in s, f b) ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := begin simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top'], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_left_of_le le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) } end variable [complete_space α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing] /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := summable_iff_vanishing.2 $ assume e he, let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in ⟨s, assume t ht, have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b := calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = ∑ b in t, g b : begin refine finset.sum_subset (finset.filter_subset _ _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩ protected lemma summable.indicator (hf : summable f) (s : set β) : summable (s.indicator f) := hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _ lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := begin simpa only [set.indicator_range_comp] using (hi.summable_iff _).2 (hf.indicator (set.range i)), exact λ x hx, set.indicator_of_not_mem hx _ end lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) := hf.comp_injective subtype.coe_injective lemma summable_subtype_and_compl {s : set β} : summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f := ⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩ lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) := ha.comp_injective sigma_mk_injective lemma summable.sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) := ha.sigma' (λ b, ha.sigma_factor b) lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) : summable (λ c, f (b, c)) := h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2 lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_sigma' (λ b, ha.sigma_factor b) ha lemma tsum_prod [regular_space α] {f : β × γ → α} (h : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_prod' h h.prod_factor lemma tsum_comm [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) : ∑' c b, f b c = ∑' b c, f b c := tsum_comm' h h.prod_factor h.prod_symm.prod_factor end uniform_group section topological_group variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) : ∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e := begin letI : uniform_space G := topological_add_group.to_uniform_space G, letI : uniform_add_group G := topological_add_group_is_uniform, rcases hf with ⟨y, hy⟩, exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he end /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) := begin intros e he, rw [filter.mem_map], rcases hf.vanishing he with ⟨s, hs⟩, refine s.eventually_cofinite_nmem.mono (λ x hx, _), by simpa using hs {x} (singleton_disjoint.2 hx) end end topological_group lemma summable_abs_iff [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : summable (λ x, abs (f x)) ↔ summable f := have h1 : ∀ x : {x | 0 ≤ f x}, abs (f x) = f x := λ x, abs_of_nonneg x.2, have h2 : ∀ x : {x | 0 ≤ f x}ᶜ, abs (f x) = -f x := λ x, abs_of_neg (not_le.1 x.2), calc summable (λ x, abs (f x)) ↔ summable (λ x : {x | 0 ≤ f x}, abs (f x)) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, abs (f x)) : summable_subtype_and_compl.symm ... ↔ summable (λ x : {x | 0 ≤ f x}, f x) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, -f x) : by simp only [h1, h2] ... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl] alias summable_abs_iff ↔ summable.of_abs summable.abs section cauchy_seq open finset.Ico filter /-- If the extended distance between consequent points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_edist_le_of_summable [emetric_space α] {f : ℕ → α} (d : ℕ → ℝ≥0) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _), -- Actually we need partial sums of `d` to be a Cauchy sequence replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, -- Now we take the same `N` as in one of the definitions of a Cauchy sequence refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _), have hsum := hN n hn, -- We simplify the known inequality rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, nnreal.add_sub_cancel'] at hsum, norm_cast at hsum, replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum, rw edist_comm, -- Then use `hf` to simplify the goal to the same form apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)), assumption_mod_cast end /-- If the distance between consequent points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_dist_le_of_summable [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine metric.cauchy_seq_iff'.2 (λε εpos, _), replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _), have hsum := hN n hn, rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum, calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _ ... ≤ ∑ x in Ico N n, d x : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k) ... ≤ abs (∑ x in Ico N n, d x) : le_abs_self _ ... < ε : hsum end lemma cauchy_seq_of_summable_dist [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ (λ _, le_refl _) h lemma dist_le_tsum_of_dist_le_of_tendsto [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.dist ha) (eventually_at_top.2 ⟨n, λ m hnm, _⟩), refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _, rw [sum_Ico_eq_sum_range], refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _, exact hd.comp_injective (add_right_injective n) end lemma dist_le_tsum_of_dist_le_of_tendsto₀ [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 lemma dist_le_tsum_dist_of_tendsto [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) : dist (f n) a ≤ ∑' m, dist (f (n+m)) (f (n+m).succ) := show dist (f n) a ≤ ∑' m, (λx, dist (f x) (f x.succ)) (n + m), from dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_refl _) h ha n lemma dist_le_tsum_dist_of_tendsto₀ [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 end cauchy_seq
77a815e15b09eb99b3844a94c3ae5ee5c853dae8
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/ring_theory/multiplicity.lean
2b8d96f5ab31edd1e61d0d091c8754b03f4bbf7f
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
14,760
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, Chris Hughes -/ import algebra.associated data.int.gcd data.nat.enat import tactic.converter.interactive variables {α : Type*} open nat roption /-- `multiplicity a b` returns the largest natural number `n` such that `a ^ n ∣ b`, as an `enat` or natural with infinity. If `∀ n, a ^ n ∣ b`, then it returns `⊤`-/ def multiplicity [comm_semiring α] [decidable_rel ((∣) : α → α → Prop)] (a b : α) : enat := ⟨∃ n : ℕ, ¬a ^ (n + 1) ∣ b, λ h, nat.find h⟩ namespace multiplicity section comm_semiring variables [comm_semiring α] @[reducible] def finite (a b : α) : Prop := ∃ n : ℕ, ¬a ^ (n + 1) ∣ b lemma finite_iff_dom [decidable_rel ((∣) : α → α → Prop)] {a b : α} : finite a b ↔ (multiplicity a b).dom := iff.rfl lemma finite_def {a b : α} : finite a b ↔ ∃ n : ℕ, ¬a ^ (n + 1) ∣ b := iff.rfl lemma not_finite_iff_forall {a b : α} : (¬ finite a b) ↔ ∀ n : ℕ, a ^ n ∣ b := ⟨λ h n, nat.cases_on n (one_dvd _) (by simpa [finite, classical.not_not] using h), by simp [finite, multiplicity, classical.not_not]; tauto⟩ lemma not_unit_of_finite {a b : α} (h : finite a b) : ¬is_unit a := let ⟨n, hn⟩ := h in mt (is_unit_iff_forall_dvd.1 ∘ is_unit_pow (n + 1)) $ λ h, hn (h b) lemma ne_zero_of_finite {a b : α} (h : finite a b) : b ≠ 0 := let ⟨n, hn⟩ := h in λ hb, by simpa [hb] using hn lemma finite_of_finite_mul_left {a b c : α} : finite a (b * c) → finite a c := λ ⟨n, hn⟩, ⟨n, λ h, hn (dvd.trans h (by simp [_root_.mul_pow]))⟩ lemma finite_of_finite_mul_right {a b c : α} : finite a (b * c) → finite a b := by rw mul_comm; exact finite_of_finite_mul_left variable [decidable_rel ((∣) : α → α → Prop)] lemma pow_dvd_of_le_multiplicity {a b : α} {k : ℕ} : (k : enat) ≤ multiplicity a b → a ^ k ∣ b := nat.cases_on k (λ _, one_dvd _) (λ k ⟨h₁, h₂⟩, by_contradiction (λ hk, (nat.find_min _ (lt_of_succ_le (h₂ ⟨k, hk⟩)) hk))) lemma pow_multiplicity_dvd {a b : α} (h : finite a b) : a ^ get (multiplicity a b) h ∣ b := pow_dvd_of_le_multiplicity (by rw enat.coe_get) lemma is_greatest {a b : α} {m : ℕ} (hm : multiplicity a b < m) : ¬a ^ m ∣ b := λ h, have finite a b, from enat.dom_of_le_some (le_of_lt hm), by rw [← enat.coe_get (finite_iff_dom.1 this), enat.coe_lt_coe] at hm; exact nat.find_spec this (dvd.trans (pow_dvd_pow _ hm) h) lemma is_greatest' {a b : α} {m : ℕ} (h : finite a b) (hm : get (multiplicity a b) h < m) : ¬a ^ m ∣ b := is_greatest (by rwa [← enat.coe_lt_coe, enat.coe_get] at hm) lemma unique {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬a ^ (k + 1) ∣ b) : (k : enat) = multiplicity a b := le_antisymm (le_of_not_gt (λ hk', is_greatest hk' hk)) $ have finite a b, from ⟨k, hsucc⟩, by rw [← enat.coe_get (finite_iff_dom.1 this), enat.coe_le_coe]; exact nat.find_min' _ hsucc lemma unique' {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬ a ^ (k + 1) ∣ b) : k = get (multiplicity a b) ⟨k, hsucc⟩ := by rw [← enat.coe_inj, enat.coe_get, unique hk hsucc] lemma le_multiplicity_of_pow_dvd {a b : α} {k : ℕ} (hk : a ^ k ∣ b) : (k : enat) ≤ multiplicity a b := le_of_not_gt $ λ hk', is_greatest hk' hk lemma pow_dvd_iff_le_multiplicity {a b : α} {k : ℕ} : a ^ k ∣ b ↔ (k : enat) ≤ multiplicity a b := ⟨le_multiplicity_of_pow_dvd, pow_dvd_of_le_multiplicity⟩ lemma eq_some_iff {a b : α} {n : ℕ} : multiplicity a b = (n : enat) ↔ a ^ n ∣ b ∧ ¬a ^ (n + 1) ∣ b := ⟨λ h, let ⟨h₁, h₂⟩ := eq_some_iff.1 h in h₂ ▸ ⟨pow_multiplicity_dvd _, is_greatest (by conv_lhs {rw ← enat.coe_get h₁ }; rw [enat.coe_lt_coe]; exact lt_succ_self _)⟩, λ h, eq_some_iff.2 ⟨⟨n, h.2⟩, eq.symm $ unique' h.1 h.2⟩⟩ lemma eq_top_iff {a b : α} : multiplicity a b = ⊤ ↔ ∀ n : ℕ, a ^ n ∣ b := ⟨λ h n, nat.cases_on n (one_dvd _) (λ n, by_contradiction (not_exists.1 (eq_none_iff'.1 h) n : _)), λ h, eq_none_iff.2 (λ n ⟨⟨_, h₁⟩, _⟩, h₁ (h _))⟩ @[simp] protected lemma zero (a : α) : multiplicity a 0 = ⊤ := roption.eq_none_iff.2 (λ n ⟨⟨k, hk⟩, _⟩, hk (dvd_zero _)) lemma one_right {a : α} (ha : ¬is_unit a) : multiplicity a 1 = 0 := eq_some_iff.2 ⟨dvd_refl _, mt is_unit_iff_dvd_one.2 $ by simpa⟩ @[simp] lemma get_one_right {a : α} (ha : finite a 1) : get (multiplicity a 1) ha = 0 := get_eq_iff_eq_some.2 (eq_some_iff.2 ⟨dvd_refl _, by simpa [is_unit_iff_dvd_one.symm] using not_unit_of_finite ha⟩) @[simp] lemma one_left (b : α) : multiplicity 1 b = ⊤ := by simp [eq_top_iff] @[simp] lemma multiplicity_unit {a : α} (b : α) (ha : is_unit a) : multiplicity a b = ⊤ := eq_top_iff.2 (λ _, is_unit_iff_forall_dvd.1 (is_unit_pow _ ha) _) lemma multiplicity_eq_zero_of_not_dvd {a b : α} (ha : ¬a ∣ b) : multiplicity a b = 0 := eq_some_iff.2 (by simpa) lemma eq_top_iff_not_finite {a b : α} : multiplicity a b = ⊤ ↔ ¬ finite a b := roption.eq_none_iff' local attribute [instance, priority 0] classical.prop_decidable lemma multiplicity_le_multiplicity_iff {a b c d : α} : multiplicity a b ≤ multiplicity c d ↔ (∀ n : ℕ, a ^ n ∣ b → c ^ n ∣ d) := ⟨λ h n hab, (pow_dvd_of_le_multiplicity (le_trans (le_multiplicity_of_pow_dvd hab) h)), λ h, if hab : finite a b then by rw [← enat.coe_get (finite_iff_dom.1 hab)]; exact le_multiplicity_of_pow_dvd (h _ (pow_multiplicity_dvd _)) else have ∀ n : ℕ, c ^ n ∣ d, from λ n, h n (not_finite_iff_forall.1 hab _), by rw [eq_top_iff_not_finite.2 hab, eq_top_iff_not_finite.2 (not_finite_iff_forall.2 this)]⟩ lemma min_le_multiplicity_add {p a b : α} : min (multiplicity p a) (multiplicity p b) ≤ multiplicity p (a + b) := (le_total (multiplicity p a) (multiplicity p b)).elim (λ h, by rw [min_eq_left h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add hn (multiplicity_le_multiplicity_iff.1 h n hn)) (λ h, by rw [min_eq_right h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add (multiplicity_le_multiplicity_iff.1 h n hn) hn) lemma dvd_of_multiplicity_pos {a b : α} (h : (0 : enat) < multiplicity a b) : a ∣ b := by rw [← _root_.pow_one a]; exact pow_dvd_of_le_multiplicity (enat.pos_iff_one_le.1 h) lemma finite_nat_iff {a b : ℕ} : finite a b ↔ (a ≠ 1 ∧ 0 < b) := begin rw [← not_iff_not, not_finite_iff_forall, not_and_distrib, ne.def, not_not, not_lt, nat.le_zero_iff], exact ⟨λ h, or_iff_not_imp_right.2 (λ hb, have ha : a ≠ 0, from λ ha, by simpa [ha] using h 1, by_contradiction (λ ha1 : a ≠ 1, have ha_gt_one : 1 < a, from have ∀ a : ℕ, a ≤ 1 → a ≠ 0 → a ≠ 1 → false, from dec_trivial, lt_of_not_ge (λ ha', this a ha' ha ha1), not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero hb) (h b)) (by simp only [nat.pow_eq_pow]; exact lt_pow_self ha_gt_one b))), λ h, by cases h; simp *⟩ end lemma finite_int_iff_nat_abs_finite {a b : ℤ} : finite a b ↔ finite a.nat_abs b.nat_abs := begin rw [finite_def, finite_def], conv in (a ^ _ ∣ b) { rw [← int.nat_abs_dvd_abs_iff, int.nat_abs_pow, ← pow_eq_pow] } end lemma finite_int_iff {a b : ℤ} : finite a b ↔ (a.nat_abs ≠ 1 ∧ b ≠ 0) := begin have := int.nat_abs_eq a, have := @int.nat_abs_ne_zero_of_ne_zero b, rw [finite_int_iff_nat_abs_finite, finite_nat_iff, nat.pos_iff_ne_zero'], split; finish end instance decidable_nat : decidable_rel (λ a b : ℕ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_nat_iff.symm instance decidable_int : decidable_rel (λ a b : ℤ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_int_iff.symm end comm_semiring section comm_ring variables [comm_ring α] [decidable_rel ((∣) : α → α → Prop)] local attribute [instance, priority 0] classical.prop_decidable @[simp] protected lemma neg (a b : α) : multiplicity a (-b) = multiplicity a b := roption.ext' (by simp only [multiplicity]; conv in (_ ∣ - _) {rw dvd_neg}) (λ h₁ h₂, enat.coe_inj.1 (by rw [enat.coe_get]; exact eq.symm (unique ((dvd_neg _ _).2 (pow_multiplicity_dvd _)) (mt (dvd_neg _ _).1 (is_greatest' _ (lt_succ_self _)))))) end comm_ring section integral_domain variables [integral_domain α] [decidable_rel ((∣) : α → α → Prop)] @[simp] lemma multiplicity_self {a : α} (ha : ¬is_unit a) (ha0 : a ≠ 0) : multiplicity a a = 1 := eq_some_iff.2 ⟨by simp, λ ⟨b, hb⟩, ha (is_unit_iff_dvd_one.2 ⟨b, (domain.mul_left_inj ha0).1 $ by clear _fun_match; simpa [_root_.pow_succ, mul_assoc] using hb⟩)⟩ @[simp] lemma get_multiplicity_self {a : α} (ha : finite a a) : get (multiplicity a a) ha = 1 := roption.get_eq_iff_eq_some.2 (eq_some_iff.2 ⟨by simp, λ ⟨b, hb⟩, by rw [← mul_one a, _root_.pow_add, _root_.pow_one, mul_assoc, mul_assoc, domain.mul_left_inj (ne_zero_of_finite ha)] at hb; exact mt is_unit_iff_dvd_one.2 (not_unit_of_finite ha) ⟨b, by clear _fun_match; simp * at *⟩⟩) lemma finite_mul_aux {p : α} (hp : prime p) : ∀ {n m : ℕ} {a b : α}, ¬p ^ (n + 1) ∣ a → ¬p ^ (m + 1) ∣ b → ¬p ^ (n + m + 1) ∣ a * b | n m := λ a b ha hb ⟨s, hs⟩, have p ∣ a * b, from ⟨p ^ (n + m) * s, by simp [hs, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩, (hp.2.2 a b this).elim (λ ⟨x, hx⟩, have hn0 : 0 < n, from nat.pos_of_ne_zero (λ hn0, by clear _fun_match _fun_match; simpa [hx, hn0] using ha), have wf : (n - 1) < n, from nat.sub_lt_self hn0 dec_trivial, have hpx : ¬ p ^ (n - 1 + 1) ∣ x, from λ ⟨y, hy⟩, ha (hx.symm ▸ ⟨y, (domain.mul_left_inj hp.1).1 $ by rw [nat.sub_add_cancel hn0] at hy; simp [hy, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), have 1 ≤ n + m, from le_trans hn0 (le_add_right n m), finite_mul_aux hpx hb ⟨s, (domain.mul_left_inj hp.1).1 begin rw [← nat.sub_add_comm hn0, nat.sub_add_cancel this], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add] at * end⟩) (λ ⟨x, hx⟩, have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, by clear _fun_match _fun_match; simpa [hx, hm0] using hb), have wf : (m - 1) < m, from nat.sub_lt_self hm0 dec_trivial, have hpx : ¬ p ^ (m - 1 + 1) ∣ x, from λ ⟨y, hy⟩, hb (hx.symm ▸ ⟨y, (domain.mul_left_inj hp.1).1 $ by rw [nat.sub_add_cancel hm0] at hy; simp [hy, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), finite_mul_aux ha hpx ⟨s, (domain.mul_left_inj hp.1).1 begin rw [add_assoc, nat.sub_add_cancel hm0], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add] at * end⟩) lemma finite_mul {p a b : α} (hp : prime p) : finite p a → finite p b → finite p (a * b) := λ ⟨n, hn⟩ ⟨m, hm⟩, ⟨n + m, finite_mul_aux hp hn hm⟩ lemma finite_mul_iff {p a b : α} (hp : prime p) : finite p (a * b) ↔ finite p a ∧ finite p b := ⟨λ h, ⟨finite_of_finite_mul_right h, finite_of_finite_mul_left h⟩, λ h, finite_mul hp h.1 h.2⟩ lemma finite_pow {p a : α} (hp : prime p) : Π {k : ℕ} (ha : finite p a), finite p (a ^ k) | 0 ha := ⟨0, by simp [mt is_unit_iff_dvd_one.2 hp.2.1]⟩ | (k+1) ha := by rw [_root_.pow_succ]; exact finite_mul hp ha (finite_pow ha) protected lemma mul' {p a b : α} (hp : prime p) (h : (multiplicity p (a * b)).dom) : get (multiplicity p (a * b)) h = get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2 := have hdiva : p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 ∣ a, from pow_multiplicity_dvd _, have hdivb : p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2 ∣ b, from pow_multiplicity_dvd _, have hpoweq : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) = p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 * p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2, by simp [_root_.pow_add], have hdiv : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) ∣ a * b, by rw [hpoweq]; apply mul_dvd_mul; assumption, have hsucc : ¬p ^ ((get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) + 1) ∣ a * b, from λ h, not_or (is_greatest' _ (lt_succ_self _)) (is_greatest' _ (lt_succ_self _)) (succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul hp (by convert hdiva) (by convert hdivb) h), by rw [← enat.coe_inj, enat.coe_get, eq_some_iff]; exact ⟨hdiv, hsucc⟩ local attribute [instance, priority 0] classical.prop_decidable protected lemma mul {p a b : α} (hp : prime p) : multiplicity p (a * b) = multiplicity p a + multiplicity p b := if h : finite p a ∧ finite p b then by rw [← enat.coe_get (finite_iff_dom.1 h.1), ← enat.coe_get (finite_iff_dom.1 h.2), ← enat.coe_get (finite_iff_dom.1 (finite_mul hp h.1 h.2)), ← enat.coe_add, enat.coe_inj, multiplicity.mul' hp]; refl else begin rw [eq_top_iff_not_finite.2 (mt (finite_mul_iff hp).1 h)], cases not_and_distrib.1 h with h h; simp [eq_top_iff_not_finite.2 h] end protected lemma pow' {p a : α} (hp : prime p) (ha : finite p a) : ∀ {k : ℕ}, get (multiplicity p (a ^ k)) (finite_pow hp ha) = k * get (multiplicity p a) ha | 0 := by dsimp [_root_.pow_zero]; simp [one_right hp.2.1]; refl | (k+1) := by dsimp only [_root_.pow_succ]; erw [multiplicity.mul' hp, pow', add_mul, one_mul, add_comm] lemma pow {p a : α} (hp : prime p) : ∀ {k : ℕ}, multiplicity p (a ^ k) = add_monoid.smul k (multiplicity p a) | 0 := by simp [one_right hp.2.1] | (succ k) := by simp [_root_.pow_succ, succ_smul, pow, multiplicity.mul hp] end integral_domain end multiplicity section nat open multiplicity lemma multiplicity_eq_zero_of_coprime {p a b : ℕ} (hp : p ≠ 1) (hle : multiplicity p a ≤ multiplicity p b) (hab : nat.coprime a b) : multiplicity p a = 0 := begin rw [multiplicity_le_multiplicity_iff] at hle, rw [← le_zero_iff_eq, ← not_lt, enat.pos_iff_one_le, ← enat.coe_one, ← pow_dvd_iff_le_multiplicity], assume h, have := nat.dvd_gcd h (hle _ h), rw [coprime.gcd_eq_one hab, nat.dvd_one, _root_.pow_one] at this, exact hp this end end nat
64e2d354b3234ded4c995e243f2018819fbaa7e6
a7602958ab456501ff85db8cf5553f7bcab201d7
/Notes/Theorem_Proving_in_Lean/Chapter3/3.1.lean
378f4fc1339469e049cad365fbc3f934c16ced46
[]
no_license
enlauren/math-logic
081e2e737c8afb28dbb337968df95ead47321ba0
086b6935543d1841f1db92d0e49add1124054c37
refs/heads/master
1,594,506,621,950
1,558,634,976,000
1,558,634,976,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,112
lean
-- 3.1 Propositions as types -- We can build our own "proof" and assertion language on top of -- dependent type theory. namespace hidden -- Introduce a new type `Prop` to represent propositions, as well as -- constructors that can build new Props from others. variables p q r: Prop -- Constructors: constant and: Prop → Prop → Prop constant or: Prop → Prop → Prop constant implies: Prop → Prop → Prop #check and p q #check or (and p q) r #check implies (and p q) (and q p) -- For every element p ∈ Prop, we can have a new type called `Proof p` -- that represents a proof of the element's existence. constant Proof: Prop → Prop constant and_comm: Π a b: Prop, Proof (implies (and a b) (and b a)) #check and_comm #check and_comm p q -- Modus Ponens. -- From a proof of p → q, and p, we obtain a proof of q. constant modus_ponens: Π p q: Prop, Proof (implies p q) → Proof p → Proof q -- Other way around would be nice to have as well: constant implies_intro: Π p q: Prop, (Proof p → Proof q) → Proof (implies p q) end hidden
ae6e5064b4db3c285b38e2bdcaa08e062d6284ce
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/parity.lean
76fb68b174c997bd3dec04fb7d0fcd1a27d64327
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
638
lean
import data.nat open nat inductive Parity : nat → Type := | even : ∀ n : nat, Parity (2 * n) | odd : ∀ n : nat, Parity (2 * n + 1) open Parity definition parity : Π (n : nat), Parity n | parity 0 := even 0 | parity (n+1) := begin have aux : Parity n, from parity n, cases aux with [k, k], begin apply (odd k) end, begin change (Parity (2*k + 2*1)), rewrite -mul.left_distrib, apply (even (k+1)) end end print definition parity definition half (n : nat) : nat := match ⟨n, parity n⟩ with | ⟨⌞2 * k⌟, even k⟩ := k | ⟨⌞2 * k + 1⌟, odd k⟩ := k end
6fd233cc40cc431d8f72b8fd9dd35e7817f4fb1a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/filtered.lean
2ac24e16f159b889054e93d4d1ff0f099e15f432
[ "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,491
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.filtered import category_theory.limits.has_limits /-! # Possession of filtered colimits > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universes w' w v u noncomputable theory open category_theory variables {C : Type u} [category.{v} C] namespace category_theory.limits section variables (C) /-- Class for having all cofiltered limits of a given size. -/ class has_cofiltered_limits_of_size : Prop := (has_limits_of_shape : Π (I : Type w) [category.{w'} I] [is_cofiltered I], has_limits_of_shape I C) /-- Class for having all filtered colimits of a given size. -/ class has_filtered_colimits_of_size : Prop := (has_colimits_of_shape : Π (I : Type w) [category.{w'} I] [is_filtered I], has_colimits_of_shape I C) end @[priority 100] instance has_limits_of_shape_of_has_cofiltered_limits [has_cofiltered_limits_of_size.{w' w} C] (I : Type w) [category.{w'} I] [is_cofiltered I] : has_limits_of_shape I C := has_cofiltered_limits_of_size.has_limits_of_shape _ @[priority 100] instance has_colimits_of_shape_of_has_filtered_colimits [has_filtered_colimits_of_size.{w' w} C] (I : Type w) [category.{w'} I] [is_filtered I] : has_colimits_of_shape I C := has_filtered_colimits_of_size.has_colimits_of_shape _ end category_theory.limits
bf1af2bfb4233aafc8842b8fbd55ee87e9323dde
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/extension/linear.lean
cdfb97de16c56a8654bf8a260c494aae2a54c5ab
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,976
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import order.zorn import tactic.by_contra /-! # Extend a partial order to a linear order > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file constructs a linear order which is an extension of the given partial order, using Zorn's lemma. -/ universes u open set classical open_locale classical /-- Any partial order can be extended to a linear order. -/ theorem extend_partial_order {α : Type u} (r : α → α → Prop) [is_partial_order α r] : ∃ (s : α → α → Prop) (_ : is_linear_order α s), r ≤ s := begin let S := {s | is_partial_order α s}, have hS : ∀ c, c ⊆ S → is_chain (≤) c → ∀ y ∈ c, (∃ ub ∈ S, ∀ z ∈ c, z ≤ ub), { rintro c hc₁ hc₂ s hs, haveI := (hc₁ hs).1, refine ⟨Sup c, _, λ z hz, le_Sup hz⟩, refine { refl := _, trans := _, antisymm := _ }; simp_rw binary_relation_Sup_iff, { intro x, exact ⟨s, hs, refl x⟩ }, { rintro x y z ⟨s₁, h₁s₁, h₂s₁⟩ ⟨s₂, h₁s₂, h₂s₂⟩, haveI : is_partial_order _ _ := hc₁ h₁s₁, haveI : is_partial_order _ _ := hc₁ h₁s₂, cases hc₂.total h₁s₁ h₁s₂, { exact ⟨s₂, h₁s₂, trans (h _ _ h₂s₁) h₂s₂⟩ }, { exact ⟨s₁, h₁s₁, trans h₂s₁ (h _ _ h₂s₂)⟩ } }, { rintro x y ⟨s₁, h₁s₁, h₂s₁⟩ ⟨s₂, h₁s₂, h₂s₂⟩, haveI : is_partial_order _ _ := hc₁ h₁s₁, haveI : is_partial_order _ _ := hc₁ h₁s₂, cases hc₂.total h₁s₁ h₁s₂, { exact antisymm (h _ _ h₂s₁) h₂s₂ }, { apply antisymm h₂s₁ (h _ _ h₂s₂) } } }, obtain ⟨s, hs₁ : is_partial_order _ _, rs, hs₂⟩ := zorn_nonempty_partial_order₀ S hS r ‹_›, resetI, refine ⟨s, { total := _ }, rs⟩, intros x y, by_contra' h, let s' := λ x' y', s x' y' ∨ s x' x ∧ s y y', rw ←hs₂ s' _ (λ _ _, or.inl) at h, { apply h.1 (or.inr ⟨refl _, refl _⟩) }, { refine { refl := λ x, or.inl (refl _), trans := _, antisymm := _ }, { rintro a b c (ab | ⟨ax : s a x, yb : s y b⟩) (bc | ⟨bx : s b x, yc : s y c⟩), { exact or.inl (trans ab bc), }, { exact or.inr ⟨trans ab bx, yc⟩ }, { exact or.inr ⟨ax, trans yb bc⟩ }, { exact or.inr ⟨ax, yc⟩ } }, { rintro a b (ab | ⟨ax : s a x, yb : s y b⟩) (ba | ⟨bx : s b x, ya : s y a⟩), { exact antisymm ab ba }, { exact (h.2 (trans ya (trans ab bx))).elim }, { exact (h.2 (trans yb (trans ba ax))).elim }, { exact (h.2 (trans yb bx)).elim } } }, end /-- A type alias for `α`, intended to extend a partial order on `α` to a linear order. -/ def linear_extension (α : Type u) : Type u := α noncomputable instance {α : Type u} [partial_order α] : linear_order (linear_extension α) := { le := (extend_partial_order ((≤) : α → α → Prop)).some, le_refl := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.1.1.1, le_trans := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.1.2.1, le_antisymm := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.2.1, le_total := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.2.1, decidable_le := classical.dec_rel _ } /-- The embedding of `α` into `linear_extension α` as a relation homomorphism. -/ def to_linear_extension {α : Type u} [partial_order α] : ((≤) : α → α → Prop) →r ((≤) : linear_extension α → linear_extension α → Prop) := { to_fun := λ x, x, map_rel' := λ a b, (extend_partial_order ((≤) : α → α → Prop)).some_spec.some_spec _ _ } instance {α : Type u} [inhabited α] : inhabited (linear_extension α) := ⟨(default : α)⟩
483a5782adfb92dde7d1dcd65d224da5b201af33
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/bench/rbmap4.lean
7e58649cf3ff9a521db78bef446a10e61b7424a9
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
2,829
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.data.ordering.basic init.coe init.data.option.basic init.io universes u v w w' inductive color | Red | Black inductive Tree | Leaf {} : Tree | Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree variables {σ : Type w} open color Nat Tree def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ | Leaf b := b | (Node _ l k v r) b := fold r (f k v (fold l b)) @[inline] def balance1 : Nat → Bool → Tree → Tree → Tree | kv vv t (Node _ (Node Red l kx vx r₁) ky vy r₂) := Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t) | kv vv t (Node _ l₁ ky vy (Node Red l₂ kx vx r)) := Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t) | kv vv t (Node _ l ky vy r) := Node Black (Node Red l ky vy r) kv vv t | _ _ _ _ := Leaf @[inline] def balance2 : Tree → Nat → Bool → Tree → Tree | t kv vv (Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂) := Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂) | t kv vv (Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂)) := Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂) | t kv vv (Node _ l ky vy r) := Node Black t kv vv (Node Red l ky vy r) | _ _ _ _ := Leaf def isRed : Tree → Bool | (Node Red _ _ _ _) := true | _ := false def ins : Tree → Nat → Bool → Tree | Leaf kx vx := Node Red Leaf kx vx Leaf | (Node Red a ky vy b) kx vx := (if kx < ky then Node Red (ins a kx vx) ky vy b else if kx = ky then Node Red a kx vx b else Node Red a ky vy (ins b kx vx)) | (Node Black a ky vy b) kx vx := if kx < ky then (if isRed a then balance1 ky vy b (ins a kx vx) else Node Black (ins a kx vx) ky vy b) else if kx = ky then Node Black a kx vx b else if isRed b then balance2 a ky vy (ins b kx vx) else Node Black a ky vy (ins b kx vx) def setBlack : Tree → Tree | (Node _ l k v r) := Node Black l k v r | e := e def insert (t : Tree) (k : Nat) (v : Bool) : Tree := if isRed t then setBlack (ins t k v) else ins t k v def mkMapAux : Nat → Tree → Tree | 0 m := m | (n+1) m := mkMapAux n (insert m n (n % 10 = 0)) def mkMap (n : Nat) := mkMapAux n Leaf def main (xs : List String) : IO UInt32 := let m := mkMap xs.head.toNat; let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0; IO.println (toString v) *> pure 0
8265454c5d6037994365a4725a7bc6bd7cdfe6b4
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/well_founded_set.lean
fce6a9a517d09adab95d2e95ded142ed39f580a1
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,976
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.set.finite import order.well_founded import order.order_iso_nat import algebra.pointwise /-! # Well-founded sets A well-founded subset of an ordered type is one on which the relation `<` is well-founded. ## Main Definitions * `set.well_founded_on s r` indicates that the relation `r` is well-founded when restricted to the set `s`. * `set.is_wf s` indicates that `<` is well-founded when restricted to `s`. * `set.partially_well_ordered_on s r` indicates that the relation `r` is partially well-ordered (also known as well quasi-ordered) when restricted to the set `s`. * `set.is_pwo s` indicates that any infinite sequence of elements in `s` contains an infinite monotone subsequence. Note that ### Definitions for Hahn Series * `set.add_antidiagonal s t a` and `set.mul_antidiagonal s t a` are the sets of pairs of elements from `s` and `t` that add/multiply to `a`. * `finset.add_antidiagonal` and `finset.mul_antidiagonal` are finite versions of `set.add_antidiagonal` and `set.mul_antidiagonal` defined when `s` and `t` are well-founded. ## Main Results * Higman's Lemma, `set.partially_well_ordered_on.partially_well_ordered_on_sublist_forall₂`, shows that if `r` is partially well-ordered on `s`, then `list.sublist_forall₂` is partially well-ordered on the set of lists of elements of `s`. The result was originally published by Higman, but this proof more closely follows Nash-Williams. * `set.well_founded_on_iff` relates `well_founded_on` to the well-foundedness of a relation on the original type, to avoid dealing with subtypes. * `set.is_wf.mono` shows that a subset of a well-founded subset is well-founded. * `set.is_wf.union` shows that the union of two well-founded subsets is well-founded. * `finset.is_wf` shows that all `finset`s are well-founded. ## References * [Higman, *Ordering by Divisibility in Abstract Algebras*][Higman52] * [Nash-Williams, *On Well-Quasi-Ordering Finite Trees*][Nash-Williams63] -/ open_locale pointwise variables {α : Type*} namespace set /-- `s.well_founded_on r` indicates that the relation `r` is well-founded when restricted to `s`. -/ def well_founded_on (s : set α) (r : α → α → Prop) : Prop := well_founded (λ (a : s) (b : s), r a b) lemma well_founded_on_iff {s : set α} {r : α → α → Prop} : s.well_founded_on r ↔ well_founded (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := begin have f : rel_embedding (λ (a : s) (b : s), r a b) (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := ⟨⟨coe, subtype.coe_injective⟩, λ a b, by simp⟩, refine ⟨λ h, _, f.well_founded⟩, rw well_founded.well_founded_iff_has_min, intros t ht, by_cases hst : (s ∩ t).nonempty, { rw ← subtype.preimage_coe_nonempty at hst, rcases well_founded.well_founded_iff_has_min.1 h (coe ⁻¹' t) hst with ⟨⟨m, ms⟩, mt, hm⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hm ⟨x, xs⟩ xt xm⟩ }, { rcases ht with ⟨m, mt⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hst ⟨m, ⟨ms, mt⟩⟩⟩ } end lemma well_founded_on.induction {s : set α} {r : α → α → Prop} (hs : s.well_founded_on r) {x : α} (hx : x ∈ s) {P : α → Prop} (hP : ∀ (y ∈ s), (∀ (z ∈ s), r z y → P z) → P y) : P x := begin let Q : s → Prop := λ y, P y, change Q ⟨x, hx⟩, refine well_founded.induction hs ⟨x, hx⟩ _, rintros ⟨y, ys⟩ ih, exact hP _ ys (λ z zs zy, ih ⟨z, zs⟩ zy), end instance is_strict_order.subset {s : set α} {r : α → α → Prop} [is_strict_order α r] : is_strict_order α (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := { to_is_irrefl := ⟨λ a con, irrefl_of r a con.1 ⟩, to_is_trans := ⟨λ a b c ab bc, ⟨trans_of r ab.1 bc.1, ab.2.1, bc.2.2⟩ ⟩ } theorem well_founded_on_iff_no_descending_seq {s : set α} {r : α → α → Prop} [is_strict_order α r] : s.well_founded_on r ↔ ∀ (f : ((>) : ℕ → ℕ → Prop) ↪r r), ¬ (range f) ⊆ s := begin rw [well_founded_on_iff, rel_embedding.well_founded_iff_no_descending_seq], refine ⟨λ h f con, begin refine h.elim' ⟨⟨f, f.injective⟩, λ a b, _⟩, simp only [con (mem_range_self a), con (mem_range_self b), and_true, gt_iff_lt, function.embedding.coe_fn_mk, f.map_rel_iff] end, λ h, ⟨λ con, _⟩⟩, rcases con with ⟨f, hf⟩, have hfs' : ∀ n : ℕ, f n ∈ s := λ n, (hf.2 n.lt_succ_self).2.2, refine h ⟨f, λ a b, _⟩ (λ n hn, _), { rw ← hf, exact ⟨λ h, ⟨h, hfs' _, hfs' _⟩, λ h, h.1⟩ }, { rcases set.mem_range.1 hn with ⟨m, hm⟩, rw ← hm, apply hfs' } end section has_lt variables [has_lt α] /-- `s.is_wf` indicates that `<` is well-founded when restricted to `s`. -/ def is_wf (s : set α) : Prop := well_founded_on s (<) lemma is_wf_univ_iff : is_wf (univ : set α) ↔ well_founded ((<) : α → α → Prop) := by simp [is_wf, well_founded_on_iff] variables {s t : set α} theorem is_wf.mono (h : is_wf t) (st : s ⊆ t) : is_wf s := begin rw [is_wf, well_founded_on_iff] at *, refine subrelation.wf (λ x y xy, _) h, exact ⟨xy.1, st xy.2.1, st xy.2.2⟩, end end has_lt section partial_order variables [partial_order α] {s t : set α} {a : α} theorem is_wf_iff_no_descending_seq : is_wf s ↔ ∀ (f : (order_dual ℕ) ↪o α), ¬ (range f) ⊆ s := begin haveI : is_strict_order α (λ (a b : α), a < b ∧ a ∈ s ∧ b ∈ s) := { to_is_irrefl := ⟨λ x con, lt_irrefl x con.1⟩, to_is_trans := ⟨λ a b c ab bc, ⟨lt_trans ab.1 bc.1, ab.2.1, bc.2.2⟩⟩, }, rw [is_wf, well_founded_on_iff_no_descending_seq], exact ⟨λ h f, h f.lt_embedding, λ h f, h (order_embedding.of_strict_mono f (λ _ _, f.map_rel_iff.2))⟩, end theorem is_wf.union (hs : is_wf s) (ht : is_wf t) : is_wf (s ∪ t) := begin classical, rw [is_wf_iff_no_descending_seq] at *, rintros f fst, have h : infinite (f ⁻¹' s) ∨ infinite (f ⁻¹' t), { have h : infinite (univ : set ℕ) := infinite_univ, have hpre : f ⁻¹' (s ∪ t) = set.univ, { rw [← image_univ, image_subset_iff, univ_subset_iff] at fst, exact fst }, rw preimage_union at hpre, rw ← hpre at h, rw [infinite, infinite], rw infinite at h, contrapose! h, exact finite.union h.1 h.2, }, rw [← infinite_coe_iff, ← infinite_coe_iff] at h, cases h with inf inf; haveI := inf, { apply hs ((nat.order_embedding_of_set (f ⁻¹' s)).dual.trans f), change range (function.comp f (nat.order_embedding_of_set (f ⁻¹' s))) ⊆ s, rw [range_comp, image_subset_iff], simp }, { apply ht ((nat.order_embedding_of_set (f ⁻¹' t)).dual.trans f), change range (function.comp f (nat.order_embedding_of_set (f ⁻¹' t))) ⊆ t, rw [range_comp, image_subset_iff], simp } end end partial_order end set namespace set /-- A subset is partially well-ordered by a relation `r` when any infinite sequence contains two elements where the first is related to the second by `r`. -/ def partially_well_ordered_on (s) (r : α → α → Prop) : Prop := ∀ (f : ℕ → α), range f ⊆ s → ∃ (m n : ℕ), m < n ∧ r (f m) (f n) /-- A subset of a preorder is partially well-ordered when any infinite sequence contains a monotone subsequence of length 2 (or equivalently, an infinite monotone subsequence). -/ def is_pwo [preorder α] (s) : Prop := partially_well_ordered_on s ((≤) : α → α → Prop) theorem partially_well_ordered_on.mono {s t : set α} {r : α → α → Prop} (ht : t.partially_well_ordered_on r) (hsub : s ⊆ t) : s.partially_well_ordered_on r := λ f hf, ht f (set.subset.trans hf hsub) theorem partially_well_ordered_on.image_of_monotone_on {s : set α} {r : α → α → Prop} {β : Type*} {r' : β → β → Prop} (hs : s.partially_well_ordered_on r) {f : α → β} (hf : ∀ a1 a2 : α, a1 ∈ s → a2 ∈ s → r a1 a2 → r' (f a1) (f a2)) : (f '' s).partially_well_ordered_on r' := λ g hg, begin have h := λ (n : ℕ), ((mem_image _ _ _).1 (hg (mem_range_self n))), obtain ⟨m, n, hlt, hmn⟩ := hs (λ n, classical.some (h n)) _, { refine ⟨m, n, hlt, _⟩, rw [← (classical.some_spec (h m)).2, ← (classical.some_spec (h n)).2], exact hf _ _ (classical.some_spec (h m)).1 (classical.some_spec (h n)).1 hmn }, { rintros _ ⟨n, rfl⟩, exact (classical.some_spec (h n)).1 } end section partial_order variables {s : set α} {t : set α} {r : α → α → Prop} theorem partially_well_ordered_on.exists_monotone_subseq [is_refl α r] [is_trans α r] (h : s.partially_well_ordered_on r) (f : ℕ → α) (hf : range f ⊆ s) : ∃ (g : ℕ ↪o ℕ), ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := begin obtain ⟨g, h1 | h2⟩ := exists_increasing_or_nonincreasing_subseq r f, { refine ⟨g, λ m n hle, _⟩, obtain hlt | heq := lt_or_eq_of_le hle, { exact h1 m n hlt, }, { rw [heq], apply refl_of r } }, { exfalso, obtain ⟨m, n, hlt, hle⟩ := h (f ∘ g) (subset.trans (range_comp_subset_range _ _) hf), exact h2 m n hlt hle } end theorem partially_well_ordered_on_iff_exists_monotone_subseq [is_refl α r] [is_trans α r] : s.partially_well_ordered_on r ↔ ∀ f : ℕ → α, range f ⊆ s → ∃ (g : ℕ ↪o ℕ), ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := begin classical, split; intros h f hf, { exact h.exists_monotone_subseq f hf }, { obtain ⟨g, gmon⟩ := h f hf, refine ⟨g 0, g 1, g.lt_iff_lt.2 zero_lt_one, gmon _ _ zero_le_one⟩, } end lemma partially_well_ordered_on.well_founded_on [is_partial_order α r] (h : s.partially_well_ordered_on r) : s.well_founded_on (λ a b, r a b ∧ a ≠ b) := begin haveI : is_strict_order α (λ a b, r a b ∧ a ≠ b) := { to_is_irrefl := ⟨λ a con, con.2 rfl⟩, to_is_trans := ⟨λ a b c ab bc, ⟨trans ab.1 bc.1, λ ac, ab.2 (antisymm ab.1 (ac.symm ▸ bc.1))⟩⟩ }, rw well_founded_on_iff_no_descending_seq, intros f con, obtain ⟨m, n, hlt, hle⟩ := h f con, exact (f.map_rel_iff.2 hlt).2 (antisymm hle (f.map_rel_iff.2 hlt).1).symm, end variables [partial_order α] lemma is_pwo.is_wf (h : s.is_pwo) : s.is_wf := begin rw [is_wf], convert h.well_founded_on, ext x y, rw lt_iff_le_and_ne, end theorem is_pwo.exists_monotone_subseq (h : s.is_pwo) (f : ℕ → α) (hf : range f ⊆ s) : ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := h.exists_monotone_subseq f hf theorem is_pwo_iff_exists_monotone_subseq : s.is_pwo ↔ ∀ f : ℕ → α, range f ⊆ s → ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := partially_well_ordered_on_iff_exists_monotone_subseq lemma is_pwo.prod (hs : s.is_pwo) (ht : t.is_pwo) : (s.prod t).is_pwo := begin classical, rw is_pwo_iff_exists_monotone_subseq at *, intros f hf, obtain ⟨g1, h1⟩ := hs (prod.fst ∘ f) _, swap, { rw [range_comp, image_subset_iff], refine subset.trans hf _, rintros ⟨x1, x2⟩ hx, simp only [mem_preimage, hx.1] }, obtain ⟨g2, h2⟩ := ht (prod.snd ∘ f ∘ g1) _, refine ⟨g2.trans g1, λ m n mn, _⟩, swap, { rw [range_comp, image_subset_iff], refine subset.trans (range_comp_subset_range _ _) (subset.trans hf _), rintros ⟨x1, x2⟩ hx, simp only [mem_preimage, hx.2] }, simp only [rel_embedding.coe_trans, function.comp_app], exact ⟨h1 (g2.le_iff_le.2 mn), h2 mn⟩, end theorem is_pwo.image_of_monotone {β : Type*} [partial_order β] (hs : s.is_pwo) {f : α → β} (hf : monotone f) : is_pwo (f '' s) := hs.image_of_monotone_on (λ _ _ _ _ ab, hf ab) theorem is_pwo.union (hs : is_pwo s) (ht : is_pwo t) : is_pwo (s ∪ t) := begin classical, rw [is_pwo_iff_exists_monotone_subseq] at *, rintros f fst, have h : infinite (f ⁻¹' s) ∨ infinite (f ⁻¹' t), { have h : infinite (univ : set ℕ) := infinite_univ, have hpre : f ⁻¹' (s ∪ t) = set.univ, { rw [← image_univ, image_subset_iff, univ_subset_iff] at fst, exact fst }, rw preimage_union at hpre, rw ← hpre at h, rw [infinite, infinite], rw infinite at h, contrapose! h, exact finite.union h.1 h.2, }, rw [← infinite_coe_iff, ← infinite_coe_iff] at h, cases h with inf inf; haveI := inf, { obtain ⟨g, hg⟩ := hs (f ∘ (nat.order_embedding_of_set (f ⁻¹' s))) _, { rw [function.comp.assoc, ← rel_embedding.coe_trans] at hg, exact ⟨_, hg⟩ }, rw [range_comp, image_subset_iff], simp }, { obtain ⟨g, hg⟩ := ht (f ∘ (nat.order_embedding_of_set (f ⁻¹' t))) _, { rw [function.comp.assoc, ← rel_embedding.coe_trans] at hg, exact ⟨_, hg⟩ }, rw [range_comp, image_subset_iff], simp } end end partial_order theorem is_wf.is_pwo [linear_order α] {s : set α} (hs : s.is_wf) : s.is_pwo := λ f hf, begin rw [is_wf, well_founded_on_iff] at hs, have hrange : (range f).nonempty := ⟨f 0, mem_range_self 0⟩, let a := hs.min (range f) hrange, obtain ⟨m, hm⟩ := hs.min_mem (range f) hrange, refine ⟨m, m.succ, m.lt_succ_self, le_of_not_lt (λ con, _)⟩, rw hm at con, apply hs.not_lt_min (range f) hrange (mem_range_self m.succ) ⟨con, hf (mem_range_self m.succ), hf _⟩, rw ← hm, apply mem_range_self, end theorem is_wf_iff_is_pwo [linear_order α] {s : set α} : s.is_wf ↔ s.is_pwo := ⟨is_wf.is_pwo, is_pwo.is_wf⟩ end set namespace finset @[simp] theorem partially_well_ordered_on {r : α → α → Prop} [is_refl α r] (f : finset α) : set.partially_well_ordered_on (↑f : set α) r := begin intros g hg, by_cases hinj : function.injective g, { exact (set.infinite_of_injective_forall_mem hinj (set.range_subset_iff.1 hg) f.finite_to_set).elim }, { rw [function.injective] at hinj, push_neg at hinj, obtain ⟨m, n, gmgn, hne⟩ := hinj, cases lt_or_gt_of_ne hne with hlt hlt; { refine ⟨_, _, hlt, _⟩, rw gmgn, exact refl_of r _, } } end @[simp] theorem is_pwo [partial_order α] (f : finset α) : set.is_pwo (↑f : set α) := f.partially_well_ordered_on @[simp] theorem well_founded_on {r : α → α → Prop} [is_strict_order α r] (f : finset α) : set.well_founded_on (↑f : set α) r := begin rw [set.well_founded_on_iff_no_descending_seq], intros g con, apply set.infinite_of_injective_forall_mem g.injective (set.range_subset_iff.1 con), exact f.finite_to_set, end @[simp] theorem is_wf [partial_order α] (f : finset α) : set.is_wf (↑f : set α) := f.is_pwo.is_wf end finset namespace set variables [partial_order α] {s : set α} {a : α} theorem finite.is_pwo (h : s.finite) : s.is_pwo := begin rw ← h.coe_to_finset, exact h.to_finset.is_pwo, end @[simp] theorem fintype.is_pwo [fintype α] : s.is_pwo := (finite.of_fintype s).is_pwo @[simp] theorem is_pwo_empty : is_pwo (∅ : set α) := finite_empty.is_pwo @[simp] theorem is_pwo_singleton (a) : is_pwo ({a} : set α) := (finite_singleton a).is_pwo theorem is_pwo.insert (a) (hs : is_pwo s) : is_pwo (insert a s) := by { rw ← union_singleton, exact hs.union (is_pwo_singleton a) } /-- `is_wf.min` returns a minimal element of a nonempty well-founded set. -/ noncomputable def is_wf.min (hs : is_wf s) (hn : s.nonempty) : α := hs.min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) lemma is_wf.min_mem (hs : is_wf s) (hn : s.nonempty) : hs.min hn ∈ s := (well_founded.min hs univ (nonempty_iff_univ_nonempty.1 hn.to_subtype)).2 lemma is_wf.not_lt_min (hs : is_wf s) (hn : s.nonempty) (ha : a ∈ s) : ¬ a < hs.min hn := hs.not_lt_min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) (mem_univ (⟨a, ha⟩ : s)) @[simp] lemma is_wf_min_singleton (a) {hs : is_wf ({a} : set α)} {hn : ({a} : set α).nonempty} : hs.min hn = a := eq_of_mem_singleton (is_wf.min_mem hs hn) end set @[simp] theorem finset.is_wf_sup {ι : Type*} [partial_order α] (f : finset ι) (g : ι → set α) (hf : ∀ i : ι, i ∈ f → (g i).is_wf) : (f.sup g).is_wf := begin classical, revert hf, apply f.induction_on, { intro h, simp [set.is_pwo_empty.is_wf], }, { intros s f sf hf hsf, rw finset.sup_insert, exact (hsf s (finset.mem_insert_self _ _)).union (hf (λ s' s'f, hsf _ (finset.mem_insert_of_mem s'f))) } end @[simp] theorem finset.is_pwo_sup {ι : Type*} [partial_order α] (f : finset ι) (g : ι → set α) (hf : ∀ i : ι, i ∈ f → (g i).is_pwo) : (f.sup g).is_pwo := begin classical, revert hf, apply f.induction_on, { intro h, simp [set.is_pwo_empty.is_wf], }, { intros s f sf hf hsf, rw finset.sup_insert, exact (hsf s (finset.mem_insert_self _ _)).union (hf (λ s' s'f, hsf _ (finset.mem_insert_of_mem s'f))) } end namespace set variables [linear_order α] {s t : set α} {a : α} lemma is_wf.min_le (hs : s.is_wf) (hn : s.nonempty) (ha : a ∈ s) : hs.min hn ≤ a := le_of_not_lt (hs.not_lt_min hn ha) lemma is_wf.le_min_iff (hs : s.is_wf) (hn : s.nonempty) : a ≤ hs.min hn ↔ ∀ b, b ∈ s → a ≤ b := ⟨λ ha b hb, le_trans ha (hs.min_le hn hb), λ h, h _ (hs.min_mem _)⟩ lemma is_wf.min_le_min_of_subset {hs : s.is_wf} {hsn : s.nonempty} {ht : t.is_wf} {htn : t.nonempty} (hst : s ⊆ t) : ht.min htn ≤ hs.min hsn := (is_wf.le_min_iff _ _).2 (λ b hb, ht.min_le htn (hst hb)) lemma is_wf.min_union (hs : s.is_wf) (hsn : s.nonempty) (ht : t.is_wf) (htn : t.nonempty) : (hs.union ht).min (union_nonempty.2 (or.intro_left _ hsn)) = min (hs.min hsn) (ht.min htn) := begin refine le_antisymm (le_min (is_wf.min_le_min_of_subset (subset_union_left _ _)) (is_wf.min_le_min_of_subset (subset_union_right _ _))) _, rw min_le_iff, exact ((mem_union _ _ _).1 ((hs.union ht).min_mem (union_nonempty.2 (or.intro_left _ hsn)))).imp (hs.min_le _) (ht.min_le _), end end set namespace set variables {s : set α} {t : set α} @[to_additive] theorem is_pwo.mul [ordered_cancel_comm_monoid α] (hs : s.is_pwo) (ht : t.is_pwo) : is_pwo (s * t) := begin rw ← image_mul_prod, exact (is_pwo.prod hs ht).image_of_monotone (λ _ _ h, mul_le_mul' h.1 h.2), end variable [linear_ordered_cancel_comm_monoid α] @[to_additive] theorem is_wf.mul (hs : s.is_wf) (ht : t.is_wf) : is_wf (s * t) := (hs.is_pwo.mul ht.is_pwo).is_wf @[to_additive] theorem is_wf.min_mul (hs : s.is_wf) (ht : t.is_wf) (hsn : s.nonempty) (htn : t.nonempty) : (hs.mul ht).min (hsn.mul htn) = hs.min hsn * ht.min htn := begin refine le_antisymm (is_wf.min_le _ _ (mem_mul.2 ⟨_, _, hs.min_mem _, ht.min_mem _, rfl⟩)) _, rw is_wf.le_min_iff, rintros _ ⟨x, y, hx, hy, rfl⟩, exact mul_le_mul' (hs.min_le _ hx) (ht.min_le _ hy), end end set namespace set namespace partially_well_ordered_on /-- In the context of partial well-orderings, a bad sequence is a nonincreasing sequence whose range is contained in a particular set `s`. One exists if and only if `s` is not partially well-ordered. -/ def is_bad_seq (r : α → α → Prop) (s : set α) (f : ℕ → α) : Prop := set.range f ⊆ s ∧ ∀ (m n : ℕ), m < n → ¬ r (f m) (f n) lemma iff_forall_not_is_bad_seq (r : α → α → Prop) (s : set α) : s.partially_well_ordered_on r ↔ ∀ f, ¬ is_bad_seq r s f := begin rw [set.partially_well_ordered_on], apply forall_congr (λ f, _), simp [is_bad_seq] end /-- This indicates that every bad sequence `g` that agrees with `f` on the first `n` terms has `rk (f n) ≤ rk (g n)`. -/ def is_min_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) : Prop := ∀ g : ℕ → α, (∀ (m : ℕ), m < n → f m = g m) → rk (g n) < rk (f n) → ¬ is_bad_seq r s g /-- Given a bad sequence `f`, this constructs a bad sequence that agrees with `f` on the first `n` terms and is minimal at `n`. -/ noncomputable def min_bad_seq_of_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) (hf : is_bad_seq r s f) : { g : ℕ → α // (∀ (m : ℕ), m < n → f m = g m) ∧ is_bad_seq r s g ∧ is_min_bad_seq r rk s n g } := begin classical, have h : ∃ (k : ℕ) (g : ℕ → α), (∀ m, m < n → f m = g m) ∧ is_bad_seq r s g ∧ rk (g n) = k := ⟨_, f, λ _ _, rfl, hf, rfl⟩, obtain ⟨h1, h2, h3⟩ := classical.some_spec (nat.find_spec h), refine ⟨classical.some (nat.find_spec h), h1, by convert h2, λ g hg1 hg2 con, _⟩, refine nat.find_min h _ ⟨g, λ m mn, (h1 m mn).trans (hg1 m mn), by convert con, rfl⟩, rwa ← h3, end lemma exists_min_bad_of_exists_bad (r : α → α → Prop) (rk : α → ℕ) (s : set α) : (∃ f, is_bad_seq r s f) → ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f := begin rintro ⟨f0, (hf0 : is_bad_seq r s f0)⟩, let fs : Π (n : ℕ), { f : ℕ → α // is_bad_seq r s f ∧ is_min_bad_seq r rk s n f }, { refine nat.rec _ _, { exact ⟨(min_bad_seq_of_bad_seq r rk s 0 f0 hf0).1, (min_bad_seq_of_bad_seq r rk s 0 f0 hf0).2.2⟩, }, { exact λ n fn, ⟨(min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).1, (min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).2.2⟩ } }, have h : ∀ m n, m ≤ n → (fs m).1 m = (fs n).1 m, { intros m n mn, obtain ⟨k, rfl⟩ := exists_add_of_le mn, clear mn, induction k with k ih, { refl }, rw [ih, ((min_bad_seq_of_bad_seq r rk s (m + k).succ (fs (m + k)).1 (fs (m + k)).2.1).2.1 m (nat.lt_succ_iff.2 (nat.add_le_add_left k.zero_le m)))], refl }, refine ⟨λ n, (fs n).1 n, ⟨set.range_subset_iff.2 (λ n, ((fs n).2).1.1 (mem_range_self n)), λ m n mn, _⟩, λ n g hg1 hg2, _⟩, { dsimp, rw [← subtype.val_eq_coe, h m n (le_of_lt mn)], convert (fs n).2.1.2 m n mn }, { convert (fs n).2.2 g (λ m mn, eq.trans _ (hg1 m mn)) (lt_of_lt_of_le hg2 (le_refl _)), rw ← h m n (le_of_lt mn) }, end lemma iff_not_exists_is_min_bad_seq {r : α → α → Prop} (rk : α → ℕ) {s : set α} : s.partially_well_ordered_on r ↔ ¬ ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f := begin rw [iff_forall_not_is_bad_seq, ← not_exists, not_congr], split, { apply exists_min_bad_of_exists_bad }, rintro ⟨f, hf1, hf2⟩, exact ⟨f, hf1⟩, end /-- Higman's Lemma, which states that for any reflexive, transitive relation `r` which is partially well-ordered on a set `s`, the relation `list.sublist_forall₂ r` is partially well-ordered on the set of lists of elements of `s`. That relation is defined so that `list.sublist_forall₂ r l₁ l₂` whenever `l₁` related pointwise by `r` to a sublist of `l₂`. -/ lemma partially_well_ordered_on_sublist_forall₂ (r : α → α → Prop) [is_refl α r] [is_trans α r] {s : set α} (h : s.partially_well_ordered_on r) : { l : list α | ∀ x, x ∈ l → x ∈ s }.partially_well_ordered_on (list.sublist_forall₂ r) := begin rcases s.eq_empty_or_nonempty with rfl | ⟨as, has⟩, { apply partially_well_ordered_on.mono (finset.partially_well_ordered_on {list.nil}), { intros l hl, rw [finset.mem_coe, finset.mem_singleton, list.eq_nil_iff_forall_not_mem], exact hl, }, apply_instance }, haveI : inhabited α := ⟨as⟩, rw [iff_not_exists_is_min_bad_seq (list.length)], rintro ⟨f, hf1, hf2⟩, have hnil : ∀ n, f n ≠ list.nil := λ n con, (hf1).2 n n.succ n.lt_succ_self (con.symm ▸ list.sublist_forall₂.nil), obtain ⟨g, hg⟩ := h.exists_monotone_subseq (list.head ∘ f) _, swap, { simp only [set.range_subset_iff, function.comp_apply], exact λ n, hf1.1 (set.mem_range_self n) _ (list.head_mem_self (hnil n)) }, have hf' := hf2 (g 0) (λ n, if n < g 0 then f n else list.tail (f (g (n - g 0)))) (λ m hm, (if_pos hm).symm) _, swap, { simp only [if_neg (lt_irrefl (g 0)), tsub_self], rw [list.length_tail, ← nat.pred_eq_sub_one], exact nat.pred_lt (λ con, hnil _ (list.length_eq_zero.1 con)) }, rw [is_bad_seq] at hf', push_neg at hf', obtain ⟨m, n, mn, hmn⟩ := hf' _, swap, { rw set.range_subset_iff, rintro n x hx, split_ifs at hx with hn hn, { exact hf1.1 (set.mem_range_self _) _ hx }, { refine hf1.1 (set.mem_range_self _) _ (list.tail_subset _ hx), } }, by_cases hn : n < g 0, { apply hf1.2 m n mn, rwa [if_pos hn, if_pos (mn.trans hn)] at hmn }, { obtain ⟨n', rfl⟩ := le_iff_exists_add.1 (not_lt.1 hn), rw [if_neg hn, add_comm (g 0) n', add_tsub_cancel_right] at hmn, split_ifs at hmn with hm hm, { apply hf1.2 m (g n') (lt_of_lt_of_le hm (g.monotone n'.zero_le)), exact trans hmn (list.tail_sublist_forall₂_self _) }, { rw [← (tsub_lt_iff_left (le_of_not_lt hm))] at mn, apply hf1.2 _ _ (g.lt_iff_lt.2 mn), rw [← list.cons_head_tail (hnil (g (m - g 0))), ← list.cons_head_tail (hnil (g n'))], exact list.sublist_forall₂.cons (hg _ _ (le_of_lt mn)) hmn, } } end end partially_well_ordered_on namespace is_pwo @[to_additive] lemma submonoid_closure [ordered_cancel_comm_monoid α] {s : set α} (hpos : ∀ x : α, x ∈ s → 1 ≤ x) (h : s.is_pwo) : is_pwo ((submonoid.closure s) : set α) := begin have hl : ((submonoid.closure s) : set α) ⊆ list.prod '' { l : list α | ∀ x, x ∈ l → x ∈ s }, { intros x hx, rw set_like.mem_coe at hx, refine submonoid.closure_induction hx (λ x hx, ⟨_, λ y hy, _, list.prod_singleton⟩) ⟨_, λ y hy, (list.not_mem_nil _ hy).elim, list.prod_nil⟩ _, { rwa list.mem_singleton.1 hy }, rintros _ _ ⟨l, hl, rfl⟩ ⟨l', hl', rfl⟩, refine ⟨_, λ y hy, _, list.prod_append⟩, cases list.mem_append.1 hy with hy hy, { exact hl _ hy }, { exact hl' _ hy } }, apply ((h.partially_well_ordered_on_sublist_forall₂ (≤)).image_of_monotone_on _).mono hl, intros l1 l2 hl1 hl2 h12, obtain ⟨l, hll1, hll2⟩ := list.sublist_forall₂_iff.1 h12, refine le_trans (list.rel_prod (le_refl 1) (λ a b ab c d cd, mul_le_mul' ab cd) hll1) _, obtain ⟨l', hl'⟩ := hll2.exists_perm_append, rw [hl'.prod_eq, list.prod_append, ← mul_one l.prod, mul_assoc, one_mul], apply mul_le_mul_left', have hl's := λ x hx, hl2 x (list.subset.trans (l.subset_append_right _) hl'.symm.subset hx), clear hl', induction l' with x1 x2 x3 x4 x5, { refl }, rw [list.prod_cons, ← one_mul (1 : α)], exact mul_le_mul' (hpos x1 (hl's x1 (list.mem_cons_self x1 x2))) (x3 (λ x hx, hl's x (list.mem_cons_of_mem _ hx))) end end is_pwo /-- `set.mul_antidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that multiply to `a`. -/ @[to_additive "`set.add_antidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that add to `a`."] def mul_antidiagonal [monoid α] (s t : set α) (a : α) : set (α × α) := { x | x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t } namespace mul_antidiagonal @[simp, to_additive] lemma mem_mul_antidiagonal [monoid α] {s t : set α} {a : α} {x : α × α} : x ∈ mul_antidiagonal s t a ↔ x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t := iff.refl _ section cancel_comm_monoid variables [cancel_comm_monoid α] {s t : set α} {a : α} @[to_additive] lemma fst_eq_fst_iff_snd_eq_snd {x y : (mul_antidiagonal s t a)} : (x : α × α).fst = (y : α × α).fst ↔ (x : α × α).snd = (y : α × α).snd := ⟨λ h, begin have hx := x.2.1, rw [subtype.val_eq_coe, h] at hx, apply mul_left_cancel (hx.trans y.2.1.symm), end, λ h, begin have hx := x.2.1, rw [subtype.val_eq_coe, h] at hx, apply mul_right_cancel (hx.trans y.2.1.symm), end⟩ @[to_additive] lemma eq_of_fst_eq_fst {x y : (mul_antidiagonal s t a)} (h : (x : α × α).fst = (y : α × α).fst) : x = y := subtype.ext (prod.ext h (mul_antidiagonal.fst_eq_fst_iff_snd_eq_snd.1 h)) @[to_additive] lemma eq_of_snd_eq_snd {x y : (mul_antidiagonal s t a)} (h : (x : α × α).snd = (y : α × α).snd) : x = y := subtype.ext (prod.ext (mul_antidiagonal.fst_eq_fst_iff_snd_eq_snd.2 h) h) end cancel_comm_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] (s t : set α) (a : α) @[to_additive] lemma eq_of_fst_le_fst_of_snd_le_snd {x y : (mul_antidiagonal s t a)} (h1 : (x : α × α).fst ≤ (y : α × α).fst) (h2 : (x : α × α).snd ≤ (y : α × α).snd ) : x = y := begin apply eq_of_fst_eq_fst, cases eq_or_lt_of_le h1 with heq hlt, { exact heq }, exfalso, exact ne_of_lt (mul_lt_mul_of_lt_of_le hlt h2) ((mem_mul_antidiagonal.1 x.2).1.trans (mem_mul_antidiagonal.1 y.2).1.symm) end variables {s} {t} @[to_additive] theorem finite_of_is_pwo (hs : s.is_pwo) (ht : t.is_pwo) (a) : (mul_antidiagonal s t a).finite := begin by_contra h, rw [← set.infinite] at h, have h1 : (mul_antidiagonal s t a).partially_well_ordered_on (prod.fst ⁻¹'o (≤)), { intros f hf, refine hs (prod.fst ∘ f) _, rw range_comp, rintros _ ⟨⟨x, y⟩, hxy, rfl⟩, exact (mem_mul_antidiagonal.1 (hf hxy)).2.1 }, have h2 : (mul_antidiagonal s t a).partially_well_ordered_on (prod.snd ⁻¹'o (≤)), { intros f hf, refine ht (prod.snd ∘ f) _, rw range_comp, rintros _ ⟨⟨x, y⟩, hxy, rfl⟩, exact (mem_mul_antidiagonal.1 (hf hxy)).2.2 }, obtain ⟨g, hg⟩ := h1.exists_monotone_subseq (λ x, h.nat_embedding _ x) _, swap, { rintro _ ⟨k, rfl⟩, exact ((infinite.nat_embedding (s.mul_antidiagonal t a) h) _).2 }, obtain ⟨m, n, mn, h2'⟩ := h2 (λ x, (h.nat_embedding _) (g x)) _, swap, { rintro _ ⟨k, rfl⟩, exact ((infinite.nat_embedding (s.mul_antidiagonal t a) h) _).2, }, apply ne_of_lt mn (g.injective ((h.nat_embedding _).injective _)), exact eq_of_fst_le_fst_of_snd_le_snd _ _ _ (hg _ _ (le_of_lt mn)) h2', end end ordered_cancel_comm_monoid @[to_additive] theorem finite_of_is_wf [linear_ordered_cancel_comm_monoid α] {s t : set α} (hs : s.is_wf) (ht : t.is_wf) (a) : (mul_antidiagonal s t a).finite := finite_of_is_pwo hs.is_pwo ht.is_pwo a end mul_antidiagonal end set namespace finset variables [ordered_cancel_comm_monoid α] variables {s t : set α} (hs : s.is_pwo) (ht : t.is_pwo) (a : α) /-- `finset.mul_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in `s` and an element in `t` that multiply to `a`, but its construction requires proofs `hs` and `ht` that `s` and `t` are well-ordered. -/ @[to_additive "`finset.add_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in `s` and an element in `t` that add to `a`, but its construction requires proofs `hs` and `ht` that `s` and `t` are well-ordered."] noncomputable def mul_antidiagonal : finset (α × α) := (set.mul_antidiagonal.finite_of_is_pwo hs ht a).to_finset variables {hs} {ht} {u : set α} {hu : u.is_pwo} {a} {x : α × α} @[simp, to_additive] lemma mem_mul_antidiagonal : x ∈ mul_antidiagonal hs ht a ↔ x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t := by simp [mul_antidiagonal] @[to_additive] lemma mul_antidiagonal_mono_left (hus : u ⊆ s) : (finset.mul_antidiagonal hu ht a) ⊆ (finset.mul_antidiagonal hs ht a) := λ x hx, begin rw mem_mul_antidiagonal at *, exact ⟨hx.1, hus hx.2.1, hx.2.2⟩, end @[to_additive] lemma mul_antidiagonal_mono_right (hut : u ⊆ t) : (finset.mul_antidiagonal hs hu a) ⊆ (finset.mul_antidiagonal hs ht a) := λ x hx, begin rw mem_mul_antidiagonal at *, exact ⟨hx.1, hx.2.1, hut hx.2.2⟩, end @[to_additive] lemma support_mul_antidiagonal_subset_mul : { a : α | (mul_antidiagonal hs ht a).nonempty } ⊆ s * t := (λ x ⟨⟨a1, a2⟩, ha⟩, begin obtain ⟨hmul, h1, h2⟩ := mem_mul_antidiagonal.1 ha, exact ⟨a1, a2, h1, h2, hmul⟩, end) @[to_additive] theorem is_pwo_support_mul_antidiagonal : { a : α | (mul_antidiagonal hs ht a).nonempty }.is_pwo := (hs.mul ht).mono support_mul_antidiagonal_subset_mul @[to_additive] theorem mul_antidiagonal_min_mul_min {α} [linear_ordered_cancel_comm_monoid α] {s t : set α} (hs : s.is_wf) (ht : t.is_wf) (hns : s.nonempty) (hnt : t.nonempty) : mul_antidiagonal hs.is_pwo ht.is_pwo ((hs.min hns) * (ht.min hnt)) = {(hs.min hns, ht.min hnt)} := begin ext ⟨a1, a2⟩, rw [mem_mul_antidiagonal, finset.mem_singleton, prod.ext_iff], split, { rintro ⟨hast, has, hat⟩, cases eq_or_lt_of_le (hs.min_le hns has) with heq hlt, { refine ⟨heq.symm, _⟩, rw heq at hast, exact mul_left_cancel hast }, { contrapose hast, exact ne_of_gt (mul_lt_mul_of_lt_of_le hlt (ht.min_le hnt hat)) } }, { rintro ⟨ha1, ha2⟩, rw [ha1, ha2], exact ⟨rfl, hs.min_mem _, ht.min_mem _⟩ } end end finset lemma well_founded.is_wf [has_lt α] (h : well_founded ((<) : α → α → Prop)) (s : set α) : s.is_wf := (set.is_wf_univ_iff.2 h).mono (set.subset_univ s)
7deaabc7c901671ebd25970e2f8b0c1783534bca
367134ba5a65885e863bdc4507601606690974c1
/src/group_theory/free_abelian_group.lean
bf2d83094ea27a9d776e6f7bebb008961be219c9
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
18,851
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.group.pi import group_theory.free_group import group_theory.abelianization import algebra.module.basic -- we use the ℤ-module structure on an add_comm_group in punit_equiv /-! # Free abelian groups The free abelian group on a type `α`, defined as the abelianisation of the free group on `α`. The free abelian group on `α` can be abstractly defined as the left adjoint of the forgetful functor from abelian groups to types. Alternatively, one could define it as the functions `α → ℤ` which send all but finitely many `(a : α)` to `0`, under pointwise addition. In this file, it is defined as the abelianisation of the free group on `α`. All the constructions and theorems required to show the adjointness of the construction and the forgetful functor are proved in this file, but the category-theoretic adjunction statement is in `algebra.category.Group.adjunctions` . ## Main definitions Here we use the following variables: `(α β : Type*) (A : Type*) [add_comm_group A]` * `free_abelian_group α` : the free abelian group on a type `α`. As an abelian group it is `α →₀ ℤ`, the functions from `α` to `ℤ` such that all but finitely many elements get mapped to zero, however this is not how it is implemented. * `lift f : free_abelian_group α →+ A` : the group homomorphism induced by the map `f : α → A`. * `map (f : α → β) : free_abelian_group α →+ free_abelian_group β` : functoriality of `free_abelian_group` * `instance [monoid α] : semigroup (free_abelian_group α)` * `instance [comm_monoid α] : comm_ring (free_abelian_group α)` It has been suggested that we would be better off refactoring this file and using `finsupp` instead. ## Implementation issues The definition is `def free_abelian_group : Type u := additive $ abelianization $ free_group α` Chris Hughes has suggested that this all be rewritten in terms of `finsupp`. Johan Commelin has written all the API relating the definition to `finsupp` in the lean-liquid repo. The lemmas `map_pure`, `map_of`, `map_zero`, `map_add`, `map_neg` and `map_sub` are proved about the `functor.map` `<$>` construction, and need `α` and `β` to be in the same universe. But `free_abelian_group.map (f : α → β)` is defined to be the `add_group` homomorphism `free_abelian_group α →+ free_abelian_group β` (with `α` and `β` now allowed to be in different universes), so `(map f).map_add` etc can be used to prove that `free_abelian_group.map` preserves addition. The functions `map_id`, `map_id_apply`, `map_comp`, `map_comp_apply` and `map_of_apply` are about `free_abelian_group.map`. -/ universes u v variables (α : Type u) /-- The free abelian group on a type. -/ def free_abelian_group : Type u := additive $ abelianization $ free_group α instance : add_comm_group (free_abelian_group α) := @additive.add_comm_group _ $ abelianization.comm_group _ instance : inhabited (free_abelian_group α) := ⟨0⟩ variable {α} namespace free_abelian_group /-- The canonical map from α to `free_abelian_group α` -/ def of (x : α) : free_abelian_group α := abelianization.of $ free_group.of x /-- The map `free_abelian_group α →+ A` induced by a map of types `α → A`. -/ def lift {β : Type v} [add_comm_group β] : (α → β) ≃ (free_abelian_group α →+ β) := (@free_group.lift _ (multiplicative β) _).trans $ (@abelianization.lift _ _ (multiplicative β) _).trans monoid_hom.to_additive namespace lift variables {β : Type v} [add_comm_group β] (f : α → β) open free_abelian_group @[simp] protected lemma of (x : α) : lift f (of x) = f x := begin convert @abelianization.lift.of (free_group α) _ (multiplicative β) _ _ _, convert free_group.lift.of.symm end protected theorem unique (g : free_abelian_group α →+ β) (hg : ∀ x, g (of x) = f x) {x} : g x = lift f x := add_monoid_hom.congr_fun ((lift.symm_apply_eq).mp (funext hg : g ∘ of = f)) _ /-- See note [partially-applied ext lemmas]. -/ @[ext] protected theorem ext (g h : free_abelian_group α →+ β) (H : ∀ x, g (of x) = h (of x)) : g = h := lift.symm.injective $ funext H lemma map_hom {α β γ} [add_comm_group β] [add_comm_group γ] (a : free_abelian_group α) (f : α → β) (g : β →+ γ) : g (lift f a) = lift (g ∘ f) a := begin suffices : (g.comp (lift f)) a = lift (g ∘ f) a, exact this, apply @lift.unique, assume a, show g ((lift f) (of a)) = g (f a), simp only [(∘), lift.of], end end lift section open_locale classical lemma of_injective : function.injective (of : α → free_abelian_group α) := λ x y hoxy, classical.by_contradiction $ assume hxy : x ≠ y, let f : free_abelian_group α →+ ℤ := lift (λ z, if x = z then (1 : ℤ) else 0) in have hfx1 : f (of x) = 1, from (lift.of _ _).trans $ if_pos rfl, have hfy1 : f (of y) = 1, from hoxy ▸ hfx1, have hfy0 : f (of y) = 0, from (lift.of _ _).trans $ if_neg hxy, one_ne_zero $ hfy1.symm.trans hfy0 end local attribute [instance] quotient_group.left_rel @[elab_as_eliminator] protected theorem induction_on {C : free_abelian_group α → Prop} (z : free_abelian_group α) (C0 : C 0) (C1 : ∀ x, C $ of x) (Cn : ∀ x, C (of x) → C (-of x)) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := quotient.induction_on' z $ λ x, quot.induction_on x $ λ L, list.rec_on L C0 $ λ ⟨x, b⟩ tl ih, bool.rec_on b (Cp _ _ (Cn _ (C1 x)) ih) (Cp _ _ (C1 x) ih) theorem lift.add' {α β} [add_comm_group β] (a : free_abelian_group α) (f g : α → β) : lift (f + g) a = lift f a + lift g a := begin refine free_abelian_group.induction_on a _ _ _ _, { simp only [(lift _).map_zero, zero_add] }, { assume x, simp only [lift.of, pi.add_apply] }, { assume x h, simp only [(lift _).map_neg, lift.of, pi.add_apply, neg_add] }, { assume x y hx hy, simp only [(lift _).map_add, hx, hy], ac_refl } end instance is_add_group_hom_lift' {α} (β) [add_comm_group β] (a : free_abelian_group α) : is_add_group_hom (λf, (lift f a : β)) := { map_add := λ f g, lift.add' a f g } section monad variables {β : Type u} instance : monad free_abelian_group.{u} := { pure := λ α, of, bind := λ α β x f, lift f x } @[elab_as_eliminator] protected theorem induction_on' {C : free_abelian_group α → Prop} (z : free_abelian_group α) (C0 : C 0) (C1 : ∀ x, C $ pure x) (Cn : ∀ x, C (pure x) → C (-pure x)) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := free_abelian_group.induction_on z C0 C1 Cn Cp @[simp] lemma map_pure (f : α → β) (x : α) : f <$> (pure x : free_abelian_group α) = pure (f x) := rfl @[simp] lemma map_zero (f : α → β) : f <$> (0 : free_abelian_group α) = 0 := (lift (of ∘ f)).map_zero @[simp] lemma map_add (f : α → β) (x y : free_abelian_group α) : f <$> (x + y) = f <$> x + f <$> y := (lift _).map_add _ _ @[simp] lemma map_neg (f : α → β) (x : free_abelian_group α) : f <$> (-x) = -(f <$> x) := (lift _).map_neg _ @[simp] lemma map_sub (f : α → β) (x y : free_abelian_group α) : f <$> (x - y) = f <$> x - f <$> y := (lift _).map_sub _ _ @[simp] lemma map_of (f : α → β) (y : α) : f <$> of y = of (f y) := rfl @[simp] lemma pure_bind (f : α → free_abelian_group β) (x) : pure x >>= f = f x := lift.of _ _ @[simp] lemma zero_bind (f : α → free_abelian_group β) : 0 >>= f = 0 := (lift f).map_zero @[simp] lemma add_bind (f : α → free_abelian_group β) (x y : free_abelian_group α) : x + y >>= f = (x >>= f) + (y >>= f) := (lift _).map_add _ _ @[simp] lemma neg_bind (f : α → free_abelian_group β) (x : free_abelian_group α) : -x >>= f = -(x >>= f) := (lift _).map_neg _ @[simp] lemma sub_bind (f : α → free_abelian_group β) (x y : free_abelian_group α) : x - y >>= f = (x >>= f) - (y >>= f) := (lift _).map_sub _ _ @[simp] lemma pure_seq (f : α → β) (x : free_abelian_group α) : pure f <*> x = f <$> x := pure_bind _ _ @[simp] lemma zero_seq (x : free_abelian_group α) : (0 : free_abelian_group (α → β)) <*> x = 0 := zero_bind _ @[simp] lemma add_seq (f g : free_abelian_group (α → β)) (x : free_abelian_group α) : f + g <*> x = (f <*> x) + (g <*> x) := add_bind _ _ _ @[simp] lemma neg_seq (f : free_abelian_group (α → β)) (x : free_abelian_group α) : -f <*> x = -(f <*> x) := neg_bind _ _ @[simp] lemma sub_seq (f g : free_abelian_group (α → β)) (x : free_abelian_group α) : f - g <*> x = (f <*> x) - (g <*> x) := sub_bind _ _ _ instance is_add_group_hom_seq (f : free_abelian_group (α → β)) : is_add_group_hom ((<*>) f) := { map_add := λ x y, show lift (<$> (x+y)) _ = _, by simp only [map_add]; exact @@is_add_hom.map_add _ _ _ (@@free_abelian_group.is_add_group_hom_lift' (free_abelian_group β) _ _).to_is_add_hom _ _ } @[simp] lemma seq_zero (f : free_abelian_group (α → β)) : f <*> 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma seq_add (f : free_abelian_group (α → β)) (x y : free_abelian_group α) : f <*> (x + y) = (f <*> x) + (f <*> y) := is_add_hom.map_add _ _ _ @[simp] lemma seq_neg (f : free_abelian_group (α → β)) (x : free_abelian_group α) : f <*> (-x) = -(f <*> x) := is_add_group_hom.map_neg _ _ @[simp] lemma seq_sub (f : free_abelian_group (α → β)) (x y : free_abelian_group α) : f <*> (x - y) = (f <*> x) - (f <*> y) := is_add_group_hom.map_sub _ _ _ instance : is_lawful_monad free_abelian_group.{u} := { id_map := λ α x, free_abelian_group.induction_on' x (map_zero id) (λ x, map_pure id x) (λ x ih, by rw [map_neg, ih]) (λ x y ihx ihy, by rw [map_add, ihx, ihy]), pure_bind := λ α β x f, pure_bind f x, bind_assoc := λ α β γ x f g, free_abelian_group.induction_on' x (by iterate 3 { rw zero_bind }) (λ x, by iterate 2 { rw pure_bind }) (λ x ih, by iterate 3 { rw neg_bind }; rw ih) (λ x y ihx ihy, by iterate 3 { rw add_bind }; rw [ihx, ihy]) } instance : is_comm_applicative free_abelian_group.{u} := { commutative_prod := λ α β x y, free_abelian_group.induction_on' x (by rw [map_zero, zero_seq, seq_zero]) (λ p, by rw [map_pure, pure_seq]; exact free_abelian_group.induction_on' y (by rw [map_zero, map_zero, zero_seq]) (λ q, by rw [map_pure, map_pure, pure_seq, map_pure]) (λ q ih, by rw [map_neg, map_neg, neg_seq, ih]) (λ y₁ y₂ ih1 ih2, by rw [map_add, map_add, add_seq, ih1, ih2])) (λ p ih, by rw [map_neg, neg_seq, seq_neg, ih]) (λ x₁ x₂ ih1 ih2, by rw [map_add, add_seq, seq_add, ih1, ih2]) } end monad universe w variables {β : Type v} {γ : Type w} /-- The additive group homomorphism `free_abelian_group α →+ free_abelian_group β` induced from a map `α → β` -/ def map (f : α → β) : free_abelian_group α →+ free_abelian_group β := lift (of ∘ f) lemma lift_comp {α} {β} {γ} [add_comm_group γ] (f : α → β) (g : β → γ) (x : free_abelian_group α) : lift (g ∘ f) x = lift g (map f x) := begin apply free_abelian_group.induction_on x, { exact add_monoid_hom.map_zero _ }, { intro y, refl }, { intros x h, simp only [h, add_monoid_hom.map_neg] }, { intros x y h₁ h₂, simp only [h₁, h₂, add_monoid_hom.map_add] } end lemma map_id : map id = add_monoid_hom.id (free_abelian_group α) := eq.symm $ lift.ext _ _ $ λ x, lift.unique of (add_monoid_hom.id _) $ λ y, add_monoid_hom.id_apply _ lemma map_id_apply (x : free_abelian_group α) : map id x = x := by {rw map_id, refl } lemma map_comp {f : α → β} {g : β → γ} : map (g ∘ f) = (map g).comp (map f) := eq.symm $ lift.ext _ _ $ λ x, eq.symm $ lift_comp _ _ _ lemma map_comp_apply {f : α → β} {g : β → γ} (x : free_abelian_group α) : map (g ∘ f) x = (map g) ((map f) x) := by { rw map_comp, refl } -- version of map_of which uses `map` lemma map_of_apply {f : α → β} (a : α) : map f (of a) = of (f a) := rfl variable (α) section monoid variables {R : Type*} [monoid α] [ring R] instance : semigroup (free_abelian_group α) := { mul := λ x, lift $ λ x₂, lift (λ x₁, of $ x₁ * x₂) x, mul_assoc := λ x y z, begin unfold has_mul.mul, refine free_abelian_group.induction_on z (by simp) _ _ _, { intros L3, rw [lift.of, lift.of], refine free_abelian_group.induction_on y (by simp) _ _ _, { intros L2, iterate 3 { rw lift.of }, refine free_abelian_group.induction_on x (by simp) _ _ _, { intros L1, iterate 3 { rw lift.of }, congr' 1, exact mul_assoc _ _ _ }, { intros L1 ih, iterate 3 { rw (lift _).map_neg }, rw ih }, { intros x1 x2 ih1 ih2, iterate 3 { rw (lift _).map_add }, rw [ih1, ih2] } }, { intros L2 ih, iterate 4 { rw (lift _).map_neg }, rw ih }, { intros y1 y2 ih1 ih2, iterate 4 { rw (lift _).map_add }, rw [ih1, ih2] } }, { intros L3 ih, iterate 3 { rw (lift _).map_neg }, rw ih }, { intros z1 z2 ih1 ih2, iterate 2 { rw (lift _).map_add }, rw [ih1, ih2], exact ((lift _).map_add _ _).symm } end } variable {α} lemma mul_def (x y : free_abelian_group α) : x * y = lift (λ x₂, lift (λ x₁, of (x₁ * x₂)) x) y := rfl lemma of_mul_of (x y : α) : of x * of y = of (x * y) := rfl lemma of_mul (x y : α) : of (x * y) = of x * of y := rfl variable (α) instance : ring (free_abelian_group α) := { one := free_abelian_group.of 1, mul_one := λ x, begin unfold has_mul.mul semigroup.mul has_one.one, rw lift.of, refine free_abelian_group.induction_on x rfl _ _ _, { intros L, erw [lift.of], congr' 1, exact mul_one L }, { intros L ih, rw [(lift _).map_neg, ih] }, { intros x1 x2 ih1 ih2, rw [(lift _).map_add, ih1, ih2] } end, one_mul := λ x, begin unfold has_mul.mul semigroup.mul has_one.one, refine free_abelian_group.induction_on x rfl _ _ _, { intros L, rw [lift.of, lift.of], congr' 1, exact one_mul L }, { intros L ih, rw [(lift _).map_neg, ih] }, { intros x1 x2 ih1 ih2, rw [(lift _).map_add, ih1, ih2] } end, left_distrib := λ x y z, (lift _).map_add _ _, right_distrib := λ x y z, begin unfold has_mul.mul semigroup.mul, refine free_abelian_group.induction_on z rfl _ _ _, { intros L, iterate 3 { rw lift.of }, rw (lift _).map_add, refl }, { intros L ih, iterate 3 { rw (lift _).map_neg }, rw [ih, neg_add], refl }, { intros z1 z2 ih1 ih2, iterate 3 { rw (lift _).map_add }, rw [ih1, ih2], rw [add_assoc, add_assoc], congr' 1, apply add_left_comm } end, .. free_abelian_group.add_comm_group α, .. free_abelian_group.semigroup α } variable {α} /-- `free_abelian_group.of` is a `monoid_hom` when `α` is a `monoid`. -/ def of_mul_hom : α →* free_abelian_group α := { to_fun := of, map_one' := rfl, map_mul' := of_mul } @[simp] lemma of_mul_hom_coe : (of_mul_hom : α → free_abelian_group α) = of := rfl /-- If `f` preserves multiplication, then so does `lift f`. -/ def lift_monoid : (α →* R) ≃ (free_abelian_group α →+* R) := { to_fun := λ f, { map_one' := (lift.of f _).trans f.map_one, map_mul' := λ x y, begin simp only [add_monoid_hom.to_fun_eq_coe], refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _, { intros L2, rw mul_def x, simp only [lift.of], refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _, { intros L1, iterate 3 { rw lift.of }, exact f.map_mul _ _ }, { intros L1 ih, iterate 3 { rw (lift _).map_neg }, rw [ih, neg_mul_eq_neg_mul] }, { intros x1 x2 ih1 ih2, iterate 3 { rw (lift _).map_add }, rw [ih1, ih2, add_mul] } }, { intros L2 ih, rw [mul_neg_eq_neg_mul_symm, add_monoid_hom.map_neg, add_monoid_hom.map_neg, mul_neg_eq_neg_mul_symm, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, add_monoid_hom.map_add, add_monoid_hom.map_add, mul_add, ih1, ih2] }, end, .. lift f }, inv_fun := λ F, monoid_hom.comp ↑F of_mul_hom, left_inv := λ f, monoid_hom.ext $ lift.of _, right_inv := λ F, ring_hom.coe_add_monoid_hom_injective $ lift.apply_symm_apply (↑F : free_abelian_group α →+ R) } @[simp] lemma lift_monoid_coe_add_monoid_hom (f : α →* R) : ↑(lift_monoid f) = lift f := rfl @[simp] lemma lift_monoid_coe (f : α →* R) : ⇑(lift_monoid f) = lift f := rfl @[simp] lemma lift_monoid_symm_coe (f : free_abelian_group α →+* R) : ⇑(lift_monoid.symm f) = lift.symm ↑f := rfl lemma one_def : (1 : free_abelian_group α) = of 1 := rfl lemma of_one : (of 1 : free_abelian_group α) = 1 := rfl end monoid instance [comm_monoid α] : comm_ring (free_abelian_group α) := { mul_comm := λ x y, begin refine free_abelian_group.induction_on x (zero_mul y) _ _ _, { intros s, refine free_abelian_group.induction_on y (zero_mul _).symm _ _ _, { intros t, unfold has_mul.mul semigroup.mul ring.mul, iterate 4 { rw lift.of }, congr' 1, exact mul_comm _ _ }, { intros t ih, rw [mul_neg_eq_neg_mul_symm, ih, neg_mul_eq_neg_mul] }, { intros y1 y2 ih1 ih2, rw [mul_add, add_mul, ih1, ih2] } }, { intros s ih, rw [neg_mul_eq_neg_mul_symm, ih, neg_mul_eq_mul_neg] }, { intros x1 x2 ih1 ih2, rw [add_mul, mul_add, ih1, ih2] } end, .. free_abelian_group.ring α } instance pempty_unique : unique (free_abelian_group pempty) := { default := 0, uniq := λ x, free_abelian_group.induction_on x rfl (λ x, pempty.elim x) (λ x, pempty.elim x) (by { rintros - - rfl rfl, simp }) } /-- The free abelian group on a type with one term is isomorphic to `ℤ`. -/ def punit_equiv (T : Type*) [unique T] : free_abelian_group T ≃+ ℤ := { to_fun := free_abelian_group.lift (λ _, (1 : ℤ)), inv_fun := λ n, n • of (inhabited.default T), left_inv := λ z, free_abelian_group.induction_on z (by simp only [zero_smul, add_monoid_hom.map_zero]) (unique.forall_iff.2 $ by simp only [one_smul, lift.of]) (unique.forall_iff.2 $ by simp) (λ x y hx hy, by { simp only [add_monoid_hom.map_add, add_smul] at *, rw [hx, hy]}), right_inv := λ n, begin rw [add_monoid_hom.map_int_module_smul, lift.of], exact gsmul_int_one n end, map_add' := add_monoid_hom.map_add _ } /-- Isomorphic types have isomorphic free abelian groups. -/ def equiv_of_equiv {α β : Type*} (f : α ≃ β) : free_abelian_group α ≃+ free_abelian_group β := { to_fun := map f, inv_fun := map f.symm, left_inv := begin intros x, rw [← map_comp_apply, equiv.symm_comp_self, map_id], refl, end, right_inv := begin intros x, rw [← map_comp_apply, equiv.self_comp_symm, map_id], refl, end, map_add' := add_monoid_hom.map_add _ } end free_abelian_group
3575c1f4503f84cbdd7d9dcdd05ea2b8b51658fe
ecad13897fdb44984cf1968424224d1750040236
/lean/lean/examples/example06.lean
d751a25dbd52ff38d5194e9910520db5078f9bec
[]
no_license
MetaBorgCube/sdf3-demo
4899159b1cfb0a95ae3af325035bbba8a1255477
e831606d5b404eba75b087916a1162923143b98a
refs/heads/master
1,609,472,086,310
1,553,380,857,000
1,553,380,857,000
59,577,395
0
0
null
null
null
null
UTF-8
Lean
false
false
27
lean
(a : b)(c : d)(e : f) -> e
5a7317953dfd0ec5839dd90254c17edb1b9f2bfc
3bdd27ffdff3ffa22d4bb010eba695afcc96bc4a
/src/combinatorics/simplicial_complex/pyramid.lean
5297f833e7892e221b0be2ed83ea6b8afbaf94b5
[]
no_license
mmasdeu/brouwerfixedpoint
684d712c982c6a8b258b4e2c6b2eab923f2f1289
548270f79ecf12d7e20a256806ccb9fcf57b87e2
refs/heads/main
1,690,539,793,996
1,631,801,831,000
1,631,801,831,000
368,139,809
4
3
null
1,624,453,250,000
1,621,246,034,000
Lean
UTF-8
Lean
false
false
2,495
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import combinatorics.simplicial_complex.pure import combinatorics.simplicial_complex.subdivision namespace affine open_locale classical affine big_operators open set variables {n : ℕ} {E : Type*} [normed_group E] [normed_space ℝ E] {S S₁ S₂ : simplicial_complex E} {v : E} /-- The pyramid of a vertex v with respect to a simplicial complex S is the surcomplex consisting of all faces of S along with all faces of S with v added. Defined to be S itself if some face of S is already full dimensional or if v belongs to the convex hull of the space of X. -/ noncomputable def simplicial_complex.pyramid (S : simplicial_complex E) (v : E) : simplicial_complex E := if v ∈ convex_hull S.space ∨ ∃ X ∈ S.faces, (X : finset E).card = finite_dimensional.finrank ℝ E + 1 then S else { faces := {X' | ∃ X ∈ S.faces, X' ⊆ X ∪ {v}}, indep := begin rintro X' ⟨X, hX, hX'X⟩, sorry end, down_closed := λ X' Y ⟨X, hX, hX'X⟩ hYX', ⟨X, hX, subset.trans hYX' hX'X⟩, disjoint := begin rintro X' Y' ⟨X, hX, hX'X⟩ ⟨Y, hY, hY'Y⟩, sorry end } lemma subcomplex_pyramid : S.faces ⊆ (S.pyramid v).faces := begin by_cases v ∈ convex_hull S.space ∨ ∃ X ∈ S.faces, (X : finset E).card = finite_dimensional.finrank ℝ E + 1, { sorry }, sorry --exact λ X hX, ⟨X, hX, finset.subset_union_left X {v}⟩ end lemma pyramid_mono (hS : S₁ ≤ S₂) : S₁.pyramid v ≤ S₂.pyramid v := begin by_cases v ∈ convex_hull S₁.space ∨ ∃ X ∈ S₁.faces, (X : finset E).card = finite_dimensional.finrank ℝ E + 1, { sorry --easy case }, split, { sorry }, { sorry /-rintro X ⟨Y, hY, hXYv⟩, obtain ⟨Z, hZ, hYZhull⟩ := h.2 hY, use Z ∪ {v}, split, { exact ⟨Z, hZ, subset.refl _⟩, }, have hXYvhull : convex_hull ↑X ⊆ convex_hull ↑(Y ∪ {v}) := convex_hull_mono hXYv, have hYvZvhull : convex_hull ↑(Y ∪ {v}) ⊆ convex_hull ↑(Z ∪ {v}), { sorry }, exact subset.trans hXYvhull hYvZvhull,-/ } end lemma pure_pyramid_of_pure [finite_dimensional ℝ E] (hn : n ≤ finite_dimensional.finrank ℝ E) (hv : v ∉ convex_hull S.space) (hS : S.pure_of n) : (S.pyramid v).pure_of (n + 1) := begin sorry end end affine
169052e522089d2dc354b317add18e232803bc14
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/preserves/functor_category_auto.lean
1cbb5fdb3dbf45c8f3fca4b47b0c0ef526730702
[]
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,978
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.presheaf import Mathlib.category_theory.limits.functor_category import Mathlib.category_theory.limits.preserves.shapes.binary_products import Mathlib.PostPort universes u₂ v₁ v₂ namespace Mathlib /-! # Preservation of (co)limits in the functor category Show that if `X ⨯ -` preserves colimits in `D` for any `X : D`, then the product functor `F ⨯ -` for `F : C ⥤ D` preserves colimits. The idea of the proof is simply that products and colimits in the functor category are computed pointwise, so pointwise preservation implies general preservation. # References https://ncatlab.org/nlab/show/commutativity+of+limits+and+colimits#preservation_by_functor_categories_and_localizations -/ namespace category_theory /-- If `X × -` preserves colimits in `D` for any `X : D`, then the product functor `F ⨯ -` for `F : C ⥤ D` also preserves colimits. Note this is (mathematically) a special case of the statement that "if limits commute with colimits in `D`, then they do as well in `C ⥤ D`" but the story in Lean is a bit more complex, and this statement isn't directly a special case. That is, even with a formalised proof of the general statement, there would still need to be some work to convert to this version: namely, the natural isomorphism `(evaluation C D).obj k ⋙ prod.functor.obj (F.obj k) ≅ prod.functor.obj F ⋙ (evaluation C D).obj k` -/ def functor_category.prod_preserves_colimits {C : Type v₂} [category C] {D : Type u₂} [category D] [limits.has_binary_products D] [limits.has_colimits D] [(X : D) → limits.preserves_colimits (functor.obj limits.prod.functor X)] (F : C ⥤ D) : limits.preserves_colimits (functor.obj limits.prod.functor F) := sorry end Mathlib
24878253adac556727a2425ff0228ffd33055378
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/category_theory/monad/adjunction.lean
ea24ae9c9ea126c7803beefeb8d94664f297f6ae
[ "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
5,965
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.monad.algebra import category_theory.adjunction namespace category_theory open category universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] variables (L : C ⥤ D) (R : D ⥤ C) namespace adjunction @[simps] instance monad (R : D ⥤ C) [is_right_adjoint R] : monad (left_adjoint R ⋙ R) := { η := (of_right_adjoint R).unit, μ := whisker_right (whisker_left (left_adjoint R) (of_right_adjoint R).counit) R, assoc' := λ X, by { dsimp, rw [←R.map_comp], simp }, right_unit' := λ X, by { dsimp, rw [←R.map_comp], simp } } @[simps] instance comonad (L : C ⥤ D) [is_left_adjoint L] : comonad (right_adjoint L ⋙ L) := { ε := (of_left_adjoint L).counit, δ := whisker_right (whisker_left (right_adjoint L) (of_left_adjoint L).unit) L, coassoc' := λ X, by { dsimp, rw ← L.map_comp, simp }, right_counit' := λ X, by { dsimp, rw ← L.map_comp, simp } } end adjunction namespace monad /-- Gven any adjunction `L ⊣ R`, there is a comparison functor `category_theory.monad.comparison R` sending objects `Y : D` to Eilenberg-Moore algebras for `L ⋙ R` with underlying object `R.obj X`. We later show that this is full when `R` is full, faithful when `R` is faithful, and essentially surjective when `R` is reflective. -/ @[simps] def comparison [is_right_adjoint R] : D ⥤ algebra (left_adjoint R ⋙ R) := { obj := λ X, { A := R.obj X, a := R.map ((adjunction.of_right_adjoint R).counit.app X), assoc' := by { dsimp, rw [← R.map_comp, ← adjunction.counit_naturality, R.map_comp], refl } }, map := λ X Y f, { f := R.map f, h' := by { dsimp, rw [← R.map_comp, adjunction.counit_naturality, R.map_comp] } } }. /-- The underlying object of `(monad.comparison R).obj X` is just `R.obj X`. -/ @[simps] def comparison_forget [is_right_adjoint R] : comparison R ⋙ forget (left_adjoint R ⋙ R) ≅ R := { hom := { app := λ X, 𝟙 _, }, inv := { app := λ X, 𝟙 _, } } end monad namespace comonad /-- Gven any adjunction `L ⊣ R`, there is a comparison functor `category_theory.comonad.comparison L` sending objects `X : C` to Eilenberg-Moore coalgebras for `L ⋙ R` with underlying object `L.obj X`. -/ @[simps] def comparison [is_left_adjoint L] : C ⥤ coalgebra (right_adjoint L ⋙ L) := { obj := λ X, { A := L.obj X, a := L.map ((adjunction.of_left_adjoint L).unit.app X), coassoc' := by { dsimp, rw [← L.map_comp, ← adjunction.unit_naturality, L.map_comp], refl } }, map := λ X Y f, { f := L.map f, h' := by { dsimp, rw ← L.map_comp, simp } } } /-- The underlying object of `(comonad.comparison L).obj X` is just `L.obj X`. -/ @[simps] def comparison_forget [is_left_adjoint L] : comparison L ⋙ forget (right_adjoint L ⋙ L) ≅ L := { hom := { app := λ X, 𝟙 _, }, inv := { app := λ X, 𝟙 _, } } end comonad /-- A right adjoint functor `R : D ⥤ C` is *monadic* if the comparison functor `monad.comparison R` from `D` to the category of Eilenberg-Moore algebras for the adjunction is an equivalence. -/ class monadic_right_adjoint (R : D ⥤ C) extends is_right_adjoint R := (eqv : is_equivalence (monad.comparison R)) /-- A left adjoint functor `L : C ⥤ D` is *comonadic* if the comparison functor `comonad.comparison L` from `C` to the category of Eilenberg-Moore algebras for the adjunction is an equivalence. -/ class comonadic_left_adjoint (L : C ⥤ D) extends is_left_adjoint L := (eqv : is_equivalence (comonad.comparison L)) -- TODO: This holds more generally for idempotent adjunctions, not just reflective adjunctions. instance μ_iso_of_reflective [reflective R] : is_iso (μ_ (left_adjoint R ⋙ R)) := by { dsimp [adjunction.monad], apply_instance } attribute [instance] monadic_right_adjoint.eqv attribute [instance] comonadic_left_adjoint.eqv namespace reflective instance [reflective R] (X : monad.algebra (left_adjoint R ⋙ R)) : is_iso ((adjunction.of_right_adjoint R).unit.app X.A) := { inv := X.a, hom_inv_id' := X.unit, inv_hom_id' := begin dsimp only [functor.id_obj], rw ← (adjunction.of_right_adjoint R).unit_naturality, dsimp only [functor.comp_obj], rw [unit_obj_eq_map_unit, ←functor.map_comp, ←functor.map_comp], erw X.unit, simp, end } instance comparison_ess_surj [reflective R] : ess_surj (monad.comparison R) := begin refine ⟨λ X, ⟨(left_adjoint R).obj X.A, ⟨_⟩⟩⟩, symmetry, refine monad.algebra.iso_mk _ _, { exact as_iso ((adjunction.of_right_adjoint R).unit.app X.A) }, dsimp only [functor.comp_map, monad.comparison_obj_a, as_iso_hom, functor.comp_obj, monad.comparison_obj_A], rw [←cancel_epi ((adjunction.of_right_adjoint R).unit.app X.A), adjunction.unit_naturality_assoc, adjunction.right_triangle_components, comp_id], apply (X.unit_assoc _).symm, end instance comparison_full [full R] [is_right_adjoint R] : full (monad.comparison R) := { preimage := λ X Y f, R.preimage f.f } instance comparison_faithful [faithful R] [is_right_adjoint R] : faithful (monad.comparison R) := { map_injective' := λ X Y f g w, by { have w' := congr_arg monad.algebra.hom.f w, exact R.map_injective w' } } end reflective -- It is possible to do this computably since the construction gives the data of the inverse, not -- just the existence of an inverse on each object. /-- Any reflective inclusion has a monadic right adjoint. cf Prop 5.3.3 of [Riehl][riehl2017] -/ @[priority 100] -- see Note [lower instance priority] noncomputable instance monadic_of_reflective [reflective R] : monadic_right_adjoint R := { eqv := equivalence.equivalence_of_fully_faithfully_ess_surj _ } end category_theory
fd2e8d7b1f8f94fc98c75c5c44546ed06530bb9c
71c05f289da9a856f1d16197a32b6a874eb1052e
/hlean/contr_toys.hlean
e6701d01af8161b2be592b3e4ba2469f23063503
[]
no_license
gbaz/works-in-progress
e7701b1c2f8d0cfb6bfb8d84fc4d21ffd9937521
af7bacd7f68649106a3581c232548958aca79a08
refs/heads/master
1,661,485,946,844
1,659,018,408,000
1,659,018,408,000
32,045,948
14
1
null
null
null
null
UTF-8
Lean
false
false
1,014
hlean
import types.nat types.sigma hit.trunc open nat sigma is_trunc trunc eq prod definition isFive : ℕ -> Type.{0} := λ x, prod (5 ≤ x) (x ≤ 5) definition fiveIsFive : sigma isFive := sigma.mk 5 (prod.mk (le.refl 5) (le.refl 5)) definition isFive.elim {n : ℕ} (x : isFive n) : 5 = n := prod.rec begin intros, exfalso, discard x end x check prod.rec print classes print fields algebra.linear_ordered_semiring /- definition isFive.elim {n : ℕ} (x : isFive n) : 5 = n := prod.rec le.antisymm x definition isFiveIsContr : is_contr (sigma isFive) := is_contr.mk fiveIsFive (λ x, sigma_eq (sigma.rec_on x (λ n p, isFive.elim p)) (sigma.rec_on x (λ n p, pathover_of_tr_eq (prod_eq (is_hprop.elim _ _) (is_hprop.elim _ _))))) definition isFiveIsTr : is_hprop (sigma isFive) := @is_trunc_of_is_contr _ _ (isFiveIsContr) definition isFiveTr : trunc -1 (sigma isFive) := tr fiveIsFive definition elimFromTrunc : ℕ := pr1 (@trunc.elim _ _ _ isFiveIsTr (λ x, x) isFiveTr) eval elimFromTrunc -/
9c6accb0d06bfae07834fa07035e640e3c759c1f
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/data/real/complete.lean
d72b9d9930897e8261a3fa89c0a101129cf2ae9b
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,533
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). At this point, we no longer proceed constructively: this file makes heavy use of decidability, excluded middle, and Hilbert choice. Two sets of definitions of Cauchy sequences, convergence, etc are available in the libray, one with rates and one without. The definitions here, with rates, are amenable to be used constructively if and when that development takes place. The second set of definitions available in /library/theories/analysis/metric_space.lean are the usual classical ones. Here, we show that ℝ is complete. The proofs of Cauchy completeness and the supremum property are independent of each other. -/ import data.real.basic data.real.order data.real.division data.rat data.nat data.pnat open -[coercions] rat local notation 0 := rat.of_num 0 local notation 1 := rat.of_num 1 open -[coercions] nat open eq.ops pnat classical local notation 2 := subtype.tag (nat.of_num 2) dec_trivial local notation 3 := subtype.tag (nat.of_num 3) dec_trivial namespace rat_seq theorem rat_approx {s : seq} (H : regular s) : ∀ n : ℕ+, ∃ q : ℚ, ∃ N : ℕ+, ∀ m : ℕ+, m ≥ N → abs (s m - q) ≤ n⁻¹ := begin intro n, existsi (s (2 * n)), existsi 2 * n, intro m Hm, apply rat.le.trans, apply H, rewrite -(add_halves n), apply rat.add_le_add_right, apply inv_ge_of_le Hm end theorem rat_approx_seq {s : seq} (H : regular s) : ∀ n : ℕ+, ∃ q : ℚ, s_le (s_abs (sadd s (sneg (const q)))) (const n⁻¹) := begin intro m, rewrite ↑s_le, cases rat_approx H m with [q, Hq], cases Hq with [N, HN], existsi q, apply nonneg_of_bdd_within, repeat (apply reg_add_reg | apply reg_neg_reg | apply abs_reg_of_reg | apply const_reg | assumption), intro n, existsi N, intro p Hp, rewrite ↑[sadd, sneg, s_abs, const], apply rat.le.trans, rotate 1, apply rat.sub_le_sub_left, apply HN, apply pnat.le.trans, apply Hp, rewrite -*pnat.mul.assoc, apply pnat.mul_le_mul_left, rewrite [sub_self, -neg_zero], apply neg_le_neg, apply rat.le_of_lt, apply inv_pos end theorem r_rat_approx (s : reg_seq) : ∀ n : ℕ+, ∃ q : ℚ, r_le (r_abs (radd s (rneg (r_const q)))) (r_const n⁻¹) := rat_approx_seq (reg_seq.is_reg s) theorem const_bound {s : seq} (Hs : regular s) (n : ℕ+) : s_le (s_abs (sadd s (sneg (const (s n))))) (const n⁻¹) := begin rewrite ↑[s_le, nonneg, s_abs, sadd, sneg, const], intro m, apply iff.mp !rat.le_add_iff_neg_le_sub_left, apply rat.le.trans, apply Hs, apply rat.add_le_add_right, rewrite -*pnat.mul.assoc, apply inv_ge_of_le, apply pnat.mul_le_mul_left end theorem abs_const (a : ℚ) : const (abs a) ≡ s_abs (const a) := by apply equiv.refl theorem r_abs_const (a : ℚ) : requiv (r_const (abs a) ) (r_abs (r_const a)) := abs_const a theorem equiv_abs_of_ge_zero {s : seq} (Hs : regular s) (Hz : s_le zero s) : s_abs s ≡ s := begin apply eq_of_bdd, apply abs_reg_of_reg Hs, apply Hs, intro j, rewrite ↑s_abs, let Hz' := s_nonneg_of_ge_zero Hs Hz, existsi 2 * j, intro n Hn, cases em (s n ≥ 0) with [Hpos, Hneg], rewrite [rat.abs_of_nonneg Hpos, sub_self, abs_zero], apply rat.le_of_lt, apply inv_pos, let Hneg' := lt_of_not_ge Hneg, have Hsn : -s n - s n > 0, from add_pos (neg_pos_of_neg Hneg') (neg_pos_of_neg Hneg'), rewrite [rat.abs_of_neg Hneg', rat.abs_of_pos Hsn], apply rat.le.trans, apply rat.add_le_add, repeat (apply rat.neg_le_neg; apply Hz'), rewrite *rat.neg_neg, apply rat.le.trans, apply rat.add_le_add, repeat (apply inv_ge_of_le; apply Hn), rewrite pnat.add_halves, apply rat.le.refl end theorem equiv_neg_abs_of_le_zero {s : seq} (Hs : regular s) (Hz : s_le s zero) : s_abs s ≡ sneg s := begin apply eq_of_bdd, apply abs_reg_of_reg Hs, apply reg_neg_reg Hs, intro j, rewrite [↑s_abs, ↑s_le at Hz], have Hz' : nonneg (sneg s), begin apply nonneg_of_nonneg_equiv, rotate 3, apply Hz, rotate 2, apply s_zero_add, repeat (apply Hs | apply zero_is_reg | apply reg_neg_reg | apply reg_add_reg) end, existsi 2 * j, intro n Hn, cases em (s n ≥ 0) with [Hpos, Hneg], have Hsn : s n + s n ≥ 0, from add_nonneg Hpos Hpos, rewrite [rat.abs_of_nonneg Hpos, ↑sneg, rat.sub_neg_eq_add, rat.abs_of_nonneg Hsn], rewrite [↑nonneg at Hz', ↑sneg at Hz'], apply rat.le.trans, apply rat.add_le_add, repeat apply (rat.le_of_neg_le_neg !Hz'), apply rat.le.trans, apply rat.add_le_add, repeat (apply inv_ge_of_le; apply Hn), rewrite pnat.add_halves, apply rat.le.refl, let Hneg' := lt_of_not_ge Hneg, rewrite [rat.abs_of_neg Hneg', ↑sneg, rat.sub_neg_eq_add, rat.neg_add_eq_sub, rat.sub_self, abs_zero], apply rat.le_of_lt, apply inv_pos end theorem r_equiv_abs_of_ge_zero {s : reg_seq} (Hz : r_le r_zero s) : requiv (r_abs s) s := equiv_abs_of_ge_zero (reg_seq.is_reg s) Hz theorem r_equiv_neg_abs_of_le_zero {s : reg_seq} (Hz : r_le s r_zero) : requiv (r_abs s) (-s) := equiv_neg_abs_of_le_zero (reg_seq.is_reg s) Hz end rat_seq namespace real open [classes] rat_seq private theorem rewrite_helper9 (a b c : ℝ) : b - c = (b - a) - (c - a) := by rewrite[-sub_add_eq_sub_sub_swap,sub_add_cancel] private theorem rewrite_helper10 (a b c d : ℝ) : c - d = (c - a) + (a - b) + (b - d) := by rewrite[*add_sub,*sub_add_cancel] noncomputable definition rep (x : ℝ) : rat_seq.reg_seq := some (quot.exists_rep x) definition re_abs (x : ℝ) : ℝ := quot.lift_on x (λ a, quot.mk (rat_seq.r_abs a)) (take a b Hab, quot.sound (rat_seq.r_abs_well_defined Hab)) theorem r_abs_nonneg {x : ℝ} : zero ≤ x → re_abs x = x := quot.induction_on x (λ a Ha, quot.sound (rat_seq.r_equiv_abs_of_ge_zero Ha)) theorem r_abs_nonpos {x : ℝ} : x ≤ zero → re_abs x = -x := quot.induction_on x (λ a Ha, quot.sound (rat_seq.r_equiv_neg_abs_of_le_zero Ha)) private theorem abs_const' (a : ℚ) : of_rat (rat.abs a) = re_abs (of_rat a) := quot.sound (rat_seq.r_abs_const a) private theorem re_abs_is_abs : re_abs = real.abs := funext (begin intro x, apply eq.symm, cases em (zero ≤ x) with [Hor1, Hor2], rewrite [abs_of_nonneg Hor1, r_abs_nonneg Hor1], have Hor2' : x ≤ zero, from le_of_lt (lt_of_not_ge Hor2), rewrite [abs_of_neg (lt_of_not_ge Hor2), r_abs_nonpos Hor2'] end) theorem abs_const (a : ℚ) : of_rat (rat.abs a) = abs (of_rat a) := by rewrite -re_abs_is_abs private theorem rat_approx' (x : ℝ) : ∀ n : ℕ+, ∃ q : ℚ, re_abs (x - of_rat q) ≤ of_rat n⁻¹ := quot.induction_on x (λ s n, rat_seq.r_rat_approx s n) theorem rat_approx (x : ℝ) : ∀ n : ℕ+, ∃ q : ℚ, abs (x - of_rat q) ≤ of_rat n⁻¹ := by rewrite -re_abs_is_abs; apply rat_approx' noncomputable definition approx (x : ℝ) (n : ℕ+) := some (rat_approx x n) theorem approx_spec (x : ℝ) (n : ℕ+) : abs (x - (of_rat (approx x n))) ≤ of_rat n⁻¹ := some_spec (rat_approx x n) theorem approx_spec' (x : ℝ) (n : ℕ+) : abs ((of_rat (approx x n)) - x) ≤ of_rat n⁻¹ := by rewrite abs_sub; apply approx_spec notation `r_seq` := ℕ+ → ℝ noncomputable definition converges_to_with_rate (X : r_seq) (a : ℝ) (N : ℕ+ → ℕ+) := ∀ k : ℕ+, ∀ n : ℕ+, n ≥ N k → abs (X n - a) ≤ of_rat k⁻¹ noncomputable definition cauchy_with_rate (X : r_seq) (M : ℕ+ → ℕ+) := ∀ k : ℕ+, ∀ m n : ℕ+, m ≥ M k → n ≥ M k → abs (X m - X n) ≤ of_rat k⁻¹ theorem cauchy_with_rate_of_converges_to_with_rate {X : r_seq} {a : ℝ} {N : ℕ+ → ℕ+} (Hc : converges_to_with_rate X a N) : cauchy_with_rate X (λ k, N (2 * k)) := begin intro k m n Hm Hn, rewrite (rewrite_helper9 a), apply le.trans, apply abs_add_le_abs_add_abs, apply le.trans, apply add_le_add, apply Hc, apply Hm, krewrite abs_neg, apply Hc, apply Hn, xrewrite -of_rat_add, apply of_rat_le_of_rat_of_le, rewrite pnat.add_halves, apply rat.le.refl end private definition Nb (M : ℕ+ → ℕ+) := λ k, pnat.max (3 * k) (M (2 * k)) private theorem Nb_spec_right (M : ℕ+ → ℕ+) (k : ℕ+) : M (2 * k) ≤ Nb M k := !max_right private theorem Nb_spec_left (M : ℕ+ → ℕ+) (k : ℕ+) : 3 * k ≤ Nb M k := !max_left section lim_seq parameter {X : r_seq} parameter {M : ℕ+ → ℕ+} hypothesis Hc : cauchy_with_rate X M include Hc noncomputable definition lim_seq : ℕ+ → ℚ := λ k, approx (X (Nb M k)) (2 * k) private theorem lim_seq_reg_helper {m n : ℕ+} (Hmn : M (2 * n) ≤M (2 * m)) : abs (of_rat (lim_seq m) - X (Nb M m)) + abs (X (Nb M m) - X (Nb M n)) + abs (X (Nb M n) - of_rat (lim_seq n)) ≤ of_rat (m⁻¹ + n⁻¹) := begin apply le.trans, apply add_le_add_three, apply approx_spec', rotate 1, apply approx_spec, rotate 1, apply Hc, rotate 1, apply Nb_spec_right, rotate 1, apply pnat.le.trans, apply Hmn, apply Nb_spec_right, rewrite [-*of_rat_add, rat.add.assoc, pnat.add_halves], apply of_rat_le_of_rat_of_le, apply rat.add_le_add_right, apply inv_ge_of_le, apply pnat.mul_le_mul_left end theorem lim_seq_reg : rat_seq.regular lim_seq := begin rewrite ↑rat_seq.regular, intro m n, apply le_of_of_rat_le_of_rat, rewrite [abs_const, of_rat_sub, (rewrite_helper10 (X (Nb M m)) (X (Nb M n)))], apply real.le.trans, apply abs_add_three, cases em (M (2 * m) ≥ M (2 * n)) with [Hor1, Hor2], apply lim_seq_reg_helper Hor1, let Hor2' := pnat.le_of_lt (pnat.lt_of_not_le Hor2), rewrite [real.abs_sub (X (Nb M n)), abs_sub (X (Nb M m)), abs_sub, rat.add.comm, add_comm_three], apply lim_seq_reg_helper Hor2' end theorem lim_seq_spec (k : ℕ+) : rat_seq.s_le (rat_seq.s_abs (rat_seq.sadd lim_seq (rat_seq.sneg (rat_seq.const (lim_seq k))))) (rat_seq.const k⁻¹) := by apply rat_seq.const_bound; apply lim_seq_reg private noncomputable definition r_lim_seq : rat_seq.reg_seq := rat_seq.reg_seq.mk lim_seq lim_seq_reg private theorem r_lim_seq_spec (k : ℕ+) : rat_seq.r_le (rat_seq.r_abs ((rat_seq.radd r_lim_seq (rat_seq.rneg (rat_seq.r_const ((rat_seq.reg_seq.sq r_lim_seq) k)))))) (rat_seq.r_const k⁻¹) := lim_seq_spec k noncomputable definition lim : ℝ := quot.mk r_lim_seq theorem re_lim_spec (k : ℕ+) : re_abs (lim - (of_rat (lim_seq k))) ≤ of_rat k⁻¹ := r_lim_seq_spec k theorem lim_spec' (k : ℕ+) : abs (lim - (of_rat (lim_seq k))) ≤ of_rat k⁻¹ := by rewrite -re_abs_is_abs; apply re_lim_spec theorem lim_spec (k : ℕ+) : abs ((of_rat (lim_seq k)) - lim) ≤ of_rat k⁻¹ := by rewrite abs_sub; apply lim_spec' theorem converges_to_with_rate_of_cauchy_with_rate : converges_to_with_rate X lim (Nb M) := begin intro k n Hn, rewrite (rewrite_helper10 (X (Nb M n)) (of_rat (lim_seq n))), apply le.trans, apply abs_add_three, apply le.trans, apply add_le_add_three, apply Hc, apply pnat.le.trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_right, have HMk : M (2 * k) ≤ Nb M n, begin apply pnat.le.trans, apply Nb_spec_right, apply pnat.le.trans, apply Hn, apply pnat.le.trans, apply mul_le_mul_left 3, apply Nb_spec_left end, apply HMk, rewrite ↑lim_seq, apply approx_spec, apply lim_spec, rewrite [-*of_rat_add], apply of_rat_le_of_rat_of_le, apply rat.le.trans, apply rat.add_le_add_three, apply rat.le.refl, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le.trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_left, apply inv_ge_of_le, apply pnat.le.trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_left, rewrite [-*pnat.mul.assoc, pnat.p_add_fractions], apply rat.le.refl end end lim_seq ------------------------------------------- -- int embedding theorems -- archimedean properties, integer floor and ceiling section ints open int theorem archimedean_upper (x : ℝ) : ∃ z : ℤ, x ≤ of_int z := begin apply quot.induction_on x, intro s, cases rat_seq.bdd_of_regular (rat_seq.reg_seq.is_reg s) with [b, Hb], existsi ubound b, have H : rat_seq.s_le (rat_seq.reg_seq.sq s) (rat_seq.const (rat.of_nat (ubound b))), begin apply rat_seq.s_le_of_le_pointwise (rat_seq.reg_seq.is_reg s), apply rat_seq.const_reg, intro n, apply rat.le.trans, apply Hb, apply ubound_ge end, apply H end theorem archimedean_upper_strict (x : ℝ) : ∃ z : ℤ, x < of_int z := begin cases archimedean_upper x with [z, Hz], existsi z + 1, apply lt_of_le_of_lt, apply Hz, apply of_int_lt_of_int_of_lt, apply int.lt_add_of_pos_right, apply dec_trivial end theorem archimedean_lower (x : ℝ) : ∃ z : ℤ, x ≥ of_int z := begin cases archimedean_upper (-x) with [z, Hz], existsi -z, rewrite [of_int_neg], apply iff.mp !neg_le_iff_neg_le Hz end theorem archimedean_lower_strict (x : ℝ) : ∃ z : ℤ, x > of_int z := begin cases archimedean_upper_strict (-x) with [z, Hz], existsi -z, rewrite [of_int_neg], apply iff.mp !neg_lt_iff_neg_lt Hz end private definition ex_floor (x : ℝ) := (@exists_greatest_of_bdd (λ z, x ≥ of_int z) _ (begin existsi some (archimedean_upper_strict x), let Har := some_spec (archimedean_upper_strict x), intros z Hz, apply not_le_of_gt, apply lt_of_lt_of_le, apply Har, have H : of_int (some (archimedean_upper_strict x)) ≤ of_int z, begin apply of_int_le_of_int_of_le, apply Hz end, exact H end) (by existsi some (archimedean_lower x); apply some_spec (archimedean_lower x))) noncomputable definition floor (x : ℝ) : ℤ := some (ex_floor x) noncomputable definition ceil (x : ℝ) : ℤ := - floor (-x) theorem floor_le (x : ℝ) : floor x ≤ x := and.left (some_spec (ex_floor x)) theorem lt_of_floor_lt {x : ℝ} {z : ℤ} (Hz : floor x < z) : x < z := begin apply lt_of_not_ge, cases some_spec (ex_floor x), apply a_1 _ Hz end theorem le_ceil (x : ℝ) : x ≤ ceil x := begin rewrite [↑ceil, of_int_neg], apply iff.mp !le_neg_iff_le_neg, apply floor_le end theorem lt_of_lt_ceil {x : ℝ} {z : ℤ} (Hz : z < ceil x) : z < x := begin rewrite ↑ceil at Hz, let Hz' := lt_of_floor_lt (iff.mp !int.lt_neg_iff_lt_neg Hz), rewrite [of_int_neg at Hz'], apply lt_of_neg_lt_neg Hz' end theorem floor_succ (x : ℝ) : floor (x + 1) = floor x + 1 := begin apply by_contradiction, intro H, cases int.lt_or_gt_of_ne H with [Hgt, Hlt], let Hl := lt_of_floor_lt Hgt, rewrite [of_int_add at Hl], apply not_le_of_gt (lt_of_add_lt_add_right Hl) !floor_le, let Hl := lt_of_floor_lt (iff.mp !int.add_lt_iff_lt_sub_right Hlt), rewrite [of_int_sub at Hl], apply not_le_of_gt (iff.mpr !add_lt_iff_lt_sub_right Hl) !floor_le end theorem floor_sub_one_lt_floor (x : ℝ) : floor (x - 1) < floor x := begin apply @int.lt_of_add_lt_add_right _ 1, rewrite [-floor_succ (x - 1), sub_add_cancel], apply int.lt_add_of_pos_right dec_trivial end theorem ceil_lt_ceil_succ (x : ℝ) : ceil x < ceil (x + 1) := begin rewrite [↑ceil, neg_add], apply int.neg_lt_neg, apply floor_sub_one_lt_floor end theorem archimedean_small {ε : ℝ} (H : ε > 0) : ∃ (n : ℕ), 1 / succ n < ε := let n := int.nat_abs (ceil (2 / ε)) in have int.of_nat n ≥ ceil (2 / ε), by rewrite int.of_nat_nat_abs; apply int.le_abs_self, have int.of_nat (succ n) ≥ ceil (2 / ε), from int.le.trans this (int.of_nat_le_of_nat_of_le !le_succ), have H₁ : succ n ≥ ceil (2 / ε), from of_int_le_of_int_of_le this, have H₂ : succ n ≥ 2 / ε, from !le.trans !le_ceil H₁, have H₃ : 2 / ε > 0, from div_pos_of_pos_of_pos two_pos H, have 1 / succ n < ε, from calc 1 / succ n ≤ 1 / (2 / ε) : one_div_le_one_div_of_le H₃ H₂ ... = ε / 2 : one_div_div ... < ε : div_two_lt_of_pos H, exists.intro n this end ints -------------------------------------------------- -- supremum property -- this development roughly follows the proof of completeness done in Isabelle. -- It does not depend on the previous proof of Cauchy completeness. Much of the same -- machinery can be used to show that Cauchy completeness implies the supremum property. section supremum open prod nat local postfix `~` := nat_of_pnat -- The top part of this section could be refactored. What is the appropriate place to define -- bounds, supremum, etc? In algebra/ordered_field? They potentially apply to more than just ℝ. local notation 2 := (1 : ℚ) + 1 parameter X : ℝ → Prop definition ub (x : ℝ) := ∀ y : ℝ, X y → y ≤ x definition is_sup (x : ℝ) := ub x ∧ ∀ y : ℝ, ub y → x ≤ y definition lb (x : ℝ) := ∀ y : ℝ, X y → x ≤ y definition is_inf (x : ℝ) := lb x ∧ ∀ y : ℝ, lb y → y ≤ x parameter elt : ℝ hypothesis inh : X elt parameter bound : ℝ hypothesis bdd : ub bound include inh bdd private definition avg (a b : ℚ) := a / 2 + b / 2 private noncomputable definition bisect (ab : ℚ × ℚ) := if ub (avg (pr1 ab) (pr2 ab)) then (pr1 ab, (avg (pr1 ab) (pr2 ab))) else (avg (pr1 ab) (pr2 ab), pr2 ab) private noncomputable definition under : ℚ := rat.of_int (floor (elt - 1)) private theorem under_spec1 : of_rat under < elt := have H : of_rat under < of_int (floor elt), begin apply of_int_lt_of_int_of_lt, apply floor_sub_one_lt_floor end, lt_of_lt_of_le H !floor_le private theorem under_spec : ¬ ub under := begin rewrite ↑ub, apply not_forall_of_exists_not, existsi elt, apply iff.mpr not_implies_iff_and_not, apply and.intro, apply inh, apply not_le_of_gt under_spec1 end private noncomputable definition over : ℚ := rat.of_int (ceil (bound + 1)) -- b private theorem over_spec1 : bound < of_rat over := have H : of_int (ceil bound) < of_rat over, begin apply of_int_lt_of_int_of_lt, apply ceil_lt_ceil_succ end, lt_of_le_of_lt !le_ceil H private theorem over_spec : ub over := begin rewrite ↑ub, intro y Hy, apply le_of_lt, apply lt_of_le_of_lt, apply bdd, apply Hy, apply over_spec1 end private noncomputable definition under_seq := λ n : ℕ, pr1 (iterate bisect n (under, over)) -- A private noncomputable definition over_seq := λ n : ℕ, pr2 (iterate bisect n (under, over)) -- B private noncomputable definition avg_seq := λ n : ℕ, avg (over_seq n) (under_seq n) -- C private theorem avg_symm (n : ℕ) : avg_seq n = avg (under_seq n) (over_seq n) := by rewrite [↑avg_seq, ↑avg, rat.add.comm] private theorem over_0 : over_seq 0 = over := rfl private theorem under_0 : under_seq 0 = under := rfl private theorem succ_helper (n : ℕ) : avg (pr1 (iterate bisect n (under, over))) (pr2 (iterate bisect n (under, over))) = avg_seq n := by rewrite avg_symm private theorem under_succ (n : ℕ) : under_seq (succ n) = (if ub (avg_seq n) then under_seq n else avg_seq n) := begin cases em (ub (avg_seq n)) with [Hub, Hub], rewrite [if_pos Hub], have H : pr1 (bisect (iterate bisect n (under, over))) = under_seq n, by rewrite [↑under_seq, ↑bisect at {2}, -succ_helper at Hub, if_pos Hub], apply H, rewrite [if_neg Hub], have H : pr1 (bisect (iterate bisect n (under, over))) = avg_seq n, by rewrite [↑bisect at {2}, -succ_helper at Hub, if_neg Hub, avg_symm], apply H end private theorem over_succ (n : ℕ) : over_seq (succ n) = (if ub (avg_seq n) then avg_seq n else over_seq n) := begin cases em (ub (avg_seq n)) with [Hub, Hub], rewrite [if_pos Hub], have H : pr2 (bisect (iterate bisect n (under, over))) = avg_seq n, by rewrite [↑bisect at {2}, -succ_helper at Hub, if_pos Hub, avg_symm], apply H, rewrite [if_neg Hub], have H : pr2 (bisect (iterate bisect n (under, over))) = over_seq n, by rewrite [↑over_seq, ↑bisect at {2}, -succ_helper at Hub, if_neg Hub], apply H end private theorem width (n : ℕ) : over_seq n - under_seq n = (over - under) / (rat.pow 2 n) := nat.induction_on n (by xrewrite [over_0, under_0, rat.pow_zero, rat.div_one]) (begin intro a Ha, rewrite [over_succ, under_succ], let Hou := calc (over_seq a) / 2 - (under_seq a) / 2 = ((over - under) / rat.pow 2 a) / 2 : by rewrite [rat.div_sub_div_same, Ha] ... = (over - under) / (rat.pow 2 a * 2) : rat.div_div_eq_div_mul ... = (over - under) / rat.pow 2 (a + 1) : by rewrite rat.pow_add, cases em (ub (avg_seq a)), rewrite [*if_pos a_1, -add_one, -Hou, ↑avg_seq, ↑avg, rat.add.assoc, rat.div_two_sub_self], rewrite [*if_neg a_1, -add_one, -Hou, ↑avg_seq, ↑avg, rat.sub_add_eq_sub_sub, rat.sub_self_div_two] end) private theorem width_narrows : ∃ n : ℕ, over_seq n - under_seq n ≤ 1 := begin cases binary_bound (over - under) with [a, Ha], existsi a, rewrite (width a), apply rat.div_le_of_le_mul, apply rat.pow_pos dec_trivial, rewrite rat.mul_one, apply Ha end private noncomputable definition over' := over_seq (some width_narrows) private noncomputable definition under' := under_seq (some width_narrows) private noncomputable definition over_seq' := λ n, over_seq (n + some width_narrows) private noncomputable definition under_seq' := λ n, under_seq (n + some width_narrows) private theorem over_seq'0 : over_seq' 0 = over' := by rewrite [↑over_seq', nat.zero_add] private theorem under_seq'0 : under_seq' 0 = under' := by rewrite [↑under_seq', nat.zero_add] private theorem under_over' : over' - under' ≤ 1 := some_spec width_narrows private theorem width' (n : ℕ) : over_seq' n - under_seq' n ≤ 1 / rat.pow 2 n := nat.induction_on n (begin xrewrite [over_seq'0, under_seq'0, rat.pow_zero, rat.div_one], apply under_over' end) (begin intros a Ha, rewrite [↑over_seq' at *, ↑under_seq' at *, *succ_add at *, width at *, -add_one, -(add_one a), rat.pow_add, rat.pow_add _ a 1, *rat.pow_one], apply rat.div_mul_le_div_mul_of_div_le_div_pos' Ha dec_trivial end) private theorem PA (n : ℕ) : ¬ ub (under_seq n) := nat.induction_on n (by rewrite under_0; apply under_spec) (begin intro a Ha, rewrite under_succ, cases em (ub (avg_seq a)), rewrite (if_pos a_1), assumption, rewrite (if_neg a_1), assumption end) private theorem PB (n : ℕ) : ub (over_seq n) := nat.induction_on n (by rewrite over_0; apply over_spec) (begin intro a Ha, rewrite over_succ, cases em (ub (avg_seq a)), rewrite (if_pos a_1), assumption, rewrite (if_neg a_1), assumption end) private theorem under_lt_over : under < over := begin cases exists_not_of_not_forall under_spec with [x, Hx], cases iff.mp not_implies_iff_and_not Hx with [HXx, Hxu], apply lt_of_of_rat_lt_of_rat, apply lt_of_lt_of_le, apply lt_of_not_ge Hxu, apply over_spec _ HXx end private theorem under_seq_lt_over_seq : ∀ m n : ℕ, under_seq m < over_seq n := begin intros, cases exists_not_of_not_forall (PA m) with [x, Hx], cases iff.mp not_implies_iff_and_not Hx with [HXx, Hxu], apply lt_of_of_rat_lt_of_rat, apply lt_of_lt_of_le, apply lt_of_not_ge Hxu, apply PB, apply HXx end private theorem under_seq_lt_over_seq_single : ∀ n : ℕ, under_seq n < over_seq n := by intros; apply under_seq_lt_over_seq private theorem under_seq'_lt_over_seq' : ∀ m n : ℕ, under_seq' m < over_seq' n := by intros; apply under_seq_lt_over_seq private theorem under_seq'_lt_over_seq'_single : ∀ n : ℕ, under_seq' n < over_seq' n := by intros; apply under_seq_lt_over_seq private theorem under_seq_mono_helper (i k : ℕ) : under_seq i ≤ under_seq (i + k) := (nat.induction_on k (by rewrite nat.add_zero; apply rat.le.refl) (begin intros a Ha, rewrite [add_succ, under_succ], cases em (ub (avg_seq (i + a))) with [Havg, Havg], rewrite (if_pos Havg), apply Ha, rewrite [if_neg Havg, ↑avg_seq, ↑avg], apply rat.le.trans, apply Ha, rewrite -rat.add_halves at {1}, apply rat.add_le_add_right, apply rat.div_le_div_of_le_of_pos, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply dec_trivial end)) private theorem under_seq_mono (i j : ℕ) (H : i ≤ j) : under_seq i ≤ under_seq j := begin cases le.elim H with [k, Hk'], rewrite -Hk', apply under_seq_mono_helper end private theorem over_seq_mono_helper (i k : ℕ) : over_seq (i + k) ≤ over_seq i := nat.induction_on k (by rewrite nat.add_zero; apply rat.le.refl) (begin intros a Ha, rewrite [add_succ, over_succ], cases em (ub (avg_seq (i + a))) with [Havg, Havg], rewrite [if_pos Havg, ↑avg_seq, ↑avg], apply rat.le.trans, rotate 1, apply Ha, rotate 1, rewrite -{over_seq (i + a)}rat.add_halves at {2}, apply rat.add_le_add_left, apply rat.div_le_div_of_le_of_pos, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply dec_trivial, rewrite [if_neg Havg], apply Ha end) private theorem over_seq_mono (i j : ℕ) (H : i ≤ j) : over_seq j ≤ over_seq i := begin cases le.elim H with [k, Hk'], rewrite -Hk', apply over_seq_mono_helper end private theorem rat_power_two_inv_ge (k : ℕ+) : 1 / rat.pow 2 k~ ≤ k⁻¹ := rat.one_div_le_one_div_of_le !rat_of_pnat_is_pos !rat_power_two_le open rat_seq private theorem regular_lemma_helper {s : seq} {m n : ℕ+} (Hm : m ≤ n) (H : ∀ n i : ℕ+, i ≥ n → under_seq' n~ ≤ s i ∧ s i ≤ over_seq' n~) : rat.abs (s m - s n) ≤ m⁻¹ + n⁻¹ := begin cases H m n Hm with [T1under, T1over], cases H m m (!pnat.le.refl) with [T2under, T2over], apply rat.le.trans, apply rat.dist_bdd_within_interval, apply under_seq'_lt_over_seq'_single, rotate 1, repeat assumption, apply rat.le.trans, apply width', apply rat.le.trans, apply rat_power_two_inv_ge, apply rat.le_add_of_nonneg_right, apply rat.le_of_lt (!inv_pos) end private theorem regular_lemma (s : seq) (H : ∀ n i : ℕ+, i ≥ n → under_seq' n~ ≤ s i ∧ s i ≤ over_seq' n~) : regular s := begin rewrite ↑regular, intros, cases em (m ≤ n) with [Hm, Hn], apply regular_lemma_helper Hm H, let T := regular_lemma_helper (pnat.le_of_lt (pnat.lt_of_not_le Hn)) H, rewrite [rat.abs_sub at T, {n⁻¹ + _}rat.add.comm at T], exact T end private noncomputable definition p_under_seq : seq := λ n : ℕ+, under_seq' n~ private noncomputable definition p_over_seq : seq := λ n : ℕ+, over_seq' n~ private theorem under_seq_regular : regular p_under_seq := begin apply regular_lemma, intros n i Hni, apply and.intro, apply under_seq_mono, apply nat.add_le_add_right Hni, apply rat.le_of_lt, apply under_seq_lt_over_seq end private theorem over_seq_regular : regular p_over_seq := begin apply regular_lemma, intros n i Hni, apply and.intro, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply over_seq_mono, apply nat.add_le_add_right Hni end private noncomputable definition sup_over : ℝ := quot.mk (reg_seq.mk p_over_seq over_seq_regular) private noncomputable definition sup_under : ℝ := quot.mk (reg_seq.mk p_under_seq under_seq_regular) private theorem over_bound : ub sup_over := begin rewrite ↑ub, intros y Hy, apply le_of_le_reprs, intro n, apply PB, apply Hy end private theorem under_lowest_bound : ∀ y : ℝ, ub y → sup_under ≤ y := begin intros y Hy, apply le_of_reprs_le, intro n, cases exists_not_of_not_forall (PA _) with [x, Hx], cases iff.mp not_implies_iff_and_not Hx with [HXx, Hxn], apply le.trans, apply le_of_lt, apply lt_of_not_ge Hxn, apply Hy, apply HXx end private theorem under_over_equiv : p_under_seq ≡ p_over_seq := begin intros, apply rat.le.trans, have H : p_under_seq n < p_over_seq n, from !under_seq_lt_over_seq, rewrite [rat.abs_of_neg (iff.mpr !rat.sub_neg_iff_lt H), rat.neg_sub], apply width', apply rat.le.trans, apply rat_power_two_inv_ge, apply rat.le_add_of_nonneg_left, apply rat.le_of_lt !inv_pos end private theorem under_over_eq : sup_under = sup_over := quot.sound under_over_equiv theorem exists_is_sup_of_inh_of_bdd : ∃ x : ℝ, is_sup x := exists.intro sup_over (and.intro over_bound (under_over_eq ▸ under_lowest_bound)) end supremum definition bounding_set (X : ℝ → Prop) (x : ℝ) : Prop := ∀ y : ℝ, X y → x ≤ y theorem exists_is_inf_of_inh_of_bdd (X : ℝ → Prop) (elt : ℝ) (inh : X elt) (bound : ℝ) (bdd : lb X bound) : ∃ x : ℝ, is_inf X x := begin have Hinh : bounding_set X bound, begin intros y Hy, apply bdd, apply Hy end, have Hub : ub (bounding_set X) elt, begin intros y Hy, apply Hy, apply inh end, cases exists_is_sup_of_inh_of_bdd _ _ Hinh _ Hub with [supr, Hsupr], existsi supr, cases Hsupr with [Hubs1, Hubs2], apply and.intro, intros, apply Hubs2, intros z Hz, apply Hz, apply a, intros y Hlby, apply Hubs1, intros z Hz, apply Hlby, apply Hz end end real
2141866d4e552d96b6ad01c8905bfda465d5a2f4
f57749ca63d6416f807b770f67559503fdb21001
/library/algebra/ring.lean
87a1c9d6bd6027955f4c3c79ffe1f84d0e148427
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,292
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Structures with multiplicative and additive components, including semirings, rings, and fields. The development is modeled after Isabelle's library. -/ import logic.eq logic.connectives data.unit data.sigma data.prod import algebra.binary algebra.group open eq eq.ops namespace algebra variable {A : Type} /- auxiliary classes -/ structure distrib [class] (A : Type) extends has_mul A, has_add A := (left_distrib : ∀a b c, mul a (add b c) = add (mul a b) (mul a c)) (right_distrib : ∀a b c, mul (add a b) c = add (mul a c) (mul b c)) theorem left_distrib [s : distrib A] (a b c : A) : a * (b + c) = a * b + a * c := !distrib.left_distrib theorem right_distrib [s: distrib A] (a b c : A) : (a + b) * c = a * c + b * c := !distrib.right_distrib structure mul_zero_class [class] (A : Type) extends has_mul A, has_zero A := (zero_mul : ∀a, mul zero a = zero) (mul_zero : ∀a, mul a zero = zero) theorem zero_mul [s : mul_zero_class A] (a : A) : 0 * a = 0 := !mul_zero_class.zero_mul theorem mul_zero [s : mul_zero_class A] (a : A) : a * 0 = 0 := !mul_zero_class.mul_zero structure zero_ne_one_class [class] (A : Type) extends has_zero A, has_one A := (zero_ne_one : zero ≠ one) theorem zero_ne_one [s: zero_ne_one_class A] : 0 ≠ (1:A) := @zero_ne_one_class.zero_ne_one A s /- semiring -/ structure semiring [class] (A : Type) extends add_comm_monoid A, monoid A, distrib A, mul_zero_class A section semiring variables [s : semiring A] (a b c : A) include s theorem ne_zero_of_mul_ne_zero_right {a b : A} (H : a * b ≠ 0) : a ≠ 0 := suppose a = 0, have a * b = 0, from this⁻¹ ▸ zero_mul b, H this theorem ne_zero_of_mul_ne_zero_left {a b : A} (H : a * b ≠ 0) : b ≠ 0 := suppose b = 0, have a * b = 0, from this⁻¹ ▸ mul_zero a, H this theorem distrib_three_right (a b c d : A) : (a + b + c) * d = a * d + b * d + c * d := by rewrite *right_distrib end semiring /- comm semiring -/ structure comm_semiring [class] (A : Type) extends semiring A, comm_monoid A -- TODO: we could also define a cancelative comm_semiring, i.e. satisfying -- c ≠ 0 → c * a = c * b → a = b. section comm_semiring variables [s : comm_semiring A] (a b c : A) include s definition dvd (a b : A) : Prop := ∃c, b = a * c notation [priority algebra.prio] a ∣ b := dvd a b theorem dvd.intro {a b c : A} (H : a * c = b) : a ∣ b := exists.intro _ H⁻¹ theorem dvd.intro_left {a b c : A} (H : c * a = b) : a ∣ b := dvd.intro (!mul.comm ▸ H) theorem exists_eq_mul_right_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = a * c := H theorem dvd.elim {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = a * c → P) : P := exists.elim H₁ H₂ theorem exists_eq_mul_left_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = c * a := dvd.elim H (take c, assume H1 : b = a * c, exists.intro c (H1 ⬝ !mul.comm)) theorem dvd.elim_left {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = c * a → P) : P := exists.elim (exists_eq_mul_left_of_dvd H₁) (take c, assume H₃ : b = c * a, H₂ c H₃) theorem dvd.refl : a ∣ a := dvd.intro !mul_one theorem dvd.trans {a b c : A} (H₁ : a ∣ b) (H₂ : b ∣ c) : a ∣ c := dvd.elim H₁ (take d, assume H₃ : b = a * d, dvd.elim H₂ (take e, assume H₄ : c = b * e, dvd.intro (show a * (d * e) = c, by rewrite [-mul.assoc, -H₃, H₄]))) theorem eq_zero_of_zero_dvd {a : A} (H : 0 ∣ a) : a = 0 := dvd.elim H (take c, assume H' : a = 0 * c, H' ⬝ !zero_mul) theorem dvd_zero : a ∣ 0 := dvd.intro !mul_zero theorem one_dvd : 1 ∣ a := dvd.intro !one_mul theorem dvd_mul_right : a ∣ a * b := dvd.intro rfl theorem dvd_mul_left : a ∣ b * a := mul.comm a b ▸ dvd_mul_right a b theorem dvd_mul_of_dvd_left {a b : A} (H : a ∣ b) (c : A) : a ∣ b * c := dvd.elim H (take d, suppose b = a * d, dvd.intro (show a * (d * c) = b * c, from by rewrite [-mul.assoc]; substvars)) theorem dvd_mul_of_dvd_right {a b : A} (H : a ∣ b) (c : A) : a ∣ c * b := !mul.comm ▸ (dvd_mul_of_dvd_left H _) theorem mul_dvd_mul {a b c d : A} (dvd_ab : a ∣ b) (dvd_cd : c ∣ d) : a * c ∣ b * d := dvd.elim dvd_ab (take e, suppose b = a * e, dvd.elim dvd_cd (take f, suppose d = c * f, dvd.intro (show a * c * (e * f) = b * d, by rewrite [mul.assoc, {c*_}mul.left_comm, -mul.assoc]; substvars))) theorem dvd_of_mul_right_dvd {a b c : A} (H : a * b ∣ c) : a ∣ c := dvd.elim H (take d, assume Habdc : c = a * b * d, dvd.intro (!mul.assoc⁻¹ ⬝ Habdc⁻¹)) theorem dvd_of_mul_left_dvd {a b c : A} (H : a * b ∣ c) : b ∣ c := dvd_of_mul_right_dvd (mul.comm a b ▸ H) theorem dvd_add {a b c : A} (Hab : a ∣ b) (Hac : a ∣ c) : a ∣ b + c := dvd.elim Hab (take d, suppose b = a * d, dvd.elim Hac (take e, suppose c = a * e, dvd.intro (show a * (d + e) = b + c, by rewrite [left_distrib]; substvars))) end comm_semiring /- ring -/ structure ring [class] (A : Type) extends add_comm_group A, monoid A, distrib A theorem ring.mul_zero [s : ring A] (a : A) : a * 0 = 0 := have a * 0 + 0 = a * 0 + a * 0, from calc a * 0 + 0 = a * 0 : by rewrite add_zero ... = a * (0 + 0) : by rewrite add_zero ... = a * 0 + a * 0 : by rewrite {a*_}ring.left_distrib, show a * 0 = 0, from (add.left_cancel this)⁻¹ theorem ring.zero_mul [s : ring A] (a : A) : 0 * a = 0 := have 0 * a + 0 = 0 * a + 0 * a, from calc 0 * a + 0 = 0 * a : by rewrite add_zero ... = (0 + 0) * a : by rewrite add_zero ... = 0 * a + 0 * a : by rewrite {_*a}ring.right_distrib, show 0 * a = 0, from (add.left_cancel this)⁻¹ definition ring.to_semiring [trans-instance] [coercion] [reducible] [s : ring A] : semiring A := ⦃ semiring, s, mul_zero := ring.mul_zero, zero_mul := ring.zero_mul ⦄ section variables [s : ring A] (a b c d e : A) include s theorem neg_mul_eq_neg_mul : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rewrite [-right_distrib, add.right_inv, zero_mul] end theorem neg_mul_eq_mul_neg : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rewrite [-left_distrib, add.right_inv, mul_zero] end theorem neg_mul_neg : -a * -b = a * b := calc -a * -b = -(a * -b) : by rewrite -neg_mul_eq_neg_mul ... = - -(a * b) : by rewrite -neg_mul_eq_mul_neg ... = a * b : by rewrite neg_neg theorem neg_mul_comm : -a * b = a * -b := !neg_mul_eq_neg_mul⁻¹ ⬝ !neg_mul_eq_mul_neg theorem neg_eq_neg_one_mul : -a = -1 * a := calc -a = -(1 * a) : by rewrite one_mul ... = -1 * a : by rewrite neg_mul_eq_neg_mul theorem mul_sub_left_distrib : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib ... = a * b + - (a * c) : by rewrite -neg_mul_eq_mul_neg ... = a * b - a * c : rfl theorem mul_sub_right_distrib : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib ... = a * c + - (b * c) : by rewrite neg_mul_eq_neg_mul ... = a * c - b * c : rfl -- TODO: can calc mode be improved to make this easier? -- TODO: there is also the other direction. It will be easier when we -- have the simplifier. theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by rewrite {b*e+_}add.comm ... ↔ a * e + c - b * e = d : iff.symm !sub_eq_iff_eq_add ... ↔ a * e - b * e + c = d : by rewrite sub_add_eq_add_sub ... ↔ (a - b) * e + c = d : by rewrite mul_sub_right_distrib theorem mul_neg_one_eq_neg : a * (-1) = -a := have a + a * -1 = 0, from calc a + a * -1 = a * 1 + a * -1 : mul_one ... = a * (1 + -1) : left_distrib ... = a * 0 : add.right_inv ... = 0 : mul_zero, symm (neg_eq_of_add_eq_zero this) theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : A} (H : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := have a ≠ 0, from (suppose a = 0, have a * b = 0, by rewrite [this, zero_mul], absurd this H), have b ≠ 0, from (suppose b = 0, have a * b = 0, by rewrite [this, mul_zero], absurd this H), and.intro `a ≠ 0` `b ≠ 0` end structure comm_ring [class] (A : Type) extends ring A, comm_semigroup A definition comm_ring.to_comm_semiring [trans-instance] [coercion] [reducible] [s : comm_ring A] : comm_semiring A := ⦃ comm_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul ⦄ section variables [s : comm_ring A] (a b c d e : A) include s theorem mul_self_sub_mul_self_eq : a * a - b * b = (a + b) * (a - b) := begin krewrite [left_distrib, *right_distrib, add.assoc], rewrite [-{b*a + _}add.assoc, -*neg_mul_eq_mul_neg, {a*b}mul.comm, add.right_inv, zero_add] end theorem mul_self_sub_one_eq : a * a - 1 = (a + 1) * (a - 1) := by rewrite [-mul_self_sub_mul_self_eq, mul_one] theorem dvd_neg_iff_dvd : (a ∣ -b) ↔ (a ∣ b) := iff.intro (suppose a ∣ -b, dvd.elim this (take c, suppose -b = a * c, dvd.intro (show a * -c = b, by rewrite [-neg_mul_eq_mul_neg, -this, neg_neg]))) (suppose a ∣ b, dvd.elim this (take c, suppose b = a * c, dvd.intro (show a * -c = -b, by rewrite [-neg_mul_eq_mul_neg, -this]))) theorem neg_dvd_iff_dvd : (-a ∣ b) ↔ (a ∣ b) := iff.intro (suppose -a ∣ b, dvd.elim this (take c, suppose b = -a * c, dvd.intro (show a * -c = b, by rewrite [-neg_mul_comm, this]))) (suppose a ∣ b, dvd.elim this (take c, suppose b = a * c, dvd.intro (show -a * -c = b, by rewrite [neg_mul_neg, this]))) theorem dvd_sub (H₁ : (a ∣ b)) (H₂ : (a ∣ c)) : (a ∣ b - c) := dvd_add H₁ (iff.elim_right !dvd_neg_iff_dvd H₂) end /- integral domains -/ structure no_zero_divisors [class] (A : Type) extends has_mul A, has_zero A := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀a b, mul a b = zero → a = zero ∨ b = zero) theorem eq_zero_or_eq_zero_of_mul_eq_zero {A : Type} [s : no_zero_divisors A] {a b : A} (H : a * b = 0) : a = 0 ∨ b = 0 := !no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero H structure integral_domain [class] (A : Type) extends comm_ring A, no_zero_divisors A section variables [s : integral_domain A] (a b c d e : A) include s theorem mul_ne_zero {a b : A} (H1 : a ≠ 0) (H2 : b ≠ 0) : a * b ≠ 0 := suppose a * b = 0, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this) (assume H3, H1 H3) (assume H4, H2 H4) theorem eq_of_mul_eq_mul_right {a b c : A} (Ha : a ≠ 0) (H : b * a = c * a) : b = c := have b * a - c * a = 0, from iff.mp !eq_iff_sub_eq_zero H, have (b - c) * a = 0, using this, by rewrite [mul_sub_right_distrib, this], have b - c = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero this) Ha, iff.elim_right !eq_iff_sub_eq_zero this theorem eq_of_mul_eq_mul_left {a b c : A} (Ha : a ≠ 0) (H : a * b = a * c) : b = c := have a * b - a * c = 0, from iff.mp !eq_iff_sub_eq_zero H, have a * (b - c) = 0, using this, by rewrite [mul_sub_left_distrib, this], have b - c = 0, from or_resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero this) Ha, iff.elim_right !eq_iff_sub_eq_zero this -- TODO: do we want the iff versions? theorem mul_self_eq_mul_self_iff (a b : A) : a * a = b * b ↔ a = b ∨ a = -b := iff.intro (suppose a * a = b * b, have (a - b) * (a + b) = 0, by rewrite [mul.comm, -mul_self_sub_mul_self_eq, this, sub_self], assert a - b = 0 ∨ a + b = 0, from !eq_zero_or_eq_zero_of_mul_eq_zero this, or.elim this (suppose a - b = 0, or.inl (eq_of_sub_eq_zero this)) (suppose a + b = 0, or.inr (eq_neg_of_add_eq_zero this))) (suppose a = b ∨ a = -b, or.elim this (suppose a = b, by rewrite this) (suppose a = -b, by rewrite [this, neg_mul_neg])) theorem mul_self_eq_one_iff (a : A) : a * a = 1 ↔ a = 1 ∨ a = -1 := assert a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1, by rewrite mul_one at this; exact this -- TODO: c - b * c → c = 0 ∨ b = 1 and variants theorem dvd_of_mul_dvd_mul_left {a b c : A} (Ha : a ≠ 0) (Hdvd : (a * b ∣ a * c)) : (b ∣ c) := dvd.elim Hdvd (take d, suppose a * c = a * b * d, have b * d = c, from eq_of_mul_eq_mul_left Ha (mul.assoc a b d ▸ this⁻¹), dvd.intro this) theorem dvd_of_mul_dvd_mul_right {a b c : A} (Ha : a ≠ 0) (Hdvd : (b * a ∣ c * a)) : (b ∣ c) := dvd.elim Hdvd (take d, suppose c * a = b * a * d, have b * d * a = c * a, from by rewrite [mul.right_comm, -this], have b * d = c, from eq_of_mul_eq_mul_right Ha this, dvd.intro this) end end algebra
8e956628b1f0ddf70f2b3a8fa909b7c062a429fb
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/data/equiv/algebra.lean
a6ae83a8b640dd8ce1d1f571c20e09e35704f097
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
1,887
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 -/ import data.equiv.basic algebra.group algebra.field namespace equiv variables {α : Type*} [group α] protected def mul_left (a : α) : α ≃ α := { to_fun := λx, a * x, inv_fun := λx, a⁻¹ * x, left_inv := assume x, show a⁻¹ * (a * x) = x, from inv_mul_cancel_left a x, right_inv := assume x, show a * (a⁻¹ * x) = x, from mul_inv_cancel_left a x } attribute [to_additive equiv.add_left._proof_1] equiv.mul_left._proof_1 attribute [to_additive equiv.add_left._proof_2] equiv.mul_left._proof_2 attribute [to_additive equiv.add_left] equiv.mul_left protected def mul_right (a : α) : α ≃ α := { to_fun := λx, x * a, inv_fun := λx, x * a⁻¹, left_inv := assume x, show (x * a) * a⁻¹ = x, from mul_inv_cancel_right x a, right_inv := assume x, show (x * a⁻¹) * a = x, from inv_mul_cancel_right x a } attribute [to_additive equiv.add_right._proof_1] equiv.mul_right._proof_1 attribute [to_additive equiv.add_right._proof_2] equiv.mul_right._proof_2 attribute [to_additive equiv.add_right] equiv.mul_right protected def inv (α) [group α] : α ≃ α := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } attribute [to_additive equiv.neg._proof_1] equiv.inv._proof_1 attribute [to_additive equiv.neg._proof_2] equiv.inv._proof_2 attribute [to_additive equiv.neg] equiv.inv def units_equiv_ne_zero (α : Type*) [field α] : units α ≃ {a : α | a ≠ 0} := ⟨λ a, ⟨a.1, units.ne_zero _⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩ @[simp] lemma coe_units_equiv_ne_zero [field α] (a : units α) : ((units_equiv_ne_zero α a) : α) = a := rfl end equiv
73fdc92fc9161a21f8614241a0b2895a238e30e7
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/stage0/src/Init/Data/ByteArray/Basic.lean
a3d4e95c14446609ac5f30abf82ddd3d0c179a4d
[ "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
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
7,240
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.Array.Basic import Init.Data.Array.Subarray import Init.Data.UInt import Init.Data.Option.Basic universe u structure ByteArray where data : Array UInt8 attribute [extern "lean_byte_array_mk"] ByteArray.mk attribute [extern "lean_byte_array_data"] ByteArray.data namespace ByteArray @[extern "lean_mk_empty_byte_array"] def mkEmpty (c : @& Nat) : ByteArray := { data := #[] } def empty : ByteArray := mkEmpty 0 instance : Inhabited ByteArray where default := empty instance : EmptyCollection ByteArray where emptyCollection := ByteArray.empty @[extern "lean_byte_array_push"] def push : ByteArray → UInt8 → ByteArray | ⟨bs⟩, b => ⟨bs.push b⟩ @[extern "lean_byte_array_size"] def size : (@& ByteArray) → Nat | ⟨bs⟩ => bs.size @[extern "lean_byte_array_uget"] def uget : (a : @& ByteArray) → (i : USize) → i.toNat < a.size → UInt8 | ⟨bs⟩, i, h => bs.uget i h @[extern "lean_byte_array_get"] def get! : (@& ByteArray) → (@& Nat) → UInt8 | ⟨bs⟩, i => bs.get! i @[extern "lean_byte_array_fget"] def get : (a : @& ByteArray) → (@& Fin a.size) → UInt8 | ⟨bs⟩, i => bs.get i @[inline] def getOp (self : ByteArray) (idx : Nat) : UInt8 := self.get! idx @[extern "lean_byte_array_set"] def set! : ByteArray → (@& Nat) → UInt8 → ByteArray | ⟨bs⟩, i, b => ⟨bs.set! i b⟩ @[extern "lean_byte_array_fset"] def set : (a : ByteArray) → (@& Fin a.size) → UInt8 → ByteArray | ⟨bs⟩, i, b => ⟨bs.set i b⟩ @[extern "lean_byte_array_uset"] def uset : (a : ByteArray) → (i : USize) → UInt8 → i.toNat < a.size → ByteArray | ⟨bs⟩, i, v, h => ⟨bs.uset i v h⟩ def isEmpty (s : ByteArray) : Bool := s.size == 0 /-- Copy the slice at `[srcOff, srcOff + len)` in `src` to `[destOff, destOff + len)` in `dest`, growing `dest` if necessary. If `exact` is `false`, the capacity will be doubled when grown. -/ @[extern "lean_byte_array_copy_slice"] def copySlice (src : @& ByteArray) (srcOff : Nat) (dest : ByteArray) (destOff len : Nat) (exact : Bool := true) : ByteArray := ⟨dest.data.extract 0 destOff ++ src.data.extract srcOff len ++ dest.data.extract (destOff + len) dest.data.size⟩ def extract (a : ByteArray) (b e : Nat) : ByteArray := a.copySlice b empty 0 (e - b) protected def append (a : ByteArray) (b : ByteArray) : ByteArray := -- we assume that `append`s may be repeated, so use asymptotic growing; use `copySlice` directly to customize b.copySlice 0 a a.size b.size false instance : Append ByteArray := ⟨ByteArray.append⟩ partial def toList (bs : ByteArray) : List UInt8 := let rec loop (i : Nat) (r : List UInt8) := if i < bs.size then loop (i+1) (bs.get! i :: r) else r.reverse loop 0 [] @[inline] partial def findIdx? (a : ByteArray) (p : UInt8 → Bool) (start := 0) : Option Nat := let rec @[specialize] loop (i : Nat) := if i < a.size then if p (a.get! i) then some i else loop (i+1) else none loop start /- We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime. This is similar to the `Array` version. TODO: avoid code duplication in the future after we improve the compiler. -/ @[inline] unsafe def forInUnsafe {β : Type v} {m : Type v → Type w} [Monad m] (as : ByteArray) (b : β) (f : UInt8 → β → m (ForInStep β)) : m β := let sz := USize.ofNat as.size let rec @[specialize] loop (i : USize) (b : β) : m β := do if i < sz then let a := as.uget i lcProof match (← f a b) with | ForInStep.done b => pure b | ForInStep.yield b => loop (i+1) b else pure b loop 0 b /- Reference implementation for `forIn` -/ @[implementedBy ByteArray.forInUnsafe] protected def forIn {β : Type v} {m : Type v → Type w} [Monad m] (as : ByteArray) (b : β) (f : UInt8 → β → m (ForInStep β)) : m β := let rec loop (i : Nat) (h : i ≤ as.size) (b : β) : m β := do match i, h with | 0, _ => pure b | i+1, h => have h' : i < as.size := Nat.lt_of_lt_of_le (Nat.lt_succ_self i) h have : as.size - 1 < as.size := Nat.sub_lt (Nat.zero_lt_of_lt h') (by decide) have : as.size - 1 - i < as.size := Nat.lt_of_le_of_lt (Nat.sub_le (as.size - 1) i) this match (← f (as.get ⟨as.size - 1 - i, this⟩) b) with | ForInStep.done b => pure b | ForInStep.yield b => loop i (Nat.le_of_lt h') b loop as.size (Nat.le_refl _) b instance : ForIn m ByteArray UInt8 where forIn := ByteArray.forIn /- See comment at forInUnsafe TODO: avoid code duplication. -/ @[inline] unsafe def foldlMUnsafe {β : Type v} {m : Type v → Type w} [Monad m] (f : β → UInt8 → m β) (init : β) (as : ByteArray) (start := 0) (stop := as.size) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i+1) stop (← f b (as.uget i lcProof)) if start < stop then if stop ≤ as.size then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else pure init /- Reference implementation for `foldlM` -/ @[implementedBy foldlMUnsafe] def foldlM {β : Type v} {m : Type v → Type w} [Monad m] (f : β → UInt8 → m β) (init : β) (as : ByteArray) (start := 0) (stop := as.size) : m β := let fold (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) (b : β) : m β := do if hlt : j < stop then match i with | 0 => pure b | i'+1 => loop i' (j+1) (← f b (as.get ⟨j, Nat.lt_of_lt_of_le hlt h⟩)) else pure b loop (stop - start) start init if h : stop ≤ as.size then fold stop h else fold as.size (Nat.le_refl _) @[inline] def foldl {β : Type v} (f : β → UInt8 → β) (init : β) (as : ByteArray) (start := 0) (stop := as.size) : β := Id.run <| as.foldlM f init start stop end ByteArray def List.toByteArray (bs : List UInt8) : ByteArray := let rec loop | [], r => r | b::bs, r => loop bs (r.push b) loop bs ByteArray.empty instance : ToString ByteArray := ⟨fun bs => bs.toList.toString⟩ /-- Interpret a `ByteArray` of size 8 as a little-endian `UInt64`. -/ def ByteArray.toUInt64LE! (bs : ByteArray) : UInt64 := assert! bs.size == 8 (bs.get! 0).toUInt64 <<< 0x38 ||| (bs.get! 1).toUInt64 <<< 0x30 ||| (bs.get! 2).toUInt64 <<< 0x28 ||| (bs.get! 3).toUInt64 <<< 0x20 ||| (bs.get! 4).toUInt64 <<< 0x18 ||| (bs.get! 5).toUInt64 <<< 0x10 ||| (bs.get! 6).toUInt64 <<< 0x8 ||| (bs.get! 7).toUInt64 /-- Interpret a `ByteArray` of size 8 as a big-endian `UInt64`. -/ def ByteArray.toUInt64BE! (bs : ByteArray) : UInt64 := assert! bs.size == 8 (bs.get! 7).toUInt64 <<< 0x38 ||| (bs.get! 6).toUInt64 <<< 0x30 ||| (bs.get! 5).toUInt64 <<< 0x28 ||| (bs.get! 4).toUInt64 <<< 0x20 ||| (bs.get! 3).toUInt64 <<< 0x18 ||| (bs.get! 2).toUInt64 <<< 0x10 ||| (bs.get! 1).toUInt64 <<< 0x8 ||| (bs.get! 0).toUInt64
d29d5e927e92e01fede60a3ae6a84473980c156d
aa101d73b1a3173c7ec56de02b96baa8ca64c42e
/src/solutions/tuto_lib.lean
9589580ad755f23cf14fb6c1c231607e1a99413f
[ "Apache-2.0" ]
permissive
gihanmarasingha/tutorials
b554d4d53866c493c4341dc13e914b01444e95a6
56617114ef0f9f7b808476faffd11e22e4380918
refs/heads/master
1,671,141,758,153
1,599,173,318,000
1,599,173,318,000
282,405,870
0
0
Apache-2.0
1,595,666,751,000
1,595,666,750,000
null
UTF-8
Lean
false
false
7,205
lean
import analysis.specific_limits import data.int.parity import topology.sequences attribute [instance] classical.prop_decidable /- Lemmas from that file were hidden in my course, or restating things which were proved without name in previous files. -/ notation `|`x`|` := abs x -- The mathlib version is unusable because it is stated in terms of ≤ lemma ge_max_iff {α : Type*} [decidable_linear_order α] {p q r : α} : r ≥ max p q ↔ r ≥ p ∧ r ≥ q := max_le_iff /- No idea why this is not in mathlib-/ lemma eq_of_abs_sub_le_all (x y : ℝ) : (∀ ε > 0, |x - y| ≤ ε) → x = y := begin intro h, apply decidable_linear_ordered_add_comm_group.eq_of_abs_sub_nonpos, by_contradiction H, push_neg at H, specialize h ( |x-y|/2) (by linarith), linarith, end def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε lemma unique_limit {u l l'} : seq_limit u l → seq_limit u l' → l = l' := begin intros hl hl', apply eq_of_abs_sub_le_all, intros ε ε_pos, specialize hl (ε/2) (by linarith), cases hl with N hN, specialize hl' (ε/2) (by linarith), cases hl' with N' hN', specialize hN (max N N') (le_max_left _ _), specialize hN' (max N N') (le_max_right _ _), calc |l - l'| = |(l-u (max N N')) + (u (max N N') -l')| : by ring ... ≤ |l - u (max N N')| + |u (max N N') - l'| : by apply abs_add ... = |u (max N N') - l| + |u (max N N') - l'| : by rw abs_sub ... ≤ ε/2 + ε/2 : by linarith ... = ε : by ring, end def pair (n : ℤ) := ∃ k, n = 2*k def int.odd (n : ℤ) := ∃ k, n = 2*k + 1 lemma int.not_even_iff_odd {n : ℤ} : ¬ int.even n ↔ int.odd n := begin rw int.not_even_iff, split ; intro h, use n/2, conv_rhs { rw add_comm, congr, rw ← h }, exact (int.mod_add_div n 2).symm, rcases h with ⟨k, rfl⟩, simp [add_comm], refl, end lemma le_of_le_add_all {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin contrapose!, intro h, use (y-x)/2, split ; linarith, end def upper_bound (A : set ℝ) (x : ℝ) := ∀ a ∈ A, a ≤ x def is_sup (A : set ℝ) (x : ℝ) := upper_bound A x ∧ ∀ y, upper_bound A y → x ≤ y lemma lt_sup {A : set ℝ} {x : ℝ} (hx : is_sup A x) : ∀ y, y < x → ∃ a ∈ A, y < a := begin intro y, contrapose!, exact hx.right y, end lemma squeeze {u v w : ℕ → ℝ} {l} (hu : seq_limit u l) (hw : seq_limit w l) (h : ∀ n, u n ≤ v n) (h' : ∀ n, v n ≤ w n) : seq_limit v l := begin intros ε ε_pos, cases hu ε ε_pos with N hN, cases hw ε ε_pos with N' hN', use max N N', intros n hn, rw ge_max_iff at hn, specialize hN n (by linarith), specialize hN' n (by linarith), specialize h n, specialize h' n, rw abs_le at *, split ; linarith end def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m def tendsto_infinity (u : ℕ → ℝ) := ∀ A, ∃ N, ∀ n ≥ N, u n ≥ A lemma lim_le {x y : ℝ} {u : ℕ → ℝ} (hu : seq_limit u x) (ineg : ∀ n, u n ≤ y) : x ≤ y := begin apply le_of_le_add_all, intros ε ε_pos, cases hu ε ε_pos with N hN, specialize hN N (by linarith), specialize ineg N, rw abs_le at hN, linarith, end lemma inv_succ_le_all : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε := begin convert metric.tendsto_at_top.mp (tendsto_one_div_add_at_top_nhds_0_nat), apply propext, simp only [real.dist_eq, sub_zero], split, intros h ε ε_pos, cases h (ε/2) (by linarith) with N hN, use N, intros n hn, rw abs_of_pos (nat.one_div_pos_of_nat : 1/(n+1 : ℝ) > 0), specialize hN n hn, linarith, intros h ε ε_pos, cases h ε (by linarith) with N hN, use N, intros n hn, specialize hN n hn, rw abs_of_pos (@nat.one_div_pos_of_nat ℝ _ n) at hN, linarith, end lemma limit_const (x : ℝ) : seq_limit (λ n, x) x := λ ε ε_pos, ⟨0, λ _ _, by simp [le_of_lt ε_pos]⟩ lemma limit_of_sub_le_inv_succ {u : ℕ → ℝ} {x : ℝ} (h : ∀ n, |u n - x| ≤ 1/(n+1)) : seq_limit u x := begin intros ε ε_pos, rcases inv_succ_le_all ε ε_pos with ⟨N, hN⟩, use N, intros n hn, specialize h n, specialize hN n hn, linarith, end lemma limit_const_add_inv_succ (x : ℝ) : seq_limit (λ n, x + 1/(n+1)) x := limit_of_sub_le_inv_succ (λ n, by rw abs_of_pos ; linarith [@nat.one_div_pos_of_nat ℝ _ n]) lemma limit_const_sub_inv_succ (x : ℝ) : seq_limit (λ n, x - 1/(n+1)) x := begin refine limit_of_sub_le_inv_succ (λ n, _), rw [show x - 1 / (n + 1) - x = -(1/(n+1)), by ring, abs_neg, abs_of_pos], linarith [@nat.one_div_pos_of_nat ℝ _ n] end 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 lemma seq_limit_id : tendsto_infinity (λ n, n) := begin intros A, cases exists_nat_gt A with N hN, use N, intros n hn, have : (n : ℝ) ≥ N, exact_mod_cast hn, linarith, end variables {u : ℕ → ℝ} {l : ℝ} {φ : ℕ → ℕ} open set filter def cluster_point (u : ℕ → ℝ) (a : ℝ) := ∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a lemma bolzano_weierstrass {a b : ℝ} {u : ℕ → ℝ} (h : ∀ n, u n ∈ Icc a b) : ∃ c ∈ Icc a b, cluster_point u c := begin rcases (compact_Icc : is_compact (Icc a b)).tendsto_subseq h with ⟨c, c_in, φ, hφ, lim⟩, use [c, c_in, φ, hφ], simp_rw [metric.tendsto_nhds, eventually_at_top, real.dist_eq] at lim, intros ε ε_pos, rcases lim ε ε_pos with ⟨N, hN⟩, use N, intros n hn, exact le_of_lt (hN n hn) end lemma not_seq_limit_of_tendstoinfinity {u : ℕ → ℝ} : tendsto_infinity u → ∀ x, ¬ seq_limit u x := begin intros lim_infinie x lim_x, cases lim_x 1 (by linarith) with N hN, cases lim_infinie (x+2) with N' hN', let N₀ := max N N', specialize hN N₀ (le_max_left _ _), specialize hN' N₀ (le_max_right _ _), rw abs_le at hN, linarith, end open real lemma sup_segment {a b : ℝ} {A : set ℝ} (hnonvide : ∃ x, x ∈ A) (h : A ⊆ Icc a b) : ∃ x ∈ Icc a b, is_sup A x := begin have b_maj : ∀ (y : ℝ), y ∈ A → y ≤ b, from λ y y_in, (h y_in).2, have Sup_maj : upper_bound A (Sup A), { intro x, apply real.le_Sup, use [b, b_maj] } , refine ⟨Sup A, _, _⟩, { split, { cases hnonvide with x x_in, exact le_trans (h x_in).1 (Sup_maj _ x_in) }, { apply Sup_le_ub A hnonvide b_maj } }, { use Sup_maj, intros y y_in, rwa real.Sup_le _ hnonvide ⟨b, b_maj⟩ }, end lemma subseq_tendsto_of_tendsto (h : seq_limit u l) (hφ : extraction φ) : seq_limit (u ∘ φ) l := begin 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, end namespace tactic.interactive open tactic meta def check_me : tactic unit := `[ { repeat { unfold seq_limit}, repeat { unfold continue_en }, push_neg, try { simp only [exists_prop] }, try { exact iff.rfl }, done } <|> fail "Ce n'est pas cela. Essayez encore." ] end tactic.interactive
ca9d0ecda5b5595c6ce499f2125c0de9078c3432
82e44445c70db0f03e30d7be725775f122d72f3e
/src/topology/metric_space/antilipschitz.lean
fd3f5feb157e967e9e2dbcd9586a182bbe745a61
[ "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
8,784
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.metric_space.lipschitz import topology.uniform_space.complete_separated /-! # Antilipschitz functions We say that a map `f : α → β` between two (extended) metric spaces is `antilipschitz_with K`, `K ≥ 0`, if for all `x, y` we have `edist x y ≤ K * edist (f x) (f y)`. For a metric space, the latter inequality is equivalent to `dist x y ≤ K * dist (f x) (f y)`. ## Implementation notes The parameter `K` has type `ℝ≥0`. This way we avoid conjuction in the definition and have coercions both to `ℝ` and `ℝ≥0∞`. We do not require `0 < K` in the definition, mostly because we do not have a `posreal` type. -/ variables {α : Type*} {β : Type*} {γ : Type*} open_locale nnreal ennreal uniformity open set /-- We say that `f : α → β` is `antilipschitz_with K` if for any two points `x`, `y` we have `K * edist x y ≤ edist (f x) (f y)`. -/ def antilipschitz_with [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (f : α → β) := ∀ x y, edist x y ≤ K * edist (f x) (f y) section metric variables [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} lemma antilipschitz_with_iff_le_mul_nndist : antilipschitz_with K f ↔ ∀ x y, nndist x y ≤ K * nndist (f x) (f y) := by { simp only [antilipschitz_with, edist_nndist], norm_cast } alias antilipschitz_with_iff_le_mul_nndist ↔ antilipschitz_with.le_mul_nndist antilipschitz_with.of_le_mul_nndist lemma antilipschitz_with_iff_le_mul_dist : antilipschitz_with K f ↔ ∀ x y, dist x y ≤ K * dist (f x) (f y) := by { simp only [antilipschitz_with_iff_le_mul_nndist, dist_nndist], norm_cast } alias antilipschitz_with_iff_le_mul_dist ↔ antilipschitz_with.le_mul_dist antilipschitz_with.of_le_mul_dist namespace antilipschitz_with lemma mul_le_nndist (hf : antilipschitz_with K f) (x y : α) : K⁻¹ * nndist x y ≤ nndist (f x) (f y) := by simpa only [div_eq_inv_mul] using nnreal.div_le_of_le_mul' (hf.le_mul_nndist x y) lemma mul_le_dist (hf : antilipschitz_with K f) (x y : α) : (K⁻¹ * dist x y : ℝ) ≤ dist (f x) (f y) := by exact_mod_cast hf.mul_le_nndist x y end antilipschitz_with end metric namespace antilipschitz_with variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ] variables {K : ℝ≥0} {f : α → β} open emetric /-- Extract the constant from `hf : antilipschitz_with K f`. This is useful, e.g., if `K` is given by a long formula, and we want to reuse this value. -/ @[nolint unused_arguments] -- uses neither `f` nor `hf` protected def K (hf : antilipschitz_with K f) : ℝ≥0 := K protected lemma injective {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) : function.injective f := λ x y h, by simpa only [h, edist_self, mul_zero, edist_le_zero] using hf x y lemma mul_le_edist (hf : antilipschitz_with K f) (x y : α) : (K⁻¹ * edist x y : ℝ≥0∞) ≤ edist (f x) (f y) := begin rw [mul_comm, ← div_eq_mul_inv], exact ennreal.div_le_of_le_mul' (hf x y) end lemma ediam_preimage_le (hf : antilipschitz_with K f) (s : set β) : diam (f ⁻¹' s) ≤ K * diam s := diam_le $ λ x hx y hy, (hf x y).trans $ mul_le_mul_left' (edist_le_diam_of_mem hx hy) K lemma le_mul_ediam_image (hf : antilipschitz_with K f) (s : set α) : diam s ≤ K * diam (f '' s) := (diam_mono (subset_preimage_image _ _)).trans (hf.ediam_preimage_le (f '' s)) protected lemma id : antilipschitz_with 1 (id : α → α) := λ x y, by simp only [ennreal.coe_one, one_mul, id, le_refl] lemma comp {Kg : ℝ≥0} {g : β → γ} (hg : antilipschitz_with Kg g) {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) : antilipschitz_with (Kf * Kg) (g ∘ f) := λ x y, calc edist x y ≤ Kf * edist (f x) (f y) : hf x y ... ≤ Kf * (Kg * edist (g (f x)) (g (f y))) : ennreal.mul_left_mono (hg _ _) ... = _ : by rw [ennreal.coe_mul, mul_assoc] lemma restrict (hf : antilipschitz_with K f) (s : set α) : antilipschitz_with K (s.restrict f) := λ x y, hf x y lemma cod_restrict (hf : antilipschitz_with K f) {s : set β} (hs : ∀ x, f x ∈ s) : antilipschitz_with K (s.cod_restrict f hs) := λ x y, hf x y lemma to_right_inv_on' {s : set α} (hf : antilipschitz_with K (s.restrict f)) {g : β → α} {t : set β} (g_maps : maps_to g t s) (g_inv : right_inv_on g f t) : lipschitz_with K (t.restrict g) := λ x y, by simpa only [restrict_apply, g_inv x.mem, g_inv y.mem, subtype.edist_eq, subtype.coe_mk] using hf ⟨g x, g_maps x.mem⟩ ⟨g y, g_maps y.mem⟩ lemma to_right_inv_on (hf : antilipschitz_with K f) {g : β → α} {t : set β} (h : right_inv_on g f t) : lipschitz_with K (t.restrict g) := (hf.restrict univ).to_right_inv_on' (maps_to_univ g t) h lemma to_right_inverse (hf : antilipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : lipschitz_with K g := begin intros x y, have := hf (g x) (g y), rwa [hg x, hg y] at this end lemma comap_uniformity_le (hf : antilipschitz_with K f) : (𝓤 β).comap (prod.map f f) ≤ 𝓤 α := begin refine ((uniformity_basis_edist.comap _).le_basis_iff uniformity_basis_edist).2 (λ ε h₀, _), refine ⟨K⁻¹ * ε, ennreal.mul_pos.2 ⟨ennreal.inv_pos.2 ennreal.coe_ne_top, h₀⟩, _⟩, refine λ x hx, (hf x.1 x.2).trans_lt _, rw [mul_comm, ← div_eq_mul_inv] at hx, rw mul_comm, exact ennreal.mul_lt_of_lt_div hx end protected lemma uniform_inducing (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : uniform_inducing f := ⟨le_antisymm hf.comap_uniformity_le hfc.le_comap⟩ protected lemma uniform_embedding {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : uniform_embedding f := ⟨hf.uniform_inducing hfc, hf.injective⟩ lemma is_complete_range [complete_space α] (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : is_complete (range f) := (hf.uniform_inducing hfc).is_complete_range lemma is_closed_range {α β : Type*} [pseudo_emetric_space α] [emetric_space β] [complete_space α] {f : α → β} {K : ℝ≥0} (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : is_closed (range f) := (hf.is_complete_range hfc).is_closed lemma closed_embedding {α : Type*} {β : Type*} [emetric_space α] [emetric_space β] {K : ℝ≥0} {f : α → β} [complete_space α] (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : closed_embedding f := { closed_range := hf.is_closed_range hfc, .. (hf.uniform_embedding hfc).embedding } lemma subtype_coe (s : set α) : antilipschitz_with 1 (coe : s → α) := antilipschitz_with.id.restrict s lemma of_subsingleton [subsingleton α] {K : ℝ≥0} : antilipschitz_with K f := λ x y, by simp only [subsingleton.elim x y, edist_self, zero_le] /-- If `f : α → β` is `0`-antilipschitz, then `α` is a `subsingleton`. -/ protected lemma subsingleton {α β} [emetric_space α] [pseudo_emetric_space β] {f : α → β} (h : antilipschitz_with 0 f) : subsingleton α := ⟨λ x y, edist_le_zero.1 $ (h x y).trans_eq $ zero_mul _⟩ end antilipschitz_with namespace antilipschitz_with open metric variables [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} lemma bounded_preimage (hf : antilipschitz_with K f) {s : set β} (hs : bounded s) : bounded (f ⁻¹' s) := exists.intro (K * diam s) $ λ x y hx hy, calc dist x y ≤ K * dist (f x) (f y) : hf.le_mul_dist x y ... ≤ K * diam s : mul_le_mul_of_nonneg_left (dist_le_diam_of_mem hs hx hy) K.2 /-- The image of a proper space under an expanding onto map is proper. -/ protected lemma proper_space {α : Type*} [metric_space α] {K : ℝ≥0} {f : α → β} [proper_space α] (hK : antilipschitz_with K f) (f_cont : continuous f) (hf : function.surjective f) : proper_space β := begin apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _), let K := f ⁻¹' (closed_ball x₀ r), have A : is_closed K := is_closed_ball.preimage f_cont, have B : bounded K := hK.bounded_preimage bounded_closed_ball, have : is_compact K := compact_iff_closed_bounded.2 ⟨A, B⟩, convert this.image f_cont, exact (hf.image_preimage _).symm end end antilipschitz_with lemma lipschitz_with.to_right_inverse [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : lipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : antilipschitz_with K g := λ x y, by simpa only [hg _] using hf (g x) (g y)
3a637f927357dec0139f5e0b058bb955ff5bace2
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast27.lean
b46ec0d51a070fd8786be0f2633956f6dccda2eb
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,152
lean
-- Basic (propositional) forward chaining with conjunctive conclusions constants (a b c d e : nat) constants (p : nat → Prop) constants (q : nat → nat → Prop) constants (f : nat → nat) set_option blast.recursor false set_option blast.subst false definition lemma1 : a = d → b = e → p b → (p a → (¬ p e) ∧ p c) → ¬ p d := by blast definition lemma2a : ¬ p b → (p d → p b ∧ p c) → d = e → e = a → ¬ p a := by blast definition lemma2b : ¬ p (f b) → (p (f a) → p (f d) ∧ p (f c)) → b = d → ¬ p (f a) := by blast definition lemma3 : p (f (f b)) → (p (f a) → p (f c) ∧ (¬ p (f (f (f (f b)))))) → b = f b → ¬ p (f a) := by blast definition lemma4a : b = f b → ¬ p (f (f b)) → (p a → q c c ∧ p (f (f (f (f (f b)))))) → ¬ p a := by blast definition lemma4b : b = f b → ¬ p (f (f b)) → (p a → q c c ∧ q e c ∧ q d e ∧ p (f (f (f (f (f b))))) ∧ q e d) → ¬ p a := by blast definition lemma5 : p b → (p (f a) → (¬ p b) ∧ p e ∧ p c) → ¬ p (f a) := by blast definition lemma6 : ¬ (q b a) → d = a → (p a → p e ∧ (q b d) ∧ p c) → ¬ p a := by blast
cb918efdde7aaf2ca905ac9bca665c0efad3bcb3
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/shrinking_lemma.lean
be82d9206caafc48e0efb66e837e1c8064cbd898
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
12,200
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Reid Barton -/ import topology.separation /-! # The shrinking lemma In this file we prove a few versions of the shrinking lemma. The lemma says that in a normal topological space a point finite open covering can be “shrunk”: for a point finite open covering `u : ι → set X` there exists a refinement `v : ι → set X` such that `closure (v i) ⊆ u i`. For finite or countable coverings this lemma can be proved without the axiom of choice, see [ncatlab](https://ncatlab.org/nlab/show/shrinking+lemma) for details. We only formalize the most general result that works for any covering but needs the axiom of choice. We prove two versions of the lemma: * `exists_subset_Union_closure_subset` deals with a covering of a closed set in a normal space; * `exists_Union_eq_closure_subset` deals with a covering of the whole space. ## Tags normal space, shrinking lemma -/ open set zorn function open_locale classical noncomputable theory variables {ι X : Type*} [topological_space X] [normal_space X] namespace shrinking_lemma /-- Auxiliary definition for the proof of `shrinking_lemma`. A partial refinement of a covering `⋃ i, u i` of a set `s` is a map `v : ι → set X` and a set `carrier : set ι` such that * `s ⊆ ⋃ i, v i`; * all `v i` are open; * if `i ∈ carrier v`, then `closure (v i) ⊆ u i`; * if `i ∉ carrier`, then `v i = u i`. This type is equipped with the folowing partial order: `v ≤ v'` if `v.carrier ⊆ v'.carrier` and `v i = v' i` for `i ∈ v.carrier`. We will use Zorn's lemma to prove that this type has a maximal element, then show that the maximal element must have `carrier = univ`. -/ @[nolint has_inhabited_instance] -- the trivial refinement needs `u` to be a covering structure partial_refinement (u : ι → set X) (s : set X) := (to_fun : ι → set X) (carrier : set ι) (is_open' : ∀ i, is_open (to_fun i)) (subset_Union' : s ⊆ ⋃ i, to_fun i) (closure_subset' : ∀ i ∈ carrier, closure (to_fun i) ⊆ (u i)) (apply_eq' : ∀ i ∉ carrier, to_fun i = u i) namespace partial_refinement variables {u : ι → set X} {s : set X} instance : has_coe_to_fun (partial_refinement u s) := ⟨_, to_fun⟩ lemma subset_Union (v : partial_refinement u s) : s ⊆ ⋃ i, v i := v.subset_Union' lemma closure_subset (v : partial_refinement u s) {i : ι} (hi : i ∈ v.carrier) : closure (v i) ⊆ (u i) := v.closure_subset' i hi lemma apply_eq (v : partial_refinement u s) {i : ι} (hi : i ∉ v.carrier) : v i = u i := v.apply_eq' i hi protected lemma is_open (v : partial_refinement u s) (i : ι) : is_open (v i) := v.is_open' i protected lemma subset (v : partial_refinement u s) (i : ι) : v i ⊆ u i := if h : i ∈ v.carrier then subset.trans subset_closure (v.closure_subset h) else (v.apply_eq h).le attribute [ext] partial_refinement instance : partial_order (partial_refinement u s) := { le := λ v₁ v₂, v₁.carrier ⊆ v₂.carrier ∧ ∀ i ∈ v₁.carrier, v₁ i = v₂ i, le_refl := λ v, ⟨subset.refl _, λ _ _, rfl⟩, le_trans := λ v₁ v₂ v₃ h₁₂ h₂₃, ⟨subset.trans h₁₂.1 h₂₃.1, λ i hi, (h₁₂.2 i hi).trans (h₂₃.2 i $ h₁₂.1 hi)⟩, le_antisymm := λ v₁ v₂ h₁₂ h₂₁, have hc : v₁.carrier = v₂.carrier, from subset.antisymm h₁₂.1 h₂₁.1, ext _ _ (funext $ λ x, if hx : x ∈ v₁.carrier then h₁₂.2 _ hx else (v₁.apply_eq hx).trans (eq.symm $ v₂.apply_eq $ hc ▸ hx)) hc } /-- If two partial refinements `v₁`, `v₂` belong to a chain (hence, they are comparable) and `i` belongs to the carriers of both partial refinements, then `v₁ i = v₂ i`. -/ lemma apply_eq_of_chain {c : set (partial_refinement u s)} (hc : chain (≤) c) {v₁ v₂} (h₁ : v₁ ∈ c) (h₂ : v₂ ∈ c) {i} (hi₁ : i ∈ v₁.carrier) (hi₂ : i ∈ v₂.carrier) : v₁ i = v₂ i := begin wlog hle : v₁ ≤ v₂ := hc.total_of_refl h₁ h₂ using [v₁ v₂, v₂ v₁], exact hle.2 _ hi₁, end /-- The carrier of the least upper bound of a non-empty chain of partial refinements is the union of their carriers. -/ def chain_Sup_carrier (c : set (partial_refinement u s)) : set ι := ⋃ v ∈ c, carrier v /-- Choice of an element of a nonempty chain of partial refinements. If `i` belongs to one of `carrier v`, `v ∈ c`, then `find c ne i` is one of these partial refinements. -/ def find (c : set (partial_refinement u s)) (ne : c.nonempty) (i : ι) : partial_refinement u s := if hi : ∃ v ∈ c, i ∈ carrier v then hi.some else ne.some lemma find_mem {c : set (partial_refinement u s)} (i : ι) (ne : c.nonempty) : find c ne i ∈ c := by { rw find, split_ifs, exacts [h.some_spec.fst, ne.some_spec] } lemma mem_find_carrier_iff {c : set (partial_refinement u s)} {i : ι} (ne : c.nonempty) : i ∈ (find c ne i).carrier ↔ i ∈ chain_Sup_carrier c := begin rw find, split_ifs, { have : i ∈ h.some.carrier ∧ i ∈ chain_Sup_carrier c, from ⟨h.some_spec.snd, mem_bUnion_iff.2 h⟩, simp only [this] }, { have : i ∉ ne.some.carrier ∧ i ∉ chain_Sup_carrier c, from ⟨λ hi, h ⟨_, ne.some_spec, hi⟩, mt mem_bUnion_iff.1 h⟩, simp only [this] } end lemma find_apply_of_mem {c : set (partial_refinement u s)} (hc : chain (≤) c) (ne : c.nonempty) {i v} (hv : v ∈ c) (hi : i ∈ carrier v) : find c ne i i = v i := apply_eq_of_chain hc (find_mem _ _) hv ((mem_find_carrier_iff _).2 $ mem_bUnion_iff.2 ⟨v, hv, hi⟩) hi /-- Least upper bound of a nonempty chain of partial refinements. -/ def chain_Sup (c : set (partial_refinement u s)) (hc : chain (≤) c) (ne : c.nonempty) (hfin : ∀ x ∈ s, finite {i | x ∈ u i}) (hU : s ⊆ ⋃ i, u i) : partial_refinement u s := begin refine ⟨λ i, find c ne i i, chain_Sup_carrier c, λ i, (find _ _ _).is_open i, λ x hxs, mem_Union.2 _, λ i hi, (find c ne i).closure_subset ((mem_find_carrier_iff _).2 hi), λ i hi, (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi)⟩, rcases em (∃ i ∉ chain_Sup_carrier c, x ∈ u i) with ⟨i, hi, hxi⟩|hx, { use i, rwa (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi) }, { simp_rw [not_exists, not_imp_not, chain_Sup_carrier, mem_bUnion_iff] at hx, haveI : nonempty (partial_refinement u s) := ⟨ne.some⟩, choose! v hvc hiv using hx, rcases (hfin x hxs).exists_maximal_wrt v _ (mem_Union.1 (hU hxs)) with ⟨i, hxi : x ∈ u i, hmax : ∀ j, x ∈ u j → v i ≤ v j → v i = v j⟩, rcases mem_Union.1 ((v i).subset_Union hxs) with ⟨j, hj⟩, use j, have hj' : x ∈ u j := (v i).subset _ hj, have : v j ≤ v i, from (hc.total_of_refl (hvc _ hxi) (hvc _ hj')).elim (λ h, (hmax j hj' h).ge) id, rwa find_apply_of_mem hc ne (hvc _ hxi) (this.1 $ hiv _ hj') } end /-- `chain_Sup hu c hc ne hfin hU` is an upper bound of the chain `c`. -/ lemma le_chain_Sup {c : set (partial_refinement u s)} (hc : chain (≤) c) (ne : c.nonempty) (hfin : ∀ x ∈ s, finite {i | x ∈ u i}) (hU : s ⊆ ⋃ i, u i) {v} (hv : v ∈ c) : v ≤ chain_Sup c hc ne hfin hU := ⟨λ i hi, mem_bUnion hv hi, λ i hi, (find_apply_of_mem hc _ hv hi).symm⟩ /-- If `s` is a closed set, `v` is a partial refinement, and `i` is an index such that `i ∉ v.carrier`, then there exists a partial refinement that is strictly greater than `v`. -/ lemma exists_gt (v : partial_refinement u s) (hs : is_closed s) (i : ι) (hi : i ∉ v.carrier) : ∃ v' : partial_refinement u s, v < v' := begin have I : s ∩ (⋂ j ≠ i, (v j)ᶜ) ⊆ v i, { simp only [subset_def, mem_inter_eq, mem_Inter, and_imp], intros x hxs H, rcases mem_Union.1 (v.subset_Union hxs) with ⟨j, hj⟩, exact (em (j = i)).elim (λ h, h ▸ hj) (λ h, (H j h hj).elim) }, have C : is_closed (s ∩ (⋂ j ≠ i, (v j)ᶜ)), from is_closed.inter hs (is_closed_bInter $ λ _ _, is_closed_compl_iff.2 $ v.is_open _), rcases normal_exists_closure_subset C (v.is_open i) I with ⟨vi, ovi, hvi, cvi⟩, refine ⟨⟨update v i vi, insert i v.carrier, _, _, _, _⟩, _, _⟩, { intro j, by_cases h : j = i; simp [h, ovi, v.is_open] }, { refine λ x hx, mem_Union.2 _, rcases em (∃ j ≠ i, x ∈ v j) with ⟨j, hji, hj⟩|h, { use j, rwa update_noteq hji }, { push_neg at h, use i, rw update_same, exact hvi ⟨hx, mem_bInter h⟩ } }, { rintro j (rfl|hj), { rwa [update_same, ← v.apply_eq hi] }, { rw update_noteq (ne_of_mem_of_not_mem hj hi), exact v.closure_subset hj } }, { intros j hj, rw [mem_insert_iff, not_or_distrib] at hj, rw [update_noteq hj.1, v.apply_eq hj.2] }, { refine ⟨subset_insert _ _, λ j hj, _⟩, exact (update_noteq (ne_of_mem_of_not_mem hj hi) _ _).symm }, { exact λ hle, hi (hle.1 $ mem_insert _ _) } end end partial_refinement end shrinking_lemma open shrinking_lemma variables {u : ι → set X} {s : set X} /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new open cover so that the closure of each new open set is contained in the corresponding original open set. -/ lemma exists_subset_Union_closure_subset (hs : is_closed s) (uo : ∀ i, is_open (u i)) (uf : ∀ x ∈ s, finite {i | x ∈ u i}) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → set X, s ⊆ Union v ∧ (∀ i, is_open (v i)) ∧ ∀ i, closure (v i) ⊆ u i := begin classical, haveI : nonempty (partial_refinement u s) := ⟨⟨u, ∅, uo, us, λ _, false.elim, λ _ _, rfl⟩⟩, have : ∀ c : set (partial_refinement u s), chain (≤) c → c.nonempty → ∃ ub, ∀ v ∈ c, v ≤ ub, from λ c hc ne, ⟨partial_refinement.chain_Sup c hc ne uf us, λ v hv, partial_refinement.le_chain_Sup _ _ _ _ hv⟩, rcases zorn_nonempty_partial_order this with ⟨v, hv⟩, suffices : ∀ i, i ∈ v.carrier, from ⟨v, v.subset_Union, λ i, v.is_open _, λ i, v.closure_subset (this i)⟩, contrapose! hv, rcases hv with ⟨i, hi⟩, rcases v.exists_gt hs i hi with ⟨v', hlt⟩, exact ⟨v', hlt.le, hlt.ne'⟩ end /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new closed cover so that each new closed set is contained in the corresponding original open set. See also `exists_subset_Union_closure_subset` for a stronger statement. -/ lemma exists_subset_Union_closed_subset (hs : is_closed s) (uo : ∀ i, is_open (u i)) (uf : ∀ x ∈ s, finite {i | x ∈ u i}) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → set X, s ⊆ Union v ∧ (∀ i, is_closed (v i)) ∧ ∀ i, v i ⊆ u i := let ⟨v, hsv, hvo, hv⟩ := exists_subset_Union_closure_subset hs uo uf us in ⟨λ i, closure (v i), subset.trans hsv (Union_subset_Union $ λ i, subset_closure), λ i, is_closed_closure, hv⟩ /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new open cover so that the closure of each new open set is contained in the corresponding original open set. -/ lemma exists_Union_eq_closure_subset (uo : ∀ i, is_open (u i)) (uf : ∀ x, finite {i | x ∈ u i}) (uU : (⋃ i, u i) = univ) : ∃ v : ι → set X, Union v = univ ∧ (∀ i, is_open (v i)) ∧ ∀ i, closure (v i) ⊆ u i := let ⟨v, vU, hv⟩ := exists_subset_Union_closure_subset is_closed_univ uo (λ x _, uf x) uU.ge in ⟨v, univ_subset_iff.1 vU, hv⟩ /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new closed cover so that each of the new closed sets is contained in the corresponding original open set. See also `exists_Union_eq_closure_subset` for a stronger statement. -/ lemma exists_Union_eq_closed_subset (uo : ∀ i, is_open (u i)) (uf : ∀ x, finite {i | x ∈ u i}) (uU : (⋃ i, u i) = univ) : ∃ v : ι → set X, Union v = univ ∧ (∀ i, is_closed (v i)) ∧ ∀ i, v i ⊆ u i := let ⟨v, vU, hv⟩ := exists_subset_Union_closed_subset is_closed_univ uo (λ x _, uf x) uU.ge in ⟨v, univ_subset_iff.1 vU, hv⟩
6b524a5cfe4c491e5ff14620f36a750ac509d288
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/polynomial/vieta.lean
9c4512d5551edc1cf7417c62b171eff30d888c5d
[ "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,913
lean
/- Copyright (c) 2020 Hanting Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hanting Zhang -/ import field_theory.splitting_field import ring_theory.polynomial.symmetric /-! # Vieta's Formula The main result is `multiset.prod_X_add_C_eq_sum_esymm`, which shows that the product of linear terms `X + λ` with `λ` in a `multiset s` is equal to a linear combination of the symmetric functions `esymm s`. From this, we deduce `mv_polynomial.prod_X_add_C_eq_sum_esymm` which is the equivalent formula for the product of linear terms `X + X i` with `i` in a `fintype σ` as a linear combination of the symmetric polynomials `esymm σ R j`. For `R` be an integral domain (so that `p.roots` is defined for any `p : R[X]` as a multiset), we derive `polynomial.coeff_eq_esymm_roots_of_card`, the relationship between the coefficients and the roots of `p` for a polynomial `p` that splits (i.e. having as many roots as its degree). -/ open_locale big_operators polynomial namespace multiset open polynomial section semiring variables {R : Type*} [comm_semiring R] /-- A sum version of Vieta's formula for `multiset`: the product of the linear terms `X + λ` where `λ` runs through a multiset `s` is equal to a linear combination of the symmetric functions `esymm s` of the `λ`'s .-/ lemma prod_X_add_C_eq_sum_esymm (s : multiset R) : (s.map (λ r, X + C r)).prod = ∑ j in finset.range (s.card + 1), C (s.esymm j) * X ^ (s.card - j) := begin classical, rw [prod_map_add, antidiagonal_eq_map_powerset, map_map, ←bind_powerset_len, function.comp, map_bind, sum_bind, finset.sum_eq_multiset_sum, finset.range_coe, map_congr (eq.refl _)], intros _ _, rw [esymm, ←sum_hom', ←sum_map_mul_right, map_congr (eq.refl _)], intros _ ht, rw mem_powerset_len at ht, simp [ht, map_const, prod_repeat, prod_hom', map_id', card_sub], end /-- Vieta's formula for the coefficients of the product of linear terms `X + λ` where `λ` runs through a multiset `s` : the `k`th coefficient is the symmetric function `esymm (card s - k) s`. -/ lemma prod_X_add_C_coeff (s : multiset R) {k : ℕ} (h : k ≤ s.card) : (s.map (λ r, X + C r)).prod.coeff k = s.esymm (s.card - k) := begin convert polynomial.ext_iff.mp (prod_X_add_C_eq_sum_esymm s) k, simp_rw [finset_sum_coeff, coeff_C_mul_X_pow], rw finset.sum_eq_single_of_mem (s.card - k) _, { rw if_pos (nat.sub_sub_self h).symm, }, { intros j hj1 hj2, suffices : k ≠ card s - j, { rw if_neg this, }, { intro hn, rw [hn, nat.sub_sub_self (nat.lt_succ_iff.mp (finset.mem_range.mp hj1))] at hj2, exact ne.irrefl hj2, }}, { rw finset.mem_range, exact nat.sub_lt_succ s.card k } end lemma prod_X_add_C_coeff' {σ} (s : multiset σ) (r : σ → R) {k : ℕ} (h : k ≤ s.card) : (s.map (λ i, X + C (r i))).prod.coeff k = (s.map r).esymm (s.card - k) := by rw [← map_map (λ r, X + C r) r, prod_X_add_C_coeff]; rwa s.card_map r lemma _root_.finset.prod_X_add_C_coeff {σ} (s : finset σ) (r : σ → R) {k : ℕ} (h : k ≤ s.card) : (∏ i in s, (X + C (r i))).coeff k = ∑ t in s.powerset_len (s.card - k), ∏ i in t, r i := by { rw [finset.prod, prod_X_add_C_coeff' _ r h, finset.esymm_map_val], refl } end semiring section ring variables {R : Type*} [comm_ring R] lemma esymm_neg (s : multiset R) (k : ℕ) : (map has_neg.neg s).esymm k = (-1) ^ k * esymm s k := begin rw [esymm, esymm, ←multiset.sum_map_mul_left, multiset.powerset_len_map, multiset.map_map, map_congr (eq.refl _)], intros x hx, rw [(by { exact (mem_powerset_len.mp hx).right.symm }), ←prod_repeat, ←multiset.map_const], nth_rewrite 2 ←map_id' x, rw [←prod_map_mul, map_congr (eq.refl _)], exact λ z _, neg_one_mul z, end lemma prod_X_sub_C_eq_sum_esymm (s : multiset R) : (s.map (λ t, X - C t)).prod = ∑ j in finset.range (s.card + 1), (-1) ^ j * (C (s.esymm j) * X ^ (s.card - j)) := begin conv_lhs { congr, congr, funext, rw sub_eq_add_neg, rw ←map_neg C _, }, convert prod_X_add_C_eq_sum_esymm (map (λ t, -t) s) using 1, { rwa map_map, }, { simp only [esymm_neg, card_map, mul_assoc, map_mul, map_pow, map_neg, map_one], }, end lemma prod_X_sub_C_coeff (s : multiset R) {k : ℕ} (h : k ≤ s.card) : (s.map (λ t, X - C t)).prod.coeff k = (-1) ^ (s.card - k) * s.esymm (s.card - k) := begin conv_lhs { congr, congr, congr, funext, rw sub_eq_add_neg, rw ←map_neg C _, }, convert prod_X_add_C_coeff (map (λ t, -t) s) _ using 1, { rwa map_map, }, { rwa [esymm_neg, card_map] }, { rwa card_map }, end /-- Vieta's formula for the coefficients and the roots of a polynomial over an integral domain with as many roots as its degree. -/ theorem _root_.polynomial.coeff_eq_esymm_roots_of_card [is_domain R] {p : R[X]} (hroots : p.roots.card = p.nat_degree) {k : ℕ} (h : k ≤ p.nat_degree) : p.coeff k = p.leading_coeff * (-1) ^ (p.nat_degree - k) * p.roots.esymm (p.nat_degree - k) := begin conv_lhs { rw ← C_leading_coeff_mul_prod_multiset_X_sub_C hroots }, rw [coeff_C_mul, mul_assoc], congr, convert p.roots.prod_X_sub_C_coeff _ using 3; rw hroots, exact h, end /-- Vieta's formula for split polynomials over a field. -/ theorem _root_.polynomial.coeff_eq_esymm_roots_of_splits {F} [field F] {p : F[X]} (hsplit : p.splits (ring_hom.id F)) {k : ℕ} (h : k ≤ p.nat_degree) : p.coeff k = p.leading_coeff * (-1) ^ (p.nat_degree - k) * p.roots.esymm (p.nat_degree - k) := polynomial.coeff_eq_esymm_roots_of_card (splits_iff_card_roots.1 hsplit) h end ring end multiset section mv_polynomial open finset polynomial fintype variables (R σ : Type*) [comm_semiring R] [fintype σ] /-- A sum version of Vieta's formula for `mv_polynomial`: viewing `X i` as variables, the product of linear terms `λ + X i` is equal to a linear combination of the symmetric polynomials `esymm σ R j`. -/ lemma mv_polynomial.prod_C_add_X_eq_sum_esymm : ∏ i : σ, (X + C (mv_polynomial.X i)) = ∑ j in range (card σ + 1), (C (mv_polynomial.esymm σ R j) * X ^ (card σ - j)) := begin let s := finset.univ.val.map (λ i : σ, mv_polynomial.X i), rw (_ : card σ = s.card), { simp_rw [mv_polynomial.esymm_eq_multiset_esymm σ R, finset.prod_eq_multiset_prod], convert multiset.prod_X_add_C_eq_sum_esymm s, rwa multiset.map_map, }, { rw multiset.card_map, refl, } end lemma mv_polynomial.prod_X_add_C_coeff (k : ℕ) (h : k ≤ card σ) : (∏ i : σ, (X + C (mv_polynomial.X i))).coeff k = mv_polynomial.esymm σ R (card σ - k) := begin let s := finset.univ.val.map (λ i, (mv_polynomial.X i : mv_polynomial σ R)), rw (_ : card σ = s.card) at ⊢ h, { rw [mv_polynomial.esymm_eq_multiset_esymm σ R, finset.prod_eq_multiset_prod], convert multiset.prod_X_add_C_coeff s h, rwa multiset.map_map }, repeat { rw multiset.card_map, refl, }, end end mv_polynomial
6ffbd55fe7292dd08d2a94ace1ad182c2c22e3f1
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/topology/algebra/open_subgroup.lean
98eefa8310521794847e695caf8b34823b5c5f8b
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
7,253
lean
/- Copyright (c) 2019 Johan Commelin All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import order.filter.lift import topology.opens import topology.algebra.ring open topological_space open_locale topological_space set_option old_structure_cmd true /-- The type of open subgroups of a topological additive group. -/ @[ancestor add_subgroup] structure open_add_subgroup (G : Type*) [add_group G] [topological_space G] extends add_subgroup G := (is_open' : is_open carrier) /-- The type of open subgroups of a topological group. -/ @[ancestor subgroup, to_additive open_add_subgroup] structure open_subgroup (G : Type*) [group G] [topological_space G] extends subgroup G := (is_open' : is_open carrier) /-- Reinterpret an `open_subgroup` as a `subgroup`. -/ add_decl_doc open_subgroup.to_subgroup /-- Reinterpret an `open_add_subgroup` as an `add_subgroup`. -/ add_decl_doc open_add_subgroup.to_add_subgroup -- Tell Lean that `open_add_subgroup` is a namespace namespace open_add_subgroup end open_add_subgroup namespace open_subgroup open function topological_space variables {G : Type*} [group G] [topological_space G] variables {U V : open_subgroup G} {g : G} @[to_additive] instance has_coe_set : has_coe_t (open_subgroup G) (set G) := ⟨λ U, U.1⟩ @[to_additive] instance : has_mem G (open_subgroup G) := ⟨λ g U, g ∈ (U : set G)⟩ @[to_additive] instance has_coe_subgroup : has_coe_t (open_subgroup G) (subgroup G) := ⟨to_subgroup⟩ @[to_additive] instance has_coe_opens : has_coe_t (open_subgroup G) (opens G) := ⟨λ U, ⟨U, U.is_open'⟩⟩ @[simp, to_additive] lemma mem_coe : g ∈ (U : set G) ↔ g ∈ U := iff.rfl @[simp, to_additive] lemma mem_coe_opens : g ∈ (U : opens G) ↔ g ∈ U := iff.rfl @[simp, to_additive mem_coe_add_subgroup] lemma mem_coe_subgroup : g ∈ (U : subgroup G) ↔ g ∈ U := iff.rfl attribute [norm_cast] mem_coe mem_coe_opens mem_coe_subgroup open_add_subgroup.mem_coe open_add_subgroup.mem_coe_opens open_add_subgroup.mem_coe_add_subgroup @[to_additive] lemma ext' : injective (coe : open_subgroup G → set G) := λ U V h, by cases U; cases V; congr; assumption @[ext, to_additive] lemma ext (h : ∀ x, x ∈ U ↔ x ∈ V) : (U = V) := ext' $ set.ext h @[to_additive] lemma ext_iff : (U = V) ↔ (∀ x, x ∈ U ↔ x ∈ V) := ⟨λ h x, h ▸ iff.rfl, ext⟩ variable (U) @[to_additive] protected lemma is_open : is_open (U : set G) := U.is_open' @[to_additive] protected lemma one_mem : (1 : G) ∈ U := U.one_mem' @[to_additive] protected lemma inv_mem {g : G} (h : g ∈ U) : g⁻¹ ∈ U := U.inv_mem' h @[to_additive] protected lemma mul_mem {g₁ g₂ : G} (h₁ : g₁ ∈ U) (h₂ : g₂ ∈ U) : g₁ * g₂ ∈ U := U.mul_mem' h₁ h₂ @[to_additive] lemma mem_nhds_one : (U : set G) ∈ 𝓝 (1 : G) := mem_nhds_sets U.is_open U.one_mem variable {U} @[to_additive] instance : has_top (open_subgroup G) := ⟨{ is_open' := is_open_univ, .. (⊤ : subgroup G) }⟩ @[to_additive] instance : inhabited (open_subgroup G) := ⟨⊤⟩ @[to_additive] lemma is_closed [topological_monoid G] (U : open_subgroup G) : is_closed (U : set G) := begin refine is_open_iff_forall_mem_open.2 (λ x hx, ⟨(λ y, y * x⁻¹) ⁻¹' U, _, _, _⟩), { intros u hux, simp only [set.mem_preimage, set.mem_compl_iff, mem_coe] at hux hx ⊢, refine mt (λ hu, _) hx, convert U.mul_mem (U.inv_mem hux) hu, simp }, { exact (continuous_mul_right _) _ U.is_open }, { simp [U.one_mem] } end section variables {H : Type*} [group H] [topological_space H] @[to_additive] def prod (U : open_subgroup G) (V : open_subgroup H) : open_subgroup (G × H) := { carrier := (U : set G).prod (V : set H), is_open' := is_open_prod U.is_open V.is_open, .. (U : subgroup G).prod (V : subgroup H) } end @[to_additive] instance : partial_order (open_subgroup G) := { le := λ U V, ∀ ⦃x⦄, x ∈ U → x ∈ V, .. partial_order.lift (coe : open_subgroup G → set G) ext' } @[to_additive] instance : semilattice_inf_top (open_subgroup G) := { inf := λ U V, { is_open' := is_open_inter U.is_open V.is_open, .. (U : subgroup G) ⊓ V }, inf_le_left := λ U V, set.inter_subset_left _ _, inf_le_right := λ U V, set.inter_subset_right _ _, le_inf := λ U V W hV hW, set.subset_inter hV hW, top := ⊤, le_top := λ U, set.subset_univ _, ..open_subgroup.partial_order } @[simp, to_additive] lemma coe_inf : (↑(U ⊓ V) : set G) = (U : set G) ∩ V := rfl @[simp, to_additive] lemma coe_subset : (U : set G) ⊆ V ↔ U ≤ V := iff.rfl @[simp, to_additive] lemma coe_subgroup_le : (U : subgroup G) ≤ (V : subgroup G) ↔ U ≤ V := iff.rfl attribute [norm_cast] coe_inf coe_subset coe_subgroup_le open_add_subgroup.coe_inf open_add_subgroup.coe_subset open_add_subgroup.coe_subgroup_le end open_subgroup namespace subgroup variables {G : Type*} [group G] [topological_space G] [topological_monoid G] (H : subgroup G) @[to_additive] lemma is_open_of_mem_nhds {g : G} (hg : (H : set G) ∈ 𝓝 g) : is_open (H : set G) := begin simp only [is_open_iff_mem_nhds, subgroup.mem_coe] at hg ⊢, intros x hx, have : filter.tendsto (λ y, y * (x⁻¹ * g)) (𝓝 x) (𝓝 $ x * (x⁻¹ * g)) := (continuous_id.mul continuous_const).tendsto _, rw [mul_inv_cancel_left] at this, have := filter.mem_map.1 (this hg), replace hg : g ∈ H := subgroup.mem_coe.1 (mem_of_nhds hg), simp only [subgroup.mem_coe, H.mul_mem_cancel_right (H.mul_mem (H.inv_mem hx) hg)] at this, exact this end @[to_additive is_open_of_open_add_subgroup] lemma is_open_of_open_subgroup {U : open_subgroup G} (h : U.1 ≤ H) : is_open (H : set G) := H.is_open_of_mem_nhds (filter.mem_sets_of_superset U.mem_nhds_one h) @[to_additive] lemma is_open_mono {H₁ H₂ : subgroup G} (h : H₁ ≤ H₂) (h₁ : is_open (H₁ :set G)) : is_open (H₂ : set G) := @is_open_of_open_subgroup _ _ _ _ H₂ { is_open' := h₁, .. H₁ } h end subgroup namespace open_subgroup variables {G : Type*} [group G] [topological_space G] [topological_monoid G] @[to_additive] instance : semilattice_sup_top (open_subgroup G) := { sup := λ U V, { is_open' := show is_open (((U : subgroup G) ⊔ V : subgroup G) : set G), from subgroup.is_open_mono le_sup_left U.is_open, .. ((U : subgroup G) ⊔ V) }, le_sup_left := λ U V, coe_subgroup_le.1 le_sup_left, le_sup_right := λ U V, coe_subgroup_le.1 le_sup_right, sup_le := λ U V W hU hV, coe_subgroup_le.1 (sup_le hU hV), ..open_subgroup.semilattice_inf_top } end open_subgroup namespace submodule open open_add_subgroup variables {R : Type*} {M : Type*} [comm_ring R] variables [add_comm_group M] [topological_space M] [topological_add_group M] [module R M] lemma is_open_mono {U P : submodule R M} (h : U ≤ P) (hU : is_open (U : set M)) : is_open (P : set M) := @add_subgroup.is_open_mono M _ _ _ U.to_add_subgroup P.to_add_subgroup h hU end submodule namespace ideal variables {R : Type*} [comm_ring R] variables [topological_space R] [topological_ring R] lemma is_open_of_open_subideal {U I : ideal R} (h : U ≤ I) (hU : is_open (U : set R)) : is_open (I : set R) := submodule.is_open_mono h hU end ideal
9aaebc91b1a9bce67e21052ab7901bd72ed54b2f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/polynomial/scale_roots.lean
393103daa7ccca9d71329bfd28cd703e0f6d9e43
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,582
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Devon Tuma -/ import ring_theory.non_zero_divisors import data.polynomial.algebra_map /-! # Scaling the roots of a polynomial This file defines `scale_roots p s` for a polynomial `p` in one variable and a ring element `s` to be the polynomial with root `r * s` for each root `r` of `p` and proves some basic results about it. -/ variables {A K R S : Type*} [comm_ring A] [is_domain A] [field K] [comm_ring R] [comm_ring S] variables {M : submonoid A} namespace polynomial open_locale big_operators polynomial /-- `scale_roots p s` is a polynomial with root `r * s` for each root `r` of `p`. -/ noncomputable def scale_roots (p : R[X]) (s : R) : R[X] := ∑ i in p.support, monomial i (p.coeff i * s ^ (p.nat_degree - i)) @[simp] lemma coeff_scale_roots (p : R[X]) (s : R) (i : ℕ) : (scale_roots p s).coeff i = coeff p i * s ^ (p.nat_degree - i) := by simp [scale_roots, coeff_monomial] {contextual := tt} lemma coeff_scale_roots_nat_degree (p : R[X]) (s : R) : (scale_roots p s).coeff p.nat_degree = p.leading_coeff := by rw [leading_coeff, coeff_scale_roots, tsub_self, pow_zero, mul_one] @[simp] lemma zero_scale_roots (s : R) : scale_roots 0 s = 0 := by { ext, simp } lemma scale_roots_ne_zero {p : R[X]} (hp : p ≠ 0) (s : R) : scale_roots p s ≠ 0 := begin intro h, have : p.coeff p.nat_degree ≠ 0 := mt leading_coeff_eq_zero.mp hp, have : (scale_roots p s).coeff p.nat_degree = 0 := congr_fun (congr_arg (coeff : R[X] → ℕ → R) h) p.nat_degree, rw [coeff_scale_roots_nat_degree] at this, contradiction end lemma support_scale_roots_le (p : R[X]) (s : R) : (scale_roots p s).support ≤ p.support := by { intro, simpa using left_ne_zero_of_mul } lemma support_scale_roots_eq (p : R[X]) {s : R} (hs : s ∈ non_zero_divisors R) : (scale_roots p s).support = p.support := le_antisymm (support_scale_roots_le p s) begin intro i, simp only [coeff_scale_roots, polynomial.mem_support_iff], intros p_ne_zero ps_zero, have := pow_mem hs (p.nat_degree - i) _ ps_zero, contradiction end @[simp] lemma degree_scale_roots (p : R[X]) {s : R} : degree (scale_roots p s) = degree p := begin haveI := classical.prop_decidable, by_cases hp : p = 0, { rw [hp, zero_scale_roots] }, have := scale_roots_ne_zero hp s, refine le_antisymm (finset.sup_mono (support_scale_roots_le p s)) (degree_le_degree _), rw coeff_scale_roots_nat_degree, intro h, have := leading_coeff_eq_zero.mp h, contradiction, end @[simp] lemma nat_degree_scale_roots (p : R[X]) (s : R) : nat_degree (scale_roots p s) = nat_degree p := by simp only [nat_degree, degree_scale_roots] lemma monic_scale_roots_iff {p : R[X]} (s : R) : monic (scale_roots p s) ↔ monic p := by simp only [monic, leading_coeff, nat_degree_scale_roots, coeff_scale_roots_nat_degree] lemma scale_roots_eval₂_mul {p : S[X]} (f : S →+* R) (r : R) (s : S) : eval₂ f (f s * r) (scale_roots p s) = f s ^ p.nat_degree * eval₂ f r p := calc eval₂ f (f s * r) (scale_roots p s) = (scale_roots p s).support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : by simp [eval₂_eq_sum, sum_def] ... = p.support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : finset.sum_subset (support_scale_roots_le p s) (λ i hi hi', let this : coeff p i * s ^ (p.nat_degree - i) = 0 := by simpa using hi' in by simp [this]) ... = p.support.sum (λ (i : ℕ), f (p.coeff i) * f s ^ (p.nat_degree - i + i) * r ^ i) : finset.sum_congr rfl (λ i hi, by simp_rw [f.map_mul, f.map_pow, pow_add, mul_pow, mul_assoc]) ... = p.support.sum (λ (i : ℕ), f s ^ p.nat_degree * (f (p.coeff i) * r ^ i)) : finset.sum_congr rfl (λ i hi, by { rw [mul_assoc, mul_left_comm, tsub_add_cancel_of_le], exact le_nat_degree_of_ne_zero (polynomial.mem_support_iff.mp hi) }) ... = f s ^ p.nat_degree * p.support.sum (λ (i : ℕ), (f (p.coeff i) * r ^ i)) : finset.mul_sum.symm ... = f s ^ p.nat_degree * eval₂ f r p : by { simp [eval₂_eq_sum, sum_def] } lemma scale_roots_eval₂_eq_zero {p : S[X]} (f : S →+* R) {r : R} {s : S} (hr : eval₂ f r p = 0) : eval₂ f (f s * r) (scale_roots p s) = 0 := by rw [scale_roots_eval₂_mul, hr, _root_.mul_zero] lemma scale_roots_aeval_eq_zero [algebra S R] {p : S[X]} {r : R} {s : S} (hr : aeval r p = 0) : aeval (algebra_map S R s * r) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero (algebra_map S R) hr lemma scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero {p : A[X]} {f : A →+* K} (hf : function.injective f) {r s : A} (hr : eval₂ f (f r / f s) p = 0) (hs : s ∈ non_zero_divisors A) : eval₂ f (f r) (scale_roots p s) = 0 := begin convert scale_roots_eval₂_eq_zero f hr, rw [←mul_div_assoc, mul_comm, mul_div_cancel], exact map_ne_zero_of_mem_non_zero_divisors _ hf hs end lemma scale_roots_aeval_eq_zero_of_aeval_div_eq_zero [algebra A K] (inj : function.injective (algebra_map A K)) {p : A[X]} {r s : A} (hr : aeval (algebra_map A K r / algebra_map A K s) p = 0) (hs : s ∈ non_zero_divisors A) : aeval (algebra_map A K r) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero inj hr hs lemma map_scale_roots (p : R[X]) (x : R) (f : R →+* S) (h : f p.leading_coeff ≠ 0) : (p.scale_roots x).map f = (p.map f).scale_roots (f x) := begin ext, simp [polynomial.nat_degree_map_of_leading_coeff_ne_zero _ h], end end polynomial
0160a756b9c5bc9cc8ea16ad10f14827454bcfde
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Data/Lsp/Capabilities.lean
4e78c5fa3cc3565cfed75271c70d295fc6bdf272
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,108
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.JsonRpc import Lean.Data.Lsp.TextSync /-! Minimal LSP servers/clients do not have to implement a lot of functionality. Most useful additional behaviour is instead opted into via capabilities. -/ namespace Lean namespace Lsp open Json -- TODO: right now we ignore the client's capabilities inductive ClientCapabilities where | mk instance : FromJson ClientCapabilities := ⟨fun j => ClientCapabilities.mk⟩ instance ClientCapabilities.hasToJson : ToJson ClientCapabilities := ⟨fun o => mkObj []⟩ -- TODO largely unimplemented structure ServerCapabilities where textDocumentSync? : Option TextDocumentSyncOptions := none hoverProvider : Bool := false documentHighlightProvider : Bool := false documentSymbolProvider : Bool := false definitionProvider : Bool := false declarationProvider : Bool := false typeDefinitionProvider : Bool := false deriving ToJson, FromJson end Lsp end Lean
1f4565bab51c4069cf401fb1706e1927e6ba607b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/intervals/monoid.lean
30d120a5f3a257c11733b9b18eae858a74bdbeb4
[ "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,107
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot -/ import data.set.intervals.basic import data.set.function import algebra.order.monoid.cancel.defs import algebra.order.monoid.canonical.defs import algebra.group.basic /-! # Images of intervals under `(+ d)` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The lemmas in this file state that addition maps intervals bijectively. The typeclass `has_exists_add_of_le` is defined specifically to make them work when combined with `ordered_cancel_add_comm_monoid`; the lemmas below therefore apply to all `ordered_add_comm_group`, but also to `ℕ` and `ℝ≥0`, which are not groups. -/ namespace set variables {M : Type*} [ordered_cancel_add_comm_monoid M] [has_exists_add_of_le M] (a b c d : M) lemma Ici_add_bij : bij_on (+d) (Ici a) (Ici (a + d)) := begin refine ⟨λ x h, add_le_add_right (mem_Ici.mp h) _, (add_left_injective d).inj_on _, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ici.mp h), rw [mem_Ici, add_right_comm, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioi_add_bij : bij_on (+d) (Ioi a) (Ioi (a + d)) := begin refine ⟨λ x h, add_lt_add_right (mem_Ioi.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ioi.mp h).le, rw [mem_Ioi, add_right_comm, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Icc_add_bij : bij_on (+d) (Icc a b) (Icc (a + d) (b + d)) := begin rw [← Ici_inter_Iic, ← Ici_inter_Iic], exact (Ici_add_bij a d).inter_maps_to (λ x hx, add_le_add_right hx _) (λ x hx, le_of_add_le_add_right hx.2) end lemma Ioo_add_bij : bij_on (+d) (Ioo a b) (Ioo (a + d) (b + d)) := begin rw [← Ioi_inter_Iio, ← Ioi_inter_Iio], exact (Ioi_add_bij a d).inter_maps_to (λ x hx, add_lt_add_right hx _) (λ x hx, lt_of_add_lt_add_right hx.2) end lemma Ioc_add_bij : bij_on (+d) (Ioc a b) (Ioc (a + d) (b + d)) := begin rw [← Ioi_inter_Iic, ← Ioi_inter_Iic], exact (Ioi_add_bij a d).inter_maps_to (λ x hx, add_le_add_right hx _) (λ x hx, le_of_add_le_add_right hx.2) end lemma Ico_add_bij : bij_on (+d) (Ico a b) (Ico (a + d) (b + d)) := begin rw [← Ici_inter_Iio, ← Ici_inter_Iio], exact (Ici_add_bij a d).inter_maps_to (λ x hx, add_lt_add_right hx _) (λ x hx, lt_of_add_lt_add_right hx.2) end /-! ### Images under `x ↦ x + a` -/ @[simp] lemma image_add_const_Ici : (λ x, x + a) '' Ici b = Ici (b + a) := (Ici_add_bij _ _).image_eq @[simp] lemma image_add_const_Ioi : (λ x, x + a) '' Ioi b = Ioi (b + a) := (Ioi_add_bij _ _).image_eq @[simp] lemma image_add_const_Icc : (λ x, x + a) '' Icc b c = Icc (b + a) (c + a) := (Icc_add_bij _ _ _).image_eq @[simp] lemma image_add_const_Ico : (λ x, x + a) '' Ico b c = Ico (b + a) (c + a) := (Ico_add_bij _ _ _).image_eq @[simp] lemma image_add_const_Ioc : (λ x, x + a) '' Ioc b c = Ioc (b + a) (c + a) := (Ioc_add_bij _ _ _).image_eq @[simp] lemma image_add_const_Ioo : (λ x, x + a) '' Ioo b c = Ioo (b + a) (c + a) := (Ioo_add_bij _ _ _).image_eq /-! ### Images under `x ↦ a + x` -/ @[simp] lemma image_const_add_Ici : (λ x, a + x) '' Ici b = Ici (a + b) := by simp only [add_comm a, image_add_const_Ici] @[simp] lemma image_const_add_Ioi : (λ x, a + x) '' Ioi b = Ioi (a + b) := by simp only [add_comm a, image_add_const_Ioi] @[simp] lemma image_const_add_Icc : (λ x, a + x) '' Icc b c = Icc (a + b) (a + c) := by simp only [add_comm a, image_add_const_Icc] @[simp] lemma image_const_add_Ico : (λ x, a + x) '' Ico b c = Ico (a + b) (a + c) := by simp only [add_comm a, image_add_const_Ico] @[simp] lemma image_const_add_Ioc : (λ x, a + x) '' Ioc b c = Ioc (a + b) (a + c) := by simp only [add_comm a, image_add_const_Ioc] @[simp] lemma image_const_add_Ioo : (λ x, a + x) '' Ioo b c = Ioo (a + b) (a + c) := by simp only [add_comm a, image_add_const_Ioo] end set