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
9c49775657d0f41cdcdf2aebb475091aa5e69d21
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/hott/calc_auto_trans_eq.hlean
205c439277f35e487d3c9aeb6562fda17437411d
[ "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
558
hlean
constant list : Type → Type constant R.{l} : Π {A : Type.{l}}, A → A → Type.{l} infix `~`:50 := R example {A : Type} {a b c d : list nat} (H₁ : a ~ b) (H₂ : b = c) (H₃ : c = d) : a ~ d := calc a ~ b : H₁ ... = c : H₂ ... = d : H₃ example {A : Type} {a b c d : list nat} (H₁ : a = b) (H₂ : b = c) (H₃ : c ~ d) : a ~ d := calc a = b : H₁ ... = c : H₂ ... ~ d : H₃ example {A : Type} {a b c d : list nat} (H₁ : a = b) (H₂ : b ~ c) (H₃ : c = d) : a ~ d := calc a = b : H₁ ... ~ c : H₂ ... = d : H₃
2265f60a61a619c33cd8e9869b7bb41466b5ef9f
5e42295de7f5bcdf224b94603a8ec29b17c2d367
/proof_reconstruction.lean
b24ed1a02b333c76fb043b7a16b6fdb187716190
[]
no_license
pnmadelaine/lean_polya
9369e0d87dce773f91383bb58ac6fde0a00a1a40
1c62b0b3fa71044b0225ce28030627d251b08ebc
refs/heads/master
1,590,161,172,243
1,515,010,019,000
1,515,010,019,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
49,384
lean
import .datatypes .sum_form .reconstruction_theorems norm_num namespace polya open expr tactic diseq_proof --#check mk_nat_val_ne_proof use something like this below? theorem fake_ne_zero_pf (q : ℚ) : q ≠ 0 := sorry theorem fake_gt_zero_pf (q : ℚ) : q > 0 := sorry theorem fake_lt_zero_pf (q : ℚ) : q < 0 := sorry theorem fake_eq_zero_pf (q : ℚ) : q = 0 := sorry theorem fake_ne_pf (q1 q2 : ℚ) : q1 ≠ q2 := sorry private meta def solve_by_norm_num (e : expr) : tactic expr := do (_, pf) ← solve_aux e `[norm_num, tactic.done], return pf meta def mk_ne_zero_pf (q : ℚ) : tactic expr := --do qe ← to_expr ``(%%(quote q) : ℚ), -- to_expr ``(fake_ne_zero_pf (%%qe : ℚ)) --return `(fake_ne_zero_pf q) solve_by_norm_num `(q ≠ 0) -- proves that q > 0, q < 0, or q = 0 meta def mk_sign_pf (q : ℚ) : tactic expr := /-do qe ← to_expr `(%%(quote q) : ℚ), if q > 0 then to_expr `(fake_gt_zero_pf (%%qe : ℚ)) else if q < 0 then to_expr `(fake_lt_zero_pf (%%qe : ℚ)) else to_expr ``(fake_eq_zero_pf (%%qe : ℚ))-/ if q > 0 then --return `(fake_gt_zero_pf q) solve_by_norm_num `(q > 0) else if q < 0 then --return `(fake_lt_zero_pf q) solve_by_norm_num `(q < 0) else --return `(fake_eq_zero_pf q) solve_by_norm_num `(q = 0) meta def mk_ne_pf (q1 q2 : ℚ) : tactic expr := /-do q1e ← to_expr ``(%%(quote q1) : ℚ), q2e ← to_expr ``(%%(quote q2) : ℚ), to_expr `(fake_ne_pf %%q1e %%q2e)-/ --return `(fake_ne_pf q1 q2) solve_by_norm_num `(q1 ≠ q2) meta def mk_int_sign_pf (z : ℤ) : tactic expr := if z > 0 then solve_by_norm_num `(z > 0) --return `(sorry : z > 0) else if z < 0 then solve_by_norm_num `(z < 0)--return `(sorry : z < 0) else solve_by_norm_num `(z = 0) --return `(sorry : z = 0) -- proves z % 2 = 0 or z % 2 = 1 meta def mk_int_mod_pf (z : ℤ) : tactic expr := if z % 2 = 0 then return `(sorry : z % 2 = 0) else return `(sorry : z % 2 = 1) namespace diseq_proof private meta def reconstruct_hyp (lhs rhs : expr) (c : ℚ) (pf : expr) : tactic expr := do mvc ← mk_mvar, pft ← infer_type pf, to_expr ``(%%lhs ≠ %%mvc * %%rhs) >>= unify pft, c' ← eval_expr rat mvc, if c = c' then return pf else fail "diseq_proof.reconstruct_hyp failed" private meta def reconstruct_sym (rc : Π {lhs rhs : expr} {c : ℚ}, diseq_proof lhs rhs c → tactic expr) {lhs rhs c} (dp : diseq_proof lhs rhs c) : tactic expr := do symp ← rc dp, cnep ← mk_ne_zero_pf c, mk_mapp ``diseq_sym [none, none, none, cnep, symp] -- why doesn't mk_app work? meta def reconstruct : Π {lhs rhs : expr} {c : ℚ}, diseq_proof lhs rhs c → tactic expr | .(_) .(_) .(_) (hyp (lhs) (rhs) (c) e) := reconstruct_hyp lhs rhs c e | .(_) .(_) .(_) (@sym lhs rhs c dp) := reconstruct_sym @reconstruct dp end diseq_proof namespace eq_proof private meta def reconstruct_hyp (lhs rhs : expr) (c : ℚ) (pf : expr) : tactic expr := do mvc ← mk_mvar, pft ← infer_type pf, to_expr ``(%%lhs = %%mvc * %%rhs) >>= unify pft, c' ← eval_expr rat mvc, if c = c' then return pf else fail "eq_proof.reconstruct_hyp failed" private meta def reconstruct_sym (rc : Π {lhs rhs : expr} {c : ℚ}, eq_proof lhs rhs c → tactic expr) {lhs rhs c} (dp : eq_proof lhs rhs c) : tactic expr := do symp ← rc dp, cnep ← mk_ne_zero_pf c, -- 5/1 ≠ 0 -- infer_type symp >>= trace, -- infer_type cnep >>= trace, mk_mapp ``eq_sym [none, none, none, cnep, symp] -- why doesn't mk_app work? variable iepr_fn : Π {lhs rhs i}, ineq_proof lhs rhs i → tactic expr private meta def reconstruct_of_opp_ineqs_aux {lhs rhs i} (c : ℚ) (iep : ineq_proof lhs rhs i) (iepr : ineq_proof lhs rhs i.reverse) : tactic expr := do guard (bnot i.strict), pr1 ← iepr_fn iep, pr2 ← iepr_fn iepr, if i.to_comp.is_less then mk_mapp ``op_ineq [none, none, none, some pr1, some pr2] else mk_mapp ``op_ineq [none, none, none, some pr2, some pr1] private theorem eq_sub_of_add_eq_facs {c1 c2 e1 e2 : ℚ} (hc1 : c1 ≠ 0) (h : c1 * e1 + c2 * e2 = 0) : e1 = -(c2/c1) * e2 := sorry private meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : expr → expr → ℚ → Π {sf}, Π (sp : sum_form_proof ⟨sf, spec_comp.eq⟩), tactic expr | lhs rhs c sf sp := if lhs.lt rhs then -- flipped? reconstruct_of_sum_form_proof rhs lhs (1/c) sp else do guard $ (sf.contains lhs) && (sf.contains rhs), let a := sf.get_coeff lhs in let b := sf.get_coeff rhs in do guard $ c = -(b/a), pf ← sfpr sp, nez ← mk_ne_zero_pf a, mk_app ``eq_sub_of_add_eq_facs [nez, pf] -- fail "eq_proof.reconstruct_of_sum_proof not implemented yet" meta def reconstruct_aux (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : Π {lhs rhs : expr} {c : ℚ}, eq_proof lhs rhs c → tactic expr | .(_) .(_) .(_) (hyp (lhs) (rhs) (c) e) := reconstruct_hyp lhs rhs c e | .(_) .(_) .(_) (@sym lhs rhs c dp) := reconstruct_sym @reconstruct_aux dp | .(_) .(_) .(_) (@of_opp_ineqs lhs rhs i c iep iepr) := reconstruct_of_opp_ineqs_aux @iepr_fn c iep iepr | .(_) .(_) .(_) (@of_sum_form_proof lhs rhs c _ sp) := reconstruct_of_sum_form_proof @sfpr lhs rhs c sp | .(_) .(_) .(_) (adhoc _ _ _ _ t) := t end eq_proof namespace ineq_proof meta def guard_is_ineq (lhs rhs : expr) (iq : ineq) (pf : expr) : tactic expr := do mvc ← mk_mvar, pft ← infer_type pf, match iq.to_comp with | comp.lt := to_expr ``(%%lhs < %%mvc * %%rhs) >>= unify pft >> return mvc | comp.le := to_expr ``(%%lhs ≤ %%mvc * %%rhs) >>= unify pft >> return mvc | comp.gt := to_expr ``(%%lhs > %%mvc * %%rhs) >>= unify pft >> return mvc | comp.ge := to_expr ``(%%lhs ≥ %%mvc * %%rhs) >>= unify pft >> return mvc end private meta def reconstruct_hyp (lhs rhs : expr) (iq : ineq) (pf : expr) : tactic expr := match iq.to_slope with | slope.horiz := do tp ← infer_type pf, --trace "unifying tp in reconstruct_hyp1", trace tp, to_expr ``( %%(iq.to_comp.to_pexpr) %%rhs 0) >>= unify tp, return pf | slope.some c := do m ← guard_is_ineq lhs rhs iq pf, m' ← eval_expr rat m, if m' = c then return pf else fail "ineq_proof.reconstruct_hyp failed" end section variable (rc : Π {lhs rhs : expr} {iq : ineq}, ineq_proof lhs rhs iq → tactic expr) include rc private meta def reconstruct_sym {lhs rhs iq} (ip : ineq_proof lhs rhs iq) : tactic expr := match iq.to_slope with | slope.horiz := do p ← pp (lhs, rhs), fail $ "reconstruct_sym failed on horiz slope: " ++ p.to_string | slope.some m := do --trace "in reconstruct sym", trace (lhs, rhs, m), symp ← rc ip, sgnp ← mk_sign_pf m, --trace "have proof of:", infer_type symp >>= trace, --trace ("m", m), trace ("lhs, rhs", lhs, rhs), trace "sgnp", infer_type sgnp >>= trace, trace "symp", trace ip, infer_type symp >>= trace, --mk_mapp (name_of_c_and_comp m iq.to_comp) [none, none, none, some sgnp, some symp] mk_app (if m < 0 then ``sym_op_neg else ``sym_op_pos) [sgnp, symp] end -- x ≥ 2y and x ≠ 2y implies x > 2y private meta def reconstruct_ineq_diseq {lhs rhs iq c} (ip : ineq_proof lhs rhs iq) (dp : diseq_proof lhs rhs c) : tactic expr := match iq.to_slope with | slope.horiz := fail "reconstruct_ineq_diseq needs non-horiz slope" | slope.some m := if bnot (m=c) then fail "reconstruct_ineq_diseq found non-matching slopes" else if iq.strict then rc ip else do ipp ← rc ip, dpp ← dp.reconstruct, /-if iq.to_comp.is_less then mk_mapp ``ineq_diseq_le [none, none, none, some dpp, some ipp] else mk_mapp ``ineq_diseq_ge [none, none, none, some dpp, some ipp]-/ mk_app ``ineq_diseq [dpp, ipp] end variable (rcs : Π {e gc}, sign_proof e gc → tactic expr) include rcs -- x ≤ 0y and x ≠ 0 implies x < 0y private meta def reconstruct_ineq_sign_lhs {lhs rhs iq c} (ip : ineq_proof lhs rhs iq) (sp : sign_proof lhs c) : tactic expr := if iq.strict || bnot (c = gen_comp.ne) then fail "reconstruct_ineq_sign_lhs assumes a weak ineq and a diseq-0" else match iq.to_slope with | slope.horiz := fail "reconstruct_ineq_sign_lhs assumes a 0 slope" | slope.some m := if m = 0 then do ipp ← rc ip, spp ← rcs sp, -- mk_app (if iq.to_comp.is_less then ``ineq_diseq_sign_lhs_le else ``ineq_diseq_sign_lhs_ge) [spp, ipp] mk_app ``ineq_diseq_sign_lhs [spp, ipp] else fail "reconstruct_ineq_sign_lhs assumes a 0 slope" end -- this might be wrong: should we produce proofs of y < 0? private meta def reconstruct_ineq_sign_rhs {lhs rhs iq c} (ip : ineq_proof lhs rhs iq) (sp : sign_proof rhs c) : tactic expr := if iq.strict || bnot (c = gen_comp.ne) then fail "reconstruct_ineq_sign_rhs assumes a weak ineq and a diseq-0" else match iq.to_slope with | slope.horiz := do ipp ← rc ip, spp ← rcs sp, -- mk_app (if iq.to_comp.is_less then ``ineq_diseq_sign_rhs_le else ``ineq_diseq_sign_rhs_ge) [spp, ipp] mk_app ``ineq_diseq_sign_rhs [spp, ipp] | _ := fail "reconstruct_ineq_sign_rhs assumes a horizontal slope" end omit rc -- x ≥ 0 implies x ≥ 0*y private meta def reconstruct_zero_comp_of_sign {lhs c} (rhs : expr) (iq : ineq) (sp : sign_proof lhs c) : tactic expr := if bnot ((iq.to_comp.to_gen_comp = c) && (iq.is_zero_slope)) then fail $ "reconstruct_zero_comp_of_sign only produces comps with zero" ++ (to_fmt iq).to_string ++ (to_fmt iq.to_comp.to_gen_comp).to_string ++ (to_fmt c).to_string --else do spp ← rcs sp, mk_app (zero_mul_name_of_comp iq.to_comp) [rhs, spp] else do spp ← rcs sp, mk_mapp ``op_zero_mul [none, some rhs, none, none, some spp] private meta def reconstruct_horiz_of_sign {rhs c} (lhs : expr) (iq : ineq) (sp : sign_proof rhs c) : tactic expr := if bnot ((iq.to_comp.to_gen_comp = c) && (iq.is_horiz)) then fail $ "reconstruct_horiz_of_sign failed" else rcs sp end /- private theorem eq_sub_of_add_eq_facs {c1 c2 e1 e2 : ℚ} (hc1 : c1 ≠ 0) (h : c1 * e1 + c2 * e2 = 0) : e1 = -(c2/c1) * e2 := sorry private meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : expr → expr → ℚ → Π {sf}, Π (sp : sum_form_proof ⟨sf, spec_comp.eq⟩), tactic expr | lhs rhs c sf sp := if rhs.lt lhs then reconstruct_of_sum_form_proof rhs lhs (1/c) sp else do guard $ (sf.contains lhs) && (sf.contains rhs), let a := sf.get_coeff lhs in let b := sf.get_coeff rhs in do guard $ c = -(b/a), pf ← sfpr sp, nez ← mk_ne_zero_pf a, mk_app ``eq_sub_of_add_eq_facs [nez, pf] -/ private meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : expr → expr → ineq → Π {sfc}, sum_form_proof sfc → tactic expr | lhs rhs i sfc sp := if lhs.lt rhs then -- flipped? reconstruct_of_sum_form_proof rhs lhs i.reverse sp else (match i.to_slope with | slope.some m := do { guard $ (sfc.sf.contains lhs) && (sfc.sf.contains rhs), guard $ sfc.sf.keys.length = 2, let a := sfc.sf.get_coeff lhs in let b := sfc.sf.get_coeff rhs in do guard $ m = -(b/a), guard $ if a < 0 then sfc.c.to_comp = i.to_comp.reverse else sfc.c.to_comp = i.to_comp, rhs' ← to_expr ``(%%(↑(rat.reflect m) : expr) * %%rhs), -- better way to do this? tp ← i.to_comp.to_function lhs rhs', sgnp ← mk_sign_pf a, pf ← sfpr sp, --trace "have: ", infer_type pf >>= trace, trace ("lhs: ", lhs), trace ("rhs: ", rhs), let thnm := if a < 0 then ``op_of_sum_op_zero_neg else ``op_of_sum_op_zero_pos in mk_app thnm [pf, sgnp]} --to_expr ``(sorry : %%tp) -- fail "ineq_proof.reconstruct_of_sum_proof not implemented yet" | slope.horiz := fail "ineq_proof.reconstruct_of_sum_proof failed, cannot turn a sum into a horiz slope" end) meta def reconstruct_aux (rcs : Π {e gc}, sign_proof e gc → tactic expr) (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : Π {lhs rhs : expr} {iq : ineq}, ineq_proof lhs rhs iq → tactic expr | _ _ _ (hyp lhs rhs iq e) := reconstruct_hyp lhs rhs iq e | _ _ _ (sym ip) := reconstruct_sym @reconstruct_aux ip | _ _ _ (of_ineq_proof_and_diseq ip dp) := reconstruct_ineq_diseq @reconstruct_aux ip dp | _ _ _ (of_ineq_proof_and_sign_lhs ip sp) := reconstruct_ineq_sign_lhs @reconstruct_aux @rcs ip sp | _ _ _ (of_ineq_proof_and_sign_rhs ip sp) := reconstruct_ineq_sign_rhs @reconstruct_aux @rcs ip sp | _ _ _ (zero_comp_of_sign_proof rhs iq sp) := reconstruct_zero_comp_of_sign @rcs rhs iq sp | _ _ _ (horiz_of_sign_proof lhs iq sp) := reconstruct_horiz_of_sign @rcs lhs iq sp | _ _ _ (of_sum_form_proof lhs rhs i sp) := reconstruct_of_sum_form_proof @sfpr lhs rhs i sp | _ _ _ (adhoc _ _ _ _ t) := t end ineq_proof namespace sign_proof private meta def reconstruct_hyp (e : expr) (gc : gen_comp) (pf : expr) : tactic expr := let pex := match gc with | gen_comp.ge := ``(%%e ≥ 0) | gen_comp.gt := ``(%%e > 0) | gen_comp.le := ``(%%e ≤ 0) | gen_comp.lt := ``(%%e < 0) | gen_comp.eq := ``(%%e = 0) | gen_comp.ne := ``(%%e ≠ 0) end in do tp ← infer_type pf, to_expr pex >>= unify tp >> return pf private meta def reconstruct_scaled_hyp (e : expr) (gc : gen_comp) (pf : expr) (q : ℚ) : tactic expr := do sp ← mk_sign_pf q, if q > 0 then mk_mapp ``op_zero_of_mul_op_zero_of_pos [none, none, none, none, pf, sp] else mk_mapp ``op_zero_of_mul_op_zero_of_neg [none, none, none, none, pf, sp] section parameter rc : Π {e c}, sign_proof e c → tactic expr parameter sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr private meta def rci := @ineq_proof.reconstruct_aux @rc @sfpr private meta def rce := @eq_proof.reconstruct_aux @rci @sfpr -- x ≤ 0*y to x ≤ 0 private meta def reconstruct_ineq_lhs (c : gen_comp) {lhs rhs iqp} (ip : ineq_proof lhs rhs iqp) : tactic expr := if bnot ((iqp.to_comp.to_gen_comp = c) && (iqp.is_zero_slope)) then fail "reconstruct_ineq_lhs must take a comparison with 0" --else do ipp ← rci ip, mk_app (zero_mul'_name_of_comp iqp.to_comp) [ipp] else do ipp ← rci ip, mk_app ``op_zero_mul' [ipp] private meta def reconstruct_ineq_rhs (c : gen_comp) {lhs rhs iqp} (ip : ineq_proof lhs rhs iqp) : tactic expr := if bnot ((iqp.to_comp.to_gen_comp = c) && (iqp.is_horiz)) then fail "reconstruct_ineq_rhs must take a horiz comp" else rci ip private meta def reconstruct_eq_of_two_eqs_lhs {lhs rhs eqp1 eqp2} (ep1 : eq_proof lhs rhs eqp1) (ep2 : eq_proof lhs rhs eqp2) : tactic expr := if h : eqp1 = eqp2 then fail "reconstruct_eq_of_two_eqs lhs cannot infer anything from the same equality twice" else do epp1 ← rce ep1, epp2 ← rce ep2, nep ← mk_ne_pf eqp1 eqp2, mk_app ``eq_zero_of_two_eqs_lhs [epp1, epp2, nep] private meta def reconstruct_eq_of_two_eqs_rhs {lhs rhs eqp1 eqp2} (ep1 : eq_proof lhs rhs eqp1) (ep2 : eq_proof lhs rhs eqp2) : tactic expr := if h : eqp1 = eqp2 then fail "reconstruct_eq_of_two_eqs lhs cannot infer anything from the same equality twice" else do epp1 ← rce ep1, epp2 ← rce ep2, nep ← mk_ne_pf eqp1 eqp2, mk_app ``eq_zero_of_two_eqs_rhs [epp1, epp2, nep] private meta def reconstruct_diseq_of_diseq_zero {lhs rhs} (dp : diseq_proof lhs rhs 0) : tactic expr := do dpp ← dp.reconstruct, mk_app ``ne_zero_of_ne_mul_zero [dpp] private meta def reconstruct_eq_of_eq_zero {lhs rhs} (ep : eq_proof lhs rhs 0) : tactic expr := do epp ← rce ep, mk_app ``eq_zero_of_eq_mul_zero [epp] /- private meta def reconstruct_ineqs (rct : contrad → tactic expr) {lhs rhs} (ii : ineq_info lhs rhs) (id : ineq_data lhs rhs) : tactic expr := do trace "ineqs!!", match ii with | ineq_info.no_comps := fail "reconstruct_ineqs cannot find a contradiction with no known comps" | ineq_info.one_comp id2 := reconstruct_two_ineq_data rct id id2 | ineq_info.equal ed := reconstruct_eq_ineq ed id | ineq_info.two_comps id1 id2 := let sfid := sum_form_comp_data.of_ineq_data id, sfid1 := sum_form_comp_data.of_ineq_data id1, sfid2 := sum_form_comp_data.of_ineq_data id2 in match find_contrad_in_sfcd_list [sfid, sfid1, sfid2] with | some ctr := rct ctr | option.none := fail "reconstruct_ineqs failed to find contr" end end -/ private theorem {u} ge_of_not_lt {α : Type u} [linear_order α] {a b : α} (h : ¬ a < b) : (a ≥ b) := le_of_not_gt h private theorem {u} gt_of_not_le {α : Type u} [linear_order α] {a b : α} (h : ¬ a ≤ b) : (a > b) := lt_of_not_ge h private meta def neg_op_lemma_name : comp → name | comp.lt := ``lt_of_not_ge | comp.le := ``le_of_not_gt | comp.ge := ``ge_of_not_lt | comp.gt := ``gt_of_not_le meta def reconstruct_ineq_of_eq_and_ineq_aux -- (sfpr : Π {sf : sum_form_comp}, Π (sp : sum_form_proof sf), tactic.{0} (expr tt)) {lhs rhs iq c} (c' : gen_comp) (ep : eq_proof lhs rhs c) (ip : ineq_proof lhs rhs iq) (pvt : expr) : tactic expr := do negt ← c'.to_comp.to_function pvt `(0 : ℚ), (_, notpf) ← solve_aux negt (do applyc $ neg_op_lemma_name c'.to_comp, hypv ← intro `h, let sfid := sum_form_comp_data.of_ineq_data ⟨_, ip⟩ in let sfed := sum_form_comp_data.of_eq_data ⟨_, ep⟩ in let sfsd := sum_form_comp_data.of_sign_data ⟨c'.negate, hyp pvt _ hypv⟩ in match find_contrad_sfcd_in_sfcd_list [sfid, sfed, sfsd] with | none := fail "reconstruct_ineq_of_eq_and_ineq failed to find proof" | some ⟨_, sfp, _⟩ := do ctrp ← sfpr sfp, fp ← mk_mapp ``lt_irrefl [none, none, none, ctrp], apply fp --applyc ``lt_irrefl, trace "apply3", apply ctrp, trace "apply4" end), return notpf --#check @reconstruct_ineq_of_eq_and_ineq_aux -- these are the hard cases. Is this the right place to handle them? private meta def reconstruct_ineq_of_eq_and_ineq_lhs {lhs rhs iq c} (c' : gen_comp) (ep : eq_proof lhs rhs c) (ip : ineq_proof lhs rhs iq) : tactic expr := reconstruct_ineq_of_eq_and_ineq_aux c' ep ip lhs --fail "reconstruct_ineq_of_eq_and_ineq not implemented" private meta def reconstruct_ineq_of_eq_and_ineq_rhs {lhs rhs iq c} (c' : gen_comp) (ep : eq_proof lhs rhs c) (ip : ineq_proof lhs rhs iq) : tactic expr := reconstruct_ineq_of_eq_and_ineq_aux c' ep ip rhs /-do negt ← c'.to_comp.to_function rhs `(0 : ℚ), (_, notpf) ← solve_aux negt (do applyc $ neg_op_lemma_name c'.to_comp, hypv ← intro `h, let sfid := sum_form_comp_data.of_ineq_data ⟨_, ip⟩ in let sfed := sum_form_comp_data.of_eq_data ⟨_, ep⟩ in let sfsd := sum_form_comp_data.of_sign_data ⟨c', hyp rhs _ hypv⟩ in match find_contrad_sfcd_in_sfcd_list [sfid, sfed, sfsd] with | none := fail "reconstruct_ineq_of_eq_and_ineq_rhs failed to find proof" | some ⟨_, sfp, _⟩ := do ctrp ← sfpr sfp, applyc ``lt_irrefl, apply ctrp end), return notpf-/ -- fail "reconstruct_ineq_of_eq_and_ineq not implemented" -- TODO private meta def reconstruct_ineq_of_ineq_and_eq_zero_rhs {lhs rhs iq} (c : gen_comp) (ip : ineq_proof lhs rhs iq) (sp : sign_proof lhs gen_comp.eq) : tactic expr := fail "reconstruct_ineq_of_ineq_and_eq_zero not implemented" private meta def reconstruct_diseq_of_strict_ineq {e c} (sp : sign_proof e c) : tactic expr := if c.is_strict then do spp ← rc sp, mk_app ``ne_of_strict_op [spp] else fail "reconstruct_diseq_of_strict_ineq failed, comp is not strict" end -- TODO private meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) (e : expr) (c : gen_comp) {sfc} (sp : sum_form_proof sfc) : tactic expr := do pf' ← sfpr sp, --trace "in sign_proof.reconstruct_of_sum_form_proof", --infer_type e >>= trace, --trace c, let coeff := sfc.sf.get_coeff e, if coeff = 0 then fail "sign_proof.reconstruct_of_sum_form_proof failed, zero coeff" else do coeff_sign_pr ← mk_sign_pf coeff, -- if coeff < 0 then mk_mapp (if coeff < 0 then ``rev_op_zero_of_neg_mul_op_zero else ``op_zero_of_pos_mul_op_zero) [none, none, none, none, coeff_sign_pr, pf'] -- else if coeff > 0 then -- mk_mapp ``op_zero_of_pos_mul_op_zero [none, none, none, none, coeff_sign_] -- fail "sign_proof.reconstruct_of_sum_form_proof failed, not implemented yet" private lemma le_antisymm' {a b : ℚ} (h1 : a ≤ b) (h2 : a ≥ b) : a = b := le_antisymm h1 h2 meta def reconstruct_eq_of_le_of_ge (rct : Π {e c}, sign_proof e c → tactic expr) {e} (lep : sign_proof e gen_comp.le) (gep : sign_proof e gen_comp.ge) : tactic expr := do lep' ← rct lep, gep' ← rct gep, mk_app ``le_antisymm' [lep', gep'] meta def reconstruct_aux (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : Π {e c}, sign_proof e c → tactic expr | .(_) .(_) (hyp e c pf) := reconstruct_hyp e c pf | .(_) .(_) (scaled_hyp e c pf q) := reconstruct_scaled_hyp e c pf q | .(_) .(_) (@ineq_lhs c _ _ _ ip) := reconstruct_ineq_lhs @reconstruct_aux @sfpr c ip | .(_) .(_) (@ineq_rhs c _ _ _ ip) := reconstruct_ineq_rhs @reconstruct_aux @sfpr c ip | .(_) .(_) (@eq_of_two_eqs_lhs _ _ _ _ ep1 ep2) := reconstruct_eq_of_two_eqs_lhs @reconstruct_aux @sfpr ep1 ep2 | .(_) .(_) (@eq_of_two_eqs_rhs _ _ _ _ ep1 ep2) := reconstruct_eq_of_two_eqs_rhs @reconstruct_aux @sfpr ep1 ep2 | .(_) .(_) (@diseq_of_diseq_zero _ _ dp) := reconstruct_diseq_of_diseq_zero dp | .(_) .(_) (@eq_of_eq_zero _ _ ep) := reconstruct_eq_of_eq_zero @reconstruct_aux @sfpr ep | .(_) .(_) (eq_of_le_of_ge lep gep) := reconstruct_eq_of_le_of_ge @reconstruct_aux lep gep | .(_) .(_) (@ineq_of_eq_and_ineq_lhs _ _ _ _ c' ep ip) := reconstruct_ineq_of_eq_and_ineq_lhs @sfpr c' ep ip | .(_) .(_) (@ineq_of_eq_and_ineq_rhs _ _ _ _ c' ep ip) := reconstruct_ineq_of_eq_and_ineq_rhs @sfpr c' ep ip | .(_) .(_) (@ineq_of_ineq_and_eq_zero_rhs _ _ _ c ip sp) := reconstruct_ineq_of_ineq_and_eq_zero_rhs c ip sp | .(_) .(_) (@diseq_of_strict_ineq _ _ sp) := reconstruct_diseq_of_strict_ineq @reconstruct_aux sp | .(_) .(_) (@of_sum_form_proof e c _ sp) := reconstruct_of_sum_form_proof @sfpr e c sp | .(_) .(_) (adhoc _ _ _ t) := t end sign_proof namespace sum_form_proof section parameter sfrc : Π {sfc}, sum_form_proof sfc → tactic expr private meta def sprc := @sign_proof.reconstruct_aux @sfrc private meta def iprc := @ineq_proof.reconstruct_aux @sprc @sfrc private meta def eprc := @eq_proof.reconstruct_aux @iprc @sfrc -- assumes lhs < rhs private meta def reconstruct_of_ineq_proof : Π {lhs rhs iq}, ineq_proof lhs rhs iq → tactic expr | lhs rhs iq ip := if expr.lt lhs rhs then reconstruct_of_ineq_proof ip.sym else --trace "ipp is:" >> iprc ip >>= infer_type >>= trace >> trace "const is:" >> infer_type ↑`(@polya.mul_lt_of_lt) >>= trace >> match iq.to_slope with | slope.horiz := do ipp ← iprc ip, tactic.mk_mapp (sum_form_name_of_comp_single iq.to_comp) [none, none, ipp] | slope.some m := do ipp ← iprc ip, --trace ("ipp", ip, ipp), infer_type ipp >>= trace, trace ("comp", iq.to_comp), trace ("iq", iq), if m = 0 then tactic.mk_mapp (sum_form_name_of_comp_single iq.to_comp) [none, none, ipp] else tactic.mk_mapp (sum_form_name_of_comp iq.to_comp) [none, none, none, ipp] -- tactic.mk_mapp ((if m = 0 then sum_form_name_of_comp_single else sum_form_name_of_comp) iq.to_comp) [none, none, ipp] end --include sfrc private meta def reconstruct_of_eq_proof : Π {lhs rhs c}, eq_proof lhs rhs c → tactic expr | lhs rhs c ep := if expr.lt lhs rhs then reconstruct_of_eq_proof ep.sym else do ipp ← eprc ep, mk_app ``sub_eq_zero_of_eq [ipp] --fail "sum_form_proof.reconstruct_of_eq_proof not implemented yet" private meta def reconstruct_of_sign_proof : Π {e c}, sign_proof e c → tactic expr | e c sp := if c.is_less then sprc sp else do spp ← sprc sp, --trace "spp type is", infer_type spp >>= trace, mk_mapp ``rev_op_zero_of_op [none, none, none, some spp] --fail "sum_form_proof.reconstruct_of_sign_proof not implemented yet" -- sum_form_proof ⟨lhs.add_factor rhs m, spec_comp.strongest c1 c2⟩ -- wait for algebraic normalizer? -- TODO private theorem reconstruct_of_add_factor_aux (P : Prop) {Q R : Prop} (h : Q) (h2 : R) : P := sorry private meta def reconstruct_of_add_factor_same_comp {lhs rhs c1 c2} (m : ℚ) (sfpl : sum_form_proof ⟨lhs, c1⟩) (sfpr : sum_form_proof ⟨rhs, c2⟩) : tactic expr := let sum := lhs + rhs.scale m in do tp ← sum_form.to_expr sum, tp' ← (spec_comp.strongest c1 c2).to_comp.to_function tp `(0 : ℚ), pf1 ← sfrc sfpl, pf2 ← sfrc sfpr, mk_mapp ``reconstruct_of_add_factor_aux [some tp', none, none, some pf1, some pf2] --to_expr `(sorry : %%tp) --fail "reconstruct_of_add_factor_same_comp failed, not implemented yet" private theorem reconstruct_of_add_eq_factor_op_comp_aux (P : Prop) {Q R : Prop} (h : Q) (h2 : R) : P := sorry /- m is negative -/ private meta def reconstruct_of_add_eq_factor_op_comp {lhs rhs c1} (m : ℚ) (sfpl : sum_form_proof ⟨lhs, c1⟩) (sfpr : sum_form_proof ⟨rhs, spec_comp.eq⟩) : tactic expr := let sum := lhs + rhs.scale m in do tp ← sum_form.to_expr sum, tp' ← c1.to_comp.to_function tp `(0 : ℚ), pf1 ← sfrc sfpl, pf2 ← sfrc sfpr, mk_mapp ``reconstruct_of_add_eq_factor_op_comp_aux [some tp', none, none, some pf1, some pf2] --fail "reconstruct_of_add_eq_factor_op_comp not implemented yet" private theorem reconstruct_of_scale_aux (P : Prop) {Q : Prop} (h : Q) : P := sorry private meta def reconstruct_of_scale (rct : Π {sfc}, sum_form_proof sfc → tactic expr) {sfc} (m : ℚ) (sfp : sum_form_proof sfc) : tactic expr := do tp ← sum_form.to_expr (sfc.sf.scale m), tp' ← sfc.c.to_comp.to_function tp `(0 : ℚ), pf ← rct sfp, mk_mapp ``reconstruct_of_scale_aux [some tp', none, some pf] -- to_expr `(sorry : %%tp') end -- TODO (alg norm) theorem reconstruct_of_expr_def_aux (P : Prop) : P := sorry private meta def reconstruct_of_expr_def (e : expr) (sf : sum_form) : tactic expr := do tp ← sum_form.to_expr sf, tp' ← to_expr ``(%%tp = 0), -- (_, pf) ← solve_aux tp' (simp >> done), mk_app ``reconstruct_of_expr_def_aux [tp'] -- instantiate_mvars pf --fail "reconstruct_of_expr_def failed, not implemented yet" meta def reconstruct : Π {sfc}, sum_form_proof sfc → tactic expr | _ (of_ineq_proof ip) := reconstruct_of_ineq_proof @reconstruct ip | _ (of_eq_proof ep) := reconstruct_of_eq_proof @reconstruct ep | _ (of_sign_proof sp) := reconstruct_of_sign_proof @reconstruct sp | _ (of_add_factor_same_comp m sfpl sfpr) := reconstruct_of_add_factor_same_comp @reconstruct m sfpl sfpr | _ (of_add_eq_factor_op_comp m sfpl sfpr) := reconstruct_of_add_eq_factor_op_comp @reconstruct m sfpl sfpr | _ (of_scale m sfp) := reconstruct_of_scale @reconstruct m sfp | _ (of_expr_def e sf) := reconstruct_of_expr_def e sf | _ (fake sd) := fail "cannot reconstruct a fake proof" /-meta def reconstruct : Π {sfc}, sum_form_proof sfc → tactic expr | sfc sfp := if sfc.sf.keys.length = 0 then do ex ← sfc.c.to_comp.to_function ```(0 : ℚ) ```(0 : ℚ), to_expr `(sorry : %%ex) else let sfcd : sum_form_comp_data := ⟨_, sfp, mk_rb_set⟩ in match sfcd.to_ineq_data with | option.some ⟨lhs, rhs, id⟩ := do ex ← ineq_data.to_expr id, to_expr `(sorry : %%ex) | none := trace sfc >> fail "fake sum_form_proof.reconstruct failed, no ineq data" end-/ end sum_form_proof meta def sign_proof.reconstruct := @sign_proof.reconstruct_aux @sum_form_proof.reconstruct meta def ineq_proof.reconstruct := @ineq_proof.reconstruct_aux @sign_proof.reconstruct @sum_form_proof.reconstruct meta def eq_proof.reconstruct := @eq_proof.reconstruct_aux @ineq_proof.reconstruct @sum_form_proof.reconstruct meta def ineq_data.to_expr {lhs rhs} (id : ineq_data lhs rhs) : tactic expr := match id.inq.to_slope with | slope.horiz := id.inq.to_comp.to_function rhs `(0 : ℚ) | slope.some m := if m = 0 then id.inq.to_comp.to_function lhs `(0 : ℚ) else do rhs' ← to_expr ``(%%(m.reflect : expr)*%%rhs), id.inq.to_comp.to_function lhs rhs' end namespace contrad private meta def reconstruct_eq_diseq {lhs rhs} (ed : eq_data lhs rhs) (dd : diseq_data lhs rhs) : tactic expr := if bnot (ed.c = dd.c) then fail "reconstruct_eq_diseq failed: given different coefficients" else do ddp ← dd.prf.reconstruct, edp ← ed.prf.reconstruct, return $ ddp.app edp private meta def reconstruct_two_ineq_data {lhs rhs} (rct : contrad → tactic expr) (id1 id2 : ineq_data lhs rhs) : tactic expr := let sfid1 := sum_form_comp_data.of_ineq_data id1, sfid2 := sum_form_comp_data.of_ineq_data id2 in match find_contrad_in_sfcd_list [sfid1, sfid2] with | some ctr := rct ctr | option.none := fail "reconstruct_two_ineq_data failed to find contr" end private meta def reconstruct_eq_ineq {lhs rhs} (ed : eq_data lhs rhs) (id : ineq_data lhs rhs) : tactic expr := fail "reconstruct_eq_ineq not implemented" -- TODO: this is the hard part. Should this be refactored into smaller pieces? private meta def reconstruct_ineqs (rct : contrad → tactic expr) {lhs rhs} (ii : ineq_info lhs rhs) (id : ineq_data lhs rhs) : tactic expr := --do trace "ineqs!!", match ii with | ineq_info.no_comps := fail "reconstruct_ineqs cannot find a contradiction with no known comps" | ineq_info.one_comp id2 := reconstruct_two_ineq_data rct id id2 | ineq_info.equal ed := reconstruct_eq_ineq ed id | ineq_info.two_comps id1 id2 := let sfid := sum_form_comp_data.of_ineq_data id, sfid1 := sum_form_comp_data.of_ineq_data id1, sfid2 := sum_form_comp_data.of_ineq_data id2 in match find_contrad_in_sfcd_list [sfid, sfid1, sfid2] with | some ctr := rct ctr | option.none := fail "reconstruct_ineqs failed to find contr" end end private meta def reconstruct_sign_ne_eq {e} (nepr : sign_proof e gen_comp.ne) (eqpr : sign_proof e gen_comp.eq) : tactic expr := do neprp ← nepr.reconstruct, eqprp ← eqpr.reconstruct, return $ neprp.app eqprp private meta def reconstruct_sign_le_gt {e} (lepr : sign_proof e gen_comp.le) (gtpr : sign_proof e gen_comp.gt) : tactic expr := do leprp ← lepr.reconstruct, gtprp ← gtpr.reconstruct, mk_app ``le_gt_contr [leprp, gtprp] private meta def reconstruct_sign_ge_lt {e} (gepr : sign_proof e gen_comp.ge) (ltpr : sign_proof e gen_comp.lt) : tactic expr := do geprp ← gepr.reconstruct, ltprp ← ltpr.reconstruct, mk_app ``ge_lt_contr [geprp, ltprp] private meta def reconstruct_sign_gt_lt {e} (gtpr : sign_proof e gen_comp.gt) (ltpr : sign_proof e gen_comp.lt) : tactic expr := do gtprp ← gtpr.reconstruct, ltprp ← ltpr.reconstruct, mk_app ``gt_lt_contr [gtprp, ltprp] private meta def reconstruct_sign {e} : sign_data e → sign_data e → tactic expr | ⟨gen_comp.ne, prf1⟩ ⟨gen_comp.eq, prf2⟩ := reconstruct_sign_ne_eq prf1 prf2 | ⟨gen_comp.eq, prf1⟩ ⟨gen_comp.ne, prf2⟩ := reconstruct_sign_ne_eq prf2 prf1 | ⟨gen_comp.le, prf1⟩ ⟨gen_comp.gt, prf2⟩ := reconstruct_sign_le_gt prf1 prf2 | ⟨gen_comp.gt, prf1⟩ ⟨gen_comp.le, prf2⟩ := reconstruct_sign_le_gt prf2 prf1 | ⟨gen_comp.lt, prf1⟩ ⟨gen_comp.ge, prf2⟩ := reconstruct_sign_ge_lt prf2 prf1 | ⟨gen_comp.ge, prf1⟩ ⟨gen_comp.lt, prf2⟩ := reconstruct_sign_ge_lt prf1 prf2 | ⟨gen_comp.gt, prf1⟩ ⟨gen_comp.lt, prf2⟩ := reconstruct_sign_gt_lt prf1 prf2 | ⟨gen_comp.lt, prf1⟩ ⟨gen_comp.gt, prf2⟩ := reconstruct_sign_gt_lt prf2 prf1 | s1 s2 := trace e >> trace s1.c >> trace s2.c >> fail "reconstruct_sign failed: given non-opposite comps" private meta def reconstruct_strict_ineq_self {e} (id : ineq_data e e) : tactic expr := match id.inq.to_comp, id.inq.to_slope with | comp.gt, slope.some m := if bnot (m = 1) then fail "reconstruct_strict_ineq_self failed: given non-one slope" else do idp ← id.prf.reconstruct, mk_app ``gt_self_contr [idp] | comp.lt, slope.some m := if bnot (m = 1) then fail "reconstruct_strict_ineq_self failed: given non-one slope" else do idp ← id.prf.reconstruct, mk_app ``lt_self_contr [idp] | _, _ := fail "reconstruct_strict_ineq_self failed: given non-strict comp or non-one slope" end meta def reconstruct_sum_form {sfc} (sfp : sum_form_proof sfc) : tactic expr := if sfc.is_contr then do zltz ← sfp.reconstruct, mk_mapp ``lt_irrefl [option.none, option.none, option.none, some zltz] else fail "reconstruct_sum_form requires proof of 0 < 0" meta def reconstruct : contrad → tactic expr | none := fail "cannot reconstruct contr: no contradiction is known" | (@eq_diseq lhs rhs ed dd) := reconstruct_eq_diseq ed dd | (@ineqs lhs rhs ii id) := reconstruct_ineqs reconstruct ii id | (@sign e sd1 sd2) := reconstruct_sign sd1 sd2 | (@strict_ineq_self e id) := reconstruct_strict_ineq_self id | (@sum_form _ sfp) := reconstruct_sum_form sfp end contrad namespace prod_form_proof meta def expr_coeff_list_to_expr_aux : expr → list (expr × ℤ) → tactic expr | a [] := return a | a ((e, z)::t) := do h ← to_expr ``(rat.pow %%e %%(z.reflect : expr)), tmp ← to_expr ``(%%a * %%h), expr_coeff_list_to_expr_aux tmp t meta def expr_coeff_list_to_expr : list (expr × ℤ) → tactic expr | [] := return `(1 : ℚ) | ((e, z)::t) := do h ← to_expr ``(rat.pow %%e %%(z.reflect : expr)), expr_coeff_list_to_expr_aux h t /-meta def expr_coeff_list_to_expr : list (expr × ℤ) → tactic expr | [] := return `(1 : ℚ) | [(e, z)] := to_expr ``(rat.pow %%e %%(z.reflect : expr)) | ((e, z)::t) := do e' ← expr_coeff_list_to_expr t, h ← to_expr ``(rat.pow %%e %%(z.reflect : expr)), to_expr ``(%%h * %%e')-/ end prod_form_proof meta def prod_form.to_expr (sf : prod_form) : tactic expr := do --trace "in prod_form.to_expr", exp ← prod_form_proof.expr_coeff_list_to_expr sf.exps.to_list, let cf : expr := sf.coeff.reflect, to_expr ``(%%cf * %%exp : ℚ) namespace prod_form_proof /-private meta def mk_prod_ne_zero_prf_aux : expr → list (Σ e : expr, sign_proof e gen_comp.ne) → tactic expr | e [] := return e | e (⟨e', sp⟩::t) := do ene ← sp.reconstruct, pf ← mk_app ``mul_ne_zero [e, ene], mk_prod_ne_zero_prf_aux pf t private meta def mk_prod_ne_zero_prf (c : ℚ) : list (Σ e : expr, sign_proof e gen_comp.ne) → tactic expr | [] := if c = 0 then fail "mk_prod_ne_zero_prf failed, c = 0" else mk_app ``fake_ne_zero_pf [`(c)] | (⟨e, sp⟩::t) := if c = 0 then fail "mk_prod_ne_zero_prf failed, c = 0" else do cprf ← mk_app ``fake_ne_zero_pf [`(c)], hpf ← sp.reconstruct, prodprf ← mk_prod_ne_zero_prf_aux hpf t, mk_app ``mul_ne_zero [hpf, prodprf] -/ /-#check spec_comp_and_flipped_of_comp -- not finished: need to orient c private meta def reconstruct_of_ineq_proof_pos_lhs {lhs rhs iq} (id : ineq_proof lhs rhs iq) (sp : sign_proof lhs gen_comp.gt) (nzprs : hash_map expr (λ e, sign_proof e gen_comp.ne)) : tactic expr := match (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with | _, slope.horiz := fail "reconstruct_of_ineq_proof_pos_lhs failed, cannot make a prod_form with 0 slope" | (c, flipped), slope.some m := if m = 0 then fail "reconstruct_of_ineq_proof_pos_lhs failed, cannot make a prod_form with 0 slope" else do -- lhs c m*rhs --> 1 c m*(lhs⁻¹*rhs) idp ← id.reconstruct, spp ← sp.reconstruct, opp ← mk_app ``one_op_inv_mul_of_op_of_pos [idp, spp], -- 1 r lhs⁻¹*rhs if bnot flipped then return opp else do mprf ← mk_sign_pf m, failed end-/ private meta def reconstruct_of_ineq_proof_aux {lhs rhs iq c1 c2} (id : ineq_proof lhs rhs iq) (spl : sign_proof lhs c1) (spr : sign_proof rhs c2) (fail_cond : ℚ → bool) (unflipped_name flipped_name : name) --flipped_lt_name flipped_le_name : name) : tactic expr := match (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with | _, slope.horiz := fail "reconstruct_of_ineq_proof_pos_pos failed, cannot make a prod_form with 0 slope" | (c, flipped), slope.some m := --trace "okay, roipa" >> trace flipped >> trace iq >> if fail_cond m then fail "reconstruct_of_ineq_proof_aux failed check" else do idp ← id.reconstruct, --trace "idp_type:", infer_type idp >>= trace, splp ← spl.reconstruct, --trace "splp_type:", infer_type splp >>= trace, trace "c1 is:", trace c1, trace spl, opp ← mk_app unflipped_name [idp, splp], --trace "opp", infer_type opp >>= trace, if bnot flipped then return opp else do msgn ← mk_sign_pf m, sprp ← spr.reconstruct, trace "HERE", infer_type opp >>= trace, infer_type splp >>= trace, infer_type sprp >>= trace, infer_type msgn >>= trace, trace unflipped_name, trace iq, mk_app flipped_name-- (if c=spec_comp.lt then flipped_lt_name else flipped_le_name) [opp, splp, sprp, msgn] end private meta def reconstruct_of_ineq_proof_pos_pos {lhs rhs iq} (id : ineq_proof lhs rhs iq) (spl : sign_proof lhs gen_comp.gt) (spr : sign_proof rhs gen_comp.gt) : tactic expr := reconstruct_of_ineq_proof_aux id spl spr (λ m, m ≤ 0) ``one_op_inv_mul_of_op_of_pos ``one_op_inv_mul_of_lt_of_pos_pos_flipped' -- ``one_le_inv_mul_of_le_of_pos_pos_flipped /-match (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with | _, slope.horiz := fail "reconstruct_of_ineq_proof_pos_pos failed, cannot make a prod_form with 0 slope" | (c, flipped), slope.some m := if m ≤ 0 then fail "reconstruct_of_ineq_proof_pos_pos failed, m ≤ 0" else do idp ← id.reconstruct, splp ← spl.reconstruct, opp ← mk_app ``one_op_inv_mul_of_op_of_pos [idp, splp], if bnot flipped then return opp else do msgn ← mk_sign_pf m, sprp ← spr.reconstruct, mk_app (if c=spec_comp.lt then ``one_lt_inv_mul_of_lt_of_pos_flipped else ``one_le_inv_mul_of_le_of_pos_flipped) [opp, splp, sprp, msgn] end-/ private meta def reconstruct_of_ineq_proof_pos_neg {lhs rhs iq} (id : ineq_proof lhs rhs iq) (spl : sign_proof lhs gen_comp.gt) (spr : sign_proof rhs gen_comp.lt) : tactic expr := reconstruct_of_ineq_proof_aux id spl spr (λ m, m ≥ 0) ``one_op_inv_mul_of_op_of_pos ``one_op_inv_mul_of_lt_of_pos_neg_flipped -- ``one_le_inv_mul_of_le_of_pos_neg_flipped private meta def reconstruct_of_ineq_proof_neg_pos {lhs rhs iq} (id : ineq_proof lhs rhs iq) (spl : sign_proof lhs gen_comp.lt) (spr : sign_proof rhs gen_comp.gt) : tactic expr := reconstruct_of_ineq_proof_aux id spl spr (λ m, m ≥ 0) ``one_op_inv_mul_of_op_of_neg ``one_op_inv_mul_of_lt_of_neg_pos_flipped -- ``one_le_inv_mul_of_le_of_neg_flipped private meta def reconstruct_of_ineq_proof_neg_neg {lhs rhs iq} (id : ineq_proof lhs rhs iq) (spl : sign_proof lhs gen_comp.lt) (spr : sign_proof rhs gen_comp.lt) : tactic expr := reconstruct_of_ineq_proof_aux id spl spr (λ m, m ≤ 0) ``one_op_inv_mul_of_op_of_neg ``one_op_inv_mul_of_lt_of_neg_neg_flipped /- pos_neg cmatch (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with | _, slope.horiz := fail "reconstruct_of_ineq_proof_pos_pos failed, cannot make a prod_form with 0 slope" | (c, flipped), slope.some m := if m ≥ 0 then fail "reconstruct_of_ineq_proof_pos_neg failed, m ≥ 0" else do idp ← id.reconstruct, splp ← spl.reconstruct, opp ← mk_app ``one_op_inv_mul_of_op_of_pos [idp, splp], if bnot flipped then return opp else do msgn ← mk_sign_pf m, sprp ← spr.reconstruct, mk_app (if c=spec_comp.lt then ``one_lt_inv_mul_of_lt_of_pos_flipped else ``one_le_inv_mul_of_le_of_pos_flipped) [opp, splp, sprp, msgn] end -/ private meta def reconstruct_of_ineq_proof {lhs rhs iq} (id : ineq_proof lhs rhs iq) : Π {cl cr}, sign_proof lhs cl → sign_proof rhs cr → tactic expr | gen_comp.gt gen_comp.gt spl spr := reconstruct_of_ineq_proof_pos_pos id spl spr | gen_comp.gt gen_comp.lt spl spr := reconstruct_of_ineq_proof_pos_neg id spl spr | gen_comp.lt gen_comp.gt spl spr := reconstruct_of_ineq_proof_neg_pos id spl spr | gen_comp.lt gen_comp.lt spl spr := reconstruct_of_ineq_proof_neg_neg id spl spr | _ _ _ _ := fail "reconstruct_of_ineq_proof failed, need to know signs of components" /- -- TODO private meta def reconstruct_of_ineq_proof_neg_lhs {lhs rhs iq} (id : ineq_proof lhs rhs iq) (sp : sign_proof lhs gen_comp.lt) (nzprs : hash_map expr (λ e, sign_proof e gen_comp.ne)) : tactic expr := match iq.to_slope with | slope.horiz := fail "reconstruct_of_ineq_proof_neg_lhs failed, cannot make a prod_form with 0 slope" | slope.some m := if m = 0 then fail "reconstruct_of_ineq_proof_pos_lhs failed, cannot make a prod_form with 0 slope" else failed end-/ private meta def reconstruct_of_eq_proof {lhs rhs c} (id : eq_proof lhs rhs c) (lhsne : sign_proof lhs gen_comp.ne) : tactic expr := if c = 0 then fail "reconstruct_of_eq_proof failed, cannot make a prod_form with 0 slope" else do lhsnep ← lhsne.reconstruct, idpf ← id.reconstruct, mk_app ``one_eq_div_of_eq [idpf, lhsnep] theorem reconstruct_of_expr_def_aux (P : Prop) : P := sorry /- -- TODO private meta def reconstruct_of_expr_def (e : expr) (sf : sum_form) : tactic expr := do tp ← sum_form.to_expr sf, tp' ← to_expr ``(%%tp = 0), -- (_, pf) ← solve_aux tp' (simp >> done), mk_app ``reconstruct_of_expr_def_aux [tp'] -- instantiate_mvars pf --fail "reconstruct_of_expr_def failed, not implemented yet" -/ -- TODO (alg_nom) private meta def reconstruct_of_expr_def (e : expr) (pf : prod_form) : tactic expr := do --trace "in reconstruct_of_expr_def", tp ← prod_form.to_expr pf, -- trace "tp:", trace tp, tp' ← to_expr ``(1 = %%tp), -- trace "tp':", trace tp', -- (_, pf) ← solve_aux tp' (simp >> done), mk_app ``reconstruct_of_expr_def_aux [tp'] section variable (rct : Π {pfc}, prod_form_proof pfc → tactic expr) -- Given an expr of the form e := (p1^e1)^k, produces a proof that -- e = p1^(e1*k) private meta def simp_pow_aux_aux (p e k : expr) : tactic expr := mk_app ``rat.pow_pow [p, e, k] /-private meta def simp_pow_aux_aux : expr → tactic expr | `(rat.pow (rat.pow %%p %%e) %%k) := mk_app ``rat.pow_pow [p, e, k] | _ := failed -/ -- Given an expr of the form e := (p1^e1*...*pn^en)^k, produces a proof that -- e = (p1^(e1*k) * ... * pn^(en*k) private meta def simp_pow_aux : expr → tactic expr | e := match e with | `(rat.pow (%%a * (rat.pow %%b %%n)) %%k) := let prod' := `(rat.pow %%a %%k) in do prod_pf ← simp_pow_aux prod', pow_pf ← mk_app ``rat.mul_pow [a, `(rat.pow %%b %%n), k], one_pow_pf ← simp_pow_aux_aux b n k, -- trace "doing rewrite", -- infer_type pow_pf >>= trace, trace e, (e', pf1, []) ← rewrite pow_pf e, (e'', pf2, []) ← rewrite one_pow_pf e', (e''', pf3, []) ← rewrite prod_pf e'', t1 ← mk_app ``eq.trans [pf1, pf2], mk_app ``eq.trans [t1, pf3] | `(rat.pow (rat.pow %%a %%n) %%k) := simp_pow_aux_aux a n k | e := do f ← pp e, fail $ "simp_pow_aux failed on " ++ f.to_string end -- Given an expr of the form e := (c*(p1^e1*...*pn^en))^k, produces a proof that -- e = c^k * (p1^(e1*k) * ... * pn^(en*k)) meta def simp_pow (e : expr) : tactic expr := --do trace "simp pow called on:", trace e, match e with | `(rat.pow (%%coeff * %%prod) %%k) := let prod' := `(rat.pow %%prod %%k) in do prod_pf ← simp_pow_aux prod', pow_pf ← mk_app ``rat.mul_pow [coeff, prod, k], --trace "doing rewrite", (e', pf1, []) ← rewrite pow_pf e, (e'', pf2, []) ← rewrite prod_pf e', mk_app ``eq.trans [pf1, pf2] | _ := fail "simp_pow got malformed arg" end /-example (a b c : ℚ) (m n k : ℤ) : rat.pow (a * (rat.pow b m * rat.pow c n)) k = rat.pow a k * (rat.pow b (m*k) * rat.pow c (n*k)) := by do (lhs, rhs) ← target >>= match_eq, e ← simp_pow lhs, infer_type e >>= trace, exact e-/ private meta def simp_pow_expr (pf tgt : expr) : tactic expr := do sls ← (simp_lemmas.mk.add_simp ``rat.mul_pow_rev) >>= λ t, t.add pf, --trace "target", trace tgt, --trace "pf tp", infer_type pf >>= trace, (do (_, npf) ← simplify sls [] tgt,-- <|> do rpr ← to_expr ``(eq.refl %%tgt), return (`(()), rpr), --(_, npf) ← solve_aux tgt (simp_target sls >> done), return npf) <|> to_expr ``(eq.refl %%tgt) meta def simp_lemmas.add_simp_list : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (h::t) := s.add_simp h >>= λ s', simp_lemmas.add_simp_list s' t private meta def simp_pow_expr' (tgt : expr) : tactic expr := do --sls ← (simp_lemmas.mk.add_simp ``rat.mul_pow) >>= (λ s, simp_lemmas.add_simp s ``rat.pow_one) >>= (λ s, simp_lemmas.add_simp s ``rat.pow_neg_one), sls ← simp_lemmas.add_simp_list simp_lemmas.mk [``rat.mul_pow, ``rat.pow_one, ``rat.pow_neg_one, ``rat.one_pow, ``rat.pow_pow, ``rat.one_div_pow], --trace "target", trace tgt, -- trace "pf tp", infer_type pf >>= trace, -- (do (_, npf) ← simplify sls [] tgt,-- <|> do rpr ← to_expr ``(eq.refl %%tgt), return (`(()), rpr), (_, npf) ← solve_aux tgt ( /-trace_state >>-/ simp_target sls >>/- trace "!!!" >> trace_state >>-/ reflexivity), -- `[simp [rat.mul_pow_rev, rat.pow_one], done], return npf section open expr private meta def reconstruct_of_pow_pos {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr := if z ≤ 0 then fail "reconstruct_of_pow_pos failed, given negative exponent" else do zsn ← mk_int_sign_pf z, pf1 ← rct pfp, --trace "here", /-trace pfc,-/ trace pfp, trace z, infer_type pf1 >>= trace, pf2 ← mk_mapp (if pfc.c = spec_comp.lt then ``lt_pos_pow' else ``le_pos_pow') [none, pf1, none, zsn], --trace "pf2tp", infer_type pf2 >>= trace, pf2tp ← infer_type pf2, match pf2tp with | (app (app (app o i) lhs) rhs) := do eqp ← simp_pow rhs, (new_type, prf, []) ← rewrite eqp pf2tp, mk_eq_mp prf pf2 -- failed | _ := fail "reconstruct_of_pow_pos failed" end /- match pf2tp with | app (app (app o i) lhs) rhs := do tgt ← prod_form.to_expr (pfc.pf.pow z), pf ← to_expr ``(%%rhs = %%tgt) >>= simp_pow_expr', trace "pf2tp", trace pf2tp, trace "pftp", infer_type pf >>= trace, trace "o", trace o, -- trace `(%%o %%lhs %%tgt), tgt' ← return $ app (app (app o i) lhs) tgt,--to_expr ``(%%o %%lhs %%tgt), trace "new tgt:", trace tgt', pf1 ← to_expr ``(eq.symm %%pf), (_, pf') ← solve_aux tgt' (rewrite_target pf1 >> apply pf2), trace "proved", infer_type pf' >>= trace, return pf' | _ := failed end -- tgt ← prod_form.to_expr (pfc.pf.pow z), -- simp_pow_expr pf2 tgt -/ end /-private meta def reconstruct_of_pow_neg {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr := if z ≥ 0 then fail "reconstruct_of_pow_neg failed, given positive exponent" else failed-/ private meta def reconstruct_of_pow_eq {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr := do --trace "pfp is:", trace pfp, pf1 ← rct pfp, --trace "reconstructed", infer_type pf1 >>= trace, tpf ← mk_app ``eq_pow [pf1, `(z)], tpf' ← mk_app ``eq_pow' [tpf], tpf_tp ← infer_type tpf', tgt ← prod_form.to_expr (pfc.pf.pow z), --trace "target is:", trace tgt, tgt' ← to_expr ``(1 = %%tgt), --trace "tgt', tpf", trace tgt', infer_type tpf >>= trace, (_, pf') ← solve_aux tgt' (assertv `h tpf_tp tpf' >> `[simp only [rat.mul_pow, rat.pow_pow], simp only [rat.mul_pow, rat.pow_pow] at h, apply h] >> done), return pf' -- simp_pow_expr tpf tgt private meta def reconstruct_of_pow {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr := if pfc.c = spec_comp.eq then reconstruct_of_pow_eq @rct z pfp else reconstruct_of_pow_pos @rct z pfp private theorem reconstruct_of_mul_aux (P : Prop) {Q R : Prop} : Q → R → P := sorry private meta def reconstruct_of_mul (rct : Π {pfc}, prod_form_proof pfc → tactic expr) {lhs rhs c1 c2} (pfp1 : prod_form_proof ⟨lhs, c1⟩) (pfp2 : prod_form_proof ⟨rhs, c2⟩) (sgns : list Σ e : expr, sign_proof e gen_comp.ne) : tactic expr := let prod := lhs * rhs in do /-trace "in reconstruct_of_mul", trace prod,-/ tp ← prod_form.to_expr prod, --trace tp, tp' ← (spec_comp.strongest c1 c2).to_comp.to_function `(1 : ℚ) tp, --trace tp', pf1 ← rct pfp1, pf2 ← rct pfp2,-- trace "**", mk_mapp ``reconstruct_of_mul_aux [tp', none, none, pf1, pf2] /- let sum := lhs + rhs.scale m in do tp ← sum_form.to_expr sum, tp' ← (spec_comp.strongest c1 c2).to_comp.to_function tp `(0 : ℚ), pf1 ← sfrc sfpl, pf2 ← sfrc sfpr, mk_mapp ``reconstruct_of_add_factor_aux [some tp', none, none, some pf1, some pf2] -/ end meta def reconstruct : Π {pfc}, prod_form_proof pfc → tactic expr --| .(_) (@of_ineq_proof_pos_lhs _ _ _ id sp nzprs) := reconstruct_of_ineq_proof_pos_lhs id sp nzprs --| .(_) (@of_ineq_proof_neg_lhs _ _ _ id sp nzprs) := reconstruct_of_ineq_proof_neg_lhs id sp nzprs | .(_) (@of_ineq_proof _ _ _ _ _ id spl spr) := reconstruct_of_ineq_proof id spl spr | .(_) (@of_eq_proof _ _ _ id lhsne) := reconstruct_of_eq_proof id lhsne | .(_) (@of_expr_def e pf) := reconstruct_of_expr_def e pf | .(_) (@of_pow _ z pfp) := reconstruct_of_pow @reconstruct z pfp | .(_) (@of_mul _ _ _ _ pfp1 pfp2 sgns) := reconstruct_of_mul @reconstruct pfp1 pfp2 sgns | .(_) (adhoc _ _ t) := t | .(_) (fake _) := fail "prod_form_proof.reconstruct failed: cannot reconstruct fake" end prod_form_proof end polya
cc316d8c87291b380ec561fc5acf77e173194ebd
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/inner_product_space/gram_schmidt_ortho.lean
495227a7c37d009233830bb03ae6fc14d15eb6e2
[ "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
17,637
lean
/- Copyright (c) 2022 Jiale Miao. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jiale Miao, Kevin Buzzard, Alexander Bentkamp -/ import analysis.inner_product_space.pi_L2 import linear_algebra.matrix.block /-! # Gram-Schmidt Orthogonalization and Orthonormalization In this file we introduce Gram-Schmidt Orthogonalization and Orthonormalization. The Gram-Schmidt process takes a set of vectors as input and outputs a set of orthogonal vectors which have the same span. ## Main results - `gram_schmidt` : the Gram-Schmidt process - `gram_schmidt_orthogonal` : `gram_schmidt` produces an orthogonal system of vectors. - `span_gram_schmidt` : `gram_schmidt` preserves span of vectors. - `gram_schmidt_ne_zero` : If the input vectors of `gram_schmidt` are linearly independent, then the output vectors are non-zero. - `gram_schmidt_basis` : The basis produced by the Gram-Schmidt process when given a basis as input. - `gram_schmidt_normed` : the normalized `gram_schmidt` (i.e each vector in `gram_schmidt_normed` has unit length.) - `gram_schmidt_orthornormal` : `gram_schmidt_normed` produces an orthornormal system of vectors. - `gram_schmidt_orthonormal_basis`: orthonormal basis constructed by the Gram-Schmidt process from an indexed set of vectors of the right size -/ open_locale big_operators open finset submodule finite_dimensional variables (𝕜 : Type*) {E : Type*} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] variables {ι : Type*} [linear_order ι] [locally_finite_order_bot ι] [is_well_order ι (<)] local attribute [instance] is_well_order.to_has_well_founded local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y /-- The Gram-Schmidt process takes a set of vectors as input and outputs a set of orthogonal vectors which have the same span. -/ noncomputable def gram_schmidt (f : ι → E) : ι → E | n := f n - ∑ i : Iio n, orthogonal_projection (𝕜 ∙ gram_schmidt i) (f n) using_well_founded { dec_tac := `[exact mem_Iio.1 i.2] } /-- This lemma uses `∑ i in` instead of `∑ i :`.-/ lemma gram_schmidt_def (f : ι → E) (n : ι): gram_schmidt 𝕜 f n = f n - ∑ i in Iio n, orthogonal_projection (𝕜 ∙ gram_schmidt 𝕜 f i) (f n) := by { rw [←sum_attach, attach_eq_univ, gram_schmidt], refl } lemma gram_schmidt_def' (f : ι → E) (n : ι): f n = gram_schmidt 𝕜 f n + ∑ i in Iio n, orthogonal_projection (𝕜 ∙ gram_schmidt 𝕜 f i) (f n) := by rw [gram_schmidt_def, sub_add_cancel] lemma gram_schmidt_def'' (f : ι → E) (n : ι): f n = gram_schmidt 𝕜 f n + ∑ i in Iio n, (⟪gram_schmidt 𝕜 f i, f n⟫ / ‖gram_schmidt 𝕜 f i‖ ^ 2) • gram_schmidt 𝕜 f i := begin convert gram_schmidt_def' 𝕜 f n, ext i, rw orthogonal_projection_singleton, end @[simp] lemma gram_schmidt_zero {ι : Type*} [linear_order ι] [locally_finite_order ι] [order_bot ι] [is_well_order ι (<)] (f : ι → E) : gram_schmidt 𝕜 f ⊥ = f ⊥ := by rw [gram_schmidt_def, Iio_eq_Ico, finset.Ico_self, finset.sum_empty, sub_zero] /-- **Gram-Schmidt Orthogonalisation**: `gram_schmidt` produces an orthogonal system of vectors. -/ theorem gram_schmidt_orthogonal (f : ι → E) {a b : ι} (h₀ : a ≠ b) : ⟪gram_schmidt 𝕜 f a, gram_schmidt 𝕜 f b⟫ = 0 := begin suffices : ∀ a b : ι, a < b → ⟪gram_schmidt 𝕜 f a, gram_schmidt 𝕜 f b⟫ = 0, { cases h₀.lt_or_lt with ha hb, { exact this _ _ ha, }, { rw inner_eq_zero_sym, exact this _ _ hb, }, }, clear h₀ a b, intros a b h₀, revert a, apply well_founded.induction (@is_well_founded.wf ι (<) _) b, intros b ih a h₀, simp only [gram_schmidt_def 𝕜 f b, inner_sub_right, inner_sum, orthogonal_projection_singleton, inner_smul_right], rw finset.sum_eq_single_of_mem a (finset.mem_Iio.mpr h₀), { by_cases h : gram_schmidt 𝕜 f a = 0, { simp only [h, inner_zero_left, zero_div, zero_mul, sub_zero], }, { rw [← inner_self_eq_norm_sq_to_K, div_mul_cancel, sub_self], rwa [ne.def, inner_self_eq_zero], }, }, simp_intros i hi hia only [finset.mem_range], simp only [mul_eq_zero, div_eq_zero_iff, inner_self_eq_zero], right, cases hia.lt_or_lt with hia₁ hia₂, { rw inner_eq_zero_sym, exact ih a h₀ i hia₁ }, { exact ih i (mem_Iio.1 hi) a hia₂ } end /-- This is another version of `gram_schmidt_orthogonal` using `pairwise` instead. -/ theorem gram_schmidt_pairwise_orthogonal (f : ι → E) : pairwise (λ a b, ⟪gram_schmidt 𝕜 f a, gram_schmidt 𝕜 f b⟫ = 0) := λ a b, gram_schmidt_orthogonal 𝕜 f lemma gram_schmidt_inv_triangular (v : ι → E) {i j : ι} (hij : i < j) : ⟪gram_schmidt 𝕜 v j, v i⟫ = 0 := begin rw gram_schmidt_def'' 𝕜 v, simp only [inner_add_right, inner_sum, inner_smul_right], set b : ι → E := gram_schmidt 𝕜 v, convert zero_add (0:𝕜), { exact gram_schmidt_orthogonal 𝕜 v hij.ne' }, apply finset.sum_eq_zero, rintros k hki', have hki : k < i := by simpa using hki', have : ⟪b j, b k⟫ = 0 := gram_schmidt_orthogonal 𝕜 v (hki.trans hij).ne', simp [this], end open submodule set order lemma mem_span_gram_schmidt (f : ι → E) {i j : ι} (hij : i ≤ j) : f i ∈ span 𝕜 (gram_schmidt 𝕜 f '' Iic j) := begin rw [gram_schmidt_def' 𝕜 f i], simp_rw orthogonal_projection_singleton, exact submodule.add_mem _ (subset_span $ mem_image_of_mem _ hij) (submodule.sum_mem _ $ λ k hk, smul_mem (span 𝕜 (gram_schmidt 𝕜 f '' Iic j)) _ $ subset_span $ mem_image_of_mem (gram_schmidt 𝕜 f) $ (finset.mem_Iio.1 hk).le.trans hij), end lemma gram_schmidt_mem_span (f : ι → E) : ∀ {j i}, i ≤ j → gram_schmidt 𝕜 f i ∈ span 𝕜 (f '' Iic j) | j := λ i hij, begin rw [gram_schmidt_def 𝕜 f i], simp_rw orthogonal_projection_singleton, refine submodule.sub_mem _ (subset_span (mem_image_of_mem _ hij)) (submodule.sum_mem _ $ λ k hk, _), let hkj : k < j := (finset.mem_Iio.1 hk).trans_le hij, exact smul_mem _ _ (span_mono (image_subset f $ Iic_subset_Iic.2 hkj.le) $ gram_schmidt_mem_span le_rfl), end using_well_founded { dec_tac := `[assumption] } lemma span_gram_schmidt_Iic (f : ι → E) (c : ι) : span 𝕜 (gram_schmidt 𝕜 f '' Iic c) = span 𝕜 (f '' Iic c) := span_eq_span (set.image_subset_iff.2 $ λ i, gram_schmidt_mem_span _ _) $ set.image_subset_iff.2 $ λ i, mem_span_gram_schmidt _ _ lemma span_gram_schmidt_Iio (f : ι → E) (c : ι) : span 𝕜 (gram_schmidt 𝕜 f '' Iio c) = span 𝕜 (f '' Iio c) := span_eq_span (set.image_subset_iff.2 $ λ i hi, span_mono (image_subset _ $ Iic_subset_Iio.2 hi) $ gram_schmidt_mem_span _ _ le_rfl) $ set.image_subset_iff.2 $ λ i hi, span_mono (image_subset _ $ Iic_subset_Iio.2 hi) $ mem_span_gram_schmidt _ _ le_rfl /-- `gram_schmidt` preserves span of vectors. -/ lemma span_gram_schmidt (f : ι → E) : span 𝕜 (range (gram_schmidt 𝕜 f)) = span 𝕜 (range f) := span_eq_span (range_subset_iff.2 $ λ i, span_mono (image_subset_range _ _) $ gram_schmidt_mem_span _ _ le_rfl) $ range_subset_iff.2 $ λ i, span_mono (image_subset_range _ _) $ mem_span_gram_schmidt _ _ le_rfl lemma gram_schmidt_of_orthogonal {f : ι → E} (hf : pairwise (λ i j, ⟪f i, f j⟫ = 0)) : gram_schmidt 𝕜 f = f := begin ext i, rw gram_schmidt_def, transitivity f i - 0, { congr, apply finset.sum_eq_zero, intros j hj, rw coe_eq_zero, suffices : span 𝕜 (f '' set.Iic j) ≤ (𝕜 ∙ f i)ᗮ, { apply orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero, rw mem_orthogonal_singleton_iff_inner_left, rw ←mem_orthogonal_singleton_iff_inner_right, exact this (gram_schmidt_mem_span 𝕜 f (le_refl j)) }, rw span_le, rintros - ⟨k, hk, rfl⟩, rw [set_like.mem_coe, mem_orthogonal_singleton_iff_inner_left], apply hf, refine (lt_of_le_of_lt hk _).ne, simpa using hj }, { simp }, end variables {𝕜} lemma gram_schmidt_ne_zero_coe {f : ι → E} (n : ι) (h₀ : linear_independent 𝕜 (f ∘ (coe : set.Iic n → ι))) : gram_schmidt 𝕜 f n ≠ 0 := begin by_contra h, have h₁ : f n ∈ span 𝕜 (f '' Iio n), { rw [← span_gram_schmidt_Iio 𝕜 f n, gram_schmidt_def' _ f, h, zero_add], apply submodule.sum_mem _ _, simp_intros a ha only [finset.mem_Ico], simp only [set.mem_image, set.mem_Iio, orthogonal_projection_singleton], apply submodule.smul_mem _ _ _, rw finset.mem_Iio at ha, refine subset_span ⟨a, ha, by refl⟩ }, have h₂ : (f ∘ (coe : set.Iic n → ι)) ⟨n, le_refl n⟩ ∈ span 𝕜 (f ∘ (coe : set.Iic n → ι) '' Iio ⟨n, le_refl n⟩), { rw [image_comp], convert h₁ using 3, ext i, simpa using @le_of_lt _ _ i n }, apply linear_independent.not_mem_span_image h₀ _ h₂, simp only [set.mem_Iio, lt_self_iff_false, not_false_iff] end /-- If the input vectors of `gram_schmidt` are linearly independent, then the output vectors are non-zero. -/ lemma gram_schmidt_ne_zero {f : ι → E} (n : ι) (h₀ : linear_independent 𝕜 f) : gram_schmidt 𝕜 f n ≠ 0 := gram_schmidt_ne_zero_coe _ (linear_independent.comp h₀ _ subtype.coe_injective) /-- `gram_schmidt` produces a triangular matrix of vectors when given a basis. -/ lemma gram_schmidt_triangular {i j : ι} (hij : i < j) (b : basis ι 𝕜 E) : b.repr (gram_schmidt 𝕜 b i) j = 0 := begin have : gram_schmidt 𝕜 b i ∈ span 𝕜 (gram_schmidt 𝕜 b '' set.Iio j), from subset_span ((set.mem_image _ _ _).2 ⟨i, hij, rfl⟩), have : gram_schmidt 𝕜 b i ∈ span 𝕜 (b '' set.Iio j), by rwa [← span_gram_schmidt_Iio 𝕜 b j], have : ↑(((b.repr) (gram_schmidt 𝕜 b i)).support) ⊆ set.Iio j, from basis.repr_support_subset_of_mem_span b (set.Iio j) this, exact (finsupp.mem_supported' _ _).1 ((finsupp.mem_supported 𝕜 _).2 this) j set.not_mem_Iio_self, end /-- `gram_schmidt` produces linearly independent vectors when given linearly independent vectors. -/ lemma gram_schmidt_linear_independent {f : ι → E} (h₀ : linear_independent 𝕜 f) : linear_independent 𝕜 (gram_schmidt 𝕜 f) := linear_independent_of_ne_zero_of_inner_eq_zero (λ i, gram_schmidt_ne_zero _ h₀) (λ i j, gram_schmidt_orthogonal 𝕜 f) /-- When given a basis, `gram_schmidt` produces a basis. -/ noncomputable def gram_schmidt_basis (b : basis ι 𝕜 E) : basis ι 𝕜 E := basis.mk (gram_schmidt_linear_independent b.linear_independent) ((span_gram_schmidt 𝕜 b).trans b.span_eq).ge lemma coe_gram_schmidt_basis (b : basis ι 𝕜 E) : (gram_schmidt_basis b : ι → E) = gram_schmidt 𝕜 b := basis.coe_mk _ _ variables (𝕜) /-- the normalized `gram_schmidt` (i.e each vector in `gram_schmidt_normed` has unit length.) -/ noncomputable def gram_schmidt_normed (f : ι → E) (n : ι) : E := (‖gram_schmidt 𝕜 f n‖ : 𝕜)⁻¹ • (gram_schmidt 𝕜 f n) variables {𝕜} lemma gram_schmidt_normed_unit_length_coe {f : ι → E} (n : ι) (h₀ : linear_independent 𝕜 (f ∘ (coe : set.Iic n → ι))) : ‖gram_schmidt_normed 𝕜 f n‖ = 1 := by simp only [gram_schmidt_ne_zero_coe n h₀, gram_schmidt_normed, norm_smul_inv_norm, ne.def, not_false_iff] lemma gram_schmidt_normed_unit_length {f : ι → E} (n : ι) (h₀ : linear_independent 𝕜 f) : ‖gram_schmidt_normed 𝕜 f n‖ = 1 := gram_schmidt_normed_unit_length_coe _ (linear_independent.comp h₀ _ subtype.coe_injective) lemma gram_schmidt_normed_unit_length' {f : ι → E} {n : ι} (hn : gram_schmidt_normed 𝕜 f n ≠ 0) : ‖gram_schmidt_normed 𝕜 f n‖ = 1 := begin rw gram_schmidt_normed at *, rw [norm_smul_inv_norm], simpa using hn, end /-- **Gram-Schmidt Orthonormalization**: `gram_schmidt_normed` applied to a linearly independent set of vectors produces an orthornormal system of vectors. -/ theorem gram_schmidt_orthonormal {f : ι → E} (h₀ : linear_independent 𝕜 f) : orthonormal 𝕜 (gram_schmidt_normed 𝕜 f) := begin unfold orthonormal, split, { simp only [gram_schmidt_normed_unit_length, h₀, eq_self_iff_true, implies_true_iff], }, { intros i j hij, simp only [gram_schmidt_normed, inner_smul_left, inner_smul_right, is_R_or_C.conj_inv, is_R_or_C.conj_of_real, mul_eq_zero, inv_eq_zero, is_R_or_C.of_real_eq_zero, norm_eq_zero], repeat { right }, exact gram_schmidt_orthogonal 𝕜 f hij } end /-- **Gram-Schmidt Orthonormalization**: `gram_schmidt_normed` produces an orthornormal system of vectors after removing the vectors which become zero in the process. -/ lemma gram_schmidt_orthonormal' (f : ι → E) : orthonormal 𝕜 (λ i : {i | gram_schmidt_normed 𝕜 f i ≠ 0}, gram_schmidt_normed 𝕜 f i) := begin refine ⟨λ i, gram_schmidt_normed_unit_length' i.prop, _⟩, rintros i j (hij : ¬ _), rw subtype.ext_iff at hij, simp [gram_schmidt_normed, inner_smul_left, inner_smul_right, gram_schmidt_orthogonal 𝕜 f hij], end lemma span_gram_schmidt_normed (f : ι → E) (s : set ι) : span 𝕜 (gram_schmidt_normed 𝕜 f '' s) = span 𝕜 (gram_schmidt 𝕜 f '' s) := begin refine span_eq_span (set.image_subset_iff.2 $ λ i hi, smul_mem _ _ $ subset_span $ mem_image_of_mem _ hi) (set.image_subset_iff.2 $ λ i hi, span_mono (image_subset _ $ singleton_subset_set_iff.2 hi) _), simp only [coe_singleton, set.image_singleton], by_cases h : gram_schmidt 𝕜 f i = 0, { simp [h] }, { refine mem_span_singleton.2 ⟨‖gram_schmidt 𝕜 f i‖, smul_inv_smul₀ _ _⟩, exact_mod_cast (norm_ne_zero_iff.2 h) } end lemma span_gram_schmidt_normed_range (f : ι → E) : span 𝕜 (range (gram_schmidt_normed 𝕜 f)) = span 𝕜 (range (gram_schmidt 𝕜 f)) := by simpa only [image_univ.symm] using span_gram_schmidt_normed f univ section orthonormal_basis variables [fintype ι] [finite_dimensional 𝕜 E] (h : finrank 𝕜 E = fintype.card ι) (f : ι → E) include h /-- Given an indexed family `f : ι → E` of vectors in an inner product space `E`, for which the size of the index set is the dimension of `E`, produce an orthonormal basis for `E` which agrees with the orthonormal set produced by the Gram-Schmidt orthonormalization process on the elements of `ι` for which this process gives a nonzero number. -/ noncomputable def gram_schmidt_orthonormal_basis : orthonormal_basis ι 𝕜 E := ((gram_schmidt_orthonormal' f).exists_orthonormal_basis_extension_of_card_eq h).some lemma gram_schmidt_orthonormal_basis_apply {f : ι → E} {i : ι} (hi : gram_schmidt_normed 𝕜 f i ≠ 0) : gram_schmidt_orthonormal_basis h f i = gram_schmidt_normed 𝕜 f i := ((gram_schmidt_orthonormal' f).exists_orthonormal_basis_extension_of_card_eq h).some_spec i hi lemma gram_schmidt_orthonormal_basis_apply_of_orthogonal {f : ι → E} (hf : pairwise (λ i j, ⟪f i, f j⟫ = 0)) {i : ι} (hi : f i ≠ 0) : gram_schmidt_orthonormal_basis h f i = (‖f i‖⁻¹ : 𝕜) • f i := begin have H : gram_schmidt_normed 𝕜 f i = (‖f i‖⁻¹ : 𝕜) • f i, { rw [gram_schmidt_normed, gram_schmidt_of_orthogonal 𝕜 hf] }, rw [gram_schmidt_orthonormal_basis_apply h, H], simpa [H] using hi, end lemma inner_gram_schmidt_orthonormal_basis_eq_zero {f : ι → E} {i : ι} (hi : gram_schmidt_normed 𝕜 f i = 0) (j : ι) : ⟪gram_schmidt_orthonormal_basis h f i, f j⟫ = 0 := begin rw ←mem_orthogonal_singleton_iff_inner_right, suffices : span 𝕜 (gram_schmidt_normed 𝕜 f '' Iic j) ≤ (𝕜 ∙ gram_schmidt_orthonormal_basis h f i)ᗮ, { apply this, rw span_gram_schmidt_normed, simpa using mem_span_gram_schmidt 𝕜 f (le_refl j) }, rw span_le, rintros - ⟨k, -, rfl⟩, rw [set_like.mem_coe, mem_orthogonal_singleton_iff_inner_left], by_cases hk : gram_schmidt_normed 𝕜 f k = 0, { simp [hk] }, rw ← gram_schmidt_orthonormal_basis_apply h hk, have : k ≠ i, { rintros rfl, exact hk hi }, exact (gram_schmidt_orthonormal_basis h f).orthonormal.2 this, end lemma gram_schmidt_orthonormal_basis_inv_triangular {i j : ι} (hij : i < j) : ⟪gram_schmidt_orthonormal_basis h f j, f i⟫ = 0 := begin by_cases hi : gram_schmidt_normed 𝕜 f j = 0, { rw inner_gram_schmidt_orthonormal_basis_eq_zero h hi }, { simp [gram_schmidt_orthonormal_basis_apply h hi, gram_schmidt_normed, inner_smul_left, gram_schmidt_inv_triangular 𝕜 f hij] } end lemma gram_schmidt_orthonormal_basis_inv_triangular' {i j : ι} (hij : i < j) : (gram_schmidt_orthonormal_basis h f).repr (f i) j = 0 := by simpa [orthonormal_basis.repr_apply_apply] using gram_schmidt_orthonormal_basis_inv_triangular h f hij /-- Given an indexed family `f : ι → E` of vectors in an inner product space `E`, for which the size of the index set is the dimension of `E`, the matrix of coefficients of `f` with respect to the orthonormal basis `gram_schmidt_orthonormal_basis` constructed from `f` is upper-triangular. -/ lemma gram_schmidt_orthonormal_basis_inv_block_triangular : ((gram_schmidt_orthonormal_basis h f).to_basis.to_matrix f).block_triangular id := λ i j, gram_schmidt_orthonormal_basis_inv_triangular' h f lemma gram_schmidt_orthonormal_basis_det : (gram_schmidt_orthonormal_basis h f).to_basis.det f = ∏ i, ⟪gram_schmidt_orthonormal_basis h f i, f i⟫ := begin convert matrix.det_of_upper_triangular (gram_schmidt_orthonormal_basis_inv_block_triangular h f), ext i, exact ((gram_schmidt_orthonormal_basis h f).repr_apply_apply (f i) i).symm, end end orthonormal_basis
dd3ccac099fac8ca31d8ff13bfe7cb932d28f98f
4727251e0cd73359b15b664c3170e5d754078599
/test/fin_cases.lean
043d4585cc8e2f53b73f868c94a55d26b7780958
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,318
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.nat.interval import data.nat.prime import group_theory.perm.sign import tactic.fin_cases example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := begin fin_cases *, simp, assumption, simp, assumption, simp, assumption, end example (f : ℕ → Prop) (p : fin 0) : f p.val := by fin_cases * example (f : ℕ → Prop) (p : fin 1) (h : f 0) : f p.val := begin fin_cases p, assumption end example (x2 : fin 2) (x3 : fin 3) (n : nat) (y : fin n) : x2.val * x3.val = x3.val * x2.val := begin fin_cases x2; fin_cases x3, success_if_fail { fin_cases * }, success_if_fail { fin_cases y }, all_goals { refl }, end open finset example (x : ℕ) (h : x ∈ Ico 2 5) : x = 2 ∨ x = 3 ∨ x = 4 := begin fin_cases h, all_goals { simp } end open nat example (x : ℕ) (h : x ∈ [2,3,5,7]) : x = 2 ∨ x = 3 ∨ x = 5 ∨ x = 7 := begin fin_cases h, all_goals { simp } end example (x : ℕ) (h : x ∈ [2,3,5,7]) : true := begin success_if_fail { fin_cases h with [3,3,5,7] }, trivial end example (x : list ℕ) (h : x ∈ [[1],[2]]) : x.length = 1 := begin fin_cases h with [[1],[1+1]], simp, guard_target (list.length [1 + 1] = 1), simp end -- testing that `with` arguments are elaborated with respect to the expected type: example (x : ℤ) (h : x ∈ ([2,3] : list ℤ)) : x = 2 ∨ x = 3 := begin fin_cases h with [2,3], all_goals { simp } end instance (n : ℕ) : decidable (nat.prime n) := decidable_prime_1 n example (x : ℕ) (h : x ∈ (range 10).filter nat.prime) : x = 2 ∨ x = 3 ∨ x = 5 ∨ x = 7 := begin fin_cases h; exact dec_trivial end open equiv.perm example (x : (Σ (a : fin 4), fin 4)) (h : x ∈ fin_pairs_lt 4) : x.1.val < 4 := begin fin_cases h; simp, any_goals { exact dec_trivial }, end example (x : fin 3) : x.val < 5 := begin fin_cases x; exact dec_trivial end example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := begin fin_cases *, all_goals { assumption } end example (n : ℕ) (h : n % 3 ∈ [0,1]) : true := begin fin_cases h, guard_hyp h : n % 3 = 0, trivial, guard_hyp h : n % 3 = 1, trivial, end /- In some circumstances involving `let`, the temporary hypothesis that `fin_cases` creates does not get deleted. We test that this is correctly named and that the name can be changed. Note: after `fin_cases`, we have `this : (a : fin 3) = (0 : fin (2 + 1))` for some reason. I don't know why, and it complicates the test. -/ example (f : ℕ → fin 3) : true := begin let a := f 3, fin_cases a, guard_hyp a := f 3, guard_hyp this : a = (0 : fin (2 + 1)), trivial, trivial, let b := f 2, fin_cases b using what, guard_hyp what : b = (0 : fin (2 + 1)), all_goals {trivial} end /- The behavior above can be worked around with `fin_cases with`. -/ example (f : ℕ → fin 3) : true := begin let a := f 3, fin_cases a with [0, 1, 2], guard_hyp a := f 3, guard_hyp this : a = 0, trivial, guard_hyp this : a = 1, trivial, guard_hyp this : a = 2, let b := f 2, fin_cases b with [0, 1, 2] using what, guard_hyp what : b = 0, all_goals {trivial} end
b1b7c2d974c21a94da913f73bf7d4eeb1c8dccaa
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/simpa.lean
5f71a1d781d091a84c16bd6e8692cdd49674a49b
[]
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
908
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.doc_commands import Mathlib.PostPort namespace Mathlib namespace tactic namespace interactive /-- This is a "finishing" tactic modification of `simp`. It has two forms. * `simpa [rules, ...] using e` will simplify the goal and the type of `e` using `rules`, then try to close the goal using `e`. Simplifying the type of `e` makes it more likely to match the goal (which has also been simplified). This construction also tends to be more robust under changes to the simp lemma set. * `simpa [rules, ...]` will simplify the goal and the type of a hypothesis `this` if present in the context, then try to close the goal using the `assumption` tactic. -/
8b0e7f7727f2feba3156cab71fc0ecfe2353e074
367134ba5a65885e863bdc4507601606690974c1
/src/data/equiv/mul_add.lean
c57c1e91fa22c0067edf1b5b0dae5319274614b6
[ "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
19,063
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import algebra.group.hom import algebra.group.type_tags import algebra.group.units_hom /-! # Multiplicative and additive equivs In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s. ## Notations * ``infix ` ≃* `:25 := mul_equiv`` * ``infix ` ≃+ `:25 := add_equiv`` The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. ## Tags equiv, mul_equiv, add_equiv -/ variables {A : Type*} {B : Type*} {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {G : Type*} {H : Type*} set_option old_structure_cmd true /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ @[ancestor equiv add_hom] structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B, add_hom A B /-- The `equiv` underlying an `add_equiv`. -/ add_decl_doc add_equiv.to_equiv /-- The `add_hom` underlying a `add_equiv`. -/ add_decl_doc add_equiv.to_add_hom /-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/ @[ancestor equiv mul_hom, to_additive] structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N, mul_hom M N /-- The `equiv` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_equiv /-- The `mul_hom` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_mul_hom infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv @[to_additive] instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) := ⟨_, mul_equiv.to_fun⟩ variables [has_mul M] [has_mul N] [has_mul P] [has_mul Q] @[simp, to_additive] lemma to_fun_eq_coe {f : M ≃* N} : f.to_fun = f := rfl @[simp, to_additive] lemma coe_to_equiv {f : M ≃* N} : ⇑f.to_equiv = f := rfl @[simp, to_additive] lemma coe_to_mul_hom {f : M ≃* N} : ⇑f.to_mul_hom = f := rfl /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ @[simp, to_additive] lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := f.map_mul' /-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive isomorphism from a bijection which preserves addition."] def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N := ⟨f.1, f.2, f.3, f.4, h⟩ @[to_additive] protected lemma bijective (e : M ≃* N) : function.bijective e := e.to_equiv.bijective @[to_additive] protected lemma injective (e : M ≃* N) : function.injective e := e.to_equiv.injective @[to_additive] protected lemma surjective (e : M ≃* N) : function.surjective e := e.to_equiv.surjective /-- The identity map is a multiplicative isomorphism. -/ @[refl, to_additive "The identity map is an additive isomorphism."] def refl (M : Type*) [has_mul M] : M ≃* M := { map_mul' := λ _ _, rfl, ..equiv.refl _} instance : inhabited (M ≃* M) := ⟨refl M⟩ /-- The inverse of an isomorphism is an isomorphism. -/ @[symm, to_additive "The inverse of an isomorphism is an isomorphism."] def symm (h : M ≃* N) : N ≃* M := { map_mul' := λ n₁ n₂, h.injective $ begin have : ∀ x, h (h.to_equiv.symm.to_fun x) = x := h.to_equiv.apply_symm_apply, simp only [this, h.map_mul] end, .. h.to_equiv.symm} /-- See Note [custom simps projection] -/ -- we don't hyperlink the note in the additive version, since that breaks syntax highlighting -- in the whole file. @[to_additive add_equiv.simps.inv_fun "See Note custom simps projection"] def simps.inv_fun (e : M ≃* N) : N → M := e.symm initialize_simps_projections add_equiv (to_fun → apply, inv_fun → symm_apply) initialize_simps_projections mul_equiv (to_fun → apply, inv_fun → symm_apply) @[simp, to_additive] theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl @[simp, to_additive] theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl @[simp, to_additive] lemma symm_symm : ∀ (f : M ≃* N), f.symm.symm = f | ⟨f, g, h₁, h₂, h₃⟩ := rfl @[to_additive] lemma symm_bijective : function.bijective (symm : (M ≃* N) → (N ≃* M)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp, to_additive] theorem symm_mk (f : M → N) (g h₁ h₂ h₃) : (mul_equiv.mk f g h₁ h₂ h₃).symm = { to_fun := g, inv_fun := f, ..(mul_equiv.mk f g h₁ h₂ h₃).symm} := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans, to_additive "Transitivity of addition-preserving isomorphisms"] def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) := { map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y), by rw [h1.map_mul, h2.map_mul], ..h1.to_equiv.trans h2.to_equiv } /-- e.right_inv in canonical form -/ @[simp, to_additive] lemma apply_symm_apply (e : M ≃* N) : ∀ y, e (e.symm y) = y := e.to_equiv.apply_symm_apply /-- e.left_inv in canonical form -/ @[simp, to_additive] lemma symm_apply_apply (e : M ≃* N) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp, to_additive] theorem refl_apply (m : M) : refl M m = m := rfl @[simp, to_additive] theorem trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (m : M) : e₁.trans e₂ m = e₂ (e₁ m) := rfl @[simp, to_additive] theorem apply_eq_iff_eq (e : M ≃* N) {x y : M} : e x = e y ↔ x = y := e.injective.eq_iff @[to_additive] lemma apply_eq_iff_symm_apply (e : M ≃* N) {x : M} {y : N} : e x = y ↔ x = e.symm y := e.to_equiv.apply_eq_iff_eq_symm_apply @[to_additive] lemma symm_apply_eq (e : M ≃* N) {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq @[to_additive] lemma eq_symm_apply (e : M ≃* N) {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply /-- Two multiplicative isomorphisms agree if they are defined by the same underlying function. -/ @[ext, to_additive "Two additive isomorphisms agree if they are defined by the same underlying function."] lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end attribute [ext] add_equiv.ext @[to_additive] lemma ext_iff {f g : mul_equiv M N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ @[simp, to_additive] lemma mk_coe (e : M ≃* N) (e' h₁ h₂ h₃) : (⟨e, e', h₁, h₂, h₃⟩ : M ≃* N) = e := ext $ λ _, rfl @[simp, to_additive] lemma mk_coe' (e : M ≃* N) (f h₁ h₂ h₃) : (mul_equiv.mk f ⇑e h₁ h₂ h₃ : N ≃* M) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[to_additive] protected lemma congr_arg {f : mul_equiv M N} : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl @[to_additive] protected lemma congr_fun {f g : mul_equiv M N} (h : f = g) (x : M) : f x = g x := h ▸ rfl /-- The `mul_equiv` between two monoids with a unique element. -/ @[to_additive "The `add_equiv` between two add_monoids with a unique element."] def mul_equiv_of_unique_of_unique {M N} [unique M] [unique N] [has_mul M] [has_mul N] : M ≃* N := { map_mul' := λ _ _, subsingleton.elim _ _, ..equiv_of_unique_of_unique } /-- There is a unique monoid homomorphism between two monoids with a unique element. -/ @[to_additive] instance {M N} [unique M] [unique N] [has_mul M] [has_mul N] : unique (M ≃* N) := { default := mul_equiv_of_unique_of_unique , uniq := λ _, ext $ λ x, subsingleton.elim _ _} /-! ## Monoids -/ /-- A multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism). -/ @[simp, to_additive] lemma map_one {M N} [monoid M] [monoid N] (h : M ≃* N) : h 1 = 1 := by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul] @[simp, to_additive] lemma map_eq_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} : h x = 1 ↔ x = 1 := h.map_one ▸ h.to_equiv.apply_eq_iff_eq @[to_additive] lemma map_ne_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} : h x ≠ 1 ↔ x ≠ 1 := ⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩ /-- A bijective `monoid` homomorphism is an isomorphism -/ @[to_additive "A bijective `add_monoid` homomorphism is an isomorphism"] noncomputable def of_bijective {M N} [monoid M] [monoid N] (f : M →* N) (hf : function.bijective f) : M ≃* N := { map_mul' := f.map_mul', ..equiv.of_bijective f hf } /-- Extract the forward direction of a multiplicative equivalence as a multiplication-preserving function. -/ @[to_additive "Extract the forward direction of an additive equivalence as an addition-preserving function."] def to_monoid_hom {M N} [monoid M] [monoid N] (h : M ≃* N) : (M →* N) := { map_one' := h.map_one, .. h } @[simp, to_additive] lemma coe_to_monoid_hom {M N} [monoid M] [monoid N] (e : M ≃* N) : ⇑e.to_monoid_hom = e := rfl @[to_additive] lemma to_monoid_hom_injective {M N} [monoid M] [monoid N] : function.injective (to_monoid_hom : (M ≃* N) → M →* N) := λ f g h, mul_equiv.ext (monoid_hom.ext_iff.1 h) /-- A multiplicative analogue of `equiv.arrow_congr`, where the equivalence between the targets is multiplicative. -/ @[simps apply, to_additive "An additive analogue of `equiv.arrow_congr`, where the equivalence between the targets is additive."] def arrow_congr {M N P Q : Type*} [monoid P] [monoid Q] (f : M ≃ N) (g : P ≃* Q) : (M → P) ≃* (N → Q) := { to_fun := λ h n, g (h (f.symm n)), inv_fun := λ k m, g.symm (k (f m)), left_inv := λ h, by { ext, simp, }, right_inv := λ k, by { ext, simp, }, map_mul' := λ h k, by { ext, simp, }, } /-- A multiplicative analogue of `equiv.arrow_congr`, for multiplicative maps from a monoid to a commutative monoid. -/ @[simps apply, to_additive "An additive analogue of `equiv.arrow_congr`, for additive maps from an additive monoid to a commutative additive monoid."] def monoid_hom_congr {M N P Q} [monoid M] [monoid N] [comm_monoid P] [comm_monoid Q] (f : M ≃* N) (g : P ≃* Q) : (M →* P) ≃* (N →* Q) := { to_fun := λ h, g.to_monoid_hom.comp (h.comp f.symm.to_monoid_hom), inv_fun := λ k, g.symm.to_monoid_hom.comp (k.comp f.to_monoid_hom), left_inv := λ h, by { ext, simp, }, right_inv := λ k, by { ext, simp, }, map_mul' := λ h k, by { ext, simp, }, } /-! # Groups -/ /-- A multiplicative equivalence of groups preserves inversion. -/ @[simp, to_additive] lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ := h.to_monoid_hom.map_inv x end mul_equiv -- We don't use `to_additive` to generate definition because it fails to tell Lean about -- equational lemmas /-- Given a pair of additive monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an additive equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for additive monoid homomorphisms. -/ def add_monoid_hom.to_add_equiv [add_monoid M] [add_monoid N] (f : M →+ N) (g : N →+ M) (h₁ : g.comp f = add_monoid_hom.id _) (h₂ : f.comp g = add_monoid_hom.id _) : M ≃+ N := { to_fun := f, inv_fun := g, left_inv := add_monoid_hom.congr_fun h₁, right_inv := add_monoid_hom.congr_fun h₂, map_add' := f.map_add } /-- Given a pair of monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an multiplicative equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for monoid homomorphisms. -/ @[to_additive] def monoid_hom.to_mul_equiv [monoid M] [monoid N] (f : M →* N) (g : N →* M) (h₁ : g.comp f = monoid_hom.id _) (h₂ : f.comp g = monoid_hom.id _) : M ≃* N := { to_fun := f, inv_fun := g, left_inv := monoid_hom.congr_fun h₁, right_inv := monoid_hom.congr_fun h₂, map_mul' := f.map_mul } @[simp, to_additive] lemma monoid_hom.coe_to_mul_equiv [monoid M] [monoid N] (f : M →* N) (g : N →* M) (h₁ h₂) : ⇑(f.to_mul_equiv g h₁ h₂) = f := rfl /-- An additive equivalence of additive groups preserves subtraction. -/ lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) : h (x - y) = h x - h y := h.to_add_monoid_hom.map_sub x y instance add_equiv.inhabited {M : Type*} [has_add M] : inhabited (M ≃+ M) := ⟨add_equiv.refl M⟩ /-- A group is isomorphic to its group of units. -/ @[to_additive to_add_units "An additive group is isomorphic to its group of additive units"] def to_units {G} [group G] : G ≃* units G := { to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩, inv_fun := coe, left_inv := λ x, rfl, right_inv := λ u, units.ext rfl, map_mul' := λ x y, units.ext rfl } namespace units variables [monoid M] [monoid N] [monoid P] /-- A multiplicative equivalence of monoids defines a multiplicative equivalence of their groups of units. -/ def map_equiv (h : M ≃* N) : units M ≃* units N := { inv_fun := map h.symm.to_monoid_hom, left_inv := λ u, ext $ h.left_inv u, right_inv := λ u, ext $ h.right_inv u, .. map h.to_monoid_hom } /-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Left addition of an additive unit is a permutation of the underlying type."] def mul_left (u : units M) : equiv.perm M := { to_fun := λx, u * x, inv_fun := λx, ↑u⁻¹ * x, left_inv := u.inv_mul_cancel_left, right_inv := u.mul_inv_cancel_left } @[simp, to_additive] lemma coe_mul_left (u : units M) : ⇑u.mul_left = (*) u := rfl @[simp, to_additive] lemma mul_left_symm (u : units M) : u.mul_left.symm = u⁻¹.mul_left := equiv.ext $ λ x, rfl /-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Right addition of an additive unit is a permutation of the underlying type."] def mul_right (u : units M) : equiv.perm M := { to_fun := λx, x * u, inv_fun := λx, x * ↑u⁻¹, left_inv := λ x, mul_inv_cancel_right x u, right_inv := λ x, inv_mul_cancel_right x u } @[simp, to_additive] lemma coe_mul_right (u : units M) : ⇑u.mul_right = λ x : M, x * u := rfl @[simp, to_additive] lemma mul_right_symm (u : units M) : u.mul_right.symm = u⁻¹.mul_right := equiv.ext $ λ x, rfl end units namespace equiv section group variables [group G] /-- Left multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Left addition in an `add_group` is a permutation of the underlying type."] protected def mul_left (a : G) : perm G := (to_units a).mul_left @[simp, to_additive] lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive] lemma mul_left_symm_apply (a : G) : ((equiv.mul_left a).symm : G → G) = (*) a⁻¹ := rfl @[simp, to_additive] lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ := ext $ λ x, rfl /-- Right multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Right addition in an `add_group` is a permutation of the underlying type."] protected def mul_right (a : G) : perm G := (to_units a).mul_right @[simp, to_additive] lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = λ x, x * a := rfl @[simp, to_additive] lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ := ext $ λ x, rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive] lemma mul_right_symm_apply (a : G) : ((equiv.mul_right a).symm : G → G) = λ x, x * a⁻¹ := rfl attribute [nolint simp_nf] add_left_symm_apply add_right_symm_apply variable (G) /-- Inversion on a `group` is a permutation of the underlying type. -/ @[to_additive "Negation on an `add_group` is a permutation of the underlying type."] protected def inv : perm G := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } variable {G} @[simp, to_additive] lemma coe_inv : ⇑(equiv.inv G) = has_inv.inv := rfl @[simp, to_additive] lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl end group end equiv section type_tags /-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative [add_monoid G] [add_monoid H] : (G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative, f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/ def mul_equiv.to_additive [monoid G] [monoid H] : (G ≃* H) ≃ (additive G ≃+ additive H) := { to_fun := λ f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative' [monoid G] [add_monoid H] : (additive G ≃+ H) ≃ (G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative', f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/ def mul_equiv.to_additive' [monoid G] [add_monoid H] : (G ≃* multiplicative H) ≃ (additive G ≃+ H) := add_equiv.to_multiplicative'.symm /-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/ def add_equiv.to_multiplicative'' [add_monoid G] [monoid H] : (G ≃+ additive H) ≃ (multiplicative G ≃* H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative'', f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/ def mul_equiv.to_additive'' [add_monoid G] [monoid H] : (multiplicative G ≃* H) ≃ (G ≃+ additive H) := add_equiv.to_multiplicative''.symm end type_tags
230fc12de4509c039d46e5683aa7abfece241d38
e9dbaaae490bc072444e3021634bf73664003760
/src/Problems/2009/IMO_2009_P4.lean
9cbd8eb735a737c0202e6a388b59e2e4360cf44a
[ "Apache-2.0" ]
permissive
liaofei1128/geometry
566d8bfe095ce0c0113d36df90635306c60e975b
3dd128e4eec8008764bb94e18b932f9ffd66e6b3
refs/heads/master
1,678,996,510,399
1,581,454,543,000
1,583,337,839,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
762
lean
/- IMO 2009 P4 is a determined problem. The problem statement is as follows: "Find all possible values of <CAB." This problem statement is replaced by the disjunctive witnesses in this formalization. Solution: https://web.evanchen.cc/exams/IMO-2009-notes.pdf -/ import Geo.Geo.Core namespace Geo open Analytic Angle Seg Triangle def IMO_2009_P4 : Prop := ∀ (A B C : Point), cong ⟨A, B⟩ ⟨A, C⟩ → ∀ (D E : Point), intersectAt (bisector ⟨C, A, B⟩) (Seg.mk B C) D → intersectAt (bisector ⟨A, B, C⟩) (Seg.mk C A) E → let K := incenter ⟨A, D, C⟩; deg2π 45 = uangle ⟨B, E, K⟩ → -- The following is a disjunctive witness to the determined problem deg2π 60 = uangle ⟨C, A, B⟩ ∨ deg2π 90 = uangle ⟨C, A, B⟩ end Geo
ae35789c4499f2785f8ccea858efc4d528df2b3a
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/field.lean
cb006f2ef751e12bd988049841124f741efebca2
[ "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
14,014
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import algebra.ring.basic import algebra.group_with_zero /-! # Fields and division rings This file introduces fields and division rings (also known as skewfields) and proves some basic statements about them. For a more extensive theory of fields, see the `field_theory` folder. ## Main definitions * `division_ring`: introduces the notion of a division ring as a `ring` such that `0 ≠ 1` and `a * a⁻¹ = 1` for `a ≠ 0` * `field`: a division ring which is also a commutative ring. * `is_field`: a predicate on a ring that it is a field, i.e. that the multiplication is commutative, that it has more than one element and that all non-zero elements have a multiplicative inverse. In contrast to `field`, which contains the data of a function associating to an element of the field its multiplicative inverse, this predicate only assumes the existence and can therefore more easily be used to e.g. transfer along ring isomorphisms. ## Implementation details By convention `0⁻¹ = 0` in a field or division ring. This is due to the fact that working with total functions has the advantage of not constantly having to check that `x ≠ 0` when writing `x⁻¹`. With this convention in place, some statements like `(a + b) * c⁻¹ = a * c⁻¹ + b * c⁻¹` still remain true, while others like the defining property `a * a⁻¹ = 1` need the assumption `a ≠ 0`. If you are a beginner in using Lean and are confused by that, you can read more about why this convention is taken in Kevin Buzzard's [blogpost](https://xenaproject.wordpress.com/2020/07/05/division-by-zero-in-type-theory-a-faq/) A division ring or field is an example of a `group_with_zero`. If you cannot find a division ring / field lemma that does not involve `+`, you can try looking for a `group_with_zero` lemma instead. ## Tags field, division ring, skew field, skew-field, skewfield -/ open set set_option old_structure_cmd true universe u variables {K : Type u} /-- A `division_ring` is a `ring` with multiplicative inverses for nonzero elements -/ @[protect_proj, ancestor ring div_inv_monoid nontrivial] class division_ring (K : Type u) extends ring K, div_inv_monoid K, nontrivial K := (mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : K)⁻¹ = 0) section division_ring variables [division_ring K] {a b : K} /-- Every division ring is a `group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance division_ring.to_group_with_zero : group_with_zero K := { .. ‹division_ring K›, .. (infer_instance : semiring K) } lemma inverse_eq_has_inv : (ring.inverse : K → K) = has_inv.inv := begin ext x, by_cases hx : x = 0, { simp [hx] }, { exact ring.inverse_unit (units.mk0 x hx) } end attribute [field_simps] inv_eq_one_div local attribute [simp] division_def mul_comm mul_assoc mul_left_comm mul_inv_cancel inv_mul_cancel lemma one_div_neg_one_eq_neg_one : (1:K) / (-1) = -1 := have (-1) * (-1) = (1:K), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one this) lemma one_div_neg_eq_neg_one_div (a : K) : 1 / (- a) = - (1 / a) := calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw one_div_mul_one_div_rev ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one] lemma div_neg_eq_neg_div (a b : K) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b / a) : by rw mul_one_div lemma neg_div (a b : K) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul] @[field_simps] lemma neg_div' (a b : K) : - (b / a) = (-b) / a := by simp [neg_div] lemma neg_div_neg_eq (a b : K) : (-a) / (-b) = a / b := by rw [div_neg_eq_neg_div, neg_div, neg_neg] @[field_simps] lemma div_add_div_same (a b c : K) : a / c + b / c = (a + b) / c := by simpa only [div_eq_mul_inv] using (right_distrib a b (c⁻¹)).symm lemma same_add_div {a b : K} (h : b ≠ 0) : (b + a) / b = 1 + a / b := by simpa only [← @div_self _ _ b h] using (div_add_div_same b a b).symm lemma one_add_div {a b : K} (h : b ≠ 0 ) : 1 + a / b = (b + a) / b := (same_add_div h).symm lemma div_add_same {a b : K} (h : b ≠ 0) : (a + b) / b = a / b + 1 := by simpa only [← @div_self _ _ b h] using (div_add_div_same a b b).symm lemma div_add_one {a b : K} (h : b ≠ 0) : a / b + 1 = (a + b) / b := (div_add_same h).symm lemma div_sub_div_same (a b c : K) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg] lemma same_sub_div {a b : K} (h : b ≠ 0) : (b - a) / b = 1 - a / b := by simpa only [← @div_self _ _ b h] using (div_sub_div_same b a b).symm lemma one_sub_div {a b : K} (h : b ≠ 0) : 1 - a / b = (b - a) / b := (same_sub_div h).symm lemma div_sub_same {a b : K} (h : b ≠ 0) : (a - b) / b = a / b - 1 := by simpa only [← @div_self _ _ b h] using (div_sub_div_same a b b).symm lemma div_sub_one {a b : K} (h : b ≠ 0) : a / b - 1 = (a - b) / b := (div_sub_same h).symm lemma neg_inv : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma add_div (a b c : K) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma sub_div (a b c : K) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma div_neg (a : K) : a / -b = -(a / b) := by rw [← div_neg_eq_neg_div] lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := by rw neg_inv lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] lemma add_div_eq_mul_add_div (a b : K) {c : K} (hc : c ≠ 0) : a + b / c = (a * c + b) / c := (eq_div_iff_mul_eq hc).2 $ by rw [right_distrib, (div_mul_cancel _ hc)] @[priority 100] -- see Note [lower instance priority] instance division_ring.is_domain : is_domain K := { ..‹division_ring K›, ..(by apply_instance : no_zero_divisors K) } end division_ring /-- A `field` is a `comm_ring` with multiplicative inverses for nonzero elements -/ @[protect_proj, ancestor comm_ring div_inv_monoid nontrivial] class field (K : Type u) extends comm_ring K, div_inv_monoid K, nontrivial K := (mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : K)⁻¹ = 0) section field variable [field K] @[priority 100] -- see Note [lower instance priority] instance field.to_division_ring : division_ring K := { ..show field K, by apply_instance } /-- Every field is a `comm_group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance field.to_comm_group_with_zero : comm_group_with_zero K := { .. (_ : group_with_zero K), .. ‹field K› } local attribute [simp] mul_assoc mul_comm mul_left_comm lemma div_add_div (a : K) {b : K} (c : K) {d : K} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [← mul_div_mul_right _ b hd, ← mul_div_mul_left c d hb, div_add_div_same] lemma one_div_add_one_div {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := by rw [div_add_div _ _ ha hb, one_mul, mul_one, add_comm] @[field_simps] lemma div_sub_div (a : K) {b : K} (c : K) {d : K} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp only [sub_eq_add_neg], rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd, ← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul] end lemma inv_add_inv {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] @[field_simps] lemma add_div' (a b c : K) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma sub_div' (a b c : K) (hc : c ≠ 0) : b - a / c = (b * c - a) / c := by simpa using div_sub_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : K) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] @[field_simps] lemma div_sub' (a b c : K) (hc : c ≠ 0) : a / c - b = (a - c * b) / c := by simpa using div_sub_div a b hc one_ne_zero @[priority 100] -- see Note [lower instance priority] instance field.is_domain : is_domain K := { ..division_ring.is_domain } end field section is_field /-- A predicate to express that a ring is a field. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. Additionaly, this is useful when trying to prove that a particular ring structure extends to a field. -/ structure is_field (R : Type u) [ring R] : Prop := (exists_pair_ne : ∃ (x y : R), x ≠ y) (mul_comm : ∀ (x y : R), x * y = y * x) (mul_inv_cancel : ∀ {a : R}, a ≠ 0 → ∃ b, a * b = 1) /-- Transferring from field to is_field -/ lemma field.to_is_field (R : Type u) [field R] : is_field R := { mul_inv_cancel := λ a ha, ⟨a⁻¹, field.mul_inv_cancel ha⟩, ..‹field R› } open_locale classical /-- Transferring from is_field to field -/ noncomputable def is_field.to_field (R : Type u) [ring R] (h : is_field R) : field R := { inv := λ a, if ha : a = 0 then 0 else classical.some (is_field.mul_inv_cancel h ha), inv_zero := dif_pos rfl, mul_inv_cancel := λ a ha, begin convert classical.some_spec (is_field.mul_inv_cancel h ha), exact dif_neg ha end, .. ‹ring R›, ..h } /-- For each field, and for each nonzero element of said field, there is a unique inverse. Since `is_field` doesn't remember the data of an `inv` function and as such, a lemma that there is a unique inverse could be useful. -/ lemma uniq_inv_of_is_field (R : Type u) [ring R] (hf : is_field R) : ∀ (x : R), x ≠ 0 → ∃! (y : R), x * y = 1 := begin intros x hx, apply exists_unique_of_exists_of_unique, { exact hf.mul_inv_cancel hx }, { intros y z hxy hxz, calc y = y * (x * z) : by rw [hxz, mul_one] ... = (x * y) * z : by rw [← mul_assoc, hf.mul_comm y x] ... = z : by rw [hxy, one_mul] } end end is_field namespace ring_hom section variables {R : Type*} [semiring R] [division_ring K] (f : R →+* K) @[simp] lemma map_units_inv (u : units R) : f ↑u⁻¹ = (f ↑u)⁻¹ := (f : R →* K).map_units_inv u end section variables {R K' : Type*} [division_ring K] [semiring R] [nontrivial R] [division_ring K'] (f : K →+* R) (g : K →+* K') {x y : K} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := f.to_monoid_with_zero_hom.map_ne_zero @[simp] lemma map_eq_zero : f x = 0 ↔ x = 0 := f.to_monoid_with_zero_hom.map_eq_zero variables (x y) lemma map_inv : g x⁻¹ = (g x)⁻¹ := g.to_monoid_with_zero_hom.map_inv x lemma map_div : g (x / y) = g x / g y := g.to_monoid_with_zero_hom.map_div x y protected lemma injective : function.injective f := f.injective_iff.2 $ λ x, f.map_eq_zero.1 end end ring_hom section noncomputable_defs variables {R : Type*} [nontrivial R] /-- Constructs a `division_ring` structure on a `ring` consisting only of units and 0. -/ noncomputable def division_ring_of_is_unit_or_eq_zero [hR : ring R] (h : ∀ (a : R), is_unit a ∨ a = 0) : division_ring R := { .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR } /-- Constructs a `field` structure on a `comm_ring` consisting only of units and 0. -/ noncomputable def field_of_is_unit_or_eq_zero [hR : comm_ring R] (h : ∀ (a : R), is_unit a ∨ a = 0) : field R := { .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR } end noncomputable_defs /-- Pullback a `division_ring` along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.division_ring [division_ring K] {K'} [has_zero K'] [has_mul K'] [has_add K'] [has_neg K'] [has_sub K'] [has_one K'] [has_inv K'] [has_div K'] (f : K' → K) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : division_ring K' := { .. hf.group_with_zero f zero one mul inv div, .. hf.ring f zero one add mul neg sub } /-- Pullback a `field` along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.field [field K] {K'} [has_zero K'] [has_mul K'] [has_add K'] [has_neg K'] [has_sub K'] [has_one K'] [has_inv K'] [has_div K'] (f : K' → K) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : field K' := { .. hf.comm_group_with_zero f zero one mul inv div, .. hf.comm_ring f zero one add mul neg sub }
dd7d9c1fb9b30d0d3a312e1144c2f324660e4812
968e2f50b755d3048175f176376eff7139e9df70
/examples/pred_logic/unnamed_493.lean
dc3f186881e400576f592b9a5c44c1a34d377b7b
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
67
lean
example (h : 5 ≥ 3) : ∃ x, x ≥ 3 := by exact exists.intro 5 h
6b4d9a8939a068c6b9033120737b9e5fb5a508c3
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/vector/zero_length_lemmas.lean
9a2a92c40df6c0c60955f4ad0c0e5ae3a5a40f22
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
686
lean
/- Lemmas for simplify terms involving zero-length vectors. -/ import data.vector universe variables u namespace vector variable {α : Type u} variable {n : ℕ} local infix `++`:65 := vector.append theorem length_zero_vector_is_nil (x : vector α 0) : x = nil := begin apply vector.eq, cases x with v p, cases v, simp, contradiction end -- Simplify 0-length vector equality to true. @[simp] theorem zero_vec_always_eq (x y : vector α 0) : x = y ↔ true := begin simp [length_zero_vector_is_nil x, length_zero_vector_is_nil y], end @[simp] theorem to_list_empty (x : vector α 0) : to_list x = list.nil := begin simp [length_zero_vector_is_nil x], end end vector
6e8b8286192a554c319cebcd0b5f8997bad94a35
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Data/LBool.lean
5bb3f32106ae109d1bf2eb47df2f40a3032aebc5
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,015
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 -/ namespace Lean inductive LBool | false | true | undef namespace LBool instance : Inhabited LBool := ⟨false⟩ def neg : LBool → LBool | true => false | false => true | undef => undef def and : LBool → LBool → LBool | true, b => b | a, _ => a def beq : LBool → LBool → Bool | true, true => Bool.true | false, false => Bool.true | undef, undef => Bool.true | _, _ => Bool.false instance : BEq LBool := ⟨beq⟩ def toString : LBool → String | true => "true" | false => "false" | undef => "undef" instance : ToString LBool := ⟨toString⟩ end LBool end Lean def Bool.toLBool : Bool → Lean.LBool | true => Lean.LBool.true | false => Lean.LBool.false @[inline] def toLBoolM {m : Type → Type} [Monad m] (x : m Bool) : m Lean.LBool := do let b ← x pure b.toLBool
9239d47ea26ca70515c5d18719f709520671b5ae
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/metric_space/emetric_space.lean
983cb4e4990cef15af7169aa82dfa60e19a9cbc0
[ "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
50,321
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.nat.interval import data.real.ennreal import topology.uniform_space.pi import topology.uniform_space.uniform_convergence import topology.uniform_space.uniform_embedding /-! # Extended metric spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ℝ≥0∞`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity. The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). Since a lot of elementary properties don't require `eq_of_edist_eq_zero` we start setting up the theory of `pseudo_emetric_space`, where we don't require `edist x y = 0 → x = y` and we specialize to `emetric_space` at the end. -/ open set filter classical open_locale uniformity topology big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} {X : Type*} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε > z, 𝓟 {p:α×α | D p.1 p.2 < ε} := has_basis.eq_binfi ⟨λ s, by simp only [H, subset_def, prod.forall, mem_set_of]⟩ /-- `has_edist α` means that `α` is equipped with an extended distance. -/ class has_edist (α : Type*) := (edist : α → α → ℝ≥0∞) export has_edist (edist) /-- Creating a uniform space from an extended distance. -/ noncomputable def uniform_space_of_edist (edist : α → α → ℝ≥0∞) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_fun edist edist_self edist_comm edist_triangle $ λ ε ε0, ⟨ε / 2, ennreal.half_pos ε0.lt.ne', λ _ h₁ _ h₂, (ennreal.add_lt_add h₁ h₂).trans_eq (ennreal.add_halves _)⟩ -- the uniform structure is embedded in the emetric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Extended (pseudo) metric spaces, with an extended distance `edist` possibly taking the value ∞ Each pseudo_emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `pseudo_emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating a `pseudo_emetric_space` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ class pseudo_emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) attribute [priority 100, instance] pseudo_emetric_space.to_uniform_space /- Pseudoemetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [pseudo_emetric_space α] export pseudo_emetric_space (edist_self edist_comm edist_triangle) attribute [simp] edist_self /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_congr_right {x y z : α} (h : edist x y = 0) : edist x z = edist y z := begin apply le_antisymm, { rw [←zero_add (edist y z), ←h], apply edist_triangle, }, { rw edist_comm at h, rw [←zero_add (edist x z), ←h], apply edist_triangle, }, end lemma edist_congr_left {x y z : α} (h : edist x y = 0) : edist z x = edist z y := by { rw [edist_comm z x, edist_comm z y], apply edist_congr_right h, } lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right (edist_triangle x y z) _ /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico_self, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `exact le_rfl` fails too. exact le_refl (0:ℝ≥0∞) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec le_rfl ... = ∑ i in finset.Ico m (n+1), _ : by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) := nat.Ico_zero_eq_range ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ ∑ i in finset.range n, d i := nat.Ico_zero_eq_range ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_pseudoedist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist theorem uniform_space_edist : ‹pseudo_emetric_space α›.to_uniform_space = uniform_space_of_edist edist edist_self edist_comm edist_triangle := uniform_space_eq uniformity_pseudoedist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniform_space_edist α _).symm ▸ uniform_space.has_basis_of_fun ⟨1, one_pos⟩ _ _ _ _ _ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : ℝ≥0, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_nnreal_le : (𝓤 α).has_basis (λ ε : ℝ≥0, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) theorem uniformity_basis_edist_inv_two_pow : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < 2⁻¹ ^ n}) := emetric.mk_uniformity_basis (λ n _, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_two_pow_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ℝ≥0∞} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric @[priority 900] instance : is_countably_generated (𝓤 α) := is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩ /-- ε-δ characterization of uniform continuity on a set for pseudoemetric spaces -/ theorem uniform_continuous_on_iff [pseudo_emetric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ {a b ∈ s}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_on_iff uniformity_basis_edist /-- ε-δ characterization of uniform continuity on pseudoemetric spaces -/ theorem uniform_continuous_iff [pseudo_emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on pseudoemetric spaces -/ theorem uniform_embedding_iff [pseudo_emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := begin simp only [uniformity_basis_edist.uniform_embedding_iff uniformity_basis_edist, exists_prop], refl end /-- If a map between pseudoemetric spaces is a uniform embedding then the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. -/ theorem controlled_of_uniform_embedding [pseudo_emetric_space β] {f : α → β} : uniform_embedding f → (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := λ h, ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ /-- ε-δ characterization of Cauchy sequences on pseudoemetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := by rw ← ne_bot_iff; exact uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ℝ≥0∞) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete pseudoemetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto /-- Expressing locally uniform convergence on a set using `edist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, mem_univ, forall_const, exists_prop, nhds_within_univ] /-- Expressing uniform convergence using `edist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by simp only [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff, mem_univ, forall_const] end emetric open emetric /-- Auxiliary function to replace the uniformity on a pseudoemetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct a pseudoemetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def pseudo_emetric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_emetric_space α) (H : 𝓤[U] = 𝓤[pseudo_emetric_space.to_uniform_space]) : pseudo_emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist α _) } /-- The extended pseudometric induced by a function taking values in a pseudoemetric space. -/ def pseudo_emetric_space.induced {α β} (f : α → β) (m : pseudo_emetric_space β) : pseudo_emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := (uniformity_basis_edist.comap _).eq_binfi } /-- Pseudoemetric space instance on subsets of pseudoemetric spaces -/ instance {α : Type*} {p : α → Prop} [pseudo_emetric_space α] : pseudo_emetric_space (subtype p) := pseudo_emetric_space.induced coe ‹_› /-- The extended psuedodistance on a subset of a pseudoemetric space is the restriction of the original pseudodistance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl namespace mul_opposite /-- Pseudoemetric space instance on the multiplicative opposite of a pseudoemetric space. -/ @[to_additive "Pseudoemetric space instance on the additive opposite of a pseudoemetric space."] instance {α : Type*} [pseudo_emetric_space α] : pseudo_emetric_space αᵐᵒᵖ := pseudo_emetric_space.induced unop ‹_› @[to_additive] theorem edist_unop (x y : αᵐᵒᵖ) : edist (unop x) (unop y) = edist x y := rfl @[to_additive] theorem edist_op (x y : α) : edist (op x) (op y) = edist x y := rfl end mul_opposite section ulift instance : pseudo_emetric_space (ulift α) := pseudo_emetric_space.induced ulift.down ‹_› lemma ulift.edist_eq (x y : ulift α) : edist x y = edist x.down y.down := rfl @[simp] lemma ulift.edist_up_up (x y : α) : edist (ulift.up x) (ulift.up y) = edist x y := rfl end ulift /-- The product of two pseudoemetric spaces, with the max distance, is an extended pseudometric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.pseudo_emetric_space_max [pseudo_emetric_space β] : pseudo_emetric_space (α × β) := { edist := λ x y, edist x.1 y.1 ⊔ edist x.2 y.2, edist_self := λ x, by simp, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp only [pseudo_emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [pseudo_emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of pseudoemetric spaces, with the max distance, is still a pseudoemetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance pseudo_emetric_space_pi [∀b, pseudo_emetric_space (π b)] : pseudo_emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, pseudo_emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [set.ext_iff, εpos] end } lemma edist_pi_def [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) : edist f g = finset.sup univ (λb, edist (f b) (g b)) := rfl lemma edist_le_pi_edist [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) (b : β) : edist (f b) (g b) ≤ edist f g := finset.le_sup (finset.mem_univ b) lemma edist_pi_le_iff [Π b, pseudo_emetric_space (π b)] {f g : Π b, π b} {d : ℝ≥0∞} : edist f g ≤ d ↔ ∀ b, edist (f b) (g b) ≤ d := finset.sup_le_iff.trans $ by simp only [finset.mem_univ, forall_const] lemma edist_pi_const_le (a b : α) : edist (λ _ : β, a) (λ _, b) ≤ edist a b := edist_pi_le_iff.2 $ λ _, le_rfl @[simp] lemma edist_pi_const [nonempty β] (a b : α) : edist (λ x : β, a) (λ _, b) = edist a b := finset.sup_const univ_nonempty (edist a b) end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ℝ≥0∞} {s t : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ℝ≥0∞) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw [edist_comm, mem_ball] /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ≥0∞) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ edist x y ≤ ε := by rw [edist_comm, mem_closed_ball] @[simp] theorem closed_ball_top (x : α) : closed_ball x ∞ = univ := eq_univ_of_forall $ λ y, le_top theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y hy, le_of_lt hy theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by rw [mem_ball', mem_ball] theorem mem_closed_ball_comm : x ∈ closed_ball y ε ↔ y ∈ closed_ball x ε := by rw [mem_closed_ball', mem_closed_ball] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : disjoint (ball x ε₁) (ball y ε₂) := set.disjoint_left.mpr $ λ z h₁ h₂, (edist_triangle_left x y z).not_lt $ (ennreal.add_lt_add h₁ h₂).trans_le h theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y ≠ ∞) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : ennreal.add_lt_add_left h' zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ (ne_top_of_lt h)⟩, exact (add_tsub_cancel_of_le (mem_ball.mp h).le).le end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ lemma ord_connected_set_of_closed_ball_subset (x : α) (s : set α) : ord_connected {r | closed_ball x r ⊆ s} := ⟨λ r₁ hr₁ r₂ hr₂ r hr, (closed_ball_subset_closed_ball hr.2).trans hr₂⟩ lemma ord_connected_set_of_ball_subset (x : α) (s : set α) : ord_connected {r | ball x r ⊆ s} := ⟨λ r₁ hr₁ r₂ hr₂ r hr, (ball_subset_ball hr.2).trans hr₂⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist lemma nhds_within_basis_eball : (𝓝[s] x).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, ball x ε ∩ s) := nhds_within_has_basis nhds_basis_eball s theorem nhds_basis_closed_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_edist_le lemma nhds_within_basis_closed_eball : (𝓝[s] x).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, closed_ball x ε ∩ s) := nhds_within_has_basis nhds_basis_closed_eball s theorem nhds_eq : 𝓝 x = (⨅ε>0, 𝓟 (ball x ε)) := nhds_basis_eball.eq_binfi theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff lemma mem_nhds_within_iff : s ∈ 𝓝[t] x ↔ ∃ ε > 0, ball x ε ∩ t ⊆ s := nhds_within_basis_eball.mem_iff section variables [pseudo_emetric_space β] {f : α → β} lemma tendsto_nhds_within_nhds_within {t : set β} {a b} : tendsto f (𝓝[s] a) (𝓝[t] b) ↔ ∀ ε > 0, ∃ δ > 0, ∀ ⦃x⦄, x ∈ s → edist x a < δ → f x ∈ t ∧ edist (f x) b < ε := (nhds_within_basis_eball.tendsto_iff nhds_within_basis_eball).trans $ forall₂_congr $ λ ε hε, exists₂_congr $ λ δ hδ, forall_congr $ λ x, by simp; itauto lemma tendsto_nhds_within_nhds {a b} : tendsto f (𝓝[s] a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → edist x a < δ → edist (f x) b < ε := by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within], simp only [mem_univ, true_and] } lemma tendsto_nhds_nhds {a b} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀ ⦃x⦄, edist x a < δ → edist (f x) b < ε := nhds_basis_eball.tendsto_iff nhds_basis_eball end theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_compl_iff.1 $ is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, (ball_disjoint $ by { rw top_add, exact le_of_not_lt hy }).subset_compl_right⟩ theorem ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := is_open_ball.mem_nhds (mem_ball_self ε0) theorem closed_ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : ball x r ×ˢ ball y r = ball (x, y) r := ext $ λ z, max_lt_iff.symm theorem closed_ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : closed_ball x r ×ˢ closed_ball y r = closed_ball (x, y) r := ext $ λ z, max_le_iff.symm /-- ε-characterization of the closure in pseudoemetric spaces -/ theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] theorem inseparable_iff : inseparable x y ↔ edist x y = 0 := by simp [inseparable_iff_mem_closure, mem_closure_iff, edist_comm, forall_lt_iff_le'] /-- In a pseudoemetric space, Cauchy sequences are characterized by the fact that, eventually, the pseudoedistance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ℝ≥0∞), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `ℝ≥0` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : ℝ≥0, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, t.finite ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, set.finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩ section compact /-- For a set `s` in a pseudo emetric space, if for every `ε > 0` there exists a countable set that is `ε`-dense in `s`, then there exists a countable subset `t ⊆ s` that is dense in `s`. -/ lemma subset_countable_closure_of_almost_dense_set (s : set α) (hs : ∀ ε > 0, ∃ t : set α, t.countable ∧ s ⊆ ⋃ x ∈ t, closed_ball x ε) : ∃ t ⊆ s, (t.countable ∧ s ⊆ closure t) := begin rcases s.eq_empty_or_nonempty with rfl|⟨x₀, hx₀⟩, { exact ⟨∅, empty_subset _, countable_empty, empty_subset _⟩ }, choose! T hTc hsT using (λ n : ℕ, hs n⁻¹ (by simp)), have : ∀ r x, ∃ y ∈ s, closed_ball x r ∩ s ⊆ closed_ball y (r * 2), { intros r x, rcases (closed_ball x r ∩ s).eq_empty_or_nonempty with he|⟨y, hxy, hys⟩, { refine ⟨x₀, hx₀, _⟩, rw he, exact empty_subset _ }, { refine ⟨y, hys, λ z hz, _⟩, calc edist z y ≤ edist z x + edist y x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add hz.1 hxy ... = r * 2 : (mul_two r).symm } }, choose f hfs hf, refine ⟨⋃ n : ℕ, (f n⁻¹) '' (T n), Union_subset $ λ n, image_subset_iff.2 (λ z hz, hfs _ _), countable_Union $ λ n, (hTc n).image _, _⟩, refine λ x hx, mem_closure_iff.2 (λ ε ε0, _), rcases ennreal.exists_inv_nat_lt (ennreal.half_pos ε0.lt.ne').ne' with ⟨n, hn⟩, rcases mem_Union₂.1 (hsT n hx) with ⟨y, hyn, hyx⟩, refine ⟨f n⁻¹ y, mem_Union.2 ⟨n, mem_image_of_mem _ hyn⟩, _⟩, calc edist x (f n⁻¹ y) ≤ n⁻¹ * 2 : hf _ _ ⟨hyx, hx⟩ ... < ε : ennreal.mul_lt_of_lt_div hn end /-- A compact set in a pseudo emetric space is separable, i.e., it is a subset of the closure of a countable set. -/ lemma subset_countable_closure_of_compact {s : set α} (hs : is_compact s) : ∃ t ⊆ s, (t.countable ∧ s ⊆ closure t) := begin refine subset_countable_closure_of_almost_dense_set s (λ ε hε, _), rcases totally_bounded_iff'.1 hs.totally_bounded ε hε with ⟨t, hts, htf, hst⟩, exact ⟨t, htf.countable, subset.trans hst $ Union₂_mono $ λ _ _, ball_subset_closed_ball⟩ end end compact section second_countable open _root_.topological_space variables (α) /-- A sigma compact pseudo emetric space has second countable topology. This is not an instance to avoid a loop with `sigma_compact_space_of_locally_compact_second_countable`. -/ lemma second_countable_of_sigma_compact [sigma_compact_space α] : second_countable_topology α := begin suffices : separable_space α, by exactI uniform_space.second_countable_of_separable α, choose T hTsub hTc hsubT using λ n, subset_countable_closure_of_compact (is_compact_compact_covering α n), refine ⟨⟨⋃ n, T n, countable_Union hTc, λ x, _⟩⟩, rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩, exact closure_mono (subset_Union _ n) (hsubT _ hn) end variable {α} lemma second_countable_of_almost_dense_set (hs : ∀ ε > 0, ∃ t : set α, t.countable ∧ (⋃ x ∈ t, closed_ball x ε) = univ) : second_countable_topology α := begin suffices : separable_space α, by exactI uniform_space.second_countable_of_separable α, rcases subset_countable_closure_of_almost_dense_set (univ : set α) (λ ε ε0, _) with ⟨t, -, htc, ht⟩, { exact ⟨⟨t, htc, λ x, ht (mem_univ x)⟩⟩ }, { rcases hs ε ε0 with ⟨t, htc, ht⟩, exact ⟨t, htc, univ_subset_iff.2 ht⟩ } end end second_countable section diam /-- The diameter of a set in a pseudoemetric space, named `emetric.diam` -/ noncomputable def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff {d : ℝ≥0∞} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] lemma diam_image_le_iff {d : ℝ≥0∞} {f : β → α} {s : set β} : diam (f '' s) ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist (f x) (f y) ≤ d := by simp only [diam_le_iff, ball_image_iff] lemma edist_le_of_diam_le {d} (hx : x ∈ s) (hy : y ∈ s) (hd : diam s ≤ d) : edist x y ≤ d := diam_le_iff.1 hd x hx y hy /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := edist_le_of_diam_le hx hy le_rfl /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le {d : ℝ≥0∞} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := nonpos_iff_eq_zero.1 $ diam_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_rfl /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_Union_mem_option {ι : Type*} (o : option ι) (s : ι → set α) : diam (⋃ i ∈ o, s i) = ⨆ i ∈ o, diam (s i) := by cases o; simp lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and, forall_and_distrib, and_self, ← and_assoc] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right] lemma diam_triple : diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_right, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add (add_le_add (edist_le_diam_of_mem ha xs) le_rfl) (edist_le_diam_of_mem yt hb), refine diam_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_self_add ... = diam s + edist x y + diam t : (add_assoc _ _ _).symm }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_self } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ℝ≥0∞} : diam (closed_ball x r) ≤ 2 * r := diam_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : (two_mul r).symm lemma diam_ball {r : ℝ≥0∞} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball lemma diam_pi_le_of_le {π : β → Type*} [fintype β] [∀ b, pseudo_emetric_space (π b)] {s : Π (b : β), set (π b)} {c : ℝ≥0∞} (h : ∀ b, diam (s b) ≤ c) : diam (set.pi univ s) ≤ c := begin apply diam_le (λ x hx y hy, edist_pi_le_iff.mpr _), rw [mem_univ_pi] at hx hy, exact λ b, diam_le_iff.1 (h b) (x b) (hx b) (y b) (hy b), end end diam end emetric --namespace /-- We now define `emetric_space`, extending `pseudo_emetric_space`. -/ class emetric_space (α : Type u) extends pseudo_emetric_space α : Type u := (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) variables {γ : Type w} [emetric_space γ] export emetric_space (eq_of_edist_eq_zero) /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : γ} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : γ} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : γ} : (edist x y ≤ 0) ↔ x = y := nonpos_iff_eq_zero.trans edist_eq_zero @[simp] theorem edist_pos {x y : γ} : 0 < edist x y ↔ x ≠ y := by simp [← not_le] /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : γ} (h : ∀ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated_space γ := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem emetric.uniform_embedding_iff' [emetric_space β] {f : γ → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, edist (f a) (f b) < ε → edist a b < δ) := begin simp only [uniform_embedding_iff_uniform_inducing, uniformity_basis_edist.uniform_inducing_iff uniformity_basis_edist, exists_prop], refl end /-- If a `pseudo_emetric_space` is a T₀ space, then it is an `emetric_space`. -/ def emetric_space.of_t0_pseudo_emetric_space (α : Type*) [pseudo_emetric_space α] [t0_space α] : emetric_space α := { eq_of_edist_eq_zero := λ x y hdist, (emetric.inseparable_iff.2 hdist).eq, ..‹pseudo_emetric_space α› } /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def emetric_space.replace_uniformity {γ} [U : uniform_space γ] (m : emetric_space γ) (H : 𝓤[U] = 𝓤[pseudo_emetric_space.to_uniform_space]) : emetric_space γ := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist γ _) } /-- The extended metric induced by an injective function taking values in a emetric space. -/ def emetric_space.induced {γ β} (f : γ → β) (hf : function.injective f) (m : emetric_space β) : emetric_space γ := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := (uniformity_basis_edist.comap _).eq_binfi } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [emetric_space α] : emetric_space (subtype p) := emetric_space.induced coe subtype.coe_injective ‹_› /-- Emetric space instance on the multiplicative opposite of an emetric space. -/ @[to_additive "Emetric space instance on the additive opposite of an emetric space."] instance {α : Type*} [emetric_space α] : emetric_space αᵐᵒᵖ := emetric_space.induced mul_opposite.unop mul_opposite.unop_injective ‹_› instance {α : Type*} [emetric_space α] : emetric_space (ulift α) := emetric_space.induced ulift.down ulift.down_injective ‹_› /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (γ × β) := { eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, ..prod.pseudo_emetric_space_max } /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 γ = ⨅ ε>0, 𝓟 {p:γ×γ | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, ..pseudo_emetric_space_pi } end pi namespace emetric /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set. -/ lemma countable_closure_of_compact {s : set γ} (hs : is_compact s) : ∃ t ⊆ s, (t.countable ∧ s = closure t) := begin rcases subset_countable_closure_of_compact hs with ⟨t, hts, htc, hsub⟩, exact ⟨t, hts, htc, subset.antisymm hsub (closure_minimal hts hs.is_closed)⟩ end section diam variables {s : set γ} lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := by simp only [pos_iff_ne_zero, ne.def, diam_eq_zero_iff, set.subsingleton, not_forall] end diam end emetric /-! ### Separation quotient -/ instance [pseudo_emetric_space X] : has_edist (uniform_space.separation_quotient X) := ⟨λ x y, quotient.lift_on₂' x y edist $ λ x y x' y' hx hy, calc edist x y = edist x' y : edist_congr_right $ emetric.inseparable_iff.1 $ separation_rel_iff_inseparable.1 hx ... = edist x' y' : edist_congr_left $ emetric.inseparable_iff.1 $ separation_rel_iff_inseparable.1 hy⟩ @[simp] theorem uniform_space.separation_quotient.edist_mk [pseudo_emetric_space X] (x y : X) : @edist (uniform_space.separation_quotient X) _ (quot.mk _ x) (quot.mk _ y) = edist x y := rfl instance [pseudo_emetric_space X] : emetric_space (uniform_space.separation_quotient X) := @emetric_space.of_t0_pseudo_emetric_space (uniform_space.separation_quotient X) { edist_self := λ x, quotient.induction_on' x edist_self, edist_comm := λ x y, quotient.induction_on₂' x y edist_comm, edist_triangle := λ x y z, quotient.induction_on₃' x y z edist_triangle, to_uniform_space := infer_instance, uniformity_edist := (uniformity_basis_edist.map _).eq_binfi.trans $ infi_congr $ λ ε, infi_congr $ λ hε, congr_arg 𝓟 begin ext ⟨⟨x⟩, ⟨y⟩⟩, refine ⟨_, λ h, ⟨(x, y), h, rfl⟩⟩, rintro ⟨⟨x', y'⟩, h', h⟩, simp only [prod.ext_iff] at h, rwa [← h.1, ← h.2] end } _ /-! ### `additive`, `multiplicative` The distance on those type synonyms is inherited without change. -/ open additive multiplicative section variables [has_edist X] instance : has_edist (additive X) := ‹has_edist X› instance : has_edist (multiplicative X) := ‹has_edist X› @[simp] lemma edist_of_mul (a b : X) : edist (of_mul a) (of_mul b) = edist a b := rfl @[simp] lemma edist_of_add (a b : X) : edist (of_add a) (of_add b) = edist a b := rfl @[simp] lemma edist_to_mul (a b : additive X) : edist (to_mul a) (to_mul b) = edist a b := rfl @[simp] lemma edist_to_add (a b : multiplicative X) : edist (to_add a) (to_add b) = edist a b := rfl end instance [pseudo_emetric_space X] : pseudo_emetric_space (additive X) := ‹pseudo_emetric_space X› instance [pseudo_emetric_space X] : pseudo_emetric_space (multiplicative X) := ‹pseudo_emetric_space X› instance [emetric_space X] : emetric_space (additive X) := ‹emetric_space X› instance [emetric_space X] : emetric_space (multiplicative X) := ‹emetric_space X› /-! ### Order dual The distance on this type synonym is inherited without change. -/ open order_dual section variables [has_edist X] instance : has_edist Xᵒᵈ := ‹has_edist X› @[simp] lemma edist_to_dual (a b : X) : edist (to_dual a) (to_dual b) = edist a b := rfl @[simp] lemma edist_of_dual (a b : Xᵒᵈ) : edist (of_dual a) (of_dual b) = edist a b := rfl end instance [pseudo_emetric_space X] : pseudo_emetric_space Xᵒᵈ := ‹pseudo_emetric_space X› instance [emetric_space X] : emetric_space Xᵒᵈ := ‹emetric_space X›
5d1de7febddd351dc068e9dfe10d7395f44ae7a4
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/implicit7.lean
b1f76468c1f2571428f84e71cc4db7d4a1f70384
[ "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
360
lean
variable f {A : Type} (a : A) {B : Type} : A -> B -> A variable g {A B : Type} (a : A) {C : Type} : B -> C -> C notation 100 _ ; _ ; _ : f notation 100 _ ; _ ; _ : g check 10 ; true ; false check 10 ; 10 ; true set_option pp::notation false check 10 ; true ; false check 10 ; 10 ; true set_option pp::implicit true check 10 ; true ; false check 10 ; 10 ; true
26e41dff7ab683efca227b7954b33a436446a0aa
5719a16e23dfc08cdea7a5bf035b81690f307965
/stage0/src/Init/Lean/Compiler/IR/EmitC.lean
1523dd3012d887deb53732337ac0e2d98de7eb25
[ "Apache-2.0" ]
permissive
postmasters/lean4
488b03969a371e1507e1e8a4df9ebf63c7cbe7ac
f3976fc53a883ac7606fc59357d43f4b51016ca7
refs/heads/master
1,655,582,707,480
1,588,682,595,000
1,588,682,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,458
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Control.Conditional import Init.Lean.Runtime import Init.Lean.Compiler.NameMangling import Init.Lean.Compiler.ExportAttr import Init.Lean.Compiler.InitAttr import Init.Lean.Compiler.IR.CompilerM import Init.Lean.Compiler.IR.EmitUtil import Init.Lean.Compiler.IR.NormIds import Init.Lean.Compiler.IR.SimpCase import Init.Lean.Compiler.IR.Boxing namespace Lean namespace IR open ExplicitBoxing (requiresBoxedVersion mkBoxedName isBoxedName) namespace EmitC def leanMainFn := "_lean_main" structure Context := (env : Environment) (modName : Name) (jpMap : JPParamsMap := {}) (mainFn : FunId := arbitrary _) (mainParams : Array Param := #[]) abbrev M := ReaderT Context (EStateM String String) def getEnv : M Environment := Context.env <$> read def getModName : M Name := Context.modName <$> read def getDecl (n : Name) : M Decl := do env ← getEnv; match findEnvDecl env n with | some d => pure d | none => throw ("unknown declaration '" ++ toString n ++ "'") @[inline] def emit {α : Type} [HasToString α] (a : α) : M Unit := modify (fun out => out ++ toString a) @[inline] def emitLn {α : Type} [HasToString α] (a : α) : M Unit := emit a *> emit "\n" def emitLns {α : Type} [HasToString α] (as : List α) : M Unit := as.forM $ fun a => emitLn a def argToCString (x : Arg) : String := match x with | Arg.var x => toString x | _ => "lean_box(0)" def emitArg (x : Arg) : M Unit := emit (argToCString x) def toCType : IRType → String | IRType.float => "double" | IRType.uint8 => "uint8_t" | IRType.uint16 => "uint16_t" | IRType.uint32 => "uint32_t" | IRType.uint64 => "uint64_t" | IRType.usize => "size_t" | IRType.object => "lean_object*" | IRType.tobject => "lean_object*" | IRType.irrelevant => "lean_object*" | IRType.struct _ _ => panic! "not implemented yet" | IRType.union _ _ => panic! "not implemented yet" def throwInvalidExportName {α : Type} (n : Name) : M α := throw ("invalid export name '" ++ toString n ++ "'") def toCName (n : Name) : M String := do env ← getEnv; -- TODO: we should support simple export names only match getExportNameFor env n with | some (Name.str Name.anonymous s _) => pure s | some _ => throwInvalidExportName n | none => if n == `main then pure leanMainFn else pure n.mangle def emitCName (n : Name) : M Unit := toCName n >>= emit def toCInitName (n : Name) : M String := do env ← getEnv; -- TODO: we should support simple export names only match getExportNameFor env n with | some (Name.str Name.anonymous s _) => pure $ "_init_" ++ s | some _ => throwInvalidExportName n | none => pure ("_init_" ++ n.mangle) def emitCInitName (n : Name) : M Unit := toCInitName n >>= emit def emitFnDeclAux (decl : Decl) (cppBaseName : String) (addExternForConsts : Bool) : M Unit := do let ps := decl.params; env ← getEnv; when (ps.isEmpty && addExternForConsts) (emit "extern "); emit (toCType decl.resultType ++ " " ++ cppBaseName); unless (ps.isEmpty) $ do { emit "("; -- We omit irrelevant parameters for extern constants let ps := if isExternC env decl.name then ps.filter (fun p => !p.ty.isIrrelevant) else ps; if ps.size > closureMaxArgs && isBoxedName decl.name then emit "lean_object**" else ps.size.forM $ fun i => do { when (i > 0) (emit ", "); emit (toCType (ps.get! i).ty) }; emit ")" }; emitLn ";" def emitFnDecl (decl : Decl) (addExternForConsts : Bool) : M Unit := do cppBaseName ← toCName decl.name; emitFnDeclAux decl cppBaseName addExternForConsts def emitExternDeclAux (decl : Decl) (cNameStr : String) : M Unit := do let cName := mkNameSimple cNameStr; env ← getEnv; let extC := isExternC env decl.name; emitFnDeclAux decl cNameStr (!extC) def emitFnDecls : M Unit := do env ← getEnv; let decls := getDecls env; let modDecls : NameSet := decls.foldl (fun s d => s.insert d.name) {}; let usedDecls : NameSet := decls.foldl (fun s d => collectUsedDecls env d (s.insert d.name)) {}; let usedDecls := usedDecls.toList; usedDecls.forM $ fun n => do decl ← getDecl n; match getExternNameFor env `c decl.name with | some cName => emitExternDeclAux decl cName | none => emitFnDecl decl (!modDecls.contains n) def emitMainFn : M Unit := do d ← getDecl `main; match d with | Decl.fdecl f xs t b => do unless (xs.size == 2 || xs.size == 1) (throw "invalid main function, incorrect arity when generating code"); env ← getEnv; let usesLeanAPI := usesModuleFrom env `Init.Lean; if usesLeanAPI then emitLn "void lean_initialize();" else emitLn "void lean_initialize_runtime_module();"; emitLn "int main(int argc, char ** argv) {\nlean_object* in; lean_object* res;"; if usesLeanAPI then emitLn "lean_initialize();" else emitLn "lean_initialize_runtime_module();"; modName ← getModName; emitLn ("res = initialize_" ++ (modName.mangle "") ++ "(lean_io_mk_world());"); emitLns ["lean_io_mark_end_initialization();", "if (lean_io_result_is_ok(res)) {", "lean_dec_ref(res);", "lean_init_task_manager();"]; if xs.size == 2 then do { emitLns ["in = lean_box(0);", "int i = argc;", "while (i > 1) {", " lean_object* n;", " i--;", " n = lean_alloc_ctor(1,2,0); lean_ctor_set(n, 0, lean_mk_string(argv[i])); lean_ctor_set(n, 1, in);", " in = n;", "}"]; emitLn ("res = " ++ leanMainFn ++ "(in, lean_io_mk_world());") } else do { emitLn ("res = " ++ leanMainFn ++ "(lean_io_mk_world());") }; emitLn "}"; emitLns ["if (lean_io_result_is_ok(res)) {", " int ret = lean_unbox(lean_io_result_get_value(res));", " lean_dec_ref(res);", " return ret;", "} else {", " lean_io_result_show_error(res);", " lean_dec_ref(res);", " return 1;", "}"]; emitLn "}" | other => throw "function declaration expected" def hasMainFn : M Bool := do env ← getEnv; let decls := getDecls env; pure $ decls.any (fun d => d.name == `main) def emitMainFnIfNeeded : M Unit := whenM hasMainFn emitMainFn def emitFileHeader : M Unit := do env ← getEnv; modName ← getModName; emitLn "// Lean compiler output"; emitLn ("// Module: " ++ toString modName); emit "// Imports:"; env.imports.forM $ fun m => emit (" " ++ toString m); emitLn ""; emitLn "#include \"runtime/lean.h\""; emitLns [ "#if defined(__clang__)", "#pragma clang diagnostic ignored \"-Wunused-parameter\"", "#pragma clang diagnostic ignored \"-Wunused-label\"", "#elif defined(__GNUC__) && !defined(__CLANG__)", "#pragma GCC diagnostic ignored \"-Wunused-parameter\"", "#pragma GCC diagnostic ignored \"-Wunused-label\"", "#pragma GCC diagnostic ignored \"-Wunused-but-set-variable\"", "#endif", "#ifdef __cplusplus", "extern \"C\" {", "#endif" ] def emitFileFooter : M Unit := emitLns [ "#ifdef __cplusplus", "}", "#endif" ] def throwUnknownVar {α : Type} (x : VarId) : M α := throw ("unknown variable '" ++ toString x ++ "'") def getJPParams (j : JoinPointId) : M (Array Param) := do ctx ← read; match ctx.jpMap.find? j with | some ps => pure ps | none => throw "unknown join point" def declareVar (x : VarId) (t : IRType) : M Unit := do emit (toCType t); emit " "; emit x; emit "; " def declareParams (ps : Array Param) : M Unit := ps.forM $ fun p => declareVar p.x p.ty partial def declareVars : FnBody → Bool → M Bool | e@(FnBody.vdecl x t _ b), d => do ctx ← read; if isTailCallTo ctx.mainFn e then pure d else declareVar x t *> declareVars b true | FnBody.jdecl j xs _ b, d => declareParams xs *> declareVars b (d || xs.size > 0) | e, d => if e.isTerminal then pure d else declareVars e.body d def emitTag (x : VarId) (xType : IRType) : M Unit := do if xType.isObj then do emit "lean_obj_tag("; emit x; emit ")" else emit x def isIf (alts : Array Alt) : Option (Nat × FnBody × FnBody) := if alts.size != 2 then none else match alts.get! 0 with | Alt.ctor c b => some (c.cidx, b, (alts.get! 1).body) | _ => none def emitIf (emitBody : FnBody → M Unit) (x : VarId) (xType : IRType) (tag : Nat) (t : FnBody) (e : FnBody) : M Unit := do emit "if ("; emitTag x xType; emit " == "; emit tag; emitLn ")"; emitBody t; emitLn "else"; emitBody e def emitCase (emitBody : FnBody → M Unit) (x : VarId) (xType : IRType) (alts : Array Alt) : M Unit := match isIf alts with | some (tag, t, e) => emitIf emitBody x xType tag t e | _ => do emit "switch ("; emitTag x xType; emitLn ") {"; let alts := ensureHasDefault alts; alts.forM $ fun alt => match alt with | Alt.ctor c b => emit "case " *> emit c.cidx *> emitLn ":" *> emitBody b | Alt.default b => emitLn "default: " *> emitBody b; emitLn "}" def emitInc (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do emit $ if checkRef then (if n == 1 then "lean_inc" else "lean_inc_n") else (if n == 1 then "lean_inc_ref" else "lean_inc_ref_n"); emit "(" *> emit x; when (n != 1) (emit ", " *> emit n); emitLn ");" def emitDec (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do emit (if checkRef then "lean_dec" else "lean_dec_ref"); emit "("; emit x; when (n != 1) (do emit ", "; emit n); emitLn ");" def emitDel (x : VarId) : M Unit := do emit "lean_free_object("; emit x; emitLn ");" def emitSetTag (x : VarId) (i : Nat) : M Unit := do emit "lean_ctor_set_tag("; emit x; emit ", "; emit i; emitLn ");" def emitSet (x : VarId) (i : Nat) (y : Arg) : M Unit := do emit "lean_ctor_set("; emit x; emit ", "; emit i; emit ", "; emitArg y; emitLn ");" def emitOffset (n : Nat) (offset : Nat) : M Unit := if n > 0 then do emit "sizeof(void*)*"; emit n; when (offset > 0) (emit " + " *> emit offset) else emit offset def emitUSet (x : VarId) (n : Nat) (y : VarId) : M Unit := do emit "lean_ctor_set_usize("; emit x; emit ", "; emit n; emit ", "; emit y; emitLn ");" def emitSSet (x : VarId) (n : Nat) (offset : Nat) (y : VarId) (t : IRType) : M Unit := do match t with | IRType.float => emit "lean_ctor_set_float" | IRType.uint8 => emit "lean_ctor_set_uint8" | IRType.uint16 => emit "lean_ctor_set_uint16" | IRType.uint32 => emit "lean_ctor_set_uint32" | IRType.uint64 => emit "lean_ctor_set_uint64" | _ => throw "invalid instruction"; emit "("; emit x; emit ", "; emitOffset n offset; emit ", "; emit y; emitLn ");" def emitJmp (j : JoinPointId) (xs : Array Arg) : M Unit := do ps ← getJPParams j; unless (xs.size == ps.size) (throw "invalid goto"); xs.size.forM $ fun i => do { let p := ps.get! i; let x := xs.get! i; emit p.x; emit " = "; emitArg x; emitLn ";" }; emit "goto "; emit j; emitLn ";" def emitLhs (z : VarId) : M Unit := do emit z; emit " = " def emitArgs (ys : Array Arg) : M Unit := ys.size.forM $ fun i => do when (i > 0) (emit ", "); emitArg (ys.get! i) def emitCtorScalarSize (usize : Nat) (ssize : Nat) : M Unit := if usize == 0 then emit ssize else if ssize == 0 then emit "sizeof(size_t)*" *> emit usize else emit "sizeof(size_t)*" *> emit usize *> emit " + " *> emit ssize def emitAllocCtor (c : CtorInfo) : M Unit := do emit "lean_alloc_ctor("; emit c.cidx; emit ", "; emit c.size; emit ", "; emitCtorScalarSize c.usize c.ssize; emitLn ");" def emitCtorSetArgs (z : VarId) (ys : Array Arg) : M Unit := ys.size.forM $ fun i => do emit "lean_ctor_set("; emit z; emit ", "; emit i; emit ", "; emitArg (ys.get! i); emitLn ");" def emitCtor (z : VarId) (c : CtorInfo) (ys : Array Arg) : M Unit := do emitLhs z; if c.size == 0 && c.usize == 0 && c.ssize == 0 then do emit "lean_box("; emit c.cidx; emitLn ");" else do emitAllocCtor c; emitCtorSetArgs z ys def emitReset (z : VarId) (n : Nat) (x : VarId) : M Unit := do emit "if (lean_is_exclusive("; emit x; emitLn ")) {"; n.forM $ fun i => do { emit " lean_ctor_release("; emit x; emit ", "; emit i; emitLn ");" }; emit " "; emitLhs z; emit x; emitLn ";"; emitLn "} else {"; emit " lean_dec_ref("; emit x; emitLn ");"; emit " "; emitLhs z; emitLn "lean_box(0);"; emitLn "}" def emitReuse (z : VarId) (x : VarId) (c : CtorInfo) (updtHeader : Bool) (ys : Array Arg) : M Unit := do emit "if (lean_is_scalar("; emit x; emitLn ")) {"; emit " "; emitLhs z; emitAllocCtor c; emitLn "} else {"; emit " "; emitLhs z; emit x; emitLn ";"; when updtHeader (do emit " lean_ctor_set_tag("; emit z; emit ", "; emit c.cidx; emitLn ");"); emitLn "}"; emitCtorSetArgs z ys def emitProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do emitLhs z; emit "lean_ctor_get("; emit x; emit ", "; emit i; emitLn ");" def emitUProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do emitLhs z; emit "lean_ctor_get_usize("; emit x; emit ", "; emit i; emitLn ");" def emitSProj (z : VarId) (t : IRType) (n offset : Nat) (x : VarId) : M Unit := do emitLhs z; match t with | IRType.float => emit "lean_ctor_get_float" | IRType.uint8 => emit "lean_ctor_get_uint8" | IRType.uint16 => emit "lean_ctor_get_uint16" | IRType.uint32 => emit "lean_ctor_get_uint32" | IRType.uint64 => emit "lean_ctor_get_uint64" | _ => throw "invalid instruction"; emit "("; emit x; emit ", "; emitOffset n offset; emitLn ");" def toStringArgs (ys : Array Arg) : List String := ys.toList.map argToCString def emitSimpleExternalCall (f : String) (ps : Array Param) (ys : Array Arg) : M Unit := do emit f; emit "("; -- We must remove irrelevant arguments to extern calls. ys.size.foldM (fun i (first : Bool) => if (ps.get! i).ty.isIrrelevant then pure first else do unless first (emit ", "); emitArg (ys.get! i); pure false) true; emitLn ");"; pure () def emitExternCall (f : FunId) (ps : Array Param) (extData : ExternAttrData) (ys : Array Arg) : M Unit := match getExternEntryFor extData `c with | some (ExternEntry.standard _ extFn) => emitSimpleExternalCall extFn ps ys | some (ExternEntry.inline _ pat) => do emit (expandExternPattern pat (toStringArgs ys)); emitLn ";" | some (ExternEntry.foreign _ extFn) => emitSimpleExternalCall extFn ps ys | _ => throw ("failed to emit extern application '" ++ toString f ++ "'") def emitFullApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do emitLhs z; decl ← getDecl f; match decl with | Decl.extern _ ps _ extData => emitExternCall f ps extData ys | _ => do emitCName f; when (ys.size > 0) (do emit "("; emitArgs ys; emit ")"); emitLn ";" def emitPartialApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do decl ← getDecl f; let arity := decl.params.size; emitLhs z; emit "lean_alloc_closure((void*)("; emitCName f; emit "), "; emit arity; emit ", "; emit ys.size; emitLn ");"; ys.size.forM $ fun i => do { let y := ys.get! i; emit "lean_closure_set("; emit z; emit ", "; emit i; emit ", "; emitArg y; emitLn ");" } def emitApp (z : VarId) (f : VarId) (ys : Array Arg) : M Unit := if ys.size > closureMaxArgs then do emit "{ lean_object* _aargs[] = {"; emitArgs ys; emitLn "};"; emitLhs z; emit "lean_apply_m("; emit f; emit ", "; emit ys.size; emitLn ", _aargs); }" else do emitLhs z; emit "lean_apply_"; emit ys.size; emit "("; emit f; emit ", "; emitArgs ys; emitLn ");" def emitBoxFn (xType : IRType) : M Unit := match xType with | IRType.usize => emit "lean_box_usize" | IRType.uint32 => emit "lean_box_uint32" | IRType.uint64 => emit "lean_box_uint64" | IRType.float => emit "lean_box_float" | other => emit "lean_box" def emitBox (z : VarId) (x : VarId) (xType : IRType) : M Unit := do emitLhs z; emitBoxFn xType; emit "("; emit x; emitLn ");" def emitUnbox (z : VarId) (t : IRType) (x : VarId) : M Unit := do emitLhs z; match t with | IRType.usize => emit "lean_unbox_usize" | IRType.uint32 => emit "lean_unbox_uint32" | IRType.uint64 => emit "lean_unbox_uint64" | IRType.float => emit "lean_unbox_float" | other => emit "lean_unbox"; emit "("; emit x; emitLn ");" def emitIsShared (z : VarId) (x : VarId) : M Unit := do emitLhs z; emit "!lean_is_exclusive("; emit x; emitLn ");" def emitIsTaggedPtr (z : VarId) (x : VarId) : M Unit := do emitLhs z; emit "!lean_is_scalar("; emit x; emitLn ");" def toHexDigit (c : Nat) : String := String.singleton c.digitChar def quoteString (s : String) : String := let q := "\""; let q := s.foldl (fun q c => q ++ if c == '\n' then "\\n" else if c == '\n' then "\\t" else if c == '\\' then "\\\\" else if c == '\"' then "\\\"" else if c.toNat <= 31 then "\\x" ++ toHexDigit (c.toNat / 16) ++ toHexDigit (c.toNat % 16) -- TODO(Leo): we should use `\unnnn` for escaping unicode characters. else String.singleton c) q; q ++ "\"" def emitNumLit (t : IRType) (v : Nat) : M Unit := if t.isObj then do if v < uint32Sz then emit "lean_unsigned_to_nat(" *> emit v *> emit "u)" else emit "lean_cstr_to_nat(\"" *> emit v *> emit "\")" else emit v def emitLit (z : VarId) (t : IRType) (v : LitVal) : M Unit := emitLhs z *> match v with | LitVal.num v => emitNumLit t v *> emitLn ";" | LitVal.str v => do emit "lean_mk_string("; emit (quoteString v); emitLn ");" def emitVDecl (z : VarId) (t : IRType) (v : Expr) : M Unit := match v with | Expr.ctor c ys => emitCtor z c ys | Expr.reset n x => emitReset z n x | Expr.reuse x c u ys => emitReuse z x c u ys | Expr.proj i x => emitProj z i x | Expr.uproj i x => emitUProj z i x | Expr.sproj n o x => emitSProj z t n o x | Expr.fap c ys => emitFullApp z c ys | Expr.pap c ys => emitPartialApp z c ys | Expr.ap x ys => emitApp z x ys | Expr.box t x => emitBox z x t | Expr.unbox x => emitUnbox z t x | Expr.isShared x => emitIsShared z x | Expr.isTaggedPtr x => emitIsTaggedPtr z x | Expr.lit v => emitLit z t v def isTailCall (x : VarId) (v : Expr) (b : FnBody) : M Bool := do ctx ← read; match v, b with | Expr.fap f _, FnBody.ret (Arg.var y) => pure $ f == ctx.mainFn && x == y | _, _ => pure false def paramEqArg (p : Param) (x : Arg) : Bool := match x with | Arg.var x => p.x == x | _ => false /- Given `[p_0, ..., p_{n-1}]`, `[y_0, ..., y_{n-1}]`, representing the assignments ``` p_0 := y_0, ... p_{n-1} := y_{n-1} ``` Return true iff we have `(i, j)` where `j > i`, and `y_j == p_i`. That is, we have ``` p_i := y_i, ... p_j := p_i, -- p_i was overwritten above ``` -/ def overwriteParam (ps : Array Param) (ys : Array Arg) : Bool := let n := ps.size; n.any $ fun i => let p := ps.get! i; (i+1, n).anyI $ fun j => paramEqArg p (ys.get! j) def emitTailCall (v : Expr) : M Unit := match v with | Expr.fap _ ys => do ctx ← read; let ps := ctx.mainParams; unless (ps.size == ys.size) (throw "invalid tail call"); if overwriteParam ps ys then do { emitLn "{"; ps.size.forM $ fun i => do { let p := ps.get! i; let y := ys.get! i; unless (paramEqArg p y) $ do { emit (toCType p.ty); emit " _tmp_"; emit i; emit " = "; emitArg y; emitLn ";" } }; ps.size.forM $ fun i => do { let p := ps.get! i; let y := ys.get! i; unless (paramEqArg p y) (do emit p.x; emit " = _tmp_"; emit i; emitLn ";") }; emitLn "}" } else do { ys.size.forM $ fun i => do { let p := ps.get! i; let y := ys.get! i; unless (paramEqArg p y) (do emit p.x; emit " = "; emitArg y; emitLn ";") } }; emitLn "goto _start;" | _ => throw "bug at emitTailCall" partial def emitBlock (emitBody : FnBody → M Unit) : FnBody → M Unit | FnBody.jdecl j xs v b => emitBlock b | d@(FnBody.vdecl x t v b) => do ctx ← read; if isTailCallTo ctx.mainFn d then emitTailCall v else emitVDecl x t v *> emitBlock b | FnBody.inc x n c p b => unless p (emitInc x n c) *> emitBlock b | FnBody.dec x n c p b => unless p (emitDec x n c) *> emitBlock b | FnBody.del x b => emitDel x *> emitBlock b | FnBody.setTag x i b => emitSetTag x i *> emitBlock b | FnBody.set x i y b => emitSet x i y *> emitBlock b | FnBody.uset x i y b => emitUSet x i y *> emitBlock b | FnBody.sset x i o y t b => emitSSet x i o y t *> emitBlock b | FnBody.mdata _ b => emitBlock b | FnBody.ret x => emit "return " *> emitArg x *> emitLn ";" | FnBody.case _ x xType alts => emitCase emitBody x xType alts | FnBody.jmp j xs => emitJmp j xs | FnBody.unreachable => emitLn "lean_panic_unreachable();" partial def emitJPs (emitBody : FnBody → M Unit) : FnBody → M Unit | FnBody.jdecl j xs v b => do emit j; emitLn ":"; emitBody v; emitJPs b | e => unless e.isTerminal (emitJPs e.body) partial def emitFnBody : FnBody → M Unit | b => do emitLn "{"; declared ← declareVars b false; when declared (emitLn ""); emitBlock emitFnBody b; emitJPs emitFnBody b; emitLn "}" def emitDeclAux (d : Decl) : M Unit := do env ← getEnv; let (vMap, jpMap) := mkVarJPMaps d; adaptReader (fun (ctx : Context) => { jpMap := jpMap, .. ctx }) $ do unless (hasInitAttr env d.name) $ match d with | Decl.fdecl f xs t b => do baseName ← toCName f; emit (toCType t); emit " "; if xs.size > 0 then do { emit baseName; emit "("; if xs.size > closureMaxArgs && isBoxedName d.name then emit "lean_object** _args" else xs.size.forM $ fun i => do { when (i > 0) (emit ", "); let x := xs.get! i; emit (toCType x.ty); emit " "; emit x.x }; emit ")" } else do { emit ("_init_" ++ baseName ++ "()") }; emitLn " {"; when (xs.size > closureMaxArgs && isBoxedName d.name) $ xs.size.forM $ fun i => do { let x := xs.get! i; emit "lean_object* "; emit x.x; emit " = _args["; emit i; emitLn "];" }; emitLn "_start:"; adaptReader (fun (ctx : Context) => { mainFn := f, mainParams := xs, .. ctx }) (emitFnBody b); emitLn "}" | _ => pure () def emitDecl (d : Decl) : M Unit := let d := d.normalizeIds; -- ensure we don't have gaps in the variable indices catch (emitDeclAux d) (fun err => throw (err ++ "\ncompiling:\n" ++ toString d)) def emitFns : M Unit := do env ← getEnv; let decls := getDecls env; decls.reverse.forM emitDecl def emitMarkPersistent (d : Decl) (n : Name) : M Unit := when d.resultType.isObj $ do { emit "lean_mark_persistent("; emitCName n; emitLn ");" } def emitDeclInit (d : Decl) : M Unit := do env ← getEnv; let n := d.name; if isIOUnitInitFn env n then do { emit "res = "; emitCName n; emitLn "(lean_io_mk_world());"; emitLn "if (lean_io_result_is_error(res)) return res;"; emitLn "lean_dec_ref(res);" } else when (d.params.size == 0) $ match getInitFnNameFor env d.name with | some initFn => do { emit "res = "; emitCName initFn; emitLn "(lean_io_mk_world());"; emitLn "if (lean_io_result_is_error(res)) return res;"; emitCName n; emitLn " = lean_io_result_get_value(res);"; emitMarkPersistent d n; emitLn "lean_dec_ref(res);" } | _ => do { emitCName n; emit " = "; emitCInitName n; emitLn "();"; emitMarkPersistent d n } def emitInitFn : M Unit := do env ← getEnv; modName ← getModName; env.imports.forM $ fun imp => emitLn ("lean_object* initialize_" ++ imp.module.mangle "" ++ "(lean_object*);"); emitLns [ "static bool _G_initialized = false;", "lean_object* initialize_" ++ modName.mangle "" ++ "(lean_object* w) {", "lean_object * res;", "if (_G_initialized) return lean_mk_io_result(lean_box(0));", "_G_initialized = true;" ]; env.imports.forM $ fun imp => emitLns [ "res = initialize_" ++ imp.module.mangle "" ++ "(lean_io_mk_world());", "if (lean_io_result_is_error(res)) return res;", "lean_dec_ref(res);"]; let decls := getDecls env; decls.reverse.forM emitDeclInit; emitLns ["return lean_mk_io_result(lean_box(0));", "}"] def main : M Unit := do emitFileHeader; emitFnDecls; emitFns; emitInitFn; emitMainFnIfNeeded; emitFileFooter end EmitC @[export lean_ir_emit_c] def emitC (env : Environment) (modName : Name) : Except String String := match (EmitC.main { env := env, modName := modName }).run "" with | EStateM.Result.ok _ s => Except.ok s | EStateM.Result.error err _ => Except.error err end IR end Lean
20a0a1bdb63aeb0111053774bcbd50e93bc94e80
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/polynomial/inductions.lean
2c7efa041b9a7195875c6fa5745e020c89089732
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,022
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.finset.intervals 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 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 : polynomial R} /-- `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 : polynomial R) : polynomial R := ∑ 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, Ico.mem, 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 : polynomial R) : 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 cases n; simp [div_X, coeff_C]; simp [coeff] lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) := ⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p, λ h, by rw [h, div_X_C]⟩ lemma div_X_add : div_X (p + q) = div_X p + div_X q := ext $ by simp 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 : polynomial R) : degree_X.symm ... ≤ degree (div_X p * X) : by rw [← zero_add (degree X), degree_mul' this]; exact add_le_add (by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff]; exact λ h0, h (h0.symm ▸ degree_C_le)) (le_refl _), by rw [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 : polynomial R → Sort*} : Π (p : polynomial R), M 0 → (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) → (Π p, p ≠ 0 → M p → M (p * X)) → M p | p := λ M0 MC MX, if hp : p = 0 then eq.rec_on hp.symm M0 else have wf : degree (div_X p) < degree p, from degree_div_X_lt hp, by rw [← div_X_mul_X_add p] at *; exact if hcp0 : coeff p 0 = 0 then by rw [hcp0, C_0, add_zero]; exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp) (rec_on_horner _ M0 MC MX) else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0 then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0 else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX)) using_well_founded {dec_tac := tactic.assumption} /-- 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 : polynomial R → Prop} (p : polynomial R) (h0 : 0 < degree p) (hC : ∀ {a}, a ≠ 0 → P (C a * X)) (hX : ∀ {p}, 0 < degree p → P p → P (p * X)) (hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p := rec_on_horner p (λ h, by rw degree_zero at h; exact absurd h dec_trivial) (λ p a _ _ ih h0, have 0 < degree p, from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $ by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0), hadd this (ih this)) (λ p _ ih h0', if h0 : 0 < degree p then hX h0 (ih h0) else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *; exact hC (λ h : coeff p 0 = 0, by simpa [h, nat.not_lt_zero] using h0')) h0 end semiring end polynomial
ce59449589f6b8fe00af2e50eeb6394c6ac41dcf
798dd332c1ad790518589a09bc82459fb12e5156
/order/basic.lean
4285fadf9a9ad118d561a9e0c50f76d53e8774c8
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,242
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import tactic.interactive logic.basic data.sum data.set.basic algebra.order open function /- TODO: automatic construction of dual definitions / theorems -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b := λ h, h ▸ le_refl a /- Convert algebraic structure style to explicit relation style typeclasses -/ instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩ instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩ instance [preorder α] : is_preorder α (≤) := {} instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩ instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩ instance [preorder α] : is_strict_order α (<) := {} instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩ instance [partial_order α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩ instance [partial_order α] : is_partial_order α (≤) := {} instance [linear_order α] : is_total α (≤) := ⟨le_total⟩ instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := {} instance [linear_order α] : is_linear_order α (≤) := {} instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩ theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin resetI, cases A, cases B, congr, { funext x y, exact propext (H x y) }, { funext x y, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] }, end theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := preorder.ext H; cases A; cases B; injection this; congr' theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := partial_order.ext H; cases A; cases B; injection this; congr' section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b theorem monotone_comp {f : α → β} {g : β → γ} (m_f : monotone f) (m_g : monotone g) : monotone (g ∘ f) := assume a b h, m_g (m_f h) end monotone def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, le_trans hbc hab, .. order_dual.has_le α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, .. order_dual.partial_order α } end order_dual /- order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] [preorder γ] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone def preorder.lift {α β} [preorder β] (f : α → β) : preorder α := { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans } def partial_order.lift {α β} [partial_order β] (f : α → β) (antisymm : ∀x y, f x ≤ f y → f y ≤ f x → x = y) : partial_order α := { le_antisymm := antisymm, ..preorder.lift f } def linear_order.lift {α β} [linear_order β] (f : α → β) (antisymm : ∀x y, f x ≤ f y → f y ≤ f x → x = y) : linear_order α := { le_total := λx y, le_total (f x) (f y), .. partial_order.lift f antisymm } /- additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}(h : ∀a₃<a₁, a₂ ≥ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ section variables {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} theorem is_irrefl_of_is_asymm [is_asymm α r] : is_irrefl α r := ⟨λ a h, asymm h h⟩ theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨@irrefl α r _⟩ theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) := ⟨λ a b c h₁ h₂, (trans h₂ h₁ : r c a)⟩ theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) := {..is_irrefl.swap r, ..is_trans.swap r} /-- Construct a partial order from a `is_strict_order` relation -/ def partial_order_of_SO (r) [is_strict_order α r] : partial_order α := { le := λ x y, x = y ∨ r x y, lt := r, le_refl := λ x, or.inl rfl, le_trans := λ x y z h₁ h₂, match y, z, h₁, h₂ with | _, _, or.inl rfl, h₂ := h₂ | _, _, h₁, or.inl rfl := h₁ | _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂) end, le_antisymm := λ x y h₁ h₂, match y, h₁, h₂ with | _, or.inl rfl, h₂ := rfl | _, h₁, or.inl rfl := rfl | _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim end, lt_iff_le_not_le := λ x y, ⟨λ h, ⟨or.inr h, not_or (λ e, by rw e at h; exact irrefl _ h) (asymm h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ } /-- This is basically the same as `is_strict_total_order`, but that definition is in Type (probably by mistake) and also has redundant assumptions. -/ @[algebra] class is_strict_total_order' (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_order α lt : Prop. /-- Construct a linear order from a `is_strict_total_order'` relation -/ def linear_order_of_STO' (r) [is_strict_total_order' α r] : linear_order α := { le_total := λ x y, match y, trichotomous_of r x y with | y, or.inl h := or.inl (or.inr h) | _, or.inr (or.inl rfl) := or.inl (or.inl rfl) | _, or.inr (or.inr h) := or.inr (or.inr h) end, ..partial_order_of_SO r } /-- Construct a decidable linear order from a `is_strict_total_order'` relation -/ def decidable_linear_order_of_STO' (r) [is_strict_total_order' α r] [decidable_rel r] : decidable_linear_order α := by letI LO := linear_order_of_STO' r; exact { decidable_le := λ x y, decidable_of_iff (¬ r y x) (@not_lt _ _ y x), ..LO } noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α := { decidable_le := classical.dec_rel _, ..LO } theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) := ⟨λ a b, by simpa [swap, or_comm, or.left_comm] using @trichotomous _ r _ a b⟩ theorem is_strict_total_order'.swap (r) [is_strict_total_order' α r] : is_strict_total_order' α (swap r) := {..is_trichotomous.swap r, ..is_strict_order.swap r} instance [linear_order α] : is_strict_total_order' α (<) := {} /-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`. This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on the constructive reals, and is also known as negative transitivity, since the contrapositive asserts transitivity of the relation `¬ a < b`. -/ @[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop := (conn : ∀ a b c, lt a c → lt a b ∨ lt b c) theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r] {a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c := mt (is_order_connected.conn a b c) $ by simp [h₁, h₂] theorem is_strict_weak_order_of_is_order_connected [is_asymm α r] [is_order_connected α r] : is_strict_weak_order α r := { trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂), incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩, ⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩, ..@is_irrefl_of_is_asymm α r _ } instance is_order_connected_of_is_strict_total_order' [is_strict_total_order' α r] : is_order_connected α r := ⟨λ a b c h, (trichotomous _ _).imp_right (λ o, o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩ instance is_strict_total_order_of_is_strict_total_order' [is_strict_total_order' α r] : is_strict_total_order α r := {..is_strict_weak_order_of_is_order_connected} instance [linear_order α] : is_strict_total_order α (<) := by apply_instance instance [linear_order α] : is_order_connected α (<) := by apply_instance instance [linear_order α] : is_incomp_trans α (<) := by apply_instance instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance /-- An extensional relation is one in which an element is determined by its set of predecessors. It is named for the `x ∈ y` relation in set theory, whose extensionality is one of the first axioms of ZFC. -/ @[algebra] class is_extensional (α : Type u) (r : α → α → Prop) : Prop := (ext : ∀ a b, (∀ x, r x a ↔ r x b) → a = b) instance is_extensional_of_is_strict_total_order' [is_strict_total_order' α r] : is_extensional α r := ⟨λ a b H, ((@trichotomous _ r _ a b) .resolve_left $ mt (H _).2 (irrefl a)) .resolve_right $ mt (H _).1 (irrefl b)⟩ /-- A well order is a well-founded linear order. -/ @[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_strict_total_order' α r : Prop := (wf : well_founded r) instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation := { trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim _ _, irrefl := λ a, id, trans := λ a b c, false.elim, wf := ⟨λ a, ⟨_, λ y, false.elim⟩⟩ } instance nat.lt.is_well_order : is_well_order ℕ (<) := ⟨nat.lt_wf⟩ instance sum.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) := { trichotomous := λ a b, by cases a; cases b; simp; apply trichotomous, irrefl := λ a, by cases a; simp; apply irrefl, trans := λ a b c, by cases a; cases b; simp; cases c; simp; apply trans, wf := sum.lex_wf (is_well_order.wf r) (is_well_order.wf s) } instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) := { trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, match @trichotomous _ r _ a₁ b₁ with | or.inl h₁ := or.inl $ prod.lex.left _ _ _ h₁ | or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ _ h₁ | or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with | or.inl h := or.inl $ prod.lex.right _ _ h | or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ _ h | or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl end end, irrefl := λ ⟨a₁, a₂⟩ h, by cases h with _ _ _ _ h _ _ _ h; [exact irrefl _ h, exact irrefl _ h], trans := λ a b c h₁ h₂, begin cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab; cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc, { exact prod.lex.left _ _ _ (trans ab bc) }, { exact prod.lex.left _ _ _ ab }, { exact prod.lex.left _ _ _ bc }, { exact prod.lex.right _ _ (trans ab bc) } end, wf := prod.lex_wf (is_well_order.wf r) (is_well_order.wf s) } theorem well_founded.has_min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) : p ≠ ∅ → ∃ a ∈ p, ∀ x ∈ p, ¬ r x a := by haveI := classical.prop_decidable; exact not_imp_comm.1 (λ he, set.eq_empty_iff_forall_not_mem.2 $ λ a, acc.rec_on (H.apply a) $ λ a H IH h, he ⟨_, h, λ y, imp_not_comm.1 (IH y)⟩) /-- The minimum element of a nonempty set in a well-founded order -/ noncomputable def well_founded.min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) : α := classical.some (H.has_min p h) theorem well_founded.min_mem {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) : H.min p h ∈ p := let ⟨h, _⟩ := classical.some_spec (H.has_min p h) in h theorem well_founded.not_lt_min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) {x} (xp : x ∈ p) : ¬ r x (H.min p h) := let ⟨_, h'⟩ := classical.some_spec (H.has_min p h) in h' _ xp end
f021a6bc33dd35a48850ad1e3c8c0a315f51dea3
abd85493667895c57a7507870867b28124b3998f
/src/ring_theory/power_series.lean
e2b148ad2d6f9dd731dc7d92853f86bfdb5fa451
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
57,819
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.mv_polynomial import ring_theory.ideal_operations import tactic.linarith /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as φ, for all m ≤ n, and 0 otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `le_order_add`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `α` as mv_power_series σ α := (σ →₀ ℕ) → α. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as power_series α := mv_power_series unit α. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by (unit →₀ ℕ), which is of course canonically isomorphic to ℕ. We then build some glue to treat formal power series as if they are indexed by ℕ. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical /-- Multivariate formal power series, where `σ` is the index set of the variables and `α` is the coefficient ring.-/ def mv_power_series (σ : Type*) (α : Type*) := (σ →₀ ℕ) → α namespace mv_power_series open finsupp variables {σ : Type*} {α : Type*} instance [inhabited α] : inhabited (mv_power_series σ α) := ⟨λ _, default _⟩ instance [has_zero α] : has_zero (mv_power_series σ α) := pi.has_zero instance [add_monoid α] : add_monoid (mv_power_series σ α) := pi.add_monoid instance [add_group α] : add_group (mv_power_series σ α) := pi.add_group instance [add_comm_monoid α] : add_comm_monoid (mv_power_series σ α) := pi.add_comm_monoid instance [add_comm_group α] : add_comm_group (mv_power_series σ α) := pi.add_comm_group section add_monoid variables [add_monoid α] variables (α) /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : α →+ mv_power_series σ α := { to_fun := λ a m, if m = n then a else 0, map_zero' := funext $ λ m, by { split_ifs; refl }, map_add' := λ a b, funext $ λ m, show (if m = n then a + b else 0) = (if m = n then a else 0) + (if m = n then b else 0), from if h : m = n then by simp only [if_pos h] else by simp only [if_neg h, add_zero] } /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ α) →+ α := { to_fun := λ φ, φ n, map_zero' := rfl, map_add' := λ _ _, rfl } variables {α} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ α} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) := ⟨λ h n, congr_arg (coeff α n) h, ext⟩ lemma coeff_monomial (m n : σ →₀ ℕ) (a : α) : coeff α m (monomial α n a) = if m = n then a else 0 := rfl @[simp] lemma coeff_monomial' (n : σ →₀ ℕ) (a : α) : coeff α n (monomial α n a) = a := if_pos rfl @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff α n).comp (monomial α n) = add_monoid_hom.id α := add_monoid_hom.ext $ coeff_monomial' n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff α n (0 : mv_power_series σ α) = 0 := rfl end add_monoid section semiring variables [semiring α] (n : σ →₀ ℕ) (φ ψ : mv_power_series σ α) instance : has_one (mv_power_series σ α) := ⟨monomial α (0 : σ →₀ ℕ) 1⟩ lemma coeff_one : coeff α n (1 : mv_power_series σ α) = if n = 0 then 1 else 0 := rfl lemma coeff_zero_one : coeff α (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial' 0 1 instance : has_mul (mv_power_series σ α) := ⟨λ φ ψ n, (finsupp.antidiagonal n).support.sum (λ p, φ p.1 * ψ p.2)⟩ lemma coeff_mul : coeff α n (φ * ψ) = (finsupp.antidiagonal n).support.sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) := rfl protected lemma zero_mul : (0 : mv_power_series σ α) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] protected lemma one_mul : (1 : mv_power_series σ α) * φ = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single ((0 : σ →₀ ℕ), n)]; simp [mem_antidiagonal_support, coeff_one], show ∀ (i j : σ →₀ ℕ), i + j = n → (i = 0 → j ≠ n) → (if i = 0 then coeff α j φ else 0) = 0, intros i j hij h, rw [if_neg], contrapose! h, simpa [h] using hij, end protected lemma mul_one : φ * 1 = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single (n, (0 : σ →₀ ℕ))], rotate, { rintros ⟨i, j⟩ hij h, rw [coeff_one, if_neg, mul_zero], rw mem_antidiagonal_support at hij, contrapose! h, simpa [h] using hij }, all_goals { simp [mem_antidiagonal_support, coeff_one] } end protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ α) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ α) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ α) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := ext $ λ n, begin simp only [coeff_mul], have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support (λ p, (antidiagonal (p.1)).support) (λ x, coeff α x.2.1 φ₁ * coeff α x.2.2 φ₂ * coeff α x.1.2 φ₃), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, exact finset.sum_mul }, have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support (λ p, (antidiagonal (p.2)).support) (λ x, coeff α x.1.1 φ₁ * (coeff α x.2.1 φ₂ * coeff α x.2.2 φ₃)), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, rw finset.mul_sum }, apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l+j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_antidiagonal_support, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i+k, l), (i, k)⟩, _, _⟩; { simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish } } end instance : semiring (mv_power_series σ α) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.has_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring α] : comm_semiring (mv_power_series σ α) := { mul_comm := λ φ ψ, ext $ λ n, finset.sum_bij (λ p hp, p.swap) (λ p hp, swap_mem_antidiagonal_support hp) (λ p hp, mul_comm _ _) (λ p q hp hq H, by simpa using congr_arg prod.swap H) (λ p hp, ⟨p.swap, swap_mem_antidiagonal_support hp, p.swap_swap.symm⟩), .. mv_power_series.semiring } instance [ring α] : ring (mv_power_series σ α) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring α] : comm_ring (mv_power_series σ α) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring α] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : α) : monomial α m a * monomial α n b = monomial α (m + n) (a * b) := begin ext k, rw [coeff_mul, coeff_monomial], split_ifs with h, { rw [h, finset.sum_eq_single (m,n)], { rw [coeff_monomial', coeff_monomial'] }, { rintros ⟨i,j⟩ hij hne, rw [ne.def, prod.mk.inj_iff, not_and] at hne, by_cases H : i = m, { rw [coeff_monomial j n b, if_neg (hne H), mul_zero] }, { rw [coeff_monomial, if_neg H, zero_mul] } }, { intro H, rw finsupp.mem_antidiagonal_support at H, exfalso, exact H rfl } }, { rw [finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, by_cases H : i = m, { subst i, have : j ≠ n, { rintro rfl, exact h hij.symm }, { rw [coeff_monomial j n b, if_neg this, mul_zero] } }, { rw [coeff_monomial, if_neg H, zero_mul] } } end variables (σ) (α) /-- The constant multivariate formal power series.-/ def C : α →+* mv_power_series σ α := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, .. monomial α (0 : σ →₀ ℕ) } variables {σ} {α} @[simp] lemma monomial_zero_eq_C : monomial α (0 : σ →₀ ℕ) = C σ α := rfl lemma monomial_zero_eq_C_apply (a : α) : monomial α (0 : σ →₀ ℕ) a = C σ α a := rfl lemma coeff_C (n : σ →₀ ℕ) (a : α) : coeff α n (C σ α a) = if n = 0 then a else 0 := rfl lemma coeff_zero_C (a : α) : coeff α (0 : σ →₀ℕ) (C σ α a) = a := coeff_monomial' 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ α := monomial α (single s 1) 1 lemma coeff_X (n : σ →₀ ℕ) (s : σ) : coeff α n (X s : mv_power_series σ α) = if n = (single s 1) then 1 else 0 := rfl lemma coeff_index_single_X (s t : σ) : coeff α (single t 1) (X s : mv_power_series σ α) = if t = s then 1 else 0 := by { simp only [coeff_X, single_left_inj one_ne_zero], split_ifs; refl } @[simp] lemma coeff_index_single_self_X (s : σ) : coeff α (single s 1) (X s : mv_power_series σ α) = 1 := if_pos rfl lemma coeff_zero_X (s : σ) : coeff α (0 : σ →₀ ℕ) (X s : mv_power_series σ α) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma X_def (s : σ) : X s = monomial α (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ α)^n = monomial α (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero], refl }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff α m ((X s : mv_power_series σ α)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] @[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ α) (a : α) : coeff α n (φ * (C σ α a)) = (coeff α n φ) * a := begin rw [coeff_mul n φ], rw [finset.sum_eq_single (n,(0 : σ →₀ ℕ))], { rw [coeff_C, if_pos rfl] }, { rintro ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, by_cases hj : j = 0, { subst hj, simp at *, contradiction }, { rw [coeff_C, if_neg hj, mul_zero] } }, { intro h, exfalso, apply h, rw finsupp.mem_antidiagonal_support, apply add_zero } end lemma coeff_zero_mul_X (φ : mv_power_series σ α) (s : σ) : coeff α (0 : σ →₀ ℕ) (φ * X s) = 0 := begin rw [coeff_mul _ φ, finset.sum_eq_zero], rintro ⟨i,j⟩ hij, obtain ⟨rfl, rfl⟩ : i = 0 ∧ j = 0, { rw finsupp.mem_antidiagonal_support at hij, simpa using hij }, simp [coeff_zero_X] end variables (σ) (α) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ α) →+* α := { to_fun := coeff α (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], .. coeff α (0 : σ →₀ ℕ) } variables {σ} {α} @[simp] lemma coeff_zero_eq_constant_coeff : coeff α (0 : σ →₀ ℕ) = constant_coeff σ α := rfl lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ α) : coeff α (0 : σ →₀ ℕ) φ = constant_coeff σ α φ := rfl @[simp] lemma constant_coeff_C (a : α) : constant_coeff σ α (C σ α a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ α).comp (C σ α) = ring_hom.id α := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ α 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ α 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ α (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ α) (h : is_unit φ) : is_unit (constant_coeff σ α φ) := h.map' (constant_coeff σ α) instance : semimodule α (mv_power_series σ α) := { smul := λ a φ, C σ α a * φ, one_smul := λ φ, one_mul _, mul_smul := λ a b φ, by simp [ring_hom.map_mul, mul_assoc], smul_add := λ a φ ψ, mul_add _ _ _, smul_zero := λ a, mul_zero _, add_smul := λ a b φ, by simp only [ring_hom.map_add, add_mul], zero_smul := λ φ, by simp only [zero_mul, ring_hom.map_zero] } end semiring instance [ring α] : module α (mv_power_series σ α) := { ..mv_power_series.semimodule } instance [comm_ring α] : algebra α (mv_power_series σ α) := { commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, rfl, .. C σ α, .. mv_power_series.module } section map variables {β : Type*} {γ : Type*} [semiring α] [semiring β] [semiring γ] variables (f : α →+* β) (g : β →+* γ) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ α →+* mv_power_series σ β := { to_fun := λ φ n, f $ coeff α n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff α n) 1) = (coeff β n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff α n) (φ + ψ)) = f ((coeff α n) φ) + f ((coeff α n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, ← finset.sum_hom _ f, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id α) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ α) : coeff β n (map σ f φ) = f (coeff α n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ α) : constant_coeff σ β (map σ f φ) = f (constant_coeff σ α φ) := rfl end map section trunc variables [comm_semiring α] (n : σ →₀ ℕ) -- Auxiliary definition for the truncation function. def trunc_fun (φ : mv_power_series σ α) : mv_polynomial σ α := { support := (n.antidiagonal.support.image prod.fst).filter (λ m, coeff α m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff α m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ finset.image prod.fst ((antidiagonal n).support) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩ s, rw finsupp.mem_antidiagonal_support at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finsupp.mem_antidiagonal_support, ext s, exact nat.add_sub_of_le (h s) } end } variable (α) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ α →+ mv_polynomial σ α := { to_fun := trunc_fun n, map_zero' := mv_polynomial.ext _ _ $ λ m, by { change ite _ _ _ = _, split_ifs; refl }, map_add' := λ φ ψ, mv_polynomial.ext _ _ $ λ m, begin rw mv_polynomial.coeff_add, change ite _ _ _ = ite _ _ _ + ite _ _ _, split_ifs with H, {refl}, {rw [zero_add]} end } variable {α} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ α) : mv_polynomial.coeff m (trunc α n φ) = if m ≤ n then coeff α m φ else 0 := rfl @[simp] lemma trunc_one : trunc α n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, erw mv_polynomial.coeff_C 0, simp }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg (ne.elim (ne.symm H')), }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg _, intro H', apply H, subst m, intro s, exact nat.zero_le _ } end @[simp] lemma trunc_C (a : α) : trunc α n (C σ α a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, intro s, exact nat.zero_le _ end end trunc section comm_semiring variable [comm_semiring α] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ α} : (X s : mv_power_series σ α)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff α m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal_support at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff α (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff α m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.nat_sub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal_support, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext, simp, cc }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using nat.sub_add_cancel H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ α} : (X s : mv_power_series σ α) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff α m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ α), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end comm_semiring section ring variables [ring α] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : α) (φ : mv_power_series σ α) : mv_power_series σ α | n := if n = 0 then a else - a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if h : x.2 < n then coeff α x.1 φ * inv.aux x.2 else 0) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux (n : σ →₀ ℕ) (a : α) (φ : mv_power_series σ α) : coeff α n (inv.aux a φ) = if n = 0 then a else - a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) := show inv.aux a φ n = _, by { rw inv.aux, refl } /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ α) (u : units α) : mv_power_series σ α := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit (n : σ →₀ ℕ) (φ : mv_power_series σ α) (u : units α) : coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ α) (u : units α) : constant_coeff σ α (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal.support, { rw [finsupp.mem_antidiagonal_support, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal_support] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring α] /-- Multivariate formal power series over a local ring form a local ring.-/ lemma is_local_ring (h : is_local_ring α) : is_local_ring (mv_power_series σ α) := begin split, { have H : (0:α) ≠ 1 := ‹is_local_ring α›.1, contrapose! H, simpa using congr_arg (constant_coeff σ α) H }, { intro φ, rcases ‹is_local_ring α›.2 (constant_coeff σ α φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _), simpa using h.symm } } end -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section nonzero variables [semiring α] [nonzero α] instance : nonzero (mv_power_series σ α) := { zero_ne_one := assume h, zero_ne_one $ show (0:α) = 1, from congr_arg (constant_coeff σ α) h } lemma X_inj {s t : σ} : (X s : mv_power_series σ α) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff α (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end nonzero section local_ring variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f] instance : local_ring (mv_power_series σ α) := local_of_is_local_ring $ is_local_ring ⟨zero_ne_one, local_ring.is_local⟩ instance map.is_local_ring_hom : is_local_ring_hom (map σ f) := ⟨begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ β) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ β ↑ψ) := @is_unit_constant_coeff σ β _ (↑ψ) (is_unit_unit ψ), rw h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm) end⟩ end local_ring section field variables [field α] protected def inv (φ : mv_power_series σ α) : mv_power_series σ α := inv.aux (constant_coeff σ α φ)⁻¹ φ instance : has_inv (mv_power_series σ α) := ⟨mv_power_series.inv⟩ lemma coeff_inv (n : σ →₀ ℕ) (φ : mv_power_series σ α) : coeff α n (φ⁻¹) = if n = 0 then (constant_coeff σ α φ)⁻¹ else - (constant_coeff σ α φ)⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ α) : constant_coeff σ α (φ⁻¹) = (constant_coeff σ α φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ α} : φ⁻¹ = 0 ↔ constant_coeff σ α φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ α) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.coe_ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv h] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {α : Type*} [comm_semiring α] /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ α) (mv_power_series σ α) := ⟨λ φ n, coeff n φ⟩ @[simp, norm_cast] lemma coeff_coe (φ : mv_polynomial σ α) (n : σ →₀ ℕ) : mv_power_series.coeff α n ↑φ = coeff n φ := rfl @[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : α) : (monomial n a : mv_power_series σ α) = mv_power_series.monomial α n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ α) : mv_power_series σ α) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ α) : mv_power_series σ α) = 1 := coe_monomial _ _ @[simp, norm_cast] lemma coe_add (φ ψ : mv_polynomial σ α) : ((φ + ψ : mv_polynomial σ α) : mv_power_series σ α) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul (φ ψ : mv_polynomial σ α) : ((φ * ψ : mv_polynomial σ α) : mv_power_series σ α) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : α) : ((C a : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.C σ α a := coe_monomial _ _ @[simp, norm_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.X s := coe_monomial _ _ namespace coe_to_mv_power_series instance : is_semiring_hom (coe : mv_polynomial σ α → mv_power_series σ α) := { map_zero := coe_zero, map_one := coe_one, map_add := coe_add, map_mul := coe_mul } end coe_to_mv_power_series end mv_polynomial /-- Formal power series over the coefficient ring `α`.-/ def power_series (α : Type*) := mv_power_series unit α namespace power_series open finsupp (single) variable {α : Type*} instance [inhabited α] : inhabited (power_series α) := by delta power_series; apply_instance instance [add_monoid α] : add_monoid (power_series α) := by delta power_series; apply_instance instance [add_group α] : add_group (power_series α) := by delta power_series; apply_instance instance [add_comm_monoid α] : add_comm_monoid (power_series α) := by delta power_series; apply_instance instance [add_comm_group α] : add_comm_group (power_series α) := by delta power_series; apply_instance instance [semiring α] : semiring (power_series α) := by delta power_series; apply_instance instance [comm_semiring α] : comm_semiring (power_series α) := by delta power_series; apply_instance instance [ring α] : ring (power_series α) := by delta power_series; apply_instance instance [comm_ring α] : comm_ring (power_series α) := by delta power_series; apply_instance instance [semiring α] [nonzero α] : nonzero (power_series α) := by delta power_series; apply_instance instance [semiring α] : semimodule α (power_series α) := by delta power_series; apply_instance instance [ring α] : module α (power_series α) := by delta power_series; apply_instance instance [comm_ring α] : algebra α (power_series α) := by delta power_series; apply_instance section add_monoid variables (α) [add_monoid α] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series α →+ α := mv_power_series.coeff α (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : α →+ power_series α := mv_power_series.monomial α (single () n) variables {α} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff α n = mv_power_series.coeff α s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series α} (h : ∀ n, coeff α n φ = coeff α n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series α} : φ = ψ ↔ (∀ n, coeff α n φ = coeff α n ψ) := ⟨λ h n, congr_arg (coeff α n) h, ext⟩ /-- Constructor for formal power series.-/ def mk {α} (f : ℕ → α) : power_series α := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → α) : coeff α n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : α) : coeff α m (monomial α n a) = if m = n then a else 0 := calc coeff α m (monomial α n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl } lemma monomial_eq_mk (n : ℕ) (a : α) : monomial α n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial' (n : ℕ) (a : α) : coeff α n (monomial α n a) = a := by convert if_pos rfl @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff α n).comp (monomial α n) = add_monoid_hom.id α := add_monoid_hom.ext $ coeff_monomial' n end add_monoid section semiring variable [semiring α] variable (α) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series α →+* α := mv_power_series.constant_coeff unit α /-- The constant formal power series.-/ def C : α →+* power_series α := mv_power_series.C unit α variable {α} /-- The variable of the formal power series ring.-/ def X : power_series α := mv_power_series.X () @[simp] lemma coeff_zero_eq_constant_coeff : coeff α 0 = constant_coeff α := begin rw [constant_coeff, ← mv_power_series.coeff_zero_eq_constant_coeff, coeff_def], refl end lemma coeff_zero_eq_constant_coeff_apply (φ : power_series α) : coeff α 0 φ = constant_coeff α φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : monomial α 0 = C α := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] lemma monomial_zero_eq_C_apply (a : α) : monomial α 0 a = C α a := by simp lemma coeff_C (n : ℕ) (a : α) : coeff α n (C α a : power_series α) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] lemma coeff_zero_C (a : α) : coeff α 0 (C α a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial' 0 a] lemma X_eq : (X : power_series α) = monomial α 1 1 := rfl lemma coeff_X (n : ℕ) : coeff α n (X : power_series α) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] lemma coeff_zero_X : coeff α 0 (X : power_series α) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff α 1 (X : power_series α) = 1 := by rw [coeff_X, if_pos rfl] lemma X_pow_eq (n : ℕ) : (X : power_series α)^n = monomial α n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff α m ((X : power_series α)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff α n ((X : power_series α)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff α n (1 : power_series α) = if n = 0 then 1 else 0 := calc coeff α n (1 : power_series α) = _ : mv_power_series.coeff_one _ ... = if n = 0 then 1 else 0 : by { simp only [finsupp.single_eq_zero], split_ifs; refl } lemma coeff_zero_one : coeff α 0 (1 : power_series α) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series α) : coeff α n (φ * ψ) = (finset.nat.antidiagonal n).sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series α) (a : α) : coeff α n (φ * (C α a)) = (coeff α n φ) * a := mv_power_series.coeff_mul_C _ φ a @[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series α) : coeff α (n+1) (φ * X) = coeff α n φ := begin rw [coeff_mul _ φ, finset.sum_eq_single (n,1)], { rw [coeff_X, if_pos rfl, mul_one] }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j = 1, { subst hj, simp at *, contradiction }, { simp [coeff_X, hj] } }, { intro h, exfalso, apply h, simp }, end @[simp] lemma constant_coeff_C (a : α) : constant_coeff α (C α a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff α).comp (C α) = ring_hom.id α := rfl @[simp] lemma constant_coeff_zero : constant_coeff α 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff α 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff α X = 0 := mv_power_series.coeff_zero_X _ lemma coeff_zero_mul_X (φ : power_series α) : coeff α 0 (φ * X) = 0 := by simp /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series α) (h : is_unit φ) : is_unit (constant_coeff α φ) := mv_power_series.is_unit_constant_coeff φ h section map variables {β : Type*} {γ : Type*} [semiring β] [semiring γ] variables (f : α →+* β) (g : β →+* γ) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series α →+* power_series β := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id α) : power_series α → power_series α) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series α) : coeff β n (map f φ) = f (coeff α n φ) := rfl end map end semiring section comm_semiring variables [comm_semiring α] lemma X_pow_dvd_iff {n : ℕ} {φ : power_series α} : (X : power_series α)^n ∣ φ ↔ ∀ m, m < n → coeff α m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit α _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series α} : (X : power_series α) ∣ φ ↔ constant_coeff α φ = 0 := begin rw [← pow_one (X : power_series α), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series α) : polynomial α := { support := ((finset.nat.antidiagonal n).image prod.fst).filter (λ m, coeff α m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff α m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ ((finset.nat.antidiagonal n).image prod.fst) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩, rw finset.nat.mem_antidiagonal at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finset.nat.mem_antidiagonal, exact nat.add_sub_of_le h } end } lemma coeff_trunc (m) (n) (φ : power_series α) : polynomial.coeff (trunc n φ) m = if m ≤ n then coeff α m φ else 0 := rfl @[simp] lemma trunc_zero (n) : trunc n (0 : power_series α) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, add_monoid_hom.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc n (1 : power_series α) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, intro H', apply H, subst m, exact nat.zero_le _ } end @[simp] lemma trunc_C (n) (a : α) : trunc n (C α a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series α) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring α] protected def inv.aux : α → power_series α → power_series α := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : α) (φ : power_series α) : coeff α n (inv.aux a φ) = if n = 0 then a else - a * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series α) (u : units α) : power_series α := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series α) (u : units α) : coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series α) (u : units α) : constant_coeff α (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h end ring section integral_domain variable [integral_domain α] lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series α) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw classical.or_iff_not_imp_left, intro H, have ex : ∃ m, coeff α m φ ≠ 0, { contrapose! H, exact ext H }, let P : ℕ → Prop := λ k, coeff α k φ ≠ 0, let m := nat.find ex, have hm₁ : coeff α m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff α k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff α n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff α (m + n)) h, rw [add_monoid_hom.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance : integral_domain (power_series α) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, .. power_series.comm_ring, .. power_series.nonzero } /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series α))).is_prime := begin suffices : ideal.span ({X} : set (power_series α)) = (constant_coeff α).ker, { rw this, exact ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series α) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff α 1) h } end end integral_domain section local_ring variables [comm_ring α] lemma is_local_ring (h : is_local_ring α) : is_local_ring (power_series α) := mv_power_series.is_local_ring h end local_ring section local_ring variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f] instance : local_ring (power_series α) := mv_power_series.local_ring instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f end local_ring section field variables [field α] protected def inv : power_series α → power_series α := mv_power_series.inv instance : has_inv (power_series α) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series α) : φ⁻¹ = inv.aux (constant_coeff α φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series α) : coeff α n (φ⁻¹) = if n = 0 then (constant_coeff α φ)⁻¹ else - (constant_coeff α φ)⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff α φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series α) : constant_coeff α (φ⁻¹) = (constant_coeff α φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series α} : φ⁻¹ = 0 ↔ constant_coeff α φ = 0 := mv_power_series.inv_eq_zero @[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series α) (h : constant_coeff α φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv (φ : power_series α) (h : constant_coeff α φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv φ h @[simp] protected lemma inv_mul (φ : power_series α) (h : constant_coeff α φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul φ h end field end power_series namespace power_series variable {α : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [comm_semiring α] /-- The order of a formal power series `φ` is the smallest `n : enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ @[reducible] def order (φ : power_series α) : enat := multiplicity X φ lemma order_finite_of_coeff_ne_zero (φ : power_series α) (h : ∃ n, coeff α n φ ≠ 0) : (order φ).dom := begin cases h with n h, refine ⟨n, _⟩, rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (φ : power_series α) (h : (order φ).dom) : coeff α (φ.order.get h) φ ≠ 0 := begin have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff, intros m hm, by_cases Hm : m < nat.find h, { have := nat.find_min h Hm, push_neg at this, rw X_pow_dvd_iff at this, exact this m (lt_add_one m) }, have : m = nat.find h, {linarith}, {rwa this} end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (φ : power_series α) (n : ℕ) (h : coeff α n φ ≠ 0) : order φ ≤ n := begin have h : ¬ X^(n+1) ∣ φ, { rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ }, have : (order φ).dom := ⟨n, h⟩, rw [← enat.coe_get this, enat.coe_le_coe], refine nat.find_min' this h end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (φ : power_series α) (n : ℕ) (h: ↑n < order φ) : coeff α n φ = 0 := by { contrapose! h, exact order_le _ _ h } /-- The `0` power series is the unique power series with infinite order.-/ lemma order_eq_top {φ : power_series α} : φ.order = ⊤ ↔ φ = 0 := begin rw multiplicity.eq_top_iff, split, { intro h, ext n, specialize h (n+1), rw X_pow_dvd_iff at h, exact h n (lt_add_one _) }, { rintros rfl n, exact dvd_zero _ } end /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series α) = ⊤ := multiplicity.zero _ /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma nat_le_order (φ : power_series α) (n : ℕ) (h : ∀ i < n, coeff α i φ = 0) : ↑n ≤ order φ := begin by_contra H, rw not_le at H, have : (order φ).dom := enat.dom_of_le_some (le_of_lt H), rw [← enat.coe_get this, enat.coe_lt_coe] at H, exact coeff_order _ this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma le_order (φ : power_series α) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff α i φ = 0) : n ≤ order φ := begin induction n using enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (enat.coe_lt_top i) }, { apply nat_le_order, simpa only [enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series α} {n : ℕ} : order φ = n ↔ (coeff α n φ ≠ 0) ∧ (∀ i, i < n → coeff α i φ = 0) := begin simp only [eq_some_iff, X_pow_dvd_iff], push_neg, split, { rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩, suffices : n = m, { rwa this }, suffices : m ≥ n, { linarith }, contrapose! hm₂, exact h₁ _ hm₂ }, { rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series α} {n : enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff α i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff α i φ = 0) := begin induction n using enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } }, { simpa [enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma le_order_add (φ ψ : power_series α) : min (order φ) (order ψ) ≤ order (φ + ψ) := multiplicity.min_le_multiplicity_add private lemma order_add_of_order_eq.aux (φ ψ : power_series α) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi, coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series α) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (le_order_add _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series α) : order φ + order ψ ≤ order (φ * ψ) := begin apply le_order, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order φ i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order ψ j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add' hi hj), rw [← enat.coe_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : α) : order (monomial α n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, add_monoid_hom.map_zero] }, { rw [order_eq], split; intros i hi, { rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial'] }, { rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : α) (h : a ≠ 0) : order (monomial α n a) = n := by rw [order_monomial, if_neg h] end order_basic section order_zero_ne_one variables [comm_semiring α] [nonzero α] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series α) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:α) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series α) = 1 := order_monomial_of_ne_zero 1 (1:α) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series α)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_integral_domain variables [integral_domain α] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series α) : order (φ * ψ) = order φ + order ψ := multiplicity.mul (X_prime) end order_integral_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {α : Type*} [comm_semiring α] /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe (polynomial α) (power_series α) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ @[simp, norm_cast] lemma coeff_coe (φ : polynomial α) (n) : power_series.coeff α n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : α) : (monomial n a : power_series α) = power_series.monomial α n a := power_series.ext $ λ m, begin rw [coeff_coe, power_series.coeff_monomial], simp only [@eq_comm _ m n], convert finsupp.single_apply, end @[simp, norm_cast] lemma coe_zero : ((0 : polynomial α) : power_series α) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : polynomial α) : power_series α) = 1 := begin have := coe_monomial 0 (1:α), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_add (φ ψ : polynomial α) : ((φ + ψ : polynomial α) : power_series α) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul (φ ψ : polynomial α) : ((φ * ψ : polynomial α) : power_series α) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : α) : ((C a : polynomial α) : power_series α) = power_series.C α a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_X : ((X : polynomial α) : power_series α) = power_series.X := coe_monomial _ _ namespace coe_to_mv_power_series instance : is_semiring_hom (coe : polynomial α → power_series α) := { map_zero := coe_zero, map_one := coe_one, map_add := coe_add, map_mul := coe_mul } end coe_to_mv_power_series end polynomial
7a343c768b9ddefb3cb5551ae07f92a8fc338a46
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/inductive_type_whnf.lean
941693e32b7a2099de1f756a2441959222d1418b
[ "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
62
lean
def pred (α : Type) := α → Prop inductive foo : pred ℕ
bb89095483bce4b323a3871e9361a94cbda00a4c
65b579fba1b0b66add04cccd4529add645eff597
/lambda/pure/src/parsing.lean
77c2880b1c3695196d1347adeacf747b5651f674
[]
no_license
teodorov/sf_lean
ba637ca8ecc538aece4d02c8442d03ef713485db
cd4832d6bee9c606014c977951f6aebc4c8d611b
refs/heads/master
1,632,890,232,054
1,543,005,745,000
1,543,005,745,000
108,566,115
1
0
null
null
null
null
UTF-8
Lean
false
false
2,775
lean
import data.buffer.parser import .types open parser lambda_types namespace lambda_parser def whitespaces := " \t\n\x0d".to_list def reserved_chars := [' ', '.', 'λ', '(', ')'] def CHAR : parser char := sat (λ c, list.all (reserved_chars ++ whitespaces) (≠ c)) def LF := ch $ char.of_nat 10 def CR := ch $ char.of_nat 13 def NL := CR >> LF <|> LF <|> CR def WS : parser unit := decorate_error "<whitespace>" $ many' $ one_of' whitespaces def Word : parser string := many_char1 CHAR def tok (s: string) := str s >> WS def VarParser : parser term := do name ← Word, pure $ term.var name def AbstractionParser (termParser : parser term) : parser term := do ch 'λ', many WS, names ← sep_by1 WS Word, ch '.', many WS, body ← termParser, pure $ multi_abstraction names body def ApplicationParser (termParser : parser term) : parser term := do function ← termParser, many WS, arguments ← sep_by WS termParser, pure $ currying function arguments def ParenthesisParser (termParser : parser term) : parser term := do termParser <|> (ch '(' >> termParser <* ch ')') def LambdaParserCore (termParser : parser term) : parser term := let term := AbstractionParser (ParenthesisParser termParser) <|> ApplicationParser (ParenthesisParser termParser) <|> VarParser in ParenthesisParser term def LambdaParser := fix LambdaParserCore def LetParser : parser (string × term) := do str "let", many1 WS, name ← Word, many1 WS, str ":=", many WS, body ← LambdaParser, pure (name, body) def Numeral : parser char := sat $ λ c, list.any "0123456789".to_list (= c) def NumberParser := many_char1 Numeral def CommandLineParser : parser repl_command := str ":quit" >> pure repl_command.quit <|> str ":help" >> pure repl_command.help <|> str ":env" >> pure repl_command.env <|> str ":depth" >> WS >> NumberParser >>= (pure ∘ repl_command.depth ∘ string.to_nat) <|> str ":import_depth" >> WS >> NumberParser >>= (pure ∘ repl_command.import_depth ∘ string.to_nat) <|> str ":show_depth" >> pure repl_command.show_depth <|> str ":show_import_depth" >> pure repl_command.show_import_depth <|> str ":clear_env" >> pure repl_command.clear_env <|> str ":load" >> WS >> many_char1 (sat (λ c, list.all (whitespaces) (≠ c))) >>= pure ∘ repl_command.load <|> LetParser >>= (pure ∘ function.uncurry repl_command.bind) <|> LambdaParser >>= (pure ∘ repl_command.term) <|> many WS >> pure repl_command.nothing def CommandParser: parser repl_command := do cmd ← CommandLineParser, optional (str "--" >> optional WS >> many (sat (λ _, tt))), optional $ many WS, pure cmd #eval run CommandLineParser "let pair := x".to_char_buffer end lambda_parser
147ff1cb8b090bb12b0cf5fee1151996b444dbdd
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/convex/jensen.lean
6dad2a1e76a823e7707ded4a4496d3417478b842
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,717
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import analysis.convex.combination import analysis.convex.function /-! # Jensen's inequality and maximum principle for convex functions In this file, we prove the finite Jensen inequality and the finite maximum principle for convex functions. The integral versions are to be found in `analysis.convex.integral`. ## Main declarations Jensen's inequalities: * `convex_on.map_center_mass_le`, `convex_on.map_sum_le`: Convex Jensen's inequality. The image of a convex combination of points under a convex function is less than the convex combination of the images. * `concave_on.le_map_center_mass`, `concave_on.le_map_sum`: Concave Jensen's inequality. As corollaries, we get: * `convex_on.exists_ge_of_mem_convex_hull `: Maximum principle for convex functions. * `concave_on.exists_le_of_mem_convex_hull`: Minimum principle for concave functions. -/ open finset linear_map set open_locale big_operators classical convex pointwise variables {𝕜 E F β ι : Type*} /-! ### Jensen's inequality -/ section jensen variables [linear_ordered_field 𝕜] [add_comm_group E] [ordered_add_comm_group β] [module 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β} {t : finset ι} {w : ι → 𝕜} {p : ι → E} /-- Convex **Jensen's inequality**, `finset.center_mass` version. -/ lemma convex_on.map_center_mass_le (hf : convex_on 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : 0 < ∑ i in t, w i) (hmem : ∀ i ∈ t, p i ∈ s) : f (t.center_mass w p) ≤ t.center_mass w (f ∘ p) := begin have hmem' : ∀ i ∈ t, (p i, (f ∘ p) i) ∈ {p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}, from λ i hi, ⟨hmem i hi, le_rfl⟩, convert (hf.convex_epigraph.center_mass_mem h₀ h₁ hmem').2; simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum], end /-- Concave **Jensen's inequality**, `finset.center_mass` version. -/ lemma concave_on.le_map_center_mass (hf : concave_on 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : 0 < ∑ i in t, w i) (hmem : ∀ i ∈ t, p i ∈ s) : t.center_mass w (f ∘ p) ≤ f (t.center_mass w p) := @convex_on.map_center_mass_le 𝕜 E βᵒᵈ _ _ _ _ _ _ _ _ _ _ _ _ hf h₀ h₁ hmem /-- Convex **Jensen's inequality**, `finset.sum` version. -/ lemma convex_on.map_sum_le (hf : convex_on 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s) : f (∑ i in t, w i • p i) ≤ ∑ i in t, w i • f (p i) := by simpa only [center_mass, h₁, inv_one, one_smul] using hf.map_center_mass_le h₀ (h₁.symm ▸ zero_lt_one) hmem /-- Concave **Jensen's inequality**, `finset.sum` version. -/ lemma concave_on.le_map_sum (hf : concave_on 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s) : ∑ i in t, w i • f (p i) ≤ f (∑ i in t, w i • p i) := @convex_on.map_sum_le 𝕜 E βᵒᵈ _ _ _ _ _ _ _ _ _ _ _ _ hf h₀ h₁ hmem end jensen /-! ### Maximum principle -/ section maximum_principle variables [linear_ordered_field 𝕜] [add_comm_group E] [linear_ordered_add_comm_group β] [module 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β} {t : finset ι} {w : ι → 𝕜} {p : ι → E} {x : E} lemma le_sup_of_mem_convex_hull {s : finset E} (hf : convex_on 𝕜 (convex_hull 𝕜 (s : set E)) f) (hx : x ∈ convex_hull 𝕜 (s : set E)) : f x ≤ s.sup' (coe_nonempty.1 $ convex_hull_nonempty_iff.1 ⟨x, hx⟩) f := begin obtain ⟨w, hw₀, hw₁, rfl⟩ := mem_convex_hull.1 hx, exact (hf.map_center_mass_le hw₀ (by positivity) $ subset_convex_hull _ _).trans (center_mass_le_sup hw₀ $ by positivity), end lemma inf_le_of_mem_convex_hull {s : finset E} (hf : concave_on 𝕜 (convex_hull 𝕜 (s : set E)) f) (hx : x ∈ convex_hull 𝕜 (s : set E)) : s.inf' (coe_nonempty.1 $ convex_hull_nonempty_iff.1 ⟨x, hx⟩) f ≤ f x := le_sup_of_mem_convex_hull hf.dual hx /-- If a function `f` is convex on `s`, then the value it takes at some center of mass of points of `s` is less than the value it takes on one of those points. -/ lemma convex_on.exists_ge_of_center_mass (h : convex_on 𝕜 s f) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : 0 < ∑ i in t, w i) (hp : ∀ i ∈ t, p i ∈ s) : ∃ i ∈ t, f (t.center_mass w p) ≤ f (p i) := begin set y := t.center_mass w p, rsuffices ⟨i, hi, hfi⟩ : ∃ i ∈ t.filter (λ i, w i ≠ 0), w i • f y ≤ w i • (f ∘ p) i, { rw mem_filter at hi, exact ⟨i, hi.1, (smul_le_smul_iff_of_pos $ (hw₀ i hi.1).lt_of_ne hi.2.symm).1 hfi⟩ }, have hw' : (0 : 𝕜) < ∑ i in filter (λ i, w i ≠ 0) t, w i := by rwa sum_filter_ne_zero, refine exists_le_of_sum_le (nonempty_of_sum_ne_zero hw'.ne') _, rw [←sum_smul, ←smul_le_smul_iff_of_pos (inv_pos.2 hw'), inv_smul_smul₀ hw'.ne', ←finset.center_mass, finset.center_mass_filter_ne_zero], exact h.map_center_mass_le hw₀ hw₁ hp, apply_instance, end /-- If a function `f` is concave on `s`, then the value it takes at some center of mass of points of `s` is greater than the value it takes on one of those points. -/ lemma concave_on.exists_le_of_center_mass (h : concave_on 𝕜 s f) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : 0 < ∑ i in t, w i) (hp : ∀ i ∈ t, p i ∈ s) : ∃ i ∈ t, f (p i) ≤ f (t.center_mass w p) := @convex_on.exists_ge_of_center_mass 𝕜 E βᵒᵈ _ _ _ _ _ _ _ _ _ _ _ _ h hw₀ hw₁ hp /-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`, then the eventual maximum of `f` on `convex_hull 𝕜 s` lies in `s`. -/ lemma convex_on.exists_ge_of_mem_convex_hull (hf : convex_on 𝕜 (convex_hull 𝕜 s) f) {x} (hx : x ∈ convex_hull 𝕜 s) : ∃ y ∈ s, f x ≤ f y := begin rw _root_.convex_hull_eq at hx, obtain ⟨α, t, w, p, hw₀, hw₁, hp, rfl⟩ := hx, rcases hf.exists_ge_of_center_mass hw₀ (hw₁.symm ▸ zero_lt_one) (λ i hi, subset_convex_hull 𝕜 s (hp i hi)) with ⟨i, hit, Hi⟩, exact ⟨p i, hp i hit, Hi⟩ end /-- Minimum principle for concave functions. If a function `f` is concave on the convex hull of `s`, then the eventual minimum of `f` on `convex_hull 𝕜 s` lies in `s`. -/ lemma concave_on.exists_le_of_mem_convex_hull (hf : concave_on 𝕜 (convex_hull 𝕜 s) f) {x} (hx : x ∈ convex_hull 𝕜 s) : ∃ y ∈ s, f y ≤ f x := @convex_on.exists_ge_of_mem_convex_hull 𝕜 E βᵒᵈ _ _ _ _ _ _ _ _ hf _ hx end maximum_principle
159e7eaa752ec8004d5f957ec67804fe993e140a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/countable/defs.lean
c24a9c97eab72fa61d942f4f1264111b9c9a53a7
[ "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,534
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.finite.defs /-! # Countable types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define a typeclass saying that a given `Sort*` is countable. See also `encodable` for a version that singles out a specific encoding of elements of `α` by natural numbers. This file also provides a few instances of this typeclass. More instances can be found in other files. -/ open function universes u v variables {α : Sort u} {β : Sort v} /-! ### Definition and basic properties -/ /-- A type `α` is countable if there exists an injective map `α → ℕ`. -/ @[mk_iff countable_iff_exists_injective] class countable (α : Sort u) : Prop := (exists_injective_nat [] : ∃ f : α → ℕ, injective f) instance : countable ℕ := ⟨⟨id, injective_id⟩⟩ export countable (exists_injective_nat) protected lemma function.injective.countable [countable β] {f : α → β} (hf : injective f) : countable α := let ⟨g, hg⟩ := exists_injective_nat β in ⟨⟨g ∘ f, hg.comp hf⟩⟩ protected lemma function.surjective.countable [countable α] {f : α → β} (hf : surjective f) : countable β := (injective_surj_inv hf).countable lemma exists_surjective_nat (α : Sort u) [nonempty α] [countable α] : ∃ f : ℕ → α, surjective f := let ⟨f, hf⟩ := exists_injective_nat α in ⟨inv_fun f, inv_fun_surjective hf⟩ lemma countable_iff_exists_surjective [nonempty α] : countable α ↔ ∃ f : ℕ → α, surjective f := ⟨@exists_surjective_nat _ _, λ ⟨f, hf⟩, hf.countable⟩ lemma countable.of_equiv (α : Sort*) [countable α] (e : α ≃ β) : countable β := e.symm.injective.countable lemma equiv.countable_iff (e : α ≃ β) : countable α ↔ countable β := ⟨λ h, @countable.of_equiv _ _ h e, λ h, @countable.of_equiv _ _ h e.symm⟩ instance {β : Type v} [countable β] : countable (ulift.{u} β) := countable.of_equiv _ equiv.ulift.symm /-! ### Operations on `Sort*`s -/ instance [countable α] : countable (plift α) := equiv.plift.injective.countable @[priority 100] instance subsingleton.to_countable [subsingleton α] : countable α := ⟨⟨λ _, 0, λ x y h, subsingleton.elim x y⟩⟩ @[priority 500] instance [countable α] {p : α → Prop} : countable {x // p x} := subtype.val_injective.countable instance {n : ℕ} : countable (fin n) := function.injective.countable (@fin.eq_of_veq n) @[priority 100] instance finite.to_countable [finite α] : countable α := let ⟨n, ⟨e⟩⟩ := finite.exists_equiv_fin α in countable.of_equiv _ e.symm instance : countable punit.{u} := subsingleton.to_countable -- Since this always succeeds, there is no reason not to have this at normal priority. -- Perhaps the `instance_priority` linter could be clever enough to notice this itself. @[nolint instance_priority] instance Prop.countable (p : Prop) : countable p := subsingleton.to_countable instance bool.countable : countable bool := ⟨⟨λ b, cond b 0 1, bool.injective_iff.2 nat.one_ne_zero⟩⟩ instance Prop.countable' : countable Prop := countable.of_equiv bool equiv.Prop_equiv_bool.symm @[priority 500] instance [countable α] {r : α → α → Prop} : countable (quot r) := (surjective_quot_mk r).countable @[priority 500] instance [countable α] {s : setoid α} : countable (quotient s) := quot.countable
c1997d221e52ef4218f455007b1a1fc08e90d9e6
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/wf.lean
1e6bbcf240233ab6a1e428d4d57b3d6b05c07e3b
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,811
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 -/ prelude import init.data.nat.basic init.data.prod universes u v inductive acc {α : Type u} (r : α → α → Prop) : α → Prop | intro : ∀ x, (∀ y, r y x → acc y) → acc x namespace acc variables {α : Type u} {r : α → α → Prop} def inv {x y : α} (h₁ : acc r x) (h₂ : r y x) : acc r y := acc.rec_on h₁ (λ x₁ ac₁ ih h₂, ac₁ y h₂) h₂ -- dependent elimination for acc attribute [recursor] protected def drec {C : Π (a : α), acc r a → Sort v} (h₁ : Π (x : α) (acx : Π (y : α), r y x → acc r y), (Π (y : α) (ryx : r y x), C y (acx y ryx)) → C x (acc.intro x acx)) {a : α} (h₂ : acc r a) : C a h₂ := acc.rec (λ x acx ih h₂, h₁ x acx (λ y ryx, ih y ryx (acx y ryx))) h₂ h₂ end acc inductive well_founded {α : Type u} (r : α → α → Prop) : Prop | intro : (∀ a, acc r a) → well_founded namespace well_founded def apply {α : Type u} {r : α → α → Prop} (wf : well_founded r) : ∀ a, acc r a := take a, well_founded.rec_on wf (λ p, p) a section parameters {α : Type u} {r : α → α → Prop} local infix `≺`:50 := r hypothesis hwf : well_founded r lemma recursion {C : α → Sort v} (a : α) (h : Π x, (Π y, y ≺ x → C y) → C x) : C a := acc.rec_on (apply hwf a) (λ x₁ ac₁ ih, h x₁ ih) lemma induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, y ≺ x → C y) → C x) : C a := recursion a h variable {C : α → Sort v} variable F : Π x, (Π y, y ≺ x → C y) → C x def fix_F (x : α) (a : acc r x) : C x := acc.rec_on a (λ x₁ ac₁ ih, F x₁ ih) lemma fix_F_eq (x : α) (r : acc r x) : fix_F F x r = F x (λ (y : α) (p : y ≺ x), fix_F F y (acc.inv r p)) := acc.drec (λ x r ih, rfl) r end variables {α : Type u} {C : α → Sort v} {r : α → α → Prop} -- Well-founded fixpoint def fix (hwf : well_founded r) (F : Π x, (Π y, r y x → C y) → C x) (x : α) : C x := fix_F F x (apply hwf x) -- Well-founded fixpoint satisfies fixpoint equation lemma fix_eq (hwf : well_founded r) (F : Π x, (Π y, r y x → C y) → C x) (x : α) : fix hwf F x = F x (λ y h, fix hwf F y) := fix_F_eq F x (apply hwf x) end well_founded open well_founded -- Empty relation is well-founded def empty_wf {α : Type u} : well_founded empty_relation := well_founded.intro (λ (a : α), acc.intro a (λ (b : α) (lt : false), false.rec _ lt)) -- Subrelation of a well-founded relation is well-founded namespace subrelation section parameters {α : Type u} {r Q : α → α → Prop} parameters (h₁ : subrelation Q r) parameters (h₂ : well_founded r) def accessible {a : α} (ac : acc r a) : acc Q a := acc.rec_on ac (λ x ax ih, acc.intro x (λ (y : α) (lt : Q y x), ih y (h₁ lt))) def wf : well_founded Q := ⟨λ a, accessible (apply h₂ a)⟩ end end subrelation -- The inverse image of a well-founded relation is well-founded namespace inv_image section parameters {α : Type u} {β : Type v} {r : β → β → Prop} parameters (f : α → β) parameters (h : well_founded r) private def acc_aux {b : β} (ac : acc r b) : ∀ (x : α), f x = b → acc (inv_image r f) x := acc.rec_on ac (λ x acx ih z e, acc.intro z (λ y lt, eq.rec_on e (λ acx ih, ih (f y) lt y rfl) acx ih)) def accessible {a : α} (ac : acc r (f a)) : acc (inv_image r f) a := acc_aux ac a rfl def wf : well_founded (inv_image r f) := ⟨λ a, accessible (apply h (f a))⟩ end end inv_image -- The transitive closure of a well-founded relation is well-founded namespace tc section parameters {α : Type u} {r : α → α → Prop} local notation `r⁺` := tc r def accessible {z : α} (ac : acc r z) : acc (tc r) z := acc.rec_on ac (λ x acx ih, acc.intro x (λ y rel, tc.rec_on rel (λ a b rab acx ih, ih a rab) (λ a b c rab rbc ih₁ ih₂ acx ih, acc.inv (ih₂ acx ih) rab) acx ih)) def wf (h : well_founded r) : well_founded r⁺ := ⟨λ a, accessible (apply h a)⟩ end end tc -- less-than is well-founded def nat.lt_wf : well_founded nat.lt := ⟨nat.rec (acc.intro 0 (λ n h, absurd h (nat.not_lt_zero n))) (λ n ih, acc.intro (nat.succ n) (λ m h, or.elim (nat.eq_or_lt_of_le (nat.le_of_succ_le_succ h)) (λ e, eq.substr e ih) (acc.inv ih)))⟩ def measure {α : Type u} : (α → ℕ) → α → α → Prop := inv_image lt def measure_wf {α : Type u} (f : α → ℕ) : well_founded (measure f) := inv_image.wf f nat.lt_wf namespace prod open well_founded section variables {α : Type u} {β : Type v} variable (ra : α → α → Prop) variable (rb : β → β → Prop) -- Lexicographical order based on ra and rb inductive lex : α × β → α × β → Prop | left : ∀ {a₁} b₁ {a₂} b₂, ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂) | right : ∀ a {b₁ b₂}, rb b₁ b₂ → lex (a, b₁) (a, b₂) -- relational product based on ra and rb inductive rprod : α × β → α × β → Prop | intro : ∀ {a₁ b₁ a₂ b₂}, ra a₁ a₂ → rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂) end section parameters {α : Type u} {β : Type v} parameters {ra : α → α → Prop} {rb : β → β → Prop} local infix `≺`:50 := lex ra rb def lex_accessible {a} (aca : acc ra a) (acb : ∀ b, acc rb b): ∀ b, acc (lex ra rb) (a, b) := acc.rec_on aca (λ xa aca iha b, acc.rec_on (acb b) (λ xb acb ihb, acc.intro (xa, xb) (λ p lt, have aux : xa = xa → xb = xb → acc (lex ra rb) p, from @prod.lex.rec_on α β ra rb (λ p₁ p₂, fst p₂ = xa → snd p₂ = xb → acc (lex ra rb) p₁) p (xa, xb) lt (λ a₁ b₁ a₂ b₂ h (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), iha a₁ (eq.rec_on eq₂ h) b₁) (λ a b₁ b₂ h (eq₂ : a = xa) (eq₃ : b₂ = xb), eq.rec_on eq₂~>symm (ihb b₁ (eq.rec_on eq₃ h))), aux rfl rfl))) -- The lexicographical order of well founded relations is well-founded def lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) := ⟨λ p, destruct p (λ a b, lex_accessible (apply ha a) (well_founded.apply hb) b)⟩ -- relational product is a subrelation of the lex def rprod_sub_lex : ∀ a b, rprod ra rb a b → lex ra rb a b := λ a b h, prod.rprod.rec_on h (λ a₁ b₁ a₂ b₂ h₁ h₂, lex.left rb b₁ b₂ h₁) -- The relational product of well founded relations is well-founded def rprod_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (rprod ra rb) := subrelation.wf (rprod_sub_lex) (lex_wf ha hb) end end prod
6432744b331d39d27a59e25835c69f8ec2953c8f
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/algebra/ordered_group.lean
b0f529f2a4dfec1eb132fe7c7c3837a58d1d26ab
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
67,734
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.group.with_one import algebra.group.type_tags import order.bounded_lattice set_option old_structure_cmd true set_option default_priority 100 -- see Note [default priority] /-! # Ordered monoids and groups This file develops the basics of ordered monoids and groups. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ universe u variable {α : Type u} /-- An ordered commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c * a ≤ c * b` (multiplication is monotone) * `a * b < a * c → b < c`. -/ @[protect_proj, ancestor comm_monoid partial_order] class ordered_comm_monoid (α : Type*) extends comm_monoid α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (lt_of_mul_lt_mul_left : ∀ a b c : α, a * b < a * c → b < c) /-- An ordered (additive) commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c + a ≤ c + b` (addition is monotone) * `a + b < a + c → b < c`. -/ @[protect_proj, ancestor add_comm_monoid partial_order] class ordered_add_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c) attribute [to_additive] ordered_comm_monoid section ordered_comm_monoid variables [ordered_comm_monoid α] {a b c d : α} @[to_additive add_le_add_left] lemma mul_le_mul_left' (h : a ≤ b) (c) : c * a ≤ c * b := ordered_comm_monoid.mul_le_mul_left a b h c @[to_additive add_le_add_right] lemma mul_le_mul_right' (h : a ≤ b) (c) : a * c ≤ b * c := by { convert mul_le_mul_left' h c using 1; rw mul_comm } @[to_additive lt_of_add_lt_add_left] lemma lt_of_mul_lt_mul_left' : a * b < a * c → b < c := ordered_comm_monoid.lt_of_mul_lt_mul_left a b c @[to_additive add_le_add] lemma mul_le_mul' (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := (mul_le_mul_right' h₁ _).trans $ mul_le_mul_left' h₂ _ @[to_additive] lemma mul_le_mul_three {e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a * b * c ≤ d * e * f := mul_le_mul' (mul_le_mul' h₁ h₂) h₃ @[to_additive le_add_of_nonneg_right] lemma le_mul_of_one_le_right' (h : 1 ≤ b) : a ≤ a * b := have a * 1 ≤ a * b, from mul_le_mul_left' h _, by rwa mul_one at this @[to_additive le_add_of_nonneg_left] lemma le_mul_of_one_le_left' (h : 1 ≤ b) : a ≤ b * a := have 1 * a ≤ b * a, from mul_le_mul_right' h a, by rwa one_mul at this @[to_additive lt_of_add_lt_add_right] lemma lt_of_mul_lt_mul_right' (h : a * b < c * b) : a < c := lt_of_mul_lt_mul_left' (show b * a < b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) -- here we start using properties of one. @[to_additive] lemma le_mul_of_one_le_of_le (ha : 1 ≤ a) (hbc : b ≤ c) : b ≤ a * c := one_mul b ▸ mul_le_mul' ha hbc @[to_additive] lemma le_mul_of_le_of_one_le (hbc : b ≤ c) (ha : 1 ≤ a) : b ≤ c * a := mul_one b ▸ mul_le_mul' hbc ha @[to_additive add_nonneg] lemma one_le_mul (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := le_mul_of_one_le_of_le ha hb @[to_additive add_pos_of_pos_of_nonneg] lemma one_lt_mul_of_lt_of_le' (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := lt_of_lt_of_le ha $ le_mul_of_one_le_right' hb @[to_additive add_pos_of_nonneg_of_pos] lemma one_lt_mul_of_le_of_lt' (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := lt_of_lt_of_le hb $ le_mul_of_one_le_left' ha @[to_additive add_pos] lemma one_lt_mul' (ha : 1 < a) (hb : 1 < b) : 1 < a * b := one_lt_mul_of_lt_of_le' ha hb.le @[to_additive add_nonpos] lemma mul_le_one' (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := one_mul (1:α) ▸ (mul_le_mul' ha hb) @[to_additive] lemma mul_le_of_le_one_of_le' (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one' (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one' (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := (mul_le_of_le_of_le_one' le_rfl hb).trans_lt ha @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one' (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := (mul_le_of_le_one_of_le' ha le_rfl).trans_lt hb @[to_additive] lemma mul_lt_one' (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_one_of_le_one_of_lt_one' ha.le hb @[to_additive] lemma lt_mul_of_one_le_of_lt' (ha : 1 ≤ a) (hbc : b < c) : b < a * c := hbc.trans_le $ le_mul_of_one_le_left' ha @[to_additive] lemma lt_mul_of_lt_of_one_le' (hbc : b < c) (ha : 1 ≤ a) : b < c * a := hbc.trans_le $ le_mul_of_one_le_right' ha @[to_additive] lemma lt_mul_of_one_lt_of_lt' (ha : 1 < a) (hbc : b < c) : b < a * c := lt_mul_of_one_le_of_lt' ha.le hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt' (hbc : b < c) (ha : 1 < a) : b < c * a := lt_mul_of_lt_of_one_le' hbc ha.le @[to_additive] lemma mul_lt_of_le_one_of_lt' (ha : a ≤ 1) (hbc : b < c) : a * b < c := lt_of_le_of_lt (mul_le_of_le_one_of_le' ha le_rfl) hbc @[to_additive] lemma mul_lt_of_lt_of_le_one' (hbc : b < c) (ha : a ≤ 1) : b * a < c := lt_of_le_of_lt (mul_le_of_le_of_le_one' le_rfl ha) hbc @[to_additive] lemma mul_lt_of_lt_one_of_lt' (ha : a < 1) (hbc : b < c) : a * b < c := mul_lt_of_le_one_of_lt' ha.le hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one' (hbc : b < c) (ha : a < 1) : b * a < c := mul_lt_of_lt_of_le_one' hbc ha.le @[to_additive] lemma mul_eq_one_iff' (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := iff.intro (assume hab : a * b = 1, have a ≤ 1, from hab ▸ le_mul_of_le_of_one_le le_rfl hb, have a = 1, from le_antisymm this ha, have b ≤ 1, from hab ▸ le_mul_of_one_le_of_le ha le_rfl, have b = 1, from le_antisymm this hb, and.intro ‹a = 1› ‹b = 1›) (assume ⟨ha', hb'⟩, by rw [ha', hb', mul_one]) section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add] lemma monotone.mul' (hf : monotone f) (hg : monotone g) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul' (hf h) (hg h) @[to_additive monotone.add_const] lemma monotone.mul_const' (hf : monotone f) (a : α) : monotone (λ x, f x * a) := hf.mul' monotone_const @[to_additive monotone.const_add] lemma monotone.const_mul' (hf : monotone f) (a : α) : monotone (λ x, a * f x) := monotone_const.mul' hf end mono end ordered_comm_monoid lemma bit0_pos [ordered_add_comm_monoid α] {a : α} (h : 0 < a) : 0 < bit0 a := add_pos h h namespace units @[to_additive] instance [monoid α] [preorder α] : preorder (units α) := preorder.lift (coe : units α → α) @[simp, to_additive, norm_cast] theorem coe_le_coe [monoid α] [preorder α] {a b : units α} : (a : α) ≤ b ↔ a ≤ b := iff.rfl @[simp, to_additive, norm_cast] theorem coe_lt_coe [monoid α] [preorder α] {a b : units α} : (a : α) < b ↔ a < b := iff.rfl @[to_additive] instance [monoid α] [partial_order α] : partial_order (units α) := partial_order.lift coe units.ext @[to_additive] instance [monoid α] [linear_order α] : linear_order (units α) := linear_order.lift coe units.ext @[to_additive] instance [monoid α] [decidable_linear_order α] : decidable_linear_order (units α) := decidable_linear_order.lift coe units.ext @[simp, to_additive, norm_cast] theorem max_coe [monoid α] [decidable_linear_order α] {a b : units α} : (↑(max a b) : α) = max a b := by by_cases b ≤ a; simp [max, h] @[simp, to_additive, norm_cast] theorem min_coe [monoid α] [decidable_linear_order α] {a b : units α} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [min, h] end units namespace with_zero local attribute [semireducible] with_zero instance [preorder α] : preorder (with_zero α) := with_bot.preorder instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order instance [partial_order α] : order_bot (with_zero α) := with_bot.order_bot lemma zero_le [partial_order α] (a : with_zero α) : 0 ≤ a := order_bot.bot_le a lemma zero_lt_coe [partial_order α] (a : α) : (0 : with_zero α) < a := with_bot.bot_lt_coe a @[simp, norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_zero α) < b ↔ a < b := with_bot.coe_lt_coe @[simp, norm_cast] lemma coe_le_coe [partial_order α] {a b : α} : (a : with_zero α) ≤ b ↔ a ≤ b := with_bot.coe_le_coe instance [lattice α] : lattice (with_zero α) := with_bot.lattice instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order instance [decidable_linear_order α] : decidable_linear_order (with_zero α) := with_bot.decidable_linear_order lemma mul_le_mul_left {α : Type u} [ordered_comm_monoid α] : ∀ (a b : with_zero α), a ≤ b → ∀ (c : with_zero α), c * a ≤ c * b := begin rintro (_ | a) (_ | b) h (_ | c), { apply with_zero.zero_le }, { apply with_zero.zero_le }, { apply with_zero.zero_le }, { apply with_zero.zero_le }, { apply with_zero.zero_le }, { exact false.elim (not_lt_of_le h (with_zero.zero_lt_coe a))}, { apply with_zero.zero_le }, { simp_rw [some_eq_coe] at h ⊢, norm_cast at h ⊢, exact mul_le_mul_left' h c } end lemma lt_of_mul_lt_mul_left {α : Type u} [ordered_comm_monoid α] : ∀ (a b c : with_zero α), a * b < a * c → b < c := begin rintro (_ | a) (_ | b) (_ | c) h, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact with_zero.zero_lt_coe c }, { exact false.elim (not_le_of_lt h (with_zero.zero_le _)) }, { simp_rw [some_eq_coe] at h ⊢, norm_cast at h ⊢, apply lt_of_mul_lt_mul_left' h } end instance [ordered_comm_monoid α] : ordered_comm_monoid (with_zero α) := { mul_le_mul_left := with_zero.mul_le_mul_left, lt_of_mul_lt_mul_left := with_zero.lt_of_mul_lt_mul_left, ..with_zero.comm_monoid_with_zero, ..with_zero.partial_order } /-- If `0` is the least element in `α`, then `with_zero α` is an `ordered_add_comm_monoid`. -/ def ordered_add_comm_monoid [ordered_add_comm_monoid α] (zero_le : ∀ a : α, 0 ≤ a) : ordered_add_comm_monoid (with_zero α) := begin suffices, refine { add_le_add_left := this, ..with_zero.partial_order, ..with_zero.add_comm_monoid, .. }, { intros a b c h, have h' := lt_iff_le_not_le.1 h, rw lt_iff_le_not_le at ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases c with c, { cases h'.2 (this _ _ bot_le a) }, { refine ⟨_, rfl, _⟩, cases a with a, { exact with_bot.some_le_some.1 h'.1 }, { exact le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h), } } }, { intros a b h c ca h₂, cases b with b, { rw le_antisymm h bot_le at h₂, exact ⟨_, h₂, le_refl _⟩ }, cases a with a, { change c + 0 = some ca at h₂, simp at h₂, simp [h₂], exact ⟨_, rfl, by simpa using add_le_add_left (zero_le b) _⟩ }, { simp at h, cases c with c; change some _ = _ at h₂; simp [-add_comm] at h₂; subst ca; refine ⟨_, rfl, _⟩, { exact h }, { exact add_le_add_left h _ } } } end end with_zero namespace with_top section has_one variables [has_one α] @[to_additive] instance : has_one (with_top α) := ⟨(1 : α)⟩ @[simp, to_additive] lemma coe_one : ((1 : α) : with_top α) = 1 := rfl @[simp, to_additive] lemma coe_eq_one {a : α} : (a : with_top α) = 1 ↔ a = 1 := coe_eq_coe @[simp, to_additive] theorem one_eq_coe {a : α} : 1 = (a : with_top α) ↔ a = 1 := by rw [eq_comm, coe_eq_one] attribute [norm_cast] coe_one coe_eq_one coe_zero coe_eq_zero one_eq_coe zero_eq_coe @[simp, to_additive] theorem top_ne_one : ⊤ ≠ (1 : with_top α) . @[simp, to_additive] theorem one_ne_top : (1 : with_top α) ≠ ⊤ . end has_one instance [has_add α] : has_add (with_top α) := ⟨λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a + b))⟩ local attribute [reducible] with_zero instance [add_semigroup α] : add_semigroup (with_top α) := { add := (+), ..@additive.add_semigroup _ $ @with_zero.semigroup (multiplicative α) _ } @[norm_cast] lemma coe_add [has_add α] {a b : α} : ((a + b : α) : with_top α) = a + b := rfl @[norm_cast] lemma coe_bit0 [has_add α] {a : α} : ((bit0 a : α) : with_top α) = bit0 a := rfl @[norm_cast] lemma coe_bit1 [has_add α] [has_one α] {a : α} : ((bit1 a : α) : with_top α) = bit1 a := rfl instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) := { ..@additive.add_comm_semigroup _ $ @with_zero.comm_semigroup (multiplicative α) _ } instance [add_monoid α] : add_monoid (with_top α) := { zero := some 0, add := (+), ..@additive.add_monoid _ $ @monoid_with_zero.to_monoid _ $ @with_zero.monoid_with_zero (multiplicative α) _ } instance [add_comm_monoid α] : add_comm_monoid (with_top α) := { zero := 0, add := (+), ..@additive.add_comm_monoid _ $ @comm_monoid_with_zero.to_comm_monoid _ $ @with_zero.comm_monoid_with_zero (multiplicative α) _ } instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_top α) := begin suffices, refine { add_le_add_left := this, ..with_top.partial_order, ..with_top.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ c h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim le_top }, cases b with b, { exact (not_le_of_lt h).elim le_top }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $ with_top.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases b with b; cases h₂, cases a with a, {cases le_antisymm h le_top }, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end @[simp] lemma zero_lt_top [ordered_add_comm_monoid α] : (0 : with_top α) < ⊤ := coe_lt_top 0 @[simp, norm_cast] lemma zero_lt_coe [ordered_add_comm_monoid α] (a : α) : (0 : with_top α) < a ↔ 0 < a := coe_lt_coe @[simp] lemma add_top [ordered_add_comm_monoid α] : ∀{a : with_top α}, a + ⊤ = ⊤ | none := rfl | (some a) := rfl @[simp] lemma top_add [ordered_add_comm_monoid α] {a : with_top α} : ⊤ + a = ⊤ := rfl lemma add_eq_top [ordered_add_comm_monoid α] (a b : with_top α) : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by {cases a; cases b; simp [none_eq_top, some_eq_coe, ←with_top.coe_add, ←with_zero.coe_add]} lemma add_lt_top [ordered_add_comm_monoid α] (a b : with_top α) : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ := by simp [lt_top_iff_ne_top, add_eq_top, not_or_distrib] end with_top namespace with_bot instance [has_zero α] : has_zero (with_bot α) := with_top.has_zero instance [has_one α] : has_one (with_bot α) := with_top.has_one instance [add_semigroup α] : add_semigroup (with_bot α) := with_top.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (with_bot α) := with_top.add_comm_semigroup instance [add_monoid α] : add_monoid (with_bot α) := with_top.add_monoid instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_bot α) := begin suffices, refine { add_le_add_left := this, ..with_bot.partial_order, ..with_bot.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim bot_le }, cases c with c, { exact (not_le_of_lt h).elim bot_le }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases a with a; cases h₂, cases b with b, {cases le_antisymm h bot_le}, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_zero [has_zero α] : ((0 : α) : with_bot α) = 0 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_one [has_one α] : ((1 : α) : with_bot α) = 1 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_eq_zero {α : Type*} [add_monoid α] {a : α} : (a : with_bot α) = 0 ↔ a = 0 := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_add [add_semigroup α] (a b : α) : ((a + b : α) : with_bot α) = a + b := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit0 [add_semigroup α] {a : α} : ((bit0 a : α) : with_bot α) = bit0 a := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit1 [add_semigroup α] [has_one α] {a : α} : ((bit1 a : α) : with_bot α) = bit1 a := by norm_cast @[simp] lemma bot_add [ordered_add_comm_monoid α] (a : with_bot α) : ⊥ + a = ⊥ := rfl @[simp] lemma add_bot [ordered_add_comm_monoid α] (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl end with_bot /-- A canonically ordered additive monoid is an ordered commutative additive monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ @[protect_proj] class canonically_ordered_add_monoid (α : Type*) extends ordered_add_comm_monoid α, order_bot α := (le_iff_exists_add : ∀a b:α, a ≤ b ↔ ∃c, b = a + c) section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] {a b c d : α} lemma le_iff_exists_add : a ≤ b ↔ ∃c, b = a + c := canonically_ordered_add_monoid.le_iff_exists_add a b @[simp] lemma zero_le (a : α) : 0 ≤ a := le_iff_exists_add.mpr ⟨a, by simp⟩ @[simp] lemma bot_eq_zero : (⊥ : α) = 0 := le_antisymm bot_le (zero_le ⊥) @[simp] lemma add_eq_zero_iff : a + b = 0 ↔ a = 0 ∧ b = 0 := add_eq_zero_iff' (zero_le _) (zero_le _) @[simp] lemma le_zero_iff_eq : a ≤ 0 ↔ a = 0 := iff.intro (assume h, le_antisymm h (zero_le a)) (assume h, h ▸ le_refl a) lemma zero_lt_iff_ne_zero : 0 < a ↔ a ≠ 0 := iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (zero_le _) hne.symm lemma exists_pos_add_of_lt (h : a < b) : ∃ c > 0, a + c = b := begin obtain ⟨c, hc⟩ := le_iff_exists_add.1 h.le, refine ⟨c, zero_lt_iff_ne_zero.2 _, hc.symm⟩, rintro rfl, simpa [hc, lt_irrefl] using h end lemma le_add_left (h : a ≤ c) : a ≤ b + c := calc a = 0 + a : by simp ... ≤ b + c : add_le_add (zero_le _) h lemma le_add_right (h : a ≤ b) : a ≤ b + c := calc a = a + 0 : by simp ... ≤ b + c : add_le_add h (zero_le _) local attribute [semireducible] with_zero instance with_zero.canonically_ordered_add_monoid : canonically_ordered_add_monoid (with_zero α) := { le_iff_exists_add := λ a b, begin cases a with a, { exact iff_of_true bot_le ⟨b, (zero_add b).symm⟩ }, cases b with b, { exact iff_of_false (mt (le_antisymm bot_le) (by simp)) (λ ⟨c, h⟩, by cases c; cases h) }, { simp [le_iff_exists_add, -add_comm], split; intro h; rcases h with ⟨c, h⟩, { exact ⟨some c, congr_arg some h⟩ }, { cases c; cases h, { exact ⟨_, (add_zero _).symm⟩ }, { exact ⟨_, rfl⟩ } } } end, bot := 0, bot_le := assume a a' h, option.no_confusion h, .. with_zero.ordered_add_comm_monoid zero_le } instance with_top.canonically_ordered_add_monoid : canonically_ordered_add_monoid (with_top α) := { le_iff_exists_add := assume a b, match a, b with | a, none := show a ≤ ⊤ ↔ ∃c, ⊤ = a + c, by simp; refine ⟨⊤, _⟩; cases a; refl | (some a), (some b) := show (a:with_top α) ≤ ↑b ↔ ∃c:with_top α, ↑b = ↑a + c, begin simp [canonically_ordered_add_monoid.le_iff_exists_add, -add_comm], split, { rintro ⟨c, rfl⟩, refine ⟨c, _⟩, norm_cast }, { exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end } end | none, some b := show (⊤ : with_top α) ≤ b ↔ ∃c:with_top α, ↑b = ⊤ + c, by simp end, .. with_top.order_bot, .. with_top.ordered_add_comm_monoid } end canonically_ordered_add_monoid /-- A canonically linear-ordered additive monoid is a canonically ordered additive monoid whose ordering is a decidable linear order. -/ @[protect_proj] class canonically_linear_ordered_add_monoid (α : Type*) extends canonically_ordered_add_monoid α, decidable_linear_order α section canonically_linear_ordered_add_monoid variables [canonically_linear_ordered_add_monoid α] instance canonically_linear_ordered_add_monoid.semilattice_sup_bot : semilattice_sup_bot α := { ..lattice_of_decidable_linear_order, ..canonically_ordered_add_monoid.to_order_bot α } end canonically_linear_ordered_add_monoid /-- An ordered cancellative additive commutative monoid is an additive commutative monoid with a partial order, in which addition is cancellative and strictly monotone. -/ @[protect_proj, ancestor add_comm_monoid add_left_cancel_semigroup add_right_cancel_semigroup partial_order] class ordered_cancel_add_comm_monoid (α : Type u) extends add_comm_monoid α, add_left_cancel_semigroup α, add_right_cancel_semigroup α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (le_of_add_le_add_left : ∀ a b c : α, a + b ≤ a + c → b ≤ c) /-- An ordered cancellative commutative monoid is a commutative monoid with a partial order, in which multiplication is cancellative and strictly monotone. -/ @[protect_proj, ancestor comm_monoid left_cancel_semigroup right_cancel_semigroup partial_order] class ordered_cancel_comm_monoid (α : Type u) extends comm_monoid α, left_cancel_semigroup α, right_cancel_semigroup α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (le_of_mul_le_mul_left : ∀ a b c : α, a * b ≤ a * c → b ≤ c) attribute [to_additive] ordered_cancel_comm_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] {a b c d : α} @[to_additive] instance ordered_cancel_comm_monoid.to_left_cancel_monoid : left_cancel_monoid α := { ..‹ordered_cancel_comm_monoid α› } @[to_additive le_of_add_le_add_left] lemma le_of_mul_le_mul_left' : ∀ {a b c : α}, a * b ≤ a * c → b ≤ c := ordered_cancel_comm_monoid.le_of_mul_le_mul_left @[to_additive] instance ordered_cancel_comm_monoid.to_ordered_comm_monoid : ordered_comm_monoid α := { lt_of_mul_lt_mul_left := λ a b c h, lt_of_le_not_le (le_of_mul_le_mul_left' h.le) $ mt (λ h, ordered_cancel_comm_monoid.mul_le_mul_left _ _ h _) (not_le_of_gt h), ..‹ordered_cancel_comm_monoid α› } @[to_additive add_lt_add_left] lemma mul_lt_mul_left' (h : a < b) (c : α) : c * a < c * b := lt_of_le_not_le (mul_le_mul_left' h.le _) $ mt le_of_mul_le_mul_left' (not_le_of_gt h) @[to_additive add_lt_add_right] lemma mul_lt_mul_right' (h : a < b) (c : α) : a * c < b * c := begin rw [mul_comm a c, mul_comm b c], exact (mul_lt_mul_left' h c) end @[to_additive add_lt_add] lemma mul_lt_mul''' (h₁ : a < b) (h₂ : c < d) : a * c < b * d := lt_trans (mul_lt_mul_right' h₁ c) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_le_of_lt (h₁ : a ≤ b) (h₂ : c < d) : a * c < b * d := lt_of_le_of_lt (mul_le_mul_right' h₁ _) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_lt_of_le (h₁ : a < b) (h₂ : c ≤ d) : a * c < b * d := lt_of_lt_of_le (mul_lt_mul_right' h₁ c) (mul_le_mul_left' h₂ _) @[to_additive lt_add_of_pos_right] lemma lt_mul_of_one_lt_right' (a : α) {b : α} (h : 1 < b) : a < a * b := have a * 1 < a * b, from mul_lt_mul_left' h a, by rwa [mul_one] at this @[to_additive lt_add_of_pos_left] lemma lt_mul_of_one_lt_left' (a : α) {b : α} (h : 1 < b) : a < b * a := have 1 * a < b * a, from mul_lt_mul_right' h a, by rwa [one_mul] at this @[to_additive le_of_add_le_add_right] lemma le_of_mul_le_mul_right' (h : a * b ≤ c * b) : a ≤ c := le_of_mul_le_mul_left' (show b * a ≤ b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) @[to_additive] lemma mul_lt_one (ha : a < 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul''' ha hb) @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_lt_of_le ha hb) @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_le_of_lt ha hb) @[to_additive] lemma lt_mul_of_one_lt_of_le (ha : 1 < a) (hbc : b ≤ c) : b < a * c := one_mul b ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma lt_mul_of_le_of_one_lt (hbc : b ≤ c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma mul_le_of_le_one_of_le (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_le (ha : a < 1) (hbc : b ≤ c) : a * b < c := one_mul c ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma mul_lt_of_le_of_lt_one (hbc : b ≤ c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma lt_mul_of_one_le_of_lt (ha : 1 ≤ a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_le (hbc : b < c) (ha : 1 ≤ a) : b < c * a := mul_one b ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma lt_mul_of_one_lt_of_lt (ha : 1 < a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul''' ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt (hbc : b < c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul''' hbc ha @[to_additive] lemma mul_lt_of_le_one_of_lt (ha : a ≤ 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma mul_lt_of_lt_of_le_one (hbc : b < c) (ha : a ≤ 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_lt (ha : a < 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul''' ha hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one (hbc : b < c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul''' hbc ha @[simp, to_additive] lemma mul_le_mul_iff_left (a : α) {b c : α} : a * b ≤ a * c ↔ b ≤ c := ⟨le_of_mul_le_mul_left', λ h, mul_le_mul_left' h _⟩ @[simp, to_additive] lemma mul_le_mul_iff_right (c : α) : a * c ≤ b * c ↔ a ≤ b := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_iff_left c @[simp, to_additive] lemma mul_lt_mul_iff_left (a : α) {b c : α} : a * b < a * c ↔ b < c := ⟨lt_of_mul_lt_mul_left', λ h, mul_lt_mul_left' h _⟩ @[simp, to_additive] lemma mul_lt_mul_iff_right (c : α) : a * c < b * c ↔ a < b := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_iff_left c @[simp, to_additive le_add_iff_nonneg_right] lemma le_mul_iff_one_le_right' (a : α) {b : α} : a ≤ a * b ↔ 1 ≤ b := have a * 1 ≤ a * b ↔ 1 ≤ b, from mul_le_mul_iff_left a, by rwa mul_one at this @[simp, to_additive le_add_iff_nonneg_left] lemma le_mul_iff_one_le_left' (a : α) {b : α} : a ≤ b * a ↔ 1 ≤ b := by rw [mul_comm, le_mul_iff_one_le_right'] @[simp, to_additive lt_add_iff_pos_right] lemma lt_mul_iff_one_lt_right' (a : α) {b : α} : a < a * b ↔ 1 < b := have a * 1 < a * b ↔ 1 < b, from mul_lt_mul_iff_left a, by rwa mul_one at this @[simp, to_additive lt_add_iff_pos_left] lemma lt_mul_iff_one_lt_left' (a : α) {b : α} : a < b * a ↔ 1 < b := by rw [mul_comm, lt_mul_iff_one_lt_right'] @[simp, to_additive add_le_iff_nonpos_left] lemma mul_le_iff_le_one_left' : a * b ≤ b ↔ a ≤ 1 := by { convert mul_le_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_le_iff_nonpos_right] lemma mul_le_iff_le_one_right' : a * b ≤ a ↔ b ≤ 1 := by { convert mul_le_mul_iff_left a, rw [mul_one] } @[simp, to_additive add_lt_iff_neg_right] lemma mul_lt_iff_lt_one_right' : a * b < b ↔ a < 1 := by { convert mul_lt_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_lt_iff_neg_left] lemma mul_lt_iff_lt_one_left' : a * b < a ↔ b < 1 := by { convert mul_lt_mul_iff_left a, rw [mul_one] } @[to_additive] lemma mul_eq_one_iff_eq_one_of_one_le (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := ⟨λ hab : a * b = 1, by split; apply le_antisymm; try {assumption}; rw ← hab; simp [ha, hb], λ ⟨ha', hb'⟩, by rw [ha', hb', mul_one]⟩ section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add_strict_mono] lemma monotone.mul_strict_mono' (hf : monotone f) (hg : strict_mono g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_le_of_lt (hf $ le_of_lt h) (hg h) @[to_additive strict_mono.add_monotone] lemma strict_mono.mul_monotone' (hf : strict_mono f) (hg : monotone g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_lt_of_le (hf h) (hg $ le_of_lt h) @[to_additive strict_mono.add_const] lemma strict_mono.mul_const' (hf : strict_mono f) (c : α) : strict_mono (λ x, f x * c) := hf.mul_monotone' monotone_const @[to_additive strict_mono.const_add] lemma strict_mono.const_mul' (hf : strict_mono f) (c : α) : strict_mono (λ x, c * f x) := monotone_const.mul_strict_mono' hf end mono end ordered_cancel_comm_monoid section ordered_cancel_add_comm_monoid variable [ordered_cancel_add_comm_monoid α] lemma with_top.add_lt_add_iff_left : ∀{a b c : with_top α}, a < ⊤ → (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊤ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe], { norm_cast, exact with_top.coe_lt_top _ }, { norm_cast, exact add_lt_add_iff_left _ } end local attribute [reducible] with_zero lemma with_top.add_lt_add_iff_right {a b c : with_top α} : a < ⊤ → (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c end ordered_cancel_add_comm_monoid /-- An ordered additive commutative group is an additive commutative group with a partial order in which addition is strictly monotone. -/ @[protect_proj, ancestor add_comm_group partial_order] class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) /-- An ordered commutative group is an commutative group with a partial order in which multiplication is strictly monotone. -/ @[protect_proj, ancestor comm_group partial_order] class ordered_comm_group (α : Type u) extends comm_group α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) attribute [to_additive] ordered_comm_group /--The units of an ordered commutative monoid form an ordered commutative group. -/ @[to_additive] instance units.ordered_comm_group [ordered_comm_monoid α] : ordered_comm_group (units α) := { mul_le_mul_left := λ a b h c, mul_le_mul_left' h _, .. units.partial_order, .. (infer_instance : comm_group (units α)) } section ordered_comm_group variables [ordered_comm_group α] {a b c d : α} @[to_additive ordered_add_comm_group.add_lt_add_left] lemma ordered_comm_group.mul_lt_mul_left' (a b : α) (h : a < b) (c : α) : c * a < c * b := begin rw lt_iff_le_not_le at h ⊢, split, { apply ordered_comm_group.mul_le_mul_left _ _ h.1 }, { intro w, replace w : c⁻¹ * (c * b) ≤ c⁻¹ * (c * a) := ordered_comm_group.mul_le_mul_left _ _ w _, simp only [mul_one, mul_comm, mul_left_inv, mul_left_comm] at w, exact h.2 w }, end @[to_additive ordered_add_comm_group.le_of_add_le_add_left] lemma ordered_comm_group.le_of_mul_le_mul_left (h : a * b ≤ a * c) : b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * (a * c), from ordered_comm_group.mul_le_mul_left _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end @[to_additive] lemma ordered_comm_group.lt_of_mul_lt_mul_left (h : a * b < a * c) : b < c := have a⁻¹ * (a * b) < a⁻¹ * (a * c), from ordered_comm_group.mul_lt_mul_left' _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end @[to_additive] instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := { mul_left_cancel := @mul_left_cancel α _, mul_right_cancel := @mul_right_cancel α _, le_of_mul_le_mul_left := @ordered_comm_group.le_of_mul_le_mul_left α _, ..s } @[to_additive neg_le_neg] lemma inv_le_inv' (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := have 1 ≤ a⁻¹ * b, from mul_left_inv a ▸ mul_le_mul_left' h _, have 1 * b⁻¹ ≤ a⁻¹ * b * b⁻¹, from mul_le_mul_right' this _, by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma le_of_inv_le_inv (h : b⁻¹ ≤ a⁻¹) : a ≤ b := suffices (a⁻¹)⁻¹ ≤ (b⁻¹)⁻¹, from begin simp [inv_inv] at this, assumption end, inv_le_inv' h @[to_additive] lemma one_le_of_inv_le_one (h : a⁻¹ ≤ 1) : 1 ≤ a := have a⁻¹ ≤ 1⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive] lemma inv_le_one_of_one_le (h : 1 ≤ a) : a⁻¹ ≤ 1 := have a⁻¹ ≤ 1⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive nonpos_of_neg_nonneg] lemma le_one_of_one_le_inv (h : 1 ≤ a⁻¹) : a ≤ 1 := have 1⁻¹ ≤ a⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive neg_nonneg_of_nonpos] lemma one_le_inv_of_le_one (h : a ≤ 1) : 1 ≤ a⁻¹ := have 1⁻¹ ≤ a⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive neg_lt_neg] lemma inv_lt_inv' (h : a < b) : b⁻¹ < a⁻¹ := have 1 < a⁻¹ * b, from mul_left_inv a ▸ mul_lt_mul_left' h (a⁻¹), have 1 * b⁻¹ < a⁻¹ * b * b⁻¹, from mul_lt_mul_right' this (b⁻¹), by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma lt_of_inv_lt_inv (h : b⁻¹ < a⁻¹) : a < b := inv_inv a ▸ inv_inv b ▸ inv_lt_inv' h @[to_additive] lemma one_lt_of_inv_inv (h : a⁻¹ < 1) : 1 < a := have a⁻¹ < 1⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive] lemma inv_inv_of_one_lt (h : 1 < a) : a⁻¹ < 1 := have a⁻¹ < 1⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive neg_of_neg_pos] lemma inv_of_one_lt_inv (h : 1 < a⁻¹) : a < 1 := have 1⁻¹ < a⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive neg_pos_of_neg] lemma one_lt_inv_of_inv (h : a < 1) : 1 < a⁻¹ := have 1⁻¹ < a⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive] lemma le_inv_of_le_inv (h : a ≤ b⁻¹) : b ≤ a⁻¹ := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_le_of_inv_le (h : a⁻¹ ≤ b) : b⁻¹ ≤ a := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma lt_inv_of_lt_inv (h : a < b⁻¹) : b < a⁻¹ := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_lt_of_inv_lt (h : a⁻¹ < b) : b⁻¹ < a := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma mul_le_of_le_inv_mul (h : b ≤ a⁻¹ * c) : a * b ≤ c := begin have h := mul_le_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma le_inv_mul_of_mul_le (h : a * b ≤ c) : b ≤ a⁻¹ * c := begin have h := mul_le_mul_left' h a⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le (h : b⁻¹ * a ≤ c) : a ≤ b * c := begin have h := mul_le_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_le_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c := begin have h := mul_le_mul_left' h b⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le_left (h : b⁻¹ * a ≤ c) : a ≤ b * c := le_mul_of_inv_mul_le h @[to_additive] lemma inv_mul_le_left_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c := inv_mul_le_of_le_mul h @[to_additive] lemma le_mul_of_inv_mul_le_right (h : c⁻¹ * a ≤ b) : a ≤ b * c := by { rw mul_comm, exact le_mul_of_inv_mul_le h } @[to_additive] lemma inv_mul_le_right_of_le_mul (h : a ≤ b * c) : c⁻¹ * a ≤ b := by { rw mul_comm at h, apply inv_mul_le_left_of_le_mul h } @[to_additive] lemma mul_lt_of_lt_inv_mul (h : b < a⁻¹ * c) : a * b < c := begin have h := mul_lt_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma lt_inv_mul_of_mul_lt (h : a * b < c) : b < a⁻¹ * c := begin have h := mul_lt_mul_left' h (a⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt (h : b⁻¹ * a < c) : a < b * c := begin have h := mul_lt_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_lt_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := begin have h := mul_lt_mul_left' h (b⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt_left (h : b⁻¹ * a < c) : a < b * c := lt_mul_of_inv_mul_lt h @[to_additive] lemma inv_mul_lt_left_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := inv_mul_lt_of_lt_mul h @[to_additive] lemma lt_mul_of_inv_mul_lt_right (h : c⁻¹ * a < b) : a < b * c := by { rw mul_comm, exact lt_mul_of_inv_mul_lt h } @[to_additive] lemma inv_mul_lt_right_of_lt_mul (h : a < b * c) : c⁻¹ * a < b := by { rw mul_comm at h, exact inv_mul_lt_of_lt_mul h } @[simp, to_additive] lemma inv_lt_one_iff_one_lt : a⁻¹ < 1 ↔ 1 < a := ⟨ one_lt_of_inv_inv, inv_inv_of_one_lt ⟩ @[simp, to_additive] lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := have a * b * a⁻¹ ≤ a * b * b⁻¹ ↔ a⁻¹ ≤ b⁻¹, from mul_le_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_le] lemma inv_le' : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := have a⁻¹ ≤ (b⁻¹)⁻¹ ↔ b⁻¹ ≤ a, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive le_neg] lemma le_inv' : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := have (a⁻¹)⁻¹ ≤ b⁻¹ ↔ b ≤ a⁻¹, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive neg_le_iff_add_nonneg] lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ a * b := (mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_iff_mul_le_one : a ≤ b⁻¹ ↔ a * b ≤ 1 := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive neg_nonpos] lemma inv_le_one' : a⁻¹ ≤ 1 ↔ 1 ≤ a := have a⁻¹ ≤ 1⁻¹ ↔ 1 ≤ a, from inv_le_inv_iff, by rwa one_inv at this @[simp, to_additive neg_nonneg] lemma one_le_inv' : 1 ≤ a⁻¹ ↔ a ≤ 1 := have 1⁻¹ ≤ a⁻¹ ↔ a ≤ 1, from inv_le_inv_iff, by rwa one_inv at this @[to_additive] lemma inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (inv_le_one'.2 h) h @[to_additive] lemma self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (one_le_inv'.2 h) @[simp, to_additive] lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a := have a * b * a⁻¹ < a * b * b⁻¹ ↔ a⁻¹ < b⁻¹, from mul_lt_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_lt_zero] lemma inv_lt_one' : a⁻¹ < 1 ↔ 1 < a := have a⁻¹ < 1⁻¹ ↔ 1 < a, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_pos] lemma one_lt_inv' : 1 < a⁻¹ ↔ a < 1 := have 1⁻¹ < a⁻¹ ↔ a < 1, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_lt] lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a := have a⁻¹ < (b⁻¹)⁻¹ ↔ b⁻¹ < a, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive lt_neg] lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ := have (a⁻¹)⁻¹ < b⁻¹ ↔ b < a⁻¹, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive] lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * c ↔ a * b ≤ c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c := have b⁻¹ * a ≤ b⁻¹ * (b * c) ↔ a ≤ b * c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma mul_inv_le_iff_le_mul : a * c⁻¹ ≤ b ↔ a ≤ b * c := by rw [mul_comm a, mul_comm b, inv_mul_le_iff_le_mul] @[simp, to_additive] lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [← inv_mul_le_iff_le_mul, mul_comm] @[to_additive] lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c := by rw [inv_mul_le_iff_le_mul, mul_comm] @[simp, to_additive] lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c := have a⁻¹ * (a * b) < a⁻¹ * c ↔ a * b < c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c := have b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma inv_mul_lt_iff_lt_mul_right : c⁻¹ * a < b ↔ a < b * c := by rw [inv_mul_lt_iff_lt_mul, mul_comm] @[to_additive sub_le_sub_iff] lemma div_le_div_iff' (a b c d : α) : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := begin split ; intro h, have := mul_le_mul_right' (mul_le_mul_right' h b) d, rwa [inv_mul_cancel_right, mul_assoc _ _ b, mul_comm _ b, ← mul_assoc, inv_mul_cancel_right] at this, have := mul_le_mul_right' (mul_le_mul_right' h d⁻¹) b⁻¹, rwa [mul_inv_cancel_right, _root_.mul_assoc, _root_.mul_comm d⁻¹ b⁻¹, ← mul_assoc, mul_inv_cancel_right] at this, end end ordered_comm_group section ordered_add_comm_group variables [ordered_add_comm_group α] {a b c d : α} lemma sub_nonneg_of_le (h : b ≤ a) : 0 ≤ a - b := begin have h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonneg (h : 0 ≤ a - b) : b ≤ a := begin have h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_nonpos_of_le (h : a ≤ b) : a - b ≤ 0 := begin have h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonpos (h : a - b ≤ 0) : a ≤ b := begin have h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_pos_of_lt (h : b < a) : 0 < a - b := begin have h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_pos (h : 0 < a - b) : b < a := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_neg_of_lt (h : a < b) : a - b < 0 := begin have h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_neg (h : a - b < 0) : a < b := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma add_le_of_le_sub_left (h : b ≤ c - a) : a + b ≤ c := begin have h := add_le_add_left h a, rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma le_sub_left_of_add_le (h : a + b ≤ c) : b ≤ c - a := begin have h := add_le_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_le_of_le_sub_right (h : a ≤ c - b) : a + b ≤ c := begin have h := add_le_add_right h b, rwa sub_add_cancel at h end lemma le_sub_right_of_add_le (h : a + b ≤ c) : a ≤ c - b := begin have h := add_le_add_right h (-b), rwa add_neg_cancel_right at h end lemma le_add_of_sub_left_le (h : a - b ≤ c) : a ≤ b + c := begin have h := add_le_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_le_of_le_add (h : a ≤ b + c) : a - b ≤ c := begin have h := add_le_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma le_add_of_sub_right_le (h : a - c ≤ b) : a ≤ b + c := begin have h := add_le_add_right h c, rwa sub_add_cancel at h end lemma sub_right_le_of_le_add (h : a ≤ b + c) : a - c ≤ b := begin have h := add_le_add_right h (-c), rwa add_neg_cancel_right at h end lemma le_add_of_neg_le_sub_left (h : -a ≤ b - c) : c ≤ a + b := le_add_of_neg_add_le_left (add_le_of_le_sub_right h) lemma neg_le_sub_left_of_le_add (h : c ≤ a + b) : -a ≤ b - c := begin have h := le_neg_add_of_add_le (sub_left_le_of_le_add h), rwa add_comm at h end lemma le_add_of_neg_le_sub_right (h : -b ≤ a - c) : c ≤ a + b := le_add_of_sub_right_le (add_le_of_le_sub_left h) lemma neg_le_sub_right_of_le_add (h : c ≤ a + b) : -b ≤ a - c := le_sub_left_of_add_le (sub_right_le_of_le_add h) lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := sub_left_le_of_le_add (le_add_of_sub_right_le h) lemma sub_le_sub_left (h : a ≤ b) (c : α) : c - b ≤ c - a := add_le_add_left (neg_le_neg h) c lemma sub_le_sub_right (h : a ≤ b) (c : α) : a - c ≤ b - c := add_le_add_right h (-c) lemma sub_le_sub (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := add_le_add hab (neg_le_neg hcd) lemma add_lt_of_lt_sub_left (h : b < c - a) : a + b < c := begin have h := add_lt_add_left h a, rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma lt_sub_left_of_add_lt (h : a + b < c) : b < c - a := begin have h := add_lt_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_lt_of_lt_sub_right (h : a < c - b) : a + b < c := begin have h := add_lt_add_right h b, rwa sub_add_cancel at h end lemma lt_sub_right_of_add_lt (h : a + b < c) : a < c - b := begin have h := add_lt_add_right h (-b), rwa add_neg_cancel_right at h end lemma lt_add_of_sub_left_lt (h : a - b < c) : a < b + c := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_lt_of_lt_add (h : a < b + c) : a - b < c := begin have h := add_lt_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma lt_add_of_sub_right_lt (h : a - c < b) : a < b + c := begin have h := add_lt_add_right h c, rwa sub_add_cancel at h end lemma sub_right_lt_of_lt_add (h : a < b + c) : a - c < b := begin have h := add_lt_add_right h (-c), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_lt_sub_left (h : -a < b - c) : c < a + b := lt_add_of_neg_add_lt_left (add_lt_of_lt_sub_right h) lemma neg_lt_sub_left_of_lt_add (h : c < a + b) : -a < b - c := begin have h := lt_neg_add_of_add_lt (sub_left_lt_of_lt_add h), rwa add_comm at h end lemma lt_add_of_neg_lt_sub_right (h : -b < a - c) : c < a + b := lt_add_of_sub_right_lt (add_lt_of_lt_sub_left h) lemma neg_lt_sub_right_of_lt_add (h : c < a + b) : -b < a - c := lt_sub_left_of_add_lt (sub_right_lt_of_lt_add h) lemma sub_lt_of_sub_lt (h : a - b < c) : a - c < b := sub_left_lt_of_lt_add (lt_add_of_sub_right_lt h) lemma sub_lt_sub_left (h : a < b) (c : α) : c - b < c - a := add_lt_add_left (neg_lt_neg h) c lemma sub_lt_sub_right (h : a < b) (c : α) : a - c < b - c := add_lt_add_right h (-c) lemma sub_lt_sub (hab : a < b) (hcd : c < d) : a - d < b - c := add_lt_add hab (neg_lt_neg hcd) lemma sub_lt_sub_of_le_of_lt (hab : a ≤ b) (hcd : c < d) : a - d < b - c := add_lt_add_of_le_of_lt hab (neg_lt_neg hcd) lemma sub_lt_sub_of_lt_of_le (hab : a < b) (hcd : c ≤ d) : a - d < b - c := add_lt_add_of_lt_of_le hab (neg_le_neg hcd) lemma sub_le_self (a : α) {b : α} (h : 0 ≤ b) : a - b ≤ a := calc a - b = a + -b : rfl ... ≤ a + 0 : add_le_add_left (neg_nonpos_of_nonneg h) _ ... = a : by rw add_zero lemma sub_lt_self (a : α) {b : α} (h : 0 < b) : a - b < a := calc a - b = a + -b : rfl ... < a + 0 : add_lt_add_left (neg_neg_of_pos h) _ ... = a : by rw add_zero @[simp] lemma sub_le_sub_iff_left (a : α) {b c : α} : a - b ≤ a - c ↔ c ≤ b := (add_le_add_iff_left _).trans neg_le_neg_iff @[simp] lemma sub_le_sub_iff_right (c : α) : a - c ≤ b - c ↔ a ≤ b := add_le_add_iff_right _ @[simp] lemma sub_lt_sub_iff_left (a : α) {b c : α} : a - b < a - c ↔ c < b := (add_lt_add_iff_left _).trans neg_lt_neg_iff @[simp] lemma sub_lt_sub_iff_right (c : α) : a - c < b - c ↔ a < b := add_lt_add_iff_right _ @[simp] lemma sub_nonneg : 0 ≤ a - b ↔ b ≤ a := have a - a ≤ a - b ↔ b ≤ a, from sub_le_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_nonpos : a - b ≤ 0 ↔ a ≤ b := have a - b ≤ b - b ↔ a ≤ b, from sub_le_sub_iff_right b, by rwa sub_self at this @[simp] lemma sub_pos : 0 < a - b ↔ b < a := have a - a < a - b ↔ b < a, from sub_lt_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b := have a - b < b - b ↔ a < b, from sub_lt_sub_iff_right b, by rwa sub_self at this lemma le_sub_iff_add_le' : b ≤ c - a ↔ a + b ≤ c := by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le] lemma le_sub_iff_add_le : a ≤ c - b ↔ a + b ≤ c := by rw [le_sub_iff_add_le', add_comm] lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add] lemma sub_le_iff_le_add : a - c ≤ b ↔ a ≤ b + c := by rw [sub_le_iff_le_add', add_comm] @[simp] lemma neg_le_sub_iff_le_add : -b ≤ a - c ↔ c ≤ a + b := le_sub_iff_add_le.trans neg_add_le_iff_le_add' lemma neg_le_sub_iff_le_add' : -a ≤ b - c ↔ c ≤ a + b := by rw [neg_le_sub_iff_le_add, add_comm] lemma sub_le : a - b ≤ c ↔ a - c ≤ b := sub_le_iff_le_add'.trans sub_le_iff_le_add.symm theorem le_sub : a ≤ b - c ↔ c ≤ b - a := le_sub_iff_add_le'.trans le_sub_iff_add_le.symm lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c := by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt] lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c := by rw [lt_sub_iff_add_lt', add_comm] lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c := by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add] lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c := by rw [sub_lt_iff_lt_add', add_comm] @[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b := lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b := by rw [neg_lt_sub_iff_lt_add, add_comm] lemma sub_lt : a - b < c ↔ a - c < b := sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm theorem lt_sub : a < b - c ↔ c < b - a := lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm lemma sub_le_self_iff (a : α) {b : α} : a - b ≤ a ↔ 0 ≤ b := sub_le_iff_le_add'.trans (le_add_iff_nonneg_left _) lemma sub_lt_self_iff (a : α) {b : α} : a - b < a ↔ 0 < b := sub_lt_iff_lt_add'.trans (lt_add_iff_pos_left _) end ordered_add_comm_group /- TODO: The `add_lt_add_left` field of `ordered_add_comm_group` is redundant, and it is no longer in core so we can remove it now. This alternative constructor is a workaround until someone fixes this. -/ /-- Alternative constructor for ordered commutative groups, that avoids the field `mul_lt_mul_left`. -/ @[to_additive "Alternative constructor for ordered commutative groups, that avoids the field `mul_lt_mul_left`."] def ordered_comm_group.mk' {α : Type u} [comm_group α] [partial_order α] (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) : ordered_comm_group α := { mul_le_mul_left := mul_le_mul_left, ..(by apply_instance : comm_group α), ..(by apply_instance : partial_order α) } /-- A decidable linearly ordered cancellative additive commutative monoid is an additive commutative monoid with a decidable linear order in which addition is cancellative and strictly monotone. -/ @[protect_proj] class decidable_linear_ordered_cancel_add_comm_monoid (α : Type u) extends ordered_cancel_add_comm_monoid α, decidable_linear_order α section decidable_linear_ordered_cancel_add_comm_monoid variables [decidable_linear_ordered_cancel_add_comm_monoid α] lemma min_add_add_left (a b c : α) : min (a + b) (a + c) = a + min b c := eq.symm (eq_min (show a + min b c ≤ a + b, from add_le_add_left (min_le_left _ _) _) (show a + min b c ≤ a + c, from add_le_add_left (min_le_right _ _) _) (assume d, assume : d ≤ a + b, assume : d ≤ a + c, decidable.by_cases (assume : b ≤ c, by rwa [min_eq_left this]) (assume : ¬ b ≤ c, by rwa [min_eq_right (le_of_lt (lt_of_not_ge this))]))) lemma min_add_add_right (a b c : α) : min (a + c) (b + c) = min a b + c := begin rw [add_comm a c, add_comm b c, add_comm _ c], apply min_add_add_left end lemma max_add_add_left (a b c : α) : max (a + b) (a + c) = a + max b c := eq.symm (eq_max (add_le_add_left (le_max_left _ _) _) (add_le_add_left (le_max_right _ _) _) (assume d, assume : a + b ≤ d, assume : a + c ≤ d, decidable.by_cases (assume : b ≤ c, by rwa [max_eq_right this]) (assume : ¬ b ≤ c, by rwa [max_eq_left (le_of_lt (lt_of_not_ge this))]))) lemma max_add_add_right (a b c : α) : max (a + c) (b + c) = max a b + c := begin rw [add_comm a c, add_comm b c, add_comm _ c], apply max_add_add_left end end decidable_linear_ordered_cancel_add_comm_monoid /-- A decidable linearly ordered additive commutative group is an additive commutative group with a decidable linear order in which addition is strictly monotone. -/ @[protect_proj] class decidable_linear_ordered_add_comm_group (α : Type u) extends add_comm_group α, decidable_linear_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) instance decidable_linear_ordered_comm_group.to_ordered_add_comm_group (α : Type u) [s : decidable_linear_ordered_add_comm_group α] : ordered_add_comm_group α := { add := s.add, ..s } section decidable_linear_ordered_add_comm_group variables [decidable_linear_ordered_add_comm_group α] @[priority 100] -- see Note [lower instance priority] instance decidable_linear_ordered_add_comm_group.to_decidable_linear_ordered_cancel_add_comm_monoid : decidable_linear_ordered_cancel_add_comm_monoid α := { le_of_add_le_add_left := λ x y z, le_of_add_le_add_left, add_left_cancel := λ x y z, add_left_cancel, add_right_cancel := λ x y z, add_right_cancel, ..‹decidable_linear_ordered_add_comm_group α› } lemma decidable_linear_ordered_add_comm_group.add_lt_add_left (a b : α) (h : a < b) (c : α) : c + a < c + b := ordered_add_comm_group.add_lt_add_left a b h c lemma max_neg_neg (a b : α) : max (-a) (-b) = - min a b := eq.symm (eq_max (show -a ≤ -(min a b), from neg_le_neg $ min_le_left a b) (show -b ≤ -(min a b), from neg_le_neg $ min_le_right a b) (assume d, assume H₁ : -a ≤ d, assume H₂ : -b ≤ d, have H : -d ≤ min a b, from le_min (neg_le_of_neg_le H₁) (neg_le_of_neg_le H₂), show -(min a b) ≤ d, from neg_le_of_neg_le H)) lemma min_eq_neg_max_neg_neg (a b : α) : min a b = - max (-a) (-b) := by rw [max_neg_neg, neg_neg] lemma min_neg_neg (a b : α) : min (-a) (-b) = - max a b := by rw [min_eq_neg_max_neg_neg, neg_neg, neg_neg] lemma max_eq_neg_min_neg_neg (a b : α) : max a b = - min (-a) (-b) := by rw [min_neg_neg, neg_neg] /-- `abs a` is the absolute value of `a`. -/ def abs (a : α) : α := max a (-a) lemma abs_of_nonneg {a : α} (h : 0 ≤ a) : abs a = a := have h' : -a ≤ a, from le_trans (neg_nonpos_of_nonneg h) h, max_eq_left h' lemma abs_of_pos {a : α} (h : 0 < a) : abs a = a := abs_of_nonneg h.le lemma abs_of_nonpos {a : α} (h : a ≤ 0) : abs a = -a := have h' : a ≤ -a, from le_trans h (neg_nonneg_of_nonpos h), max_eq_right h' lemma abs_of_neg {a : α} (h : a < 0) : abs a = -a := abs_of_nonpos h.le lemma abs_zero : abs 0 = (0:α) := abs_of_nonneg le_rfl lemma abs_neg (a : α) : abs (-a) = abs a := begin unfold abs, rw [max_comm, neg_neg] end lemma abs_pos_of_pos {a : α} (h : 0 < a) : 0 < abs a := by rwa (abs_of_pos h) lemma abs_pos_of_neg {a : α} (h : a < 0) : 0 < abs a := abs_neg a ▸ abs_pos_of_pos (neg_pos_of_neg h) lemma abs_sub (a b : α) : abs (a - b) = abs (b - a) := by rw [← neg_sub, abs_neg] lemma ne_zero_of_abs_ne_zero {a : α} (h : abs a ≠ 0) : a ≠ 0 := by { refine mt _ h, rintro rfl, exact abs_zero } /- these assume a linear order -/ lemma eq_zero_of_neg_eq {a : α} (h : -a = a) : a = 0 := match lt_trichotomy a 0 with | or.inl h₁ := have 0 < a, from h ▸ neg_pos_of_neg h₁, absurd h₁ this.asymm | or.inr (or.inl h₁) := h₁ | or.inr (or.inr h₁) := have a < 0, from h ▸ neg_neg_of_pos h₁, absurd h₁ this.asymm end lemma abs_nonneg (a : α) : 0 ≤ abs a := or.elim (le_total 0 a) (assume h : 0 ≤ a, by rwa (abs_of_nonneg h)) (assume h : a ≤ 0, calc 0 ≤ -a : neg_nonneg_of_nonpos h ... = abs a : eq.symm (abs_of_nonpos h)) lemma abs_abs (a : α) : abs (abs a) = abs a := abs_of_nonneg $ abs_nonneg a lemma le_abs_self (a : α) : a ≤ abs a := or.elim (le_total 0 a) (assume h : 0 ≤ a, begin rw [abs_of_nonneg h] end) (assume h : a ≤ 0, h.trans $ abs_nonneg a) lemma neg_le_abs_self (a : α) : -a ≤ abs a := abs_neg a ▸ le_abs_self (-a) lemma eq_zero_of_abs_eq_zero {a : α} (h : abs a = 0) : a = 0 := have h₁ : a ≤ 0, from h ▸ le_abs_self a, have h₂ : -a ≤ 0, from h ▸ abs_neg a ▸ le_abs_self (-a), le_antisymm h₁ (nonneg_of_neg_nonpos h₂) lemma eq_of_abs_sub_eq_zero {a b : α} (h : abs (a - b) = 0) : a = b := have a - b = 0, from eq_zero_of_abs_eq_zero h, show a = b, from eq_of_sub_eq_zero this lemma abs_pos_of_ne_zero {a : α} (h : a ≠ 0) : 0 < abs a := or.elim (lt_or_gt_of_ne h) abs_pos_of_neg abs_pos_of_pos lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) := or.elim (le_total 0 a) (assume h : 0 ≤ a, eq.symm (abs_of_nonneg h) ▸ h1) (assume h : a ≤ 0, eq.symm (abs_of_nonpos h) ▸ h2) lemma abs_le_of_le_of_neg_le {a b : α} (h1 : a ≤ b) (h2 : -a ≤ b) : abs a ≤ b := abs_by_cases (λ x : α, x ≤ b) h1 h2 lemma abs_lt_of_lt_of_neg_lt {a b : α} (h1 : a < b) (h2 : -a < b) : abs a < b := abs_by_cases (λ x : α, x < b) h1 h2 private lemma aux1 {a b : α} (h1 : 0 ≤ a + b) (h2 : 0 ≤ a) : abs (a + b) ≤ abs a + abs b := decidable.by_cases (assume h3 : 0 ≤ b, calc abs (a + b) ≤ abs (a + b) : by apply le_refl ... = a + b : by rw abs_of_nonneg h1 ... = abs a + b : by rw abs_of_nonneg h2 ... = abs a + abs b : by rw abs_of_nonneg h3) (assume h3 : ¬ 0 ≤ b, have h4 : b ≤ 0, from le_of_lt (lt_of_not_ge h3), calc abs (a + b) = a + b : by rw abs_of_nonneg h1 ... = abs a + b : by rw abs_of_nonneg h2 ... ≤ abs a + 0 : add_le_add_left h4 _ ... ≤ abs a + -b : add_le_add_left (neg_nonneg_of_nonpos h4) _ ... = abs a + abs b : by rw abs_of_nonpos h4) private lemma aux2 {a b : α} (h1 : 0 ≤ a + b) : abs (a + b) ≤ abs a + abs b := (le_total b 0).elim (assume h2 : b ≤ 0, have h3 : ¬ a < 0, from assume h4 : a < 0, have h5 : a + b < 0, begin have aux := add_lt_add_of_lt_of_le h4 h2, rwa [add_zero] at aux end, not_lt_of_ge h1 h5, aux1 h1 (le_of_not_gt h3)) (assume h2 : 0 ≤ b, begin have h3 : abs (b + a) ≤ abs b + abs a, begin rw add_comm at h1, exact aux1 h1 h2 end, rw [add_comm, add_comm (abs a)], exact h3 end) lemma abs_add_le_abs_add_abs (a b : α) : abs (a + b) ≤ abs a + abs b := (le_total 0 (a + b)).elim (assume h2 : 0 ≤ a + b, aux2 h2) (assume h2 : a + b ≤ 0, have h3 : -a + -b = -(a + b), by rw neg_add, have h4 : 0 ≤ -(a + b), from neg_nonneg_of_nonpos h2, have h5 : 0 ≤ -a + -b, begin rw [← h3] at h4, exact h4 end, calc abs (a + b) = abs (-a + -b) : by rw [← abs_neg, neg_add] ... ≤ abs (-a) + abs (-b) : aux2 h5 ... = abs a + abs b : by rw [abs_neg, abs_neg]) lemma abs_sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) := have h1 : abs a - abs b + abs b ≤ abs (a - b) + abs b, from calc abs a - abs b + abs b = abs a : by rw sub_add_cancel ... = abs (a - b + b) : by rw sub_add_cancel ... ≤ abs (a - b) + abs b : by apply abs_add_le_abs_add_abs, le_of_add_le_add_right h1 lemma abs_sub_le (a b c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) := calc abs (a - c) = abs (a - b + (b - c)) : by rw [sub_eq_add_neg, sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left] ... ≤ abs (a - b) + abs (b - c) : by apply abs_add_le_abs_add_abs lemma abs_add_three (a b c : α) : abs (a + b + c) ≤ abs a + abs b + abs c := begin refine (abs_add_le_abs_add_abs _ _).trans _, apply add_le_add_right, apply abs_add_le_abs_add_abs end lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb := begin cases (decidable.em (b ≤ a)) with hba hba, rw (abs_of_nonneg (sub_nonneg_of_le hba)), apply sub_le_sub, apply hau, apply hbl, rw [abs_of_neg (sub_neg_of_lt (lt_of_not_ge hba)), neg_sub], apply sub_le_sub, apply hbu, apply hal end lemma decidable_linear_ordered_add_comm_group.eq_of_abs_sub_nonpos {a b : α} (h : abs (a - b) ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) end decidable_linear_ordered_add_comm_group set_option old_structure_cmd true section prio set_option default_priority 100 -- see Note [default priority] /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_add_comm_group (α : Type*) extends add_comm_group α := (nonneg : α → Prop) (pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a)) (pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b)) (nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0) end prio namespace nonneg_add_comm_group variable [s : nonneg_add_comm_group α] include s @[reducible, priority 100] -- see Note [lower instance priority] instance to_ordered_add_comm_group : ordered_add_comm_group α := { le := λ a b, nonneg (b - a), lt := λ a b, pos (b - a), lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp, le_refl := λ a, by simp [zero_nonneg], le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact add_nonneg nbc nab, le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $ nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab, ..s } theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem pos_def {a : α} : pos a ↔ 0 < a := show _ ↔ pos _, by simp theorem not_zero_pos : ¬ pos (0 : α) := mt pos_def.1 (lt_irrefl _) theorem zero_lt_iff_nonneg_nonneg {a : α} : 0 < a ↔ nonneg a ∧ ¬ nonneg (-a) := pos_def.symm.trans (pos_iff _) theorem nonneg_total_iff : (∀ a : α, nonneg a ∨ nonneg (-a)) ↔ (∀ a b : α, a ≤ b ∨ b ≤ a) := ⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this, λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩ /-- A `nonneg_add_comm_group` is a `decidable_linear_ordered_add_comm_group` if `nonneg` is total and decidable. -/ def to_decidable_linear_ordered_add_comm_group [decidable_pred (@nonneg α _)] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : decidable_linear_ordered_add_comm_group α := { le := (≤), lt := (<), le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..@nonneg_add_comm_group.to_ordered_add_comm_group _ s } end nonneg_add_comm_group namespace order_dual instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (order_dual α) := { add_le_add_left := λ a b h c, @add_le_add_left α _ b a h _, lt_of_add_lt_add_left := λ a b c h, @lt_of_add_lt_add_left α _ a c b h, ..order_dual.partial_order α, ..show add_comm_monoid α, by apply_instance } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_add_comm_monoid (order_dual α) := { le_of_add_le_add_left := λ a b c : α, le_of_add_le_add_left, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, ..order_dual.ordered_add_comm_monoid } instance [ordered_add_comm_group α] : ordered_add_comm_group (order_dual α) := { add_left_neg := λ a : α, add_left_neg a, ..order_dual.ordered_add_comm_monoid, ..show add_comm_group α, by apply_instance } instance [decidable_linear_ordered_add_comm_group α] : decidable_linear_ordered_add_comm_group (order_dual α) := { add_le_add_left := λ a b h c, @add_le_add_left α _ b a h _, ..order_dual.decidable_linear_order α, ..show add_comm_group α, by apply_instance } end order_dual section type_tags instance : Π [preorder α], preorder (multiplicative α) := id instance : Π [preorder α], preorder (additive α) := id instance : Π [partial_order α], partial_order (multiplicative α) := id instance : Π [partial_order α], partial_order (additive α) := id instance : Π [linear_order α], linear_order (multiplicative α) := id instance : Π [linear_order α], linear_order (additive α) := id instance : Π [decidable_linear_order α], decidable_linear_order (multiplicative α) := id instance : Π [decidable_linear_order α], decidable_linear_order (additive α) := id instance [ordered_add_comm_monoid α] : ordered_comm_monoid (multiplicative α) := { mul_le_mul_left := @ordered_add_comm_monoid.add_le_add_left α _, lt_of_mul_lt_mul_left := @ordered_add_comm_monoid.lt_of_add_lt_add_left α _, ..multiplicative.partial_order, ..multiplicative.comm_monoid } instance [ordered_comm_monoid α] : ordered_add_comm_monoid (additive α) := { add_le_add_left := @ordered_comm_monoid.mul_le_mul_left α _, lt_of_add_lt_add_left := @ordered_comm_monoid.lt_of_mul_lt_mul_left α _, ..additive.partial_order, ..additive.add_comm_monoid } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_comm_monoid (multiplicative α) := { le_of_mul_le_mul_left := @ordered_cancel_add_comm_monoid.le_of_add_le_add_left α _, ..multiplicative.right_cancel_semigroup, ..multiplicative.left_cancel_semigroup, ..multiplicative.ordered_comm_monoid } instance [ordered_cancel_comm_monoid α] : ordered_cancel_add_comm_monoid (additive α) := { le_of_add_le_add_left := @ordered_cancel_comm_monoid.le_of_mul_le_mul_left α _, ..additive.add_right_cancel_semigroup, ..additive.add_left_cancel_semigroup, ..additive.ordered_add_comm_monoid } instance [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) := { ..multiplicative.comm_group, ..multiplicative.ordered_comm_monoid } instance [ordered_comm_group α] : ordered_add_comm_group (additive α) := { ..additive.add_comm_group, ..additive.ordered_add_comm_monoid } end type_tags
c7247a38178b8be10c0d1a4791f6241b018ea34c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/jumpMutual.lean
141f9a7060c403d45983b35139c7a98eb4859508
[ "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
564
lean
mutual def h (x : Nat) : Nat := match x with | 0 => 1 --v textDocument/definition --v textDocument/definition | x+1 => f x + r x + h x --^ textDocument/definition where r : Nat → Nat | 0 => 1 --v textDocument/definition | x + 1 => r x * h x --^ textDocument/definition def f (x : Nat) : Nat := let rec g : Nat → Nat | 0 => 1 --v textDocument/definition | n+1 => 2 * g n --v textDocument/definition g x + h x --^ textDocument/definition end
cf6b7c981282b7cfea9bdd63bded693e0d3133d2
4fa118f6209450d4e8d058790e2967337811b2b5
/src/sheaves/stalk_of_rings.lean
bd2eae537559aa5c73d5f039158ec34dca071cb1
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
14,370
lean
/- Stalk of rings. https://stacks.math.columbia.edu/tag/007L (just says that the category of rings is a type of algebraic structure) Author -- Ramon Fernandez Mir -/ import topology.basic import sheaves.stalk import sheaves.presheaf_of_rings universes u v w open topological_space section stalk_of_rings variables {α : Type u} [topological_space α] variables (F : presheaf_of_rings α) (x : α) definition stalk_of_rings := stalk F.to_presheaf x end stalk_of_rings -- Stalks are rings. section stalk_of_rings_is_ring parameters {α : Type u} [topological_space α] parameters (F : presheaf_of_rings α) (x : α) -- Add. private def stalk_of_rings_add_aux : stalk.elem F.to_presheaf x → stalk.elem F.to_presheaf x → stalk F.to_presheaf x := λ s t, ⟦{U := s.U ∩ t.U, HxU := ⟨s.HxU, t.HxU⟩, s := F.res s.U _ (set.inter_subset_left _ _) s.s + F.res t.U _ (set.inter_subset_right _ _) t.s}⟧ instance stalk_of_rings_has_add : has_add (stalk_of_rings F x) := { add := quotient.lift₂ (stalk_of_rings_add_aux) $ begin intros a1 a2 b1 b2 H1 H2, let F' := F.to_presheaf, rcases H1 with ⟨U1, ⟨HxU1, ⟨HU1a1U, HU1b1U, HresU1⟩⟩⟩, rcases H2 with ⟨U2, ⟨HxU2, ⟨HU2a2U, HU2b2U, HresU2⟩⟩⟩, apply quotient.sound, use [U1 ∩ U2, ⟨HxU1, HxU2⟩], use [set.inter_subset_inter HU1a1U HU2a2U, set.inter_subset_inter HU1b1U HU2b2U], repeat { rw (F.res_is_ring_hom _ _ _).map_add }, have HresU1' : (F'.res U1 (U1 ∩ U2) (set.inter_subset_left _ _) ((F'.res a1.U U1 HU1a1U) (a1.s))) = (F'.res U1 (U1 ∩ U2) (set.inter_subset_left _ _) ((F'.res b1.U U1 HU1b1U) (b1.s))) := by rw HresU1, have HresU2' : (F'.res U2 (U1 ∩ U2) (set.inter_subset_right _ _) ((F'.res a2.U U2 HU2a2U) (a2.s))) = (F'.res U2 (U1 ∩ U2) (set.inter_subset_right _ _) ((F'.res b2.U U2 HU2b2U) (b2.s))) := by rw HresU2, repeat { rw ←(presheaf.Hcomp' F') at HresU1' }, repeat { rw ←(presheaf.Hcomp' F') at HresU2' }, repeat { rw ←(presheaf.Hcomp' F') }, rw [HresU1', HresU2'], end } instance stalk_of_rings_add_semigroup : add_semigroup (stalk_of_rings F x) := { add := stalk_of_rings_has_add.add, add_assoc := begin intros a b c, refine quotient.induction_on₃ a b c _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩ ⟨W, HxW, sW⟩, have HUVWsub : U ∩ V ∩ W ⊆ U ∩ (V ∩ W) := λ x ⟨⟨HxU, HxV⟩, HxW⟩, ⟨HxU, ⟨HxV, HxW⟩⟩, apply quotient.sound, use [U ∩ V ∩ W, ⟨⟨HxU, HxV⟩, HxW⟩], use [set.subset.refl _, HUVWsub], dsimp, repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { erw ←presheaf.Hcomp' }, rw add_assoc, end } instance stalk_of_rings_add_comm_semigroup : add_comm_semigroup (stalk_of_rings F x) := { add_comm := begin intros a b, refine quotient.induction_on₂ a b _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩, apply quotient.sound, have HUVUV : U ∩ V ⊆ U ∩ V := λ x HxUV, HxUV, have HUVVU : U ∩ V ⊆ V ∩ U := λ x ⟨HxU, HxV⟩, ⟨HxV, HxU⟩, use [U ∩ V, ⟨HxU, HxV⟩, HUVUV, HUVVU], repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, rw add_comm, end, ..stalk_of_rings_add_semigroup } -- Zero. private def stalk_of_rings_zero : stalk_of_rings F x := ⟦{U := opens.univ, HxU := trivial, s:= 0}⟧ instance stalk_of_rings_has_zero : has_zero (stalk_of_rings F x) := { zero := stalk_of_rings_zero } instance stalk_of_rings_add_comm_monoid : add_comm_monoid (stalk_of_rings F x) := { zero := stalk_of_rings_zero, zero_add := begin intros a, refine quotient.induction_on a _, rintros ⟨U, HxU, sU⟩, apply quotient.sound, have HUsub : U ⊆ opens.univ ∩ U := λ x HxU, ⟨trivial, HxU⟩, use [U, HxU, HUsub, set.subset.refl U], repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, erw (is_ring_hom.map_zero ((F.to_presheaf).res _ _ _)); try { apply_instance }, rw zero_add, refl, end, add_zero := begin intros a, refine quotient.induction_on a _, rintros ⟨U, HxU, sU⟩, apply quotient.sound, have HUsub : U ⊆ U ∩ opens.univ := λ x HxU, ⟨HxU, trivial⟩, use [U, HxU, HUsub, set.subset.refl U], repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { erw ←presheaf.Hcomp' }, dsimp, erw (is_ring_hom.map_zero ((F.to_presheaf).res _ _ _)); try { apply_instance }, rw add_zero, refl, end, ..stalk_of_rings_add_comm_semigroup } -- Neg. private def stalk_sub_aux : stalk.elem F.to_presheaf x → stalk F.to_presheaf x := λ s, ⟦{U := s.U, HxU := s.HxU, s := -s.s}⟧ instance stalk_of_rings_has_neg : has_neg (stalk_of_rings F x) := { neg := quotient.lift stalk_sub_aux $ begin intros a b H, rcases H with ⟨U, ⟨HxU, ⟨HUaU, HUbU, HresU⟩⟩⟩, apply quotient.sound, use [U, HxU, HUaU, HUbU], repeat { rw @is_ring_hom.map_neg _ _ _ _ _ (F.res_is_ring_hom _ _ _) }, rw HresU, end } instance stalk_of_rings_add_comm_group : add_comm_group (stalk_of_rings F x) := { neg := stalk_of_rings_has_neg.neg, add_left_neg := begin intros a, refine quotient.induction_on a _, rintros ⟨U, HxU, sU⟩, apply quotient.sound, have HUUU : U ⊆ U ∩ U := λ x HxU, ⟨HxU, HxU⟩, have HUuniv : U ⊆ opens.univ := λ x HxU, trivial, use [U, HxU, HUUU, HUuniv], repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, erw (is_ring_hom.map_neg ((F.to_presheaf).res _ _ _)); try { apply_instance }, rw add_left_neg, erw (is_ring_hom.map_zero ((F.to_presheaf).res _ _ _)); try { apply_instance }, end, ..stalk_of_rings_add_comm_monoid } -- Mul. private def stalk_of_rings_mul_aux : stalk.elem F.to_presheaf x → stalk.elem F.to_presheaf x → stalk F.to_presheaf x := λ s t, ⟦{U := s.U ∩ t.U, HxU := ⟨s.HxU, t.HxU⟩, s := F.res s.U _ (set.inter_subset_left _ _) s.s * F.res t.U _ (set.inter_subset_right _ _) t.s}⟧ instance stalk_of_rings_has_mul : has_mul (stalk_of_rings F x) := { mul := quotient.lift₂ (stalk_of_rings_mul_aux) $ begin intros a1 a2 b1 b2 H1 H2, let F' := F.to_presheaf, rcases H1 with ⟨U1, ⟨HxU1, ⟨HU1a1U, HU1b1U, HresU1⟩⟩⟩, rcases H2 with ⟨U2, ⟨HxU2, ⟨HU2a2U, HU2b2U, HresU2⟩⟩⟩, apply quotient.sound, use [U1 ∩ U2, ⟨HxU1, HxU2⟩], use [set.inter_subset_inter HU1a1U HU2a2U, set.inter_subset_inter HU1b1U HU2b2U], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, have HresU1' : (F'.res U1 (U1 ∩ U2) (set.inter_subset_left _ _) ((F'.res a1.U U1 HU1a1U) (a1.s))) = (F'.res U1 (U1 ∩ U2) (set.inter_subset_left _ _) ((F'.res b1.U U1 HU1b1U) (b1.s))) := by rw HresU1, have HresU2' : (F'.res U2 (U1 ∩ U2) (set.inter_subset_right _ _) ((F'.res a2.U U2 HU2a2U) (a2.s))) = (F'.res U2 (U1 ∩ U2) (set.inter_subset_right _ _) ((F'.res b2.U U2 HU2b2U) (b2.s))) := by rw HresU2, repeat { rw ←(presheaf.Hcomp' F') at HresU1' }, repeat { rw ←(presheaf.Hcomp' F') at HresU2' }, repeat { rw ←(presheaf.Hcomp' F') }, rw [HresU1', HresU2'], end } instance stalk_of_rings_mul_semigroup : semigroup (stalk_of_rings F x) := { mul := stalk_of_rings_has_mul.mul, mul_assoc := begin intros a b c, refine quotient.induction_on₃ a b c _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩ ⟨W, HxW, sW⟩, have HUVWsub : U ∩ V ∩ W ⊆ U ∩ (V ∩ W) := λ x ⟨⟨HxU, HxV⟩, HxW⟩, ⟨HxU, ⟨HxV, HxW⟩⟩, apply quotient.sound, use [U ∩ V ∩ W, ⟨⟨HxU, HxV⟩, HxW⟩], use [set.subset.refl _, HUVWsub], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw ←presheaf.Hcomp' }, rw mul_assoc, end } instance stalk_of_rings_mul_comm_semigroup : comm_semigroup (stalk_of_rings F x) := { mul_comm := begin intros a b, refine quotient.induction_on₂ a b _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩, apply quotient.sound, have HUVUV : U ∩ V ⊆ U ∩ V := λ x HxUV, HxUV, have HUVVU : U ∩ V ⊆ V ∩ U := λ x ⟨HxU, HxV⟩, ⟨HxV, HxU⟩, use [U ∩ V, ⟨HxU, HxV⟩, HUVUV, HUVVU], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw ←presheaf.Hcomp' }, rw mul_comm, end, ..stalk_of_rings_mul_semigroup } -- One. private def stalk_of_rings_one : stalk_of_rings F x := ⟦{U := opens.univ, HxU := trivial, s:= 1}⟧ instance stalk_of_rings_has_one : has_one (stalk_of_rings F x) := { one := stalk_of_rings_one } instance stalk_of_rings_mul_comm_monoid : comm_monoid (stalk_of_rings F x) := { one := stalk_of_rings_one, one_mul := begin intros a, refine quotient.induction_on a _, rintros ⟨U, HxU, sU⟩, apply quotient.sound, have HUsub : U ⊆ opens.univ ∩ U := λ x HxU, ⟨trivial, HxU⟩, use [U, HxU, HUsub, set.subset.refl U], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw ←presheaf.Hcomp' }, erw (is_ring_hom.map_one ((F.to_presheaf).res _ _ _)); try { apply_instance }, rw one_mul, refl, end, mul_one := begin intros a, refine quotient.induction_on a _, rintros ⟨U, HxU, sU⟩, apply quotient.sound, have HUsub : U ⊆ U ∩ opens.univ := λ x HxU, ⟨HxU, trivial⟩, use [U, HxU, HUsub, set.subset.refl U], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw ←presheaf.Hcomp' }, dsimp, erw (is_ring_hom.map_one ((F.to_presheaf).res _ _ _)); try { apply_instance }, rw mul_one, refl, end, ..stalk_of_rings_mul_comm_semigroup } -- Ring. instance stalk_of_rings_is_comm_ring : comm_ring (stalk_of_rings F x) := { left_distrib := begin intros a b c, refine quotient.induction_on₃ a b c _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩ ⟨W, HxW, sW⟩, have HUVWsub : U ∩ V ∩ W ⊆ U ∩ (V ∩ W) := λ x ⟨⟨HxU, HxV⟩, HxW⟩, ⟨HxU, ⟨HxV, HxW⟩⟩, have HUVWsub2 : U ∩ V ∩ W ⊆ U ∩ V ∩ (U ∩ W) := λ x ⟨⟨HxU, HxV⟩, HxW⟩, ⟨⟨HxU, HxV⟩, ⟨HxU, HxW⟩⟩, apply quotient.sound, use [U ∩ V ∩ W, ⟨⟨HxU, HxV⟩, HxW⟩, HUVWsub, HUVWsub2], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, rw mul_add, end, right_distrib := begin intros a b c, refine quotient.induction_on₃ a b c _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩ ⟨W, HxW, sW⟩, have HUVWrfl : U ∩ V ∩ W ⊆ U ∩ V ∩ W := λ x Hx, Hx, have HUVWsub : U ∩ V ∩ W ⊆ U ∩ W ∩ (V ∩ W) := λ x ⟨⟨HxU, HxV⟩, HxW⟩, ⟨⟨HxU, HxW⟩, ⟨HxV, HxW⟩⟩, apply quotient.sound, use [U ∩ V ∩ W, ⟨⟨HxU, HxV⟩, HxW⟩, HUVWrfl, HUVWsub], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, rw add_mul, end, ..stalk_of_rings_add_comm_group, ..stalk_of_rings_mul_comm_monoid } end stalk_of_rings_is_ring -- Stalks are colimits. section stalk_colimit variables {α : Type u} [topological_space α] variables (F : presheaf_of_rings α) (x : α) variables (S : Type w) [comm_ring S] [decidable_eq S] variables (G : Π U, x ∈ U → F.F U → S) [HG : ∀ U, ∀ (h : x ∈ U), is_ring_hom (G U h)] variables (hg : ∀ U V (H : U ⊆ V) r, ∀ (h : x ∈ U), G U h (F.res V U H r) = G V (H h) r) def to_stalk (U : opens α) (HxU : x ∈ U) (s : F.F U) : stalk_of_rings F x := ⟦{U := U, HxU := HxU, s := s}⟧ instance to_stalk.is_ring_hom (U) (HxU) : is_ring_hom (to_stalk F x U HxU) := { map_one := quotient.sound $ ⟨U, HxU, set.subset.refl _, λ x Hx, trivial, begin erw (F.res_is_ring_hom _ _ _).map_one, erw (F.res_is_ring_hom _ _ _).map_one, end⟩, map_add := λ y z, quotient.sound $ ⟨U, HxU, set.subset.refl _, λ x Hx, ⟨Hx, Hx⟩, begin erw ←(F.res_is_ring_hom _ _ _).map_add, erw presheaf.Hcomp', end⟩, map_mul := λ y z, quotient.sound $ ⟨U, HxU, set.subset.refl _, λ x Hx, ⟨Hx, Hx⟩, begin erw ←(F.res_is_ring_hom _ _ _).map_mul, erw presheaf.Hcomp', end⟩ } include hg protected def to_stalk.rec (y : stalk_of_rings F x) : S := quotient.lift_on' y (λ Us, G Us.1 Us.2 Us.3) $ λ ⟨U, HxU, s⟩ ⟨V, HxV, t⟩ ⟨W, HxW, HWU, HWV, Hres⟩, begin dsimp, erw [←hg W U HWU s HxW, ←hg W V HWV t HxW, Hres], end /- to_stalk.rec : Π {α : Type u} [_inst_1 : topological_space α] (F : presheaf_of_rings α) (x : α) (S : Type w) [_inst_2 : comm_ring S] [_inst_3 : decidable_eq S] (G : Π (U : opens α), (F.to_presheaf).F U → S), (∀ (U V : opens α) (H : U ⊆ V) (r : (F.to_presheaf).F V), G U ((F.to_presheaf).res V U H r) = G V r) → stalk_of_rings F x → S -/ theorem to_stalk.rec_to_stalk (U HxU s) : to_stalk.rec F x S G hg (to_stalk F x U HxU s) = G U HxU s := rfl include HG instance to_stalk.rec_is_ring_hom : is_ring_hom (to_stalk.rec F x S G hg) := { map_one := (HG opens.univ (set.mem_univ x)).map_one ▸ rfl, map_add := λ y z, quotient.induction_on₂' y z $ λ ⟨U, HxU, s⟩ ⟨V, HxV, t⟩, begin have HxUV : x ∈ U ∩ V := ⟨HxU, HxV⟩, show G (U ∩ V) HxUV (_ + _) = G _ _ _ + G _ _ _, rw (HG (U ∩ V) HxUV).map_add, erw ←hg (U ∩ V) U (set.inter_subset_left _ _), erw ←hg (U ∩ V) V (set.inter_subset_right _ _), end, map_mul := λ y z, quotient.induction_on₂' y z $ λ ⟨U, HxU, s⟩ ⟨V, HxV, t⟩, begin have HxUV : x ∈ U ∩ V := ⟨HxU, HxV⟩, show G (U ∩ V) HxUV (_ * _) = G _ _ _ * G _ _ _, rw (HG (U ∩ V) HxUV).map_mul, erw ←hg (U ∩ V) U (set.inter_subset_left _ _), erw ←hg (U ∩ V) V (set.inter_subset_right _ _), end } end stalk_colimit
f94d52d54f0b0df425ecc6d02b3b6d90acdc6d71
618003631150032a5676f229d13a079ac875ff77
/src/set_theory/game/domineering.lean
528f9b444d09dc937f9029978b7cf1e2a33c84bd
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
7,935
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import set_theory.game.state /-! # Domineering as a combinatorial game. We define the game of Domineering, played on a chessboard of arbitrary shape (possibly even disconnected). Left moves by placing a domino vertically, while Right moves by placing a domino horizontally. This is only a fragment of a full development; in order to successfully analyse positions we would need some more theorems. Most importantly, we need a general statement that allows us to discard irrelevant moves. Specifically to domineering, we need the fact that disjoint parts of the chessboard give sums of games. -/ namespace pgame namespace domineering open function /-- The embedding `(x, y) ↦ (x, y+1)`. -/ def shift_up : ℤ × ℤ ↪ ℤ × ℤ := ⟨λ p : ℤ × ℤ, (p.1, p.2 + 1), have injective (λ (n : ℤ), n + 1) := λ _ _, (add_left_inj 1).mp, injective_id.prod this⟩ /-- The embedding `(x, y) ↦ (x+1, y)`. -/ def shift_right : ℤ × ℤ ↪ ℤ × ℤ := ⟨λ p : ℤ × ℤ, (p.1 + 1, p.2), have injective (λ (n : ℤ), n + 1) := λ _ _, (add_left_inj 1).mp, this.prod injective_id⟩ /-- A Domineering board is an arbitrary finite subset of `ℤ × ℤ`. -/ @[derive inhabited] def board := finset (ℤ × ℤ) local attribute [reducible] board /-- Left can play anywhere that a square and the square below it are open. -/ def left (b : board) : finset (ℤ × ℤ) := b ∩ b.map shift_up /-- Right can play anywhere that a square and the square to the left are open. -/ def right (b : board) : finset (ℤ × ℤ) := b ∩ b.map shift_right /-- After Left moves, two vertically adjacent squares are removed from the board. -/ def move_left (b : board) (m : ℤ × ℤ) : board := (b.erase m).erase (m.1, m.2 - 1) /-- After Left moves, two horizontally adjacent squares are removed from the board. -/ def move_right (b : board) (m : ℤ × ℤ) : board := (b.erase m).erase (m.1 - 1, m.2) lemma card_of_mem_left {b : board} {m : ℤ × ℤ} (h : m ∈ left b) : 2 ≤ finset.card b := begin dsimp [left] at h, have w₁ : m ∈ b, { rw finset.mem_inter at h, exact h.1 }, have w₂ : (m.1, m.2 - 1) ∈ b.erase m, { simp only [finset.mem_erase], fsplit, { exact λ w, pred_ne_self m.2 (congr_arg prod.snd w) }, { rw finset.mem_inter at h, have h₂ := h.2, clear h, rw finset.mem_map at h₂, rcases h₂ with ⟨m', ⟨h₂, rfl⟩⟩, dsimp [shift_up], simpa, }, }, have i₁ := finset.card_erase_lt_of_mem w₁, have i₂ := nat.lt_of_le_of_lt (nat.zero_le _) (finset.card_erase_lt_of_mem w₂), exact nat.lt_of_le_of_lt i₂ i₁, end lemma card_of_mem_right {b : board} {m : ℤ × ℤ} (h : m ∈ right b) : 2 ≤ finset.card b := begin dsimp [right] at h, have w₁ : m ∈ b, { rw finset.mem_inter at h, exact h.1 }, have w₂ : (m.1 - 1, m.2) ∈ b.erase m, { simp only [finset.mem_erase], fsplit, { exact λ w, pred_ne_self m.1 (congr_arg prod.fst w) }, { rw finset.mem_inter at h, have h₂ := h.2, clear h, rw finset.mem_map at h₂, rcases h₂ with ⟨m', ⟨h₂, rfl⟩⟩, dsimp [shift_right], simpa, }, }, have i₁ := finset.card_erase_lt_of_mem w₁, have i₂ := nat.lt_of_le_of_lt (nat.zero_le _) (finset.card_erase_lt_of_mem w₂), exact nat.lt_of_le_of_lt i₂ i₁, end lemma move_left_card {b : board} {m : ℤ × ℤ} (h : m ∈ left b) : finset.card (move_left b m) + 2 = finset.card b := begin dsimp [move_left], rw finset.card_erase_of_mem, { rw finset.card_erase_of_mem, { exact nat.sub_add_cancel (card_of_mem_left h), }, { exact finset.mem_of_mem_inter_left h, } }, { apply finset.mem_erase_of_ne_of_mem, { exact λ w, pred_ne_self m.2 (congr_arg prod.snd w), }, { have t := finset.mem_of_mem_inter_right h, dsimp [shift_up] at t, simp only [finset.mem_map, prod.exists] at t, rcases t with ⟨x,y,w,h⟩, rw ←h, convert w, simp, } } end lemma move_right_card {b : board} {m : ℤ × ℤ} (h : m ∈ right b) : finset.card (move_right b m) + 2 = finset.card b := begin dsimp [move_right], rw finset.card_erase_of_mem, { rw finset.card_erase_of_mem, { exact nat.sub_add_cancel (card_of_mem_right h), }, { exact finset.mem_of_mem_inter_left h, } }, { apply finset.mem_erase_of_ne_of_mem, { exact λ w, pred_ne_self m.1 (congr_arg prod.fst w), }, { have t := finset.mem_of_mem_inter_right h, dsimp [shift_right] at t, simp only [finset.mem_map, prod.exists] at t, rcases t with ⟨x,y,w,h⟩, rw ←h, convert w, simp, } } end lemma move_left_smaller {b : board} {m : ℤ × ℤ} (h : m ∈ left b) : finset.card (move_left b m) / 2 < finset.card b / 2 := by simp [←move_left_card h, lt_add_one] lemma move_right_smaller {b : board} {m : ℤ × ℤ} (h : m ∈ right b) : finset.card (move_right b m) / 2 < finset.card b / 2 := by simp [←move_right_card h, lt_add_one] /-- The instance describing allowed moves on a Domineering board. -/ instance state : state board := { turn_bound := λ s, s.card / 2, L := λ s, (left s).image (move_left s), R := λ s, (right s).image (move_right s), left_bound := λ s t m, begin simp only [finset.mem_image, prod.exists] at m, rcases m with ⟨_, _, ⟨h, rfl⟩⟩, exact move_left_smaller h end, right_bound := λ s t m, begin simp only [finset.mem_image, prod.exists] at m, rcases m with ⟨_, _, ⟨h, rfl⟩⟩, exact move_right_smaller h end, } end domineering /-- Construct a pre-game from a Domineering board. -/ def domineering (b : domineering.board) : pgame := pgame.of b /-- All games of Domineering are short, because each move removes two squares. -/ instance short_domineering (b : domineering.board) : short (domineering b) := by { dsimp [domineering], apply_instance } /-- The Domineering board with two squares arranged vertically, in which Left has the only move. -/ def domineering.one := domineering ([(0,0), (0,1)].to_finset) /-- The `L` shaped Domineering board, in which Left is exactly half a move ahead. -/ def domineering.L := domineering ([(0,2), (0,1), (0,0), (1,0)].to_finset) instance short_one : short domineering.one := by { dsimp [domineering.one], apply_instance } instance short_L : short domineering.L := by { dsimp [domineering.L], apply_instance } -- The VM can play small games successfully: -- #eval to_bool (domineering.one ≈ 1) -- #eval to_bool (domineering.L + domineering.L ≈ 1) -- We can check that `decidable` instances reduce as expected, -- and so our implementation of domineering is computable. -- run_cmd tactic.whnf `(by apply_instance : decidable (domineering.one ≤ 1)) >>= tactic.trace -- dec_trivial can handle most of the dictionary of small games described in [conway2001] example : domineering.one ≈ 1 := dec_trivial example : domineering.L + domineering.L ≈ 1 := dec_trivial example : domineering.L ≈ pgame.of_lists [0] [1] := dec_trivial example : (domineering ([(0,0), (0,1), (0,2), (0,3)].to_finset) ≈ 2) := dec_trivial example : (domineering ([(0,0), (0,1), (1,0), (1,1)].to_finset) ≈ pgame.of_lists [1] [-1]) := dec_trivial. -- The 3x3 grid is doable, but takes a minute... -- example : -- (domineering ([(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)].to_finset) ≈ -- pgame.of_lists [1] [-1]) := dec_trivial -- The 5x5 grid is actually 0, but brute-forcing this is too challenging even for the VM. -- #eval to_bool (domineering ([ -- (0,0), (0,1), (0,2), (0,3), (0,4), -- (1,0), (1,1), (1,2), (1,3), (1,4), -- (2,0), (2,1), (2,2), (2,3), (2,4), -- (3,0), (3,1), (3,2), (3,3), (3,4), -- (4,0), (4,1), (4,2), (4,3), (4,4) -- ].to_finset) ≈ 0) end pgame
c0aeb2db2dc46cb53bb30387a32039f7eeb49739
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/group_theory/coset.lean
399b04ff0351c4d2546128afb32808ac14be346f
[ "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
19,805
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import group_theory.subgroup.basic /-! # Cosets This file develops the basic theory of left and right cosets. ## Main definitions * `left_coset a s`: the left coset `a * s` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `left_add_coset a s`. * `right_coset s a`: the right coset `s * a` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `right_add_coset s a`. * `quotient_group.quotient s`: the quotient type representing the left cosets with respect to a subgroup `s`, for an `add_group` this is `quotient_add_group.quotient s`. * `quotient_group.mk`: the canonical map from `α` to `α/s` for a subgroup `s` of `α`, for an `add_group` this is `quotient_add_group.mk`. * `subgroup.left_coset_equiv_subgroup`: the natural bijection between a left coset and the subgroup, for an `add_group` this is `add_subgroup.left_coset_equiv_add_subgroup`. ## Notation * `a *l s`: for `left_coset a s`. * `a +l s`: for `left_add_coset a s`. * `s *r a`: for `right_coset s a`. * `s +r a`: for `right_add_coset s a`. ## TODO Add `to_additive` to `preimage_mk_equiv_subgroup_times_set`. -/ open set function variable {α : Type*} /-- The left coset `a * s` for an element `a : α` and a subset `s : set α` -/ @[to_additive left_add_coset "The left coset `a+s` for an element `a : α` and a subset `s : set α`"] def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s /-- The right coset `s * a` for an element `a : α` and a subset `s : set α` -/ @[to_additive right_add_coset "The right coset `s+a` for an element `a : α` and a subset `s : set α`"] def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s localized "infix ` *l `:70 := left_coset" in coset localized "infix ` +l `:70 := left_add_coset" in coset localized "infix ` *r `:70 := right_coset" in coset localized "infix ` +r `:70 := right_add_coset" in coset section coset_mul variable [has_mul α] @[to_additive mem_left_add_coset] lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s := mem_image_of_mem (λ b : α, a * b) hxS @[to_additive mem_right_add_coset] lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a := mem_image_of_mem (λ b : α, b * a) hxS /-- Equality of two left cosets `a * s` and `b * s`. -/ @[to_additive left_add_coset_equivalence "Equality of two left cosets `a + s` and `b + s`."] def left_coset_equivalence (s : set α) (a b : α) := a *l s = b *l s @[to_additive left_add_coset_equivalence_rel] lemma left_coset_equivalence_rel (s : set α) : equivalence (left_coset_equivalence s) := mk_equivalence (left_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) /-- Equality of two right cosets `s * a` and `s * b`. -/ @[to_additive right_add_coset_equivalence "Equality of two right cosets `s + a` and `s + b`."] def right_coset_equivalence (s : set α) (a b : α) := s *r a = s *r b @[to_additive right_add_coset_equivalence_rel] lemma right_coset_equivalence_rel (s : set α) : equivalence (right_coset_equivalence s) := mk_equivalence (right_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) end coset_mul section coset_semigroup variable [semigroup α] @[simp, to_additive left_add_coset_assoc] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] @[simp, to_additive right_add_coset_assoc] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] @[to_additive left_add_coset_right_add_coset] lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] end coset_semigroup section coset_monoid variables [monoid α] (s : set α) @[simp, to_additive zero_left_add_coset] lemma one_left_coset : 1 *l s = s := set.ext $ by simp [left_coset] @[simp, to_additive right_add_coset_zero] lemma right_coset_one : s *r 1 = s := set.ext $ by simp [right_coset] end coset_monoid section coset_submonoid open submonoid variables [monoid α] (s : submonoid α) @[to_additive mem_own_left_add_coset] lemma mem_own_left_coset (a : α) : a ∈ a *l s := suffices a * 1 ∈ a *l s, by simpa, mem_left_coset a (one_mem s) @[to_additive mem_own_right_add_coset] lemma mem_own_right_coset (a : α) : a ∈ (s : set α) *r a := suffices 1 * a ∈ (s : set α) *r a, by simpa, mem_right_coset a (one_mem s) @[to_additive mem_left_add_coset_left_add_coset] lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_left_coset s a @[to_additive mem_right_add_coset_right_add_coset] lemma mem_right_coset_right_coset {a : α} (ha : (s : set α) *r a = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_right_coset s a end coset_submonoid section coset_group variables [group α] {s : set α} {x : α} @[to_additive mem_left_add_coset_iff] lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨a⁻¹ * x, h, by simp⟩) @[to_additive mem_right_add_coset_iff] lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨x * a⁻¹, h, by simp⟩) end coset_group section coset_subgroup open subgroup variables [group α] (s : subgroup α) @[to_additive left_add_coset_mem_left_add_coset] lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s := set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_left s (s.inv_mem ha)] @[to_additive right_add_coset_mem_right_add_coset] lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : (s : set α) *r a = s := set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_right s (s.inv_mem ha)] @[to_additive eq_add_cosets_of_normal] theorem eq_cosets_of_normal (N : s.normal) (g : α) : g *l s = s *r g := set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [N.mem_comm_iff] @[to_additive normal_of_eq_add_cosets] theorem normal_of_eq_cosets (h : ∀ g : α, g *l s = s *r g) : s.normal := ⟨assume a ha g, show g * a * g⁻¹ ∈ (s : set α), by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩ @[to_additive normal_iff_eq_add_cosets] theorem normal_iff_eq_cosets : s.normal ↔ ∀ g : α, g *l s = s *r g := ⟨@eq_cosets_of_normal _ _ s, normal_of_eq_cosets s⟩ @[to_additive left_add_coset_eq_iff] lemma left_coset_eq_iff {x y : α} : left_coset x s = left_coset y s ↔ x⁻¹ * y ∈ s := begin rw set.ext_iff, simp_rw [mem_left_coset_iff, set_like.mem_coe], split, { intro h, apply (h y).mpr, rw mul_left_inv, exact s.one_mem }, { intros h z, rw ←mul_inv_cancel_right x⁻¹ y, rw mul_assoc, exact s.mul_mem_cancel_left h }, end @[to_additive right_add_coset_eq_iff] lemma right_coset_eq_iff {x y : α} : right_coset ↑s x = right_coset s y ↔ y * x⁻¹ ∈ s := begin rw set.ext_iff, simp_rw [mem_right_coset_iff, set_like.mem_coe], split, { intro h, apply (h y).mpr, rw mul_right_inv, exact s.one_mem }, { intros h z, rw ←inv_mul_cancel_left y x⁻¹, rw ←mul_assoc, exact s.mul_mem_cancel_right h }, end end coset_subgroup run_cmd to_additive.map_namespace `quotient_group `quotient_add_group namespace quotient_group variables [group α] (s : subgroup α) /-- The equivalence relation corresponding to the partition of a group by left cosets of a subgroup.-/ @[to_additive "The equivalence relation corresponding to the partition of a group by left cosets of a subgroup."] def left_rel : setoid α := ⟨λ x y, x⁻¹ * y ∈ s, by { simp_rw ←left_coset_eq_iff, exact left_coset_equivalence_rel s }⟩ lemma left_rel_r_eq_left_coset_equivalence : @setoid.r _ (quotient_group.left_rel s) = left_coset_equivalence s := by { ext, exact (left_coset_eq_iff s).symm } @[to_additive] instance left_rel_decidable [decidable_pred (∈ s)] : decidable_rel (left_rel s).r := λ x y, ‹decidable_pred (∈ s)› _ /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ def quotient : Type* := quotient (left_rel s) /-- The equivalence relation corresponding to the partition of a group by right cosets of a subgroup. -/ @[to_additive "The equivalence relation corresponding to the partition of a group by right cosets of a subgroup."] def right_rel : setoid α := ⟨λ x y, y * x⁻¹ ∈ s, by { simp_rw ←right_coset_eq_iff, exact right_coset_equivalence_rel s }⟩ lemma right_rel_r_eq_right_coset_equivalence : @setoid.r _ (quotient_group.right_rel s) = right_coset_equivalence s := by { ext, exact (right_coset_eq_iff s).symm } @[to_additive] instance right_rel_decidable [decidable_pred (∈ s)] : decidable_rel (right_rel s).r := λ x y, ‹decidable_pred (∈ s)› _ end quotient_group namespace quotient_add_group /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ def quotient [add_group α] (s : add_subgroup α) : Type* := quotient (left_rel s) end quotient_add_group attribute [to_additive quotient_add_group.quotient] quotient_group.quotient namespace quotient_group variables [group α] {s : subgroup α} @[to_additive] instance fintype [fintype α] (s : subgroup α) [decidable_rel (left_rel s).r] : fintype (quotient_group.quotient s) := quotient.fintype (left_rel s) /-- The canonical map from a group `α` to the quotient `α/s`. -/ @[to_additive "The canonical map from an `add_group` `α` to the quotient `α/s`."] abbreviation mk (a : α) : quotient s := quotient.mk' a @[elab_as_eliminator, to_additive] lemma induction_on {C : quotient s → Prop} (x : quotient s) (H : ∀ z, C (quotient_group.mk z)) : C x := quotient.induction_on' x H @[to_additive] instance : has_coe_t α (quotient s) := ⟨mk⟩ -- note [use has_coe_t] @[elab_as_eliminator, to_additive] lemma induction_on' {C : quotient s → Prop} (x : quotient s) (H : ∀ z : α, C z) : C x := quotient.induction_on' x H @[to_additive] lemma forall_coe {C : quotient s → Prop} : (∀ x : quotient s, C x) ↔ ∀ x : α, C x := ⟨λ hx x, hx _, quot.ind⟩ @[to_additive] instance (s : subgroup α) : inhabited (quotient s) := ⟨((1 : α) : quotient s)⟩ @[to_additive quotient_add_group.eq] protected lemma eq {a b : α} : (a : quotient s) = b ↔ a⁻¹ * b ∈ s := quotient.eq' @[to_additive quotient_add_group.eq'] lemma eq' {a b : α} : (mk a : quotient s) = mk b ↔ a⁻¹ * b ∈ s := quotient_group.eq @[to_additive quotient_add_group.out_eq'] lemma out_eq' (a : quotient s) : mk a.out' = a := quotient.out_eq' a variables (s) /- It can be useful to write `obtain ⟨h, H⟩ := mk_out'_eq_mul ...`, and then `rw [H]` or `simp_rw [H]` or `simp only [H]`. In order for `simp_rw` and `simp only` to work, this lemma is stated in terms of an arbitrary `h : s`, rathern that the specific `h = g⁻¹ * (mk g).out'`. -/ @[to_additive quotient_add_group.mk_out'_eq_mul] lemma mk_out'_eq_mul (g : α) : ∃ h : s, (mk g : quotient s).out' = g * h := ⟨⟨g⁻¹ * (mk g).out', eq'.mp (mk g).out_eq'.symm⟩, by rw [s.coe_mk, mul_inv_cancel_left]⟩ variables {s} @[to_additive quotient_add_group.mk_mul_of_mem] lemma mk_mul_of_mem (g₁ g₂ : α) (hg₂ : g₂ ∈ s) : (mk (g₁ * g₂) : quotient s) = mk g₁ := by rwa [eq', mul_inv_rev, inv_mul_cancel_right, s.inv_mem_iff] @[to_additive] lemma eq_class_eq_left_coset (s : subgroup α) (g : α) : {x : α | (x : quotient s) = g} = left_coset g s := set.ext $ λ z, by rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq, set_like.mem_coe] @[to_additive] lemma preimage_image_coe (N : subgroup α) (s : set α) : coe ⁻¹' ((coe : α → quotient N) '' s) = ⋃ x : N, (λ y : α, y * x) ⁻¹' s := begin ext x, simp only [quotient_group.eq, set_like.exists, exists_prop, set.mem_preimage, set.mem_Union, set.mem_image, subgroup.coe_mk, ← eq_inv_mul_iff_mul_eq], exact ⟨λ ⟨y, hs, hN⟩, ⟨_, N.inv_mem hN, by simpa using hs⟩, λ ⟨z, hz, hxz⟩, ⟨x*z, hxz, by simpa using hz⟩⟩, end end quotient_group namespace subgroup open quotient_group variables [group α] {s : subgroup α} /-- The natural bijection between a left coset `g * s` and `s`. -/ @[to_additive "The natural bijection between the cosets `g + s` and `s`."] def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s := ⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩, λ x, ⟨g * x.1, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- The natural bijection between a right coset `s * g` and `s`. -/ @[to_additive "The natural bijection between the cosets `s + g` and `s`."] def right_coset_equiv_subgroup (g : α) : right_coset ↑s g ≃ s := ⟨λ x, ⟨x.1 * g⁻¹, (mem_right_coset_iff _).1 x.2⟩, λ x, ⟨x.1 * g, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- A (non-canonical) bijection between a group `α` and the product `(α/s) × s` -/ @[to_additive "A (non-canonical) bijection between an add_group `α` and the product `(α/s) × s`"] noncomputable def group_equiv_quotient_times_subgroup : α ≃ quotient s × s := calc α ≃ Σ L : quotient s, {x : α // (x : quotient s) = L} : (equiv.sigma_preimage_equiv quotient_group.mk).symm ... ≃ Σ L : quotient s, left_coset (quotient.out' L) s : equiv.sigma_congr_right (λ L, begin rw ← eq_class_eq_left_coset, show _root_.subtype (λ x : α, quotient.mk' x = L) ≃ _root_.subtype (λ x : α, quotient.mk' x = quotient.mk' _), simp [-quotient.eq'], end) ... ≃ Σ L : quotient s, s : equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _) ... ≃ quotient s × s : equiv.sigma_equiv_prod _ _ variables {t : subgroup α} /-- If `H ≤ K`, then `G/H ≃ G/K × K/H` constructively, using the provided right inverse of the quotient map `G → G/K`. The classical version is `quotient_equiv_prod_of_le`. -/ @[to_additive "If `H ≤ K`, then `G/H ≃ G/K × K/H` constructively, using the provided right inverse of the quotient map `G → G/K`. The classical version is `quotient_equiv_prod_of_le`.", simps] def quotient_equiv_prod_of_le' (h_le : s ≤ t) (f : quotient t → α) (hf : function.right_inverse f quotient_group.mk) : quotient s ≃ quotient t × quotient (s.subgroup_of t) := { to_fun := λ a, ⟨a.map' id (λ b c h, h_le h), a.map' (λ g : α, ⟨(f (quotient.mk' g))⁻¹ * g, quotient.exact' (hf g)⟩) (λ b c h, by { change ((f b)⁻¹ * b)⁻¹ * ((f c)⁻¹ * c) ∈ s, have key : f b = f c := congr_arg f (quotient.sound' (h_le h)), rwa [key, mul_inv_rev, inv_inv, mul_assoc, mul_inv_cancel_left] })⟩, inv_fun := λ a, a.2.map' (λ b, f a.1 * b) (λ b c h, by { change (f a.1 * b)⁻¹ * (f a.1 * c) ∈ s, rwa [mul_inv_rev, mul_assoc, inv_mul_cancel_left] }), left_inv := by { refine quotient.ind' (λ a, _), simp_rw [quotient.map'_mk', id.def, t.coe_mk, mul_inv_cancel_left] }, right_inv := by { refine prod.rec _, refine quotient.ind' (λ a, _), refine quotient.ind' (λ b, _), have key : quotient.mk' (f (quotient.mk' a) * b) = quotient.mk' a := (quotient_group.mk_mul_of_mem (f a) ↑b b.2).trans (hf a), simp_rw [quotient.map'_mk', id.def, key, inv_mul_cancel_left, subtype.coe_eta] } } /-- If `H ≤ K`, then `G/H ≃ G/K × K/H` nonconstructively. The constructive version is `quotient_equiv_prod_of_le'`. -/ @[to_additive "If `H ≤ K`, then `G/H ≃ G/K × K/H` nonconstructively. The constructive version is `quotient_equiv_prod_of_le'`.", simps] noncomputable def quotient_equiv_prod_of_le (h_le : s ≤ t) : quotient s ≃ quotient t × quotient (s.subgroup_of t) := quotient_equiv_prod_of_le' h_le quotient.out' quotient.out_eq' @[to_additive] lemma card_eq_card_quotient_mul_card_subgroup [fintype α] (s : subgroup α) [fintype s] [decidable_pred (λ a, a ∈ s)] : fintype.card α = fintype.card (quotient s) * fintype.card s := by rw ← fintype.card_prod; exact fintype.card_congr (subgroup.group_equiv_quotient_times_subgroup) /-- **Order of a Subgroup** -/ lemma card_subgroup_dvd_card [fintype α] (s : subgroup α) [fintype s] : fintype.card s ∣ fintype.card α := by haveI := classical.prop_decidable; simp [card_eq_card_quotient_mul_card_subgroup s] lemma card_quotient_dvd_card [fintype α] (s : subgroup α) [decidable_pred (λ a, a ∈ s)] [fintype s] : fintype.card (quotient s) ∣ fintype.card α := by simp [card_eq_card_quotient_mul_card_subgroup s] open fintype variables {H : Type*} [group H] lemma card_dvd_of_injective [fintype α] [fintype H] (f : α →* H) (hf : function.injective f) : card α ∣ card H := by classical; calc card α = card (f.range : subgroup H) : card_congr (equiv.of_injective f hf) ...∣ card H : card_subgroup_dvd_card _ lemma card_dvd_of_le {H K : subgroup α} [fintype H] [fintype K] (hHK : H ≤ K) : card H ∣ card K := card_dvd_of_injective (inclusion hHK) (inclusion_injective hHK) lemma card_comap_dvd_of_injective (K : subgroup H) [fintype K] (f : α →* H) [fintype (K.comap f)] (hf : function.injective f) : fintype.card (K.comap f) ∣ fintype.card K := by haveI : fintype ((K.comap f).map f) := fintype.of_equiv _ (equiv_map_of_injective _ _ hf).to_equiv; calc fintype.card (K.comap f) = fintype.card ((K.comap f).map f) : fintype.card_congr (equiv_map_of_injective _ _ hf).to_equiv ... ∣ fintype.card K : card_dvd_of_le (map_comap_le _ _) end subgroup namespace quotient_group variables [group α] -- FIXME -- why is there no `to_additive`? /-- If `s` is a subgroup of the group `α`, and `t` is a subset of `α/s`, then there is a (typically non-canonical) bijection between the preimage of `t` in `α` and the product `s × t`. -/ noncomputable def preimage_mk_equiv_subgroup_times_set (s : subgroup α) (t : set (quotient s)) : quotient_group.mk ⁻¹' t ≃ s × t := have h : ∀ {x : quotient s} {a : α}, x ∈ t → a ∈ s → (quotient.mk' (quotient.out' x * a) : quotient s) = quotient.mk' (quotient.out' x) := λ x a hx ha, quotient.sound' (show (quotient.out' x * a)⁻¹ * quotient.out' x ∈ s, from (s.inv_mem_iff).1 $ by rwa [mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul]), { to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out' (quotient.mk' a))⁻¹ * a, @quotient.exact' _ (left_rel s) _ _ $ (quotient.out_eq' _)⟩, ⟨quotient.mk' a, ha⟩⟩, inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨quotient.out' x * a, show quotient.mk' _ ∈ t, by simp [h hx ha, hx]⟩, left_inv := λ ⟨a, ha⟩, subtype.eq $ show _ * _ = a, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, show (_, _) = _, by simp [h hx ha] } end quotient_group /-- We use the class `has_coe_t` instead of `has_coe` if the first argument is a variable, or if the second argument is a variable not occurring in the first. Using `has_coe` would cause looping of type-class inference. See <https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/remove.20all.20instances.20with.20variable.20domain> -/ library_note "use has_coe_t"
9167fd3dc5a0627f0cf373ea9c7d9badc7bd5a24
799b5de27cebaa6eaa49ff982110d59bbd6c6693
/mechanized/assumptions.lean
0d0d02824a6bbb076669e7f0e274a4c712b60111
[ "MIT" ]
permissive
philnguyen/soft-contract
263efdbc9ca2f35234b03f0d99233a66accda78b
13e7d99e061509f0a45605508dd1a27a51f4648e
refs/heads/master
1,625,975,131,435
1,617,775,585,000
1,617,775,704,000
17,326,137
33
7
MIT
1,613,722,535,000
1,393,714,126,000
Racket
UTF-8
Lean
false
false
1,533
lean
import data.set definitions metafunctions constant alloc (x: x) (σ: σ): a -- The setup of this formalism is that the "concrete semantics" is just a sub-relation -- of the full semantics with symbolic values, and there's one `alloc` function. -- The assumption of `alloc_fresh` is only needed for the concrete side -- to ensure consistency of abstraction mapping. -- We could have used 2 distinct semantics, where the symbolic side had an arbitrary -- `alloc'` function with no further assumption. axiom alloc_fresh (x: x) (σ: σ): map_excl σ (alloc x σ) -- Assume variables are partitioned by predicate `uk_x`, which tells that they come -- from purely instantiated code. constant uk_x: x → Prop noncomputable def kn_x x := ¬ uk_x x attribute [reducible] kn_x -- In retrospect, we probably don't need `uk_a` constant uk_a: a → Prop noncomputable def kn_a a := ¬ uk_a a attribute [reducible] kn_a axiom alloc_preserves_uk {x: x} (σ: σ): uk_x x → uk_a (alloc x σ) axiom alloc_preserves_kn {x: x} (σ: σ): kn_x x → kn_a (alloc x σ) -- Fully concrete expressions that can appear in instantiated code -- All variables (bound and free) must be `uk`, and blame label `ℓᵤₖ` -- distinct from those in transparent code. inductive uk_e: e → Prop | n : ∀ {n}, uk_e (e.n n) | lam: ∀ {x e}, uk_x x → uk_e e → uk_e (e.lam x e) | x : ∀ {x}, uk_x x → uk_e (e.x x) | app: ∀ {e₁ e₂}, uk_e e₁ → uk_e e₂ → uk_e (e.app ℓ.uk e₁ e₂) | set: ∀ {x e}, uk_x x → uk_e e → uk_e (e.set x e)
9562644dc21c21f45fdc147dae1a0737c6e469eb
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Init/Prelude.lean
129aa4c04abbe4648fb49a18527a7e140beb4dae
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
78,787
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude universe u v w @[inline] def id {α : Sort u} (a : α) : α := a @[inline] def Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) @[inline] def Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a set_option checkBinderAnnotations false in @[reducible] def inferInstance {α : Sort u} [i : α] : α := i set_option checkBinderAnnotations false in @[reducible] def inferInstanceAs (α : Sort u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u where | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop where | intro : True inductive False : Prop inductive Empty : Type set_option bootstrap.inductiveCheckResultingUniverse false in inductive PEmpty : Sort u where def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop where | refl {} : Eq a a @[simp] abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a @[simp] theorem id_eq (a : α) : Eq (id a) a := rfl theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c := h₂ ▸ h₁ @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) := h₁ ▸ h₂ ▸ rfl theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where | refl {} : HEq a a @[matchPattern] protected def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eq_of_heq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b := fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) where fst : α snd : β attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) where fst : α snd : β /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) where fst : α snd : β structure And (a b : Prop) : Prop where intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop where | inl (h : a) : Or a b | inr (h : b) : Or a b theorem Or.intro_left (b : Prop) (h : a) : Or a b := Or.inl h theorem Or.intro_right (a : Prop) (h : b) : Or a b := Or.inr h theorem Or.elim {c : Prop} (h : Or a b) (left : a → c) (right : b → c) : c := match h with | Or.inl h => left h | Or.inr h => right h inductive Bool : Type where | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) where val : α property : p val /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ @[extern "lean_sorry", neverExtract] axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eq_false_of_ne_true : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eq_true_of_ne_false : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem ne_false_of_eq_true : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem ne_true_of_eq_false : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) where mk {} :: (default : α) constant arbitrary [Inhabited α] : α := Inhabited.default instance : Inhabited (Sort u) where default := PUnit instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where default := fun _ => arbitrary instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where default := fun _ => arbitrary deriving instance Inhabited for Bool /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u where up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.up_down {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.down_up {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType where (type : Type u) (val : type) instance : Inhabited PointedType.{u} where default := { type := PUnit.{u+1}, val := ⟨⟩ } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) where up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.up_down {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.down_up {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) where | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decide_eq_true : [s : Decidable p] → p → Eq (decide p) true | isTrue _, _ => rfl | isFalse h₁, h₂ => absurd h₂ h₁ theorem decide_eq_false : [s : Decidable p] → Not p → Eq (decide p) false | isTrue h₁, h₂ => absurd h₁ h₂ | isFalse h, _ => rfl theorem of_decide_eq_true [s : Decidable p] : Eq (decide p) true → p := fun h => match (generalizing := false) s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (ne_true_of_eq_false (decide_eq_false h₁)) theorem of_decide_eq_false [s : Decidable p] : Eq (decide p) false → Not p := fun h => match (generalizing := false) s with | isTrue h₁ => absurd h (ne_false_of_eq_true (decide_eq_true h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) where beq : α → α → Bool open BEq (beq) instance [DecidableEq α] : BEq α where beq a b := decide (Eq a b) -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t /- if-then-else -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macroInline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /- Boolean operators -/ @[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α := match c with | true => x | false => y @[macroInline] def or (x y : Bool) : Bool := match x with | true => true | false => y @[macroInline] def and (x y : Bool) : Bool := match x with | false => false | true => y @[inline] def not : Bool → Bool | true => false | false => true inductive Nat where | zero : Nat | succ (n : Nat) : Nat instance : Inhabited Nat where default := Nat.zero /- For numeric literals notation -/ class OfNat (α : Type u) (n : Nat) where ofNat : α @[defaultInstance 100] /- low prio -/ instance (n : Nat) : OfNat Nat n where ofNat := n class LE (α : Type u) where le : α → α → Prop class LT (α : Type u) where lt : α → α → Prop @[reducible] def GE.ge {α : Type u} [LE α] (a b : α) : Prop := LE.le b a @[reducible] def GT.gt {α : Type u} [LT α] (a b : α) : Prop := LT.lt b a @[inline] def max [LT α] [DecidableRel (@LT.lt α _)] (a b : α) : α := ite (LT.lt b a) a b @[inline] def min [LE α] [DecidableRel (@LE.le α _)] (a b : α) : α := ite (LE.le a b) a b /-- Transitive chaining of proofs, used e.g. by `calc`. -/ class Trans (r : α → β → Prop) (s : β → γ → Prop) (t : outParam (α → γ → Prop)) where trans : r a b → s b c → t a c export Trans (trans) instance (r : α → γ → Prop) : Trans Eq r r where trans heq h' := heq ▸ h' instance (r : α → β → Prop) : Trans r Eq r where trans h' heq := heq ▸ h' class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAdd : α → β → γ class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where hSub : α → β → γ class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMul : α → β → γ class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where hDiv : α → β → γ class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMod : α → β → γ class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where hPow : α → β → γ class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAppend : α → β → γ class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOrElse : α → (Unit → β) → γ class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAndThen : α → (Unit → β) → γ class HAnd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAnd : α → β → γ class HXor (α : Type u) (β : Type v) (γ : outParam (Type w)) where hXor : α → β → γ class HOr (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOr : α → β → γ class HShiftLeft (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftLeft : α → β → γ class HShiftRight (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftRight : α → β → γ class Add (α : Type u) where add : α → α → α class Sub (α : Type u) where sub : α → α → α class Mul (α : Type u) where mul : α → α → α class Neg (α : Type u) where neg : α → α class Div (α : Type u) where div : α → α → α class Mod (α : Type u) where mod : α → α → α class Pow (α : Type u) (β : Type v) where pow : α → β → α class Append (α : Type u) where append : α → α → α class OrElse (α : Type u) where orElse : α → (Unit → α) → α class AndThen (α : Type u) where andThen : α → (Unit → α) → α class AndOp (α : Type u) where and : α → α → α class Xor (α : Type u) where xor : α → α → α class OrOp (α : Type u) where or : α → α → α class Complement (α : Type u) where complement : α → α class ShiftLeft (α : Type u) where shiftLeft : α → α → α class ShiftRight (α : Type u) where shiftRight : α → α → α @[defaultInstance] instance [Add α] : HAdd α α α where hAdd a b := Add.add a b @[defaultInstance] instance [Sub α] : HSub α α α where hSub a b := Sub.sub a b @[defaultInstance] instance [Mul α] : HMul α α α where hMul a b := Mul.mul a b @[defaultInstance] instance [Div α] : HDiv α α α where hDiv a b := Div.div a b @[defaultInstance] instance [Mod α] : HMod α α α where hMod a b := Mod.mod a b @[defaultInstance] instance [Pow α β] : HPow α β α where hPow a b := Pow.pow a b @[defaultInstance] instance [Append α] : HAppend α α α where hAppend a b := Append.append a b @[defaultInstance] instance [OrElse α] : HOrElse α α α where hOrElse a b := OrElse.orElse a b @[defaultInstance] instance [AndThen α] : HAndThen α α α where hAndThen a b := AndThen.andThen a b @[defaultInstance] instance [AndOp α] : HAnd α α α where hAnd a b := AndOp.and a b @[defaultInstance] instance [Xor α] : HXor α α α where hXor a b := Xor.xor a b @[defaultInstance] instance [OrOp α] : HOr α α α where hOr a b := OrOp.or a b @[defaultInstance] instance [ShiftLeft α] : HShiftLeft α α α where hShiftLeft a b := ShiftLeft.shiftLeft a b @[defaultInstance] instance [ShiftRight α] : HShiftRight α α α where hShiftRight a b := ShiftRight.shiftRight a b open HAdd (hAdd) open HMul (hMul) open HPow (hPow) open HAppend (hAppend) set_option bootstrap.genMatcherCode false in @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat where add := Nat.add /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg set_option bootstrap.genMatcherCode false in @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat where mul := Nat.mul set_option bootstrap.genMatcherCode false in @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat Nat where pow := Nat.pow set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_eq"] def Nat.beq : (@& Nat) → (@& Nat) → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem Nat.eq_of_beq_eq_true : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have : Eq (beq n m) true := h have : Eq n m := eq_of_beq_eq_true this this ▸ rfl theorem Nat.ne_of_beq_eq_false : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have : Eq (beq n m) false := h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (ne_of_beq_eq_false this)) @[extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eq_of_beq_eq_true h) | false => isFalse (ne_of_beq_eq_false h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_le"] def Nat.ble : @& Nat → @& Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected inductive Nat.le (n : Nat) : Nat → Prop | refl : Nat.le n n | step {m} : Nat.le n m → Nat.le n (succ m) instance : LE Nat where le := Nat.le protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : LT Nat where lt := Nat.lt theorem Nat.not_succ_le_zero : ∀ (n : Nat), LE.le (succ n) 0 → False | 0, h => nomatch h | succ n, h => nomatch h theorem Nat.not_lt_zero (n : Nat) : Not (LT.lt n 0) := not_succ_le_zero n theorem Nat.zero_le : (n : Nat) → LE.le 0 n | zero => Nat.le.refl | succ n => Nat.le.step (zero_le n) theorem Nat.succ_le_succ : LE.le n m → LE.le (succ n) (succ m) | Nat.le.refl => Nat.le.refl | Nat.le.step h => Nat.le.step (succ_le_succ h) theorem Nat.zero_lt_succ (n : Nat) : LT.lt 0 (succ n) := succ_le_succ (zero_le n) theorem Nat.le_step (h : LE.le n m) : LE.le n (succ m) := Nat.le.step h protected theorem Nat.le_trans {n m k : Nat} : LE.le n m → LE.le m k → LE.le n k | h, Nat.le.refl => h | h₁, Nat.le.step h₂ => Nat.le.step (Nat.le_trans h₁ h₂) protected theorem Nat.lt_trans {n m k : Nat} (h₁ : LT.lt n m) : LT.lt m k → LT.lt n k := Nat.le_trans (le_step h₁) theorem Nat.le_succ (n : Nat) : LE.le n (succ n) := Nat.le.step Nat.le.refl theorem Nat.le_succ_of_le {n m : Nat} (h : LE.le n m) : LE.le n (succ m) := Nat.le_trans h (le_succ m) protected theorem Nat.le_refl (n : Nat) : LE.le n n := Nat.le.refl theorem Nat.succ_pos (n : Nat) : LT.lt 0 (succ n) := zero_lt_succ n set_option bootstrap.genMatcherCode false in @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : (@& Nat) → Nat | 0 => 0 | succ a => a theorem Nat.pred_le_pred : {n m : Nat} → LE.le n m → LE.le (pred n) (pred m) | _, _, Nat.le.refl => Nat.le.refl | 0, succ m, Nat.le.step h => h | succ n, succ m, Nat.le.step h => Nat.le_trans (le_succ _) h theorem Nat.le_of_succ_le_succ {n m : Nat} : LE.le (succ n) (succ m) → LE.le n m := pred_le_pred theorem Nat.le_of_lt_succ {m n : Nat} : LT.lt m (succ n) → LE.le m n := le_of_succ_le_succ protected theorem Nat.eq_or_lt_of_le : {n m: Nat} → LE.le n m → Or (Eq n m) (LT.lt n m) | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr (Nat.succ_le_succ (Nat.zero_le _)) | succ n, zero, h => absurd h (not_succ_le_zero _) | succ n, succ m, h => have : LE.le n m := Nat.le_of_succ_le_succ h match Nat.eq_or_lt_of_le this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succ_le_succ h) protected theorem Nat.lt_or_ge (n m : Nat) : Or (LT.lt n m) (GE.ge n m) := match m with | zero => Or.inr (zero_le n) | succ m => match Nat.lt_or_ge n m with | Or.inl h => Or.inl (le_succ_of_le h) | Or.inr h => match Nat.eq_or_lt_of_le h with | Or.inl h1 => Or.inl (h1 ▸ Nat.le_refl _) | Or.inr h1 => Or.inr h1 theorem Nat.not_succ_le_self : (n : Nat) → Not (LE.le (succ n) n) | 0 => not_succ_le_zero _ | succ n => fun h => absurd (le_of_succ_le_succ h) (not_succ_le_self n) protected theorem Nat.lt_irrefl (n : Nat) : Not (LT.lt n n) := Nat.not_succ_le_self n protected theorem Nat.lt_of_le_of_lt {n m k : Nat} (h₁ : LE.le n m) (h₂ : LT.lt m k) : LT.lt n k := Nat.le_trans (Nat.succ_le_succ h₁) h₂ protected theorem Nat.le_antisymm {n m : Nat} (h₁ : LE.le n m) (h₂ : LE.le m n) : Eq n m := match h₁ with | Nat.le.refl => rfl | Nat.le.step h => absurd (Nat.lt_of_le_of_lt h h₂) (Nat.lt_irrefl n) protected theorem Nat.lt_of_le_of_ne {n m : Nat} (h₁ : LE.le n m) (h₂ : Not (Eq n m)) : LT.lt n m := match Nat.lt_or_ge n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.le_antisymm h₁ h₃) h₂ theorem Nat.le_of_ble_eq_true (h : Eq (Nat.ble n m) true) : LE.le n m := match n, m with | 0, _ => Nat.zero_le _ | succ _, succ _ => Nat.succ_le_succ (le_of_ble_eq_true h) theorem Nat.ble_self_eq_true : (n : Nat) → Eq (Nat.ble n n) true | 0 => rfl | succ n => ble_self_eq_true n theorem Nat.ble_succ_eq_true : {n m : Nat} → Eq (Nat.ble n m) true → Eq (Nat.ble n (succ m)) true | 0, _, _ => rfl | succ n, succ m, h => ble_succ_eq_true (n := n) h theorem Nat.ble_eq_true_of_le (h : LE.le n m) : Eq (Nat.ble n m) true := match h with | Nat.le.refl => Nat.ble_self_eq_true n | Nat.le.step h => Nat.ble_succ_eq_true (ble_eq_true_of_le h) theorem Nat.not_le_of_not_ble_eq_true (h : Not (Eq (Nat.ble n m) true)) : Not (LE.le n m) := fun h' => absurd (Nat.ble_eq_true_of_le h') h @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LE.le n m) := dite (Eq (Nat.ble n m) true) (fun h => isTrue (Nat.le_of_ble_eq_true h)) (fun h => isFalse (Nat.not_le_of_not_ble_eq_true h)) @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (LT.lt n m) := decLe (succ n) m set_option bootstrap.genMatcherCode false in @[extern "lean_nat_sub"] protected def Nat.sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, succ b => pred (Nat.sub a b) instance : Sub Nat where sub := Nat.sub @[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBits_eq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property structure Fin (n : Nat) where val : Nat isLt : LT.lt val n theorem Fin.eq_of_val_eq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Fin.val_eq_of_eq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.ne_of_val_ne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (val_eq_of_eq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eq_of_val_eq h) | isFalse h => isFalse (Fin.ne_of_val_ne h) instance {n} : LT (Fin n) where lt a b := LT.lt a.val b.val instance {n} : LE (Fin n) where le a b := LE.le a.val b.val instance Fin.decLt {n} (a b : Fin n) : Decidable (LT.lt a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LE.le a b) := Nat.decLe .. def UInt8.size : Nat := 256 structure UInt8 where val : Fin UInt8.size attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk attribute [extern "lean_uint8_to_nat"] UInt8.val @[extern "lean_uint8_of_nat"] def UInt8.ofNatCore (n : @& Nat) (h : LT.lt n UInt8.size) : UInt8 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern "lean_uint8_dec_eq"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 where default := UInt8.ofNatCore 0 (by decide) def UInt16.size : Nat := 65536 structure UInt16 where val : Fin UInt16.size attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk attribute [extern "lean_uint16_to_nat"] UInt16.val @[extern "lean_uint16_of_nat"] def UInt16.ofNatCore (n : @& Nat) (h : LT.lt n UInt16.size) : UInt16 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern "lean_uint16_dec_eq"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 where default := UInt16.ofNatCore 0 (by decide) def UInt32.size : Nat := 4294967296 structure UInt32 where val : Fin UInt32.size attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk attribute [extern "lean_uint32_to_nat"] UInt32.val @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : LT.lt n UInt32.size) : UInt32 := { val := { val := n, isLt := h } } @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.genMatcherCode false in @[extern "lean_uint32_dec_eq"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 where default := UInt32.ofNatCore 0 (by decide) instance : LT UInt32 where lt a b := LT.lt a.val b.val instance : LE UInt32 where le a b := LE.le a.val b.val set_option bootstrap.genMatcherCode false in @[extern "lean_uint32_dec_lt"] def UInt32.decLt (a b : UInt32) : Decidable (LT.lt a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LT.lt n m)) set_option bootstrap.genMatcherCode false in @[extern "lean_uint32_dec_le"] def UInt32.decLe (a b : UInt32) : Decidable (LE.le a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LE.le n m)) instance (a b : UInt32) : Decidable (LT.lt a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LE.le a b) := UInt32.decLe a b def UInt64.size : Nat := 18446744073709551616 structure UInt64 where val : Fin UInt64.size attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk attribute [extern "lean_uint64_to_nat"] UInt64.val @[extern "lean_uint64_of_nat"] def UInt64.ofNatCore (n : @& Nat) (h : LT.lt n UInt64.size) : UInt64 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern "lean_uint64_dec_eq"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 where default := UInt64.ofNatCore 0 (by decide) def USize.size : Nat := hPow 2 System.Platform.numBits theorem usize_size_eq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) := show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBits_eq with | _, Or.inl rfl => Or.inl (by decide) | _, Or.inr rfl => Or.inr (by decide) structure USize where val : Fin USize.size attribute [extern "lean_usize_of_nat_mk"] USize.mk attribute [extern "lean_usize_to_nat"] USize.val @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : LT.lt n USize.size) : USize := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern "lean_usize_dec_eq"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize where default := USize.ofNatCore 0 (match USize.size, usize_size_eq with | _, Or.inl rfl => by decide | _, Or.inr rfl => by decide) @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : LT.lt n 4294967296) : USize := { val := { val := n isLt := match USize.size, usize_size_eq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.lt_trans h (by decide) } } abbrev Nat.isValidChar (n : Nat) : Prop := Or (LT.lt n 0xd800) (And (LT.lt 0xdfff n) (LT.lt n 0x110000)) abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char where val : UInt32 valid : val.isValidChar private theorem isValidChar_UInt32 {n : Nat} (h : n.isValidChar) : LT.lt n UInt32.size := match h with | Or.inl h => Nat.lt_trans h (by decide) | Or.inr ⟨_, h⟩ => Nat.lt_trans h (by decide) @[extern "lean_uint32_of_nat"] def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := isValidChar_UInt32 h }⟩, valid := h } @[noinline, matchPattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := by decide }⟩, valid := Or.inl (by decide) }) theorem Char.eq_of_val_eq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Char.val_eq_of_eq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.ne_of_val_ne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (val_eq_of_eq h') h theorem Char.val_ne_of_ne {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eq_of_val_eq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eq_of_val_eq h) | isFalse h => isFalse (Char.ne_of_val_ne h) def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LE.le v (UInt32.ofNatCore 0x7F (by decide))) (UInt32.ofNatCore 1 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0x7FF (by decide))) (UInt32.ofNatCore 2 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0xFFFF (by decide))) (UInt32.ofNatCore 3 (by decide)) (UInt32.ofNatCore 4 (by decide)))) inductive Option (α : Type u) where | none : Option α | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) where default := none @[macroInline] def Option.getD : Option α → α → α | some x, _ => x | none, e => e inductive List (α : Type u) where | nil : List α | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) where default := List.nil protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons a as, nil => isFalse (fun h => List.noConfusion h) | nil, cons b bs => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l def List.set : List α → Nat → α → List α | cons a as, 0, b => cons b as | cons a as, Nat.succ n, b => cons a (set as n b) | nil, _, _ => nil def List.length : List α → Nat | nil => 0 | cons a as => HAdd.hAdd (length as) 1 def List.lengthTRAux : List α → Nat → Nat | nil, n => n | cons a as, n => lengthTRAux as (Nat.succ n) def List.lengthTR (as : List α) : Nat := lengthTRAux as 0 @[simp] theorem List.length_cons {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ := rfl def List.concat {α : Type u} : List α → α → List α | nil, b => cons b nil | cons a as, b => cons a (concat as b) def List.get {α : Type u} : (as : List α) → (i : Nat) → LT.lt i as.length → α | nil, i, h => absurd h (Nat.not_lt_zero _) | cons a as, 0, h => a | cons a as, Nat.succ i, h => have : LT.lt i.succ as.length.succ := length_cons .. ▸ h get as i (Nat.le_of_succ_le_succ this) structure String where data : List Char attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ abbrev String.Pos := Nat structure Substring where str : String startPos : String.Pos stopPos : String.Pos instance : Inhabited Substring where default := ⟨"", 0, 0⟩ @[inline] def Substring.bsize : Substring → Nat | ⟨_, b, e⟩ => e.sub b def String.csize (c : Char) : Nat := c.utf8Size.toNat private def String.utf8ByteSizeAux : List Char → Nat → Nat | List.nil, r => r | List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c)) @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => utf8ByteSizeAux s 0 @[inline] def String.bsize (s : String) : Nat := utf8ByteSize s @[inline] def String.toSubstring (s : String) : Substring := { str := s startPos := 0 stopPos := s.bsize } @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panicCore {α : Type u} [Inhabited α] (msg : String) : α /-- This is workaround for `panic` occurring in monadic code. See issue #695. The `panicCore` definition cannot be specialized since it is an extern. When `panic` occurs in monadic code, the `Inhabited α` parameter depends on a `[inst : Monad m]` instance. The `inst` parameter will not be eliminated during specialization if it occurs inside of a binder (to avoid work duplication), and will prevent the the actual monad from being "copied" to the code being specialized. When we reimplement the specializer, we may consider copying `inst` if it also occurs outside binders or if it is an instance. -/ @[noinline, neverExtract] def panic {α : Type u} [Inhabited α] (msg : String) : α := panicCore msg /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) where data : List α attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_mk"] Array.mk /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := { data := List.nil } def Array.empty {α : Type u} : Array α := mkEmpty 0 @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.data.length @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data.get i.val i.isLt @[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α := dite (LT.lt i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀) /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := Array.getD a i arbitrary def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α := self.get! idx @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α := { data := List.concat a.data v } @[extern "lean_array_fset"] def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := { data := a.data.set i.val v } @[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α := dite (LT.lt i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a) @[extern "lean_array_set"] def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α := Array.setD a i v -- Slower `Array.append` used in quotations. protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α := let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α := dite (LT.lt j bs.size) (fun hlt => match i with | 0 => as | Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩))) (fun _ => as) loop bs.size 0 as @[inlineIfReduce] def List.toArrayAux : List α → Array α → Array α | nil, r => r | cons a as, r => toArrayAux as (r.push a) @[inlineIfReduce] def List.redLength : List α → Nat | nil => 0 | cons _ as => as.redLength.succ @[inline, matchPattern, export lean_list_to_array] def List.toArray (as : List α) : Array α := as.toArrayAux (Array.mkEmpty as.redLength) class Bind (m : Type u → Type v) where bind : {α β : Type u} → m α → (α → m β) → m β export Bind (bind) class Pure (f : Type u → Type v) where pure {α : Type u} : α → f α export Pure (pure) class Functor (f : Type u → Type v) : Type (max (u+1) v) where map : {α β : Type u} → (α → β) → f α → f β mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) class Seq (f : Type u → Type v) : Type (max (u+1) v) where seq : {α β : Type u} → f (α → β) → (Unit → f α) → f β class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where seqLeft : {α β : Type u} → f α → (Unit → f β) → f α class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where seqRight : {α β : Type u} → f α → (Unit → f β) → f β class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where map := fun x y => Seq.seq (pure x) fun _ => y seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where map f x := bind x (Function.comp pure f) seq f x := bind f fun y => Functor.map y (x ()) seqLeft x y := bind x fun a => bind (y ()) (fun _ => pure a) seqRight x y := bind x fun _ => y () instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where default := pure instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where default := pure arbitrary -- A fusion of Haskell's `sequence` and `map` def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) := let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) := dite (LT.lt j as.size) (fun hlt => match i with | 0 => pure bs | Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b)) (fun _ => bs) loop as.size 0 Array.empty /-- A Function for lifting a computation from an inner Monad to an outer Monad. Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html), but `n` does not have to be a monad transformer. Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α export MonadLiftT (monadLift) abbrev liftM := @monadLift instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where monadLift x := MonadLift.monadLift (m := n) (monadLift x) instance (m) : MonadLiftT m m where monadLift x := x /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html), but not restricted to monad transformers. Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α export MonadFunctorT (monadMap) instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f) instance monadFunctorRefl (m) : MonadFunctorT m m where monadMap f := f inductive Except (ε : Type u) (α : Type v) where | error : ε → Except ε α | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where default := Except.error arbitrary /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α export MonadExcept (throw tryCatch) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where throw := throwThe ε tryCatch := tryCatchThe ε namespace MonadExcept variable {ε : Type u} {m : Type v → Type w} @[inline] protected def orElse [MonadExcept ε m] {α : Type v} (t₁ : m α) (t₂ : Unit → m α) : m α := tryCatch t₁ fun _ => t₂ () instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where orElse := MonadExcept.orElse end MonadExcept /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where default := fun _ => arbitrary @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r namespace ReaderT section variable {ρ : Type u} {m : Type u → Type v} {α : Type u} instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where throw e := liftM (m := m) (throw e) tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) end section variable {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => Functor.map f (x r) instance : Monad (ReaderT ρ m) where pure := ReaderT.pure bind := ReaderT.bind map := ReaderT.map instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where monadMap f x := fun ctx => f (x ctx) @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where read : m ρ @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where read : m ρ export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where read := readThe ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where read := liftM (m := m) read instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where read := ReaderT.read class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where withReader := withTheReader ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where withReader f := monadMap (m := m) (withTheReader ρ f) instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where withReader f x := fun ctx => x (f ctx) /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) where /- Obtain the top-most State of a Monad stack. -/ get : m σ /- Set the top-most State of a Monad stack. -/ set : σ → m PUnit /- Map the top-most State of a Monad stack. Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a` because the latter does not use the State linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadStateOf (set) abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where get : m σ set : σ → m PUnit modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where set := MonadStateOf.set get := getThe σ modifyGet f := MonadStateOf.modifyGet f @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where get := liftM (m := m) MonadStateOf.get set s := liftM (m := m) (MonadStateOf.set s) modifyGet f := monadLift (m := m) (MonadState.modifyGet f) namespace EStateM inductive Result (ε σ α : Type u) where | ok : α → σ → Result ε σ α | error : ε → σ → Result ε σ α variable {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where default := Result.error arbitrary arbitrary end EStateM open EStateM (Result) in def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variable {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) where default := fun s => Result.error arbitrary s @[inline] protected def pure (a : α) : EStateM ε σ α := fun s => Result.ok a s @[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ => Result.ok ⟨⟩ s @[inline] protected def get : EStateM ε σ σ := fun s => Result.ok s s @[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s => match f s with | (a, s) => Result.ok a s @[inline] protected def throw (e : ε) : EStateM ε σ α := fun s => Result.error e s /-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/ class Backtrackable (δ : outParam (Type u)) (σ : Type u) where save : σ → δ restore : σ → δ → σ @[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s match x s with | Result.error e s => handle e (Backtrackable.restore s d) | ok => ok @[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ : EStateM ε σ α) (x₂ : Unit → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ () (Backtrackable.restore s d) | ok => ok @[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s => match x s with | Result.error e s => Result.error (f e) s | Result.ok a s => Result.ok a s @[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok a s => f a s | Result.error e s => Result.error e s @[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s => match x s with | Result.ok a s => Result.ok (f a) s | Result.error e s => Result.error e s @[inline] protected def seqRight (x : EStateM ε σ α) (y : Unit → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y () s | Result.error e s => Result.error e s instance : Monad (EStateM ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where orElse := EStateM.orElse instance : MonadStateOf σ (EStateM ε σ) where set := EStateM.set get := EStateM.get modifyGet := EStateM.modifyGet instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where throw := EStateM.throw tryCatch := EStateM.tryCatch @[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s @[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error .. => none @[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩ @[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s /- Dummy default instance -/ instance nonBacktrackable : Backtrackable PUnit σ where save := dummySave restore := dummyRestore end EStateM class Hashable (α : Sort u) where hash : α → UInt64 export Hashable (hash) @[extern "lean_uint64_to_usize"] constant UInt64.toUSize (u : UInt64) : USize @[extern "lean_usize_to_uint64"] constant USize.toUInt64 (u : USize) : UInt64 @[extern "lean_uint64_mix_hash"] constant mixHash (u₁ u₂ : UInt64) : UInt64 @[extern "lean_string_hash"] protected constant String.hash (s : @& String) : UInt64 instance : Hashable String where hash := String.hash namespace Lean /- Hierarchical names -/ inductive Name where | anonymous : Name | str : Name → String → UInt64 → Name | num : Name → Nat → UInt64 → Name instance : Inhabited Name where default := Name.anonymous protected def Name.hash : Name → UInt64 | Name.anonymous => UInt64.ofNatCore 1723 (by decide) | Name.str p s h => h | Name.num p v h => h instance : Hashable Name where hash := Name.hash namespace Name @[export lean_name_mk_string] def mkStr (p : Name) (s : String) : Name := Name.str p s (mixHash (hash p) (hash s)) @[export lean_name_mk_numeral] def mkNum (p : Name) (v : Nat) : Name := Name.num p v (mixHash (hash p) (dite (LT.lt v UInt64.size) (fun h => UInt64.ofNatCore v h) (fun _ => UInt64.ofNatCore 17 (by decide)))) def mkSimple (s : String) : Name := mkStr Name.anonymous s @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name where beq := Name.beq protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => Name.mkStr (Name.append n p) s | n, num p d _ => Name.mkNum (Name.append n p) d instance : Append Name where append := Name.append end Name /- Syntax -/ /-- Source information of tokens. -/ inductive SourceInfo where /- Token from original input with whitespace and position information. `leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ | original (leading : Substring) (pos : String.Pos) (trailing : Substring) (endPos : String.Pos) /- Synthesized token (e.g. from a quotation) annotated with a span from the original source. In the delaborator, we "misuse" this constructor to store synthetic positions identifying subterms. -/ | synthetic (pos : String.Pos) (endPos : String.Pos) /- Synthesized token without position information. -/ | protected none instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩ namespace SourceInfo def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos := match info, originalOnly with | original (pos := pos) .., _ => some pos | synthetic (pos := pos) .., false => some pos | _, _ => none end SourceInfo abbrev SyntaxNodeKind := Name /- Syntax AST -/ /-- Syntax objects used by the parser, macro expander, delaborator, etc. -/ inductive Syntax where | missing : Syntax | /-- Node in the syntax tree. The `info` field is used by the delaborator to store the position of the subexpression corresponding to this node. The parser sets the `info` field to `none`. (Remark: the `node` constructor did not have an `info` field in previous versions. This caused a bug in the interactive widgets, where the popup for `a + b` was the same as for `a`. The delaborator used to associate subexpressions with pretty-printed syntax by setting the (string) position of the first atom/identifier to the (expression) position of the subexpression. For example, both `a` and `a + b` have the same first identifier, and so their infos got mixed up.) -/ node (info : SourceInfo) (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax instance : Inhabited Syntax where default := Syntax.missing /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def groupKind : SyntaxNodeKind := `group def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def scientificLitKind : SyntaxNodeKind := `scientificLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node _ k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident .. => identKind def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node info _ args => Syntax.node info k args | _ => stx def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ _ args => args.getD i Syntax.missing | _ => Syntax.missing -- Add `stx[i]` as sugar for `stx.getArg i` @[inline] def getOp (self : Syntax) (idx : Nat) : Syntax := self.getArg idx def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ _ args => args | _ => Array.empty def getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ _ args => args.size | _ => 0 def isMissing : Syntax → Bool | Syntax.missing => true | _ => false def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool := and (stx.isOfKind k) (beq stx.getNumArgs n) def isIdent : Syntax → Bool | ident _ _ _ _ => true | _ => false def getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous def matchesNull (stx : Syntax) (n : Nat) : Bool := isNodeOf stx nullKind n def matchesIdent (stx : Syntax) (id : Name) : Bool := and stx.isIdent (beq stx.getId id) def setArgs (stx : Syntax) (args : Array Syntax) : Syntax := match stx with | node info k _ => node info k args | stx => stx def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax := match stx with | node info k args => node info k (args.setD i arg) | stx => stx /-- Retrieve the left-most node or leaf's info in the Syntax tree. -/ partial def getHeadInfo? : Syntax → Option SourceInfo | atom info _ => some info | ident info .. => some info | node SourceInfo.none _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (LT.lt i args.size) with | true => match getHeadInfo? (args.get! i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | node info _ _ => some info | _ => none /-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/ partial def getHeadInfo (stx : Syntax) : SourceInfo := match stx.getHeadInfo? with | some info => info | none => SourceInfo.none def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := stx.getHeadInfo.getPos? originalOnly partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := match stx, originalOnly with | atom (SourceInfo.original (endPos := pos) ..) .., _ => some pos | atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos | ident (SourceInfo.original (endPos := pos) ..) .., _ => some pos | ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node (SourceInfo.original (endPos := pos) ..) .., _ => some pos | node (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node _ _ args, _ => let rec loop (i : Nat) : Option String.Pos := match decide (LT.lt i args.size) with | true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) originalOnly with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _, _ => none /-- An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically remove/insert the separators. -/ structure SepArray (sep : String) where elemsAndSeps : Array Syntax end Syntax def SourceInfo.fromRef (ref : Syntax) : SourceInfo := match ref.getPos?, ref.getTailPos? with | some pos, some tailPos => SourceInfo.synthetic pos tailPos | _, _ => SourceInfo.none def mkAtom (val : String) : Syntax := Syntax.atom SourceInfo.none val def mkAtomFrom (src : Syntax) (val : String) : Syntax := Syntax.atom (SourceInfo.fromRef src) val /- Parser descriptions -/ inductive ParserDescr where | const (name : Name) | unary (name : Name) (p : ParserDescr) | binary (name : Name) (p₁ p₂ : ParserDescr) | node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr) | symbol (val : String) | nonReservedSymbol (val : String) (includeIdent : Bool) | cat (catName : Name) (rbp : Nat) | parser (declName : Name) | nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr) | sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) | sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) instance : Inhabited ParserDescr where default := ParserDescr.symbol "" abbrev TrailingParserDescr := ParserDescr /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := hAdd reservedMacroScope 1 class MonadRef (m : Type → Type) where getRef : m Syntax withRef {α} : Syntax → m α → m α export MonadRef (getRef) instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where getRef := liftM (getRef : m _) withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos? with | some _ => ref | _ => oldRef @[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position. -/ class MonadQuotation (m : Type → Type) extends MonadRef m where -- Get the fresh scope of the current macro invocation getCurrMacroScope : m MacroScope getMainModule : m Name /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do SourceInfo.fromRef (← getRef) instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where getCurrMacroScope := liftM (m := m) getCurrMacroScope getMainModule := liftM (m := m) getMainModule withFreshMacroScope := monadMap (m := m) withFreshMacroScope /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | str _ s _ => beq s "_hyg" | num p _ _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p s _ => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => Name.anonymous @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n structure MacroScopesView where name : Name imported : Name mainModule : Name scopes : List MacroScope instance : Inhabited MacroScopesView where default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | List.nil, acc => acc | List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s) | List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n) | _, acc => panic "Error: unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "Error: unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "Error: unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "Error: unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule) mainModule := mainModule scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) def defaultMaxRecDepth := 512 def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Macro /- References -/ private constant MethodsRefPointed : PointedType.{0} private def MethodsRef : Type := MethodsRefPointed.type structure Context where methods : MethodsRef mainModule : Name currMacroScope : MacroScope currRecDepth : Nat := 0 maxRecDepth : Nat := defaultMaxRecDepth ref : Syntax inductive Exception where | error : Syntax → String → Exception | unsupportedSyntax : Exception structure State where macroScope : MacroScope traceMsgs : List (Prod Name String) := List.nil deriving Inhabited end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception Macro.State) abbrev Macro := Syntax → MacroM Syntax namespace Macro instance : MonadRef MacroM where getRef := bind read fun ctx => pure ctx.ref withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax def throwError {α} (msg : String) : MacroM α := bind getRef fun ref => throw (Exception.error ref msg) def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α := withRef ref (throwError msg) @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s.macroScope, { s with macroScope := hAdd s.macroScope 1 }))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM where getCurrMacroScope ctx := pure ctx.currMacroScope getMainModule ctx := pure ctx.mainModule withFreshMacroScope := Macro.withFreshMacroScope structure Methods where expandMacro? : Syntax → MacroM (Option Syntax) getCurrNamespace : MacroM Name hasDecl : Name → MacroM Bool resolveNamespace? : Name → MacroM (Option Name) resolveGlobalName : Name → MacroM (List (Prod Name (List String))) deriving Inhabited unsafe def mkMethodsImp (methods : Methods) : MethodsRef := unsafeCast methods @[implementedBy mkMethodsImp] constant mkMethods (methods : Methods) : MethodsRef := MethodsRefPointed.val instance : Inhabited MethodsRef where default := mkMethods arbitrary unsafe def getMethodsImp : MacroM Methods := bind read fun ctx => pure (unsafeCast (ctx.methods)) @[implementedBy getMethodsImp] constant getMethods : MacroM Methods /-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ def expandMacro? (stx : Syntax) : MacroM (Option Syntax) := do (← getMethods).expandMacro? stx /-- Return `true` if the environment contains a declaration with name `declName` -/ def hasDecl (declName : Name) : MacroM Bool := do (← getMethods).hasDecl declName def getCurrNamespace : MacroM Name := do (← getMethods).getCurrNamespace def resolveNamespace? (n : Name) : MacroM (Option Name) := do (← getMethods).resolveNamespace? n def resolveGlobalName (n : Name) : MacroM (List (Prod Name (List String))) := do (← getMethods).resolveGlobalName n def trace (clsName : Name) (msg : String) : MacroM Unit := do modify fun s => { s with traceMsgs := List.cons (Prod.mk clsName msg) s.traceMsgs } end Macro export Macro (expandMacro?) namespace PrettyPrinter abbrev UnexpandM := EStateM Unit Unit /-- Function that tries to reverse macro expansions as a post-processing step of delaboration. While less general than an arbitrary delaborator, it can be declared without importing `Lean`. Used by the `[appUnexpander]` attribute. -/ -- a `kindUnexpander` could reasonably be added later abbrev Unexpander := Syntax → UnexpandM Syntax -- unexpanders should not need to introduce new names instance : MonadQuotation UnexpandM where getRef := pure Syntax.missing withRef := fun _ => id getCurrMacroScope := pure 0 getMainModule := pure `_fakeMod withFreshMacroScope := id end PrettyPrinter end Lean
d58b87dd394f07e1dfcdaff6459dce01c3cc8b25
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/lie/abelian.lean
b5f957d18e04cd5692533b65322b063405bdfa3d
[ "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
7,833
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.of_associative import algebra.lie.ideal_operations /-! # Trivial Lie modules and Abelian Lie algebras The action of a Lie algebra `L` on a module `M` is trivial if `⁅x, m⁆ = 0` for all `x ∈ L` and `m ∈ M`. In the special case that `M = L` with the adjoint action, triviality corresponds to the concept of an Abelian Lie algebra. In this file we define these concepts and provide some related definitions and results. ## Main definitions * `lie_module.is_trivial` * `is_lie_abelian` * `commutative_ring_iff_abelian_lie_ring` * `lie_module.ker` * `lie_module.maximal_trivial_submodule` * `lie_algebra.center` ## Tags lie algebra, abelian, commutative, center -/ universes u v w w₁ w₂ /-- A Lie (ring) module is trivial iff all brackets vanish. -/ class lie_module.is_trivial (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] : Prop := (trivial : ∀ (x : L) (m : M), ⁅x, m⁆ = 0) @[simp] lemma trivial_lie_zero (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] [lie_module.is_trivial L M] (x : L) (m : M) : ⁅x, m⁆ = 0 := lie_module.is_trivial.trivial x m /-- A Lie algebra is Abelian iff it is trivial as a Lie module over itself. -/ abbreviation is_lie_abelian (L : Type v) [has_bracket L L] [has_zero L] : Prop := lie_module.is_trivial L L instance lie_ideal.is_lie_abelian_of_trivial (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (I : lie_ideal R L) [h : lie_module.is_trivial L I] : is_lie_abelian I := { trivial := λ x y, by apply h.trivial, } lemma function.injective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.injective f) (h₂ : is_lie_abelian L₂) : is_lie_abelian L₁ := { trivial := λ x y, by { apply h₁, rw [lie_hom.map_lie, trivial_lie_zero, lie_hom.map_zero], } } lemma function.surjective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.surjective f) (h₂ : is_lie_abelian L₁) : is_lie_abelian L₂ := { trivial := λ x y, begin obtain ⟨u, hu⟩ := h₁ x, rw ← hu, obtain ⟨v, hv⟩ := h₁ y, rw ← hv, rw [← lie_hom.map_lie, trivial_lie_zero, lie_hom.map_zero], end } lemma lie_abelian_iff_equiv_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] (e : L₁ ≃ₗ⁅R⁆ L₂) : is_lie_abelian L₁ ↔ is_lie_abelian L₂ := ⟨e.symm.injective.is_lie_abelian, e.injective.is_lie_abelian⟩ lemma commutative_ring_iff_abelian_lie_ring {A : Type v} [ring A] : is_commutative A (*) ↔ is_lie_abelian A := begin have h₁ : is_commutative A (*) ↔ ∀ (a b : A), a * b = b * a := ⟨λ h, h.1, λ h, ⟨h⟩⟩, have h₂ : is_lie_abelian A ↔ ∀ (a b : A), ⁅a, b⁆ = 0 := ⟨λ h, h.1, λ h, ⟨h⟩⟩, simp only [h₁, h₂, lie_ring.of_associative_ring_bracket, sub_eq_zero], end lemma lie_algebra.is_lie_abelian_bot (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] : is_lie_abelian (⊥ : lie_ideal R L) := ⟨begin rintros ⟨x, hx⟩ ⟨y, hy⟩, suffices : ⁅x, y⁆ = 0, { ext, simp [this], }, change x ∈ (⊥ : lie_ideal R L) at hx, rw lie_submodule.mem_bot at hx, rw [hx, zero_lie], end⟩ section center 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] namespace lie_module /-- The kernel of the action of a Lie algebra `L` on a Lie module `M` as a Lie ideal in `L`. -/ protected def ker : lie_ideal R L := (to_endomorphism R L M).ker @[simp] protected lemma mem_ker (x : L) : x ∈ lie_module.ker R L M ↔ ∀ (m : M), ⁅x, m⁆ = 0 := begin dunfold lie_module.ker, simp only [lie_hom.mem_ker, linear_map.ext_iff, linear_map.zero_apply, to_endomorphism_apply_apply], end /-- The largest submodule of a Lie module `M` on which the Lie algebra `L` acts trivially. -/ def maximal_trivial_submodule : lie_submodule R L M := { carrier := { m | ∀ (x : L), ⁅x, m⁆ = 0 }, zero_mem' := λ x, lie_zero x, add_mem' := λ x y hx hy z, by rw [lie_add, hx, hy, add_zero], smul_mem' := λ c x hx y, by rw [lie_smul, hx, smul_zero], lie_mem := λ x m hm y, by rw [leibniz_lie, hm, hm, lie_zero, add_zero], } @[simp] lemma mem_maximal_trivial_submodule (m : M) : m ∈ maximal_trivial_submodule R L M ↔ ∀ (x : L), ⁅x, m⁆ = 0 := iff.rfl instance : is_trivial L (maximal_trivial_submodule R L M) := { trivial := λ x m, subtype.ext (m.property x), } lemma trivial_iff_le_maximal_trivial (N : lie_submodule R L M) : is_trivial L N ↔ N ≤ maximal_trivial_submodule R L M := begin split, { rintros ⟨h⟩, intros m hm x, specialize h x ⟨m, hm⟩, rw subtype.ext_iff at h, exact h, }, { intros h, constructor, rintros x ⟨m, hm⟩, apply subtype.ext, apply h, exact hm, }, end lemma is_trivial_iff_maximal_trivial_eq_top : is_trivial L M ↔ maximal_trivial_submodule R L M = ⊤ := begin split, { rintros ⟨h⟩, ext, simp only [mem_maximal_trivial_submodule, h, forall_const, true_iff, eq_self_iff_true], }, { intros h, constructor, intros x m, revert x, rw [← mem_maximal_trivial_submodule R L M, h], exact lie_submodule.mem_top m, }, end end lie_module namespace lie_algebra /-- The center of a Lie algebra is the set of elements that commute with everything. It can be viewed as the maximal trivial submodule of the Lie algebra as a Lie module over itself via the adjoint representation. -/ abbreviation center : lie_ideal R L := lie_module.maximal_trivial_submodule R L L instance : is_lie_abelian (center R L) := infer_instance lemma center_eq_adjoint_kernel : center R L = lie_module.ker R L L := begin ext y, simp only [lie_module.mem_maximal_trivial_submodule, lie_module.mem_ker, ← lie_skew _ y, neg_eq_zero], end lemma abelian_of_le_center (I : lie_ideal R L) (h : I ≤ center R L) : is_lie_abelian I := begin rw ← lie_module.trivial_iff_le_maximal_trivial R L L I at h, haveI := h, exact lie_ideal.is_lie_abelian_of_trivial R L I, end lemma is_lie_abelian_iff_center_eq_top : is_lie_abelian L ↔ center R L = ⊤ := lie_module.is_trivial_iff_maximal_trivial_eq_top R L L end lie_algebra end center section ideal_operations open lie_submodule lie_subalgebra 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] variables (N N' : lie_submodule R L M) (I J : lie_ideal R L) @[simp] lemma lie_submodule.trivial_lie_oper_zero [lie_module.is_trivial L M] : ⁅I, N⁆ = ⊥ := begin suffices : ⁅I, N⁆ ≤ ⊥, { exact le_bot_iff.mp this, }, rw [lie_ideal_oper_eq_span, lie_submodule.lie_span_le], rintros m ⟨x, n, h⟩, rw trivial_lie_zero at h, simp [← h], end lemma lie_submodule.lie_abelian_iff_lie_self_eq_bot : is_lie_abelian I ↔ ⁅I, I⁆ = ⊥ := begin simp only [_root_.eq_bot_iff, lie_ideal_oper_eq_span, lie_submodule.lie_span_le, lie_submodule.bot_coe, set.subset_singleton_iff, set.mem_set_of_eq, exists_imp_distrib], split; intros h, { intros z x y hz, rw [← hz, ← coe_bracket, coe_zero_iff_zero], apply h.trivial, }, { exact ⟨λ x y, by { rw ← coe_zero_iff_zero, apply h _ x y, refl, }⟩, }, end end ideal_operations
01b2a4ffe9028d9fb21ad170b7077dcaa46374a3
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/eq15.lean
7e695acf9e92a3163b0c77984441810657807f07
[ "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
454
lean
import data.list open list set_option pp.implicit true definition append : Π {A : Type}, list A → list A → list A | append nil l := l | append (h :: t) l := h :: (append t l) theorem append_nil {A : Type} (l : list A) : append nil l = l := rfl theorem append_cons {A : Type} (h : A) (t l : list A) : append (h :: t) l = h :: (append t l) := rfl example : append (1 :: 2 :: nil) (3 :: 4 :: 5 :: nil) = (1 :: 2 :: 3 :: 4 :: 5 :: nil) := rfl
20f87ff9e943a0420dffc3c24371c580a3e31e1d
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/hott/congr_tac.hlean
af5b06da3cb20fcf01dc46630e001fa9375a3353
[ "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,101
hlean
example (f : nat → nat → nat) (a b c : nat) : b = c → f a b = f a c := begin intro bc, congruence, assumption end example (f g : nat → nat → nat) (a b c : nat) : f = g → b = c → f a b = g a c := begin intro fg bc, congruence, exact fg, exact bc end example (f g : nat → nat → nat) (a b c : nat) : f = g → b = c → f a b = g a c := by intros; congruence; repeat assumption inductive list (A : Type) := | nil {} : list A | cons : A → list A → list A namespace list notation `[` a `]` := list.cons a list.nil notation `[` l:(foldr `,` (h t, cons h t) nil `]`) := l notation h :: t := cons h t variable {T : Type} definition append : list T → list T → list T | [] l := l | (h :: s) t := h :: (append s t) notation l₁ ++ l₂ := append l₁ l₂ end list open list example (a b : nat) : a = b → [a] ++ [b] = [b] ++ [a] := begin intro ab, congruence, {congruence, exact ab}, {congruence, exact (eq.symm ab)} end example (a b : nat) : a = b → [a] ++ [b] = [b] ++ [a] := by intros; repeat (congruence | assumption | apply eq.symm)
62abc3d1e466c12a3df421713d9245fbff423ded
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/imp_curly.lean
008aebd1c02d92a266907b6f8b4c21408f06d4de
[ "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
251
lean
import data.nat.basic open nat theorem zero_left (n : ℕ) : 0 + n = n := nat.induction_on n !add_zero (take m IH, show 0 + succ m = succ m, from calc 0 + succ m = succ (0 + m) : add_succ ... = succ m : IH)
e6c50edb8bf9f6f52e5bc383a20959bb2d3068c3
37da0369b6c03e380e057bf680d81e6c9fdf9219
/hott/init/trunc.hlean
bf504c0bb150f0ff9fc48cb7669505e7a96a5eb9
[ "Apache-2.0" ]
permissive
kodyvajjha/lean2
72b120d95c3a1d77f54433fa90c9810e14a931a4
227fcad22ab2bc27bb7471be7911075d101ba3f9
refs/heads/master
1,627,157,512,295
1,501,855,676,000
1,504,809,427,000
109,317,326
0
0
null
1,509,839,253,000
1,509,655,713,000
C++
UTF-8
Lean
false
false
12,954
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Floris van Doorn Definition of is_trunc (n-truncatedness) Ported from Coq HoTT. -/ prelude import .nat .logic .equiv .pathover open eq nat sigma unit sigma.ops --set_option class.force_new true /- Truncation levels -/ inductive trunc_index : Type₀ := | minus_two : trunc_index | succ : trunc_index → trunc_index open trunc_index /- notation for trunc_index is -2, -1, 0, 1, ... from 0 and up this comes from the way numerals are parsed in Lean. Any structure with a 0, a 1, and a + have numerals defined in them. -/ notation `ℕ₋₂` := trunc_index -- input using \N-2 definition has_zero_trunc_index [instance] [priority 2000] : has_zero ℕ₋₂ := has_zero.mk (succ (succ minus_two)) definition has_one_trunc_index [instance] [priority 2000] : has_one ℕ₋₂ := has_one.mk (succ (succ (succ minus_two))) namespace trunc_index notation `-1` := trunc_index.succ trunc_index.minus_two -- ISSUE: -1 gets printed as -2.+1? notation `-2` := trunc_index.minus_two postfix `.+1`:(max+1) := trunc_index.succ postfix `.+2`:(max+1) := λn, (n .+1 .+1) --addition, where we add two to the result definition add_plus_two [reducible] (n m : ℕ₋₂) : ℕ₋₂ := trunc_index.rec_on m n (λ k l, l .+1) infix ` +2+ `:65 := trunc_index.add_plus_two -- addition of trunc_indices, where results smaller than -2 are changed to -2 protected definition add (n m : ℕ₋₂) : ℕ₋₂ := trunc_index.cases_on m (trunc_index.cases_on n -2 (λn', (trunc_index.cases_on n' -2 id))) (λm', trunc_index.cases_on m' (trunc_index.cases_on n -2 id) (add_plus_two n)) /- we give a weird name to the reflexivity step to avoid overloading le.refl (which can be used if types.trunc is imported) -/ inductive le (a : ℕ₋₂) : ℕ₋₂ → Type := | tr_refl : le a a | step : Π {b}, le a b → le a (b.+1) end trunc_index definition has_le_trunc_index [instance] [priority 2000] : has_le ℕ₋₂ := has_le.mk trunc_index.le attribute trunc_index.add [reducible] definition has_add_trunc_index [instance] [priority 2000] : has_add ℕ₋₂ := has_add.mk trunc_index.add namespace trunc_index definition sub_two [reducible] (n : ℕ) : ℕ₋₂ := nat.rec_on n -2 (λ n k, k.+1) definition add_two [reducible] (n : ℕ₋₂) : ℕ := trunc_index.rec_on n nat.zero (λ n k, nat.succ k) postfix `.-2`:(max+1) := sub_two postfix `.-1`:(max+1) := λn, (n .-2 .+1) definition of_nat [coercion] [reducible] (n : ℕ) : ℕ₋₂ := n.-2.+2 definition succ_le_succ {n m : ℕ₋₂} (H : n ≤ m) : n.+1 ≤ m.+1 := by induction H with m H IH; apply le.tr_refl; exact le.step IH definition minus_two_le (n : ℕ₋₂) : -2 ≤ n := by induction n with n IH; apply le.tr_refl; exact le.step IH end trunc_index open trunc_index namespace is_trunc export [notation] [coercion] trunc_index /- truncated types -/ /- Just as in Coq HoTT we define an internal version of contractibility and is_trunc, but we only use `is_trunc` and `is_contr` -/ structure contr_internal (A : Type) := (center : A) (center_eq : Π(a : A), center = a) definition is_trunc_internal (n : ℕ₋₂) : Type → Type := trunc_index.rec_on n (λA, contr_internal A) (λn trunc_n A, (Π(x y : A), trunc_n (x = y))) end is_trunc open is_trunc structure is_trunc [class] (n : ℕ₋₂) (A : Type) := (to_internal : is_trunc_internal n A) open nat num trunc_index namespace is_trunc abbreviation is_contr := is_trunc -2 abbreviation is_prop := is_trunc -1 abbreviation is_set := is_trunc 0 variables {A B : Type} definition is_trunc_succ_intro (A : Type) (n : ℕ₋₂) [H : ∀x y : A, is_trunc n (x = y)] : is_trunc n.+1 A := is_trunc.mk (λ x y, !is_trunc.to_internal) definition is_trunc_eq [instance] [priority 1200] (n : ℕ₋₂) [H : is_trunc (n.+1) A] (x y : A) : is_trunc n (x = y) := is_trunc.mk (is_trunc.to_internal (n.+1) A x y) /- contractibility -/ definition is_contr.mk (center : A) (center_eq : Π(a : A), center = a) : is_contr A := is_trunc.mk (contr_internal.mk center center_eq) definition center (A : Type) [H : is_contr A] : A := contr_internal.center (is_trunc.to_internal -2 A) definition center' {A : Type} (H : is_contr A) : A := center A definition center_eq [H : is_contr A] (a : A) : !center = a := contr_internal.center_eq (is_trunc.to_internal -2 A) a definition eq_of_is_contr [H : is_contr A] (x y : A) : x = y := (center_eq x)⁻¹ ⬝ (center_eq y) definition prop_eq_of_is_contr {A : Type} [H : is_contr A] {x y : A} (p q : x = y) : p = q := have K : ∀ (r : x = y), eq_of_is_contr x y = r, from (λ r, eq.rec_on r !con.left_inv), (K p)⁻¹ ⬝ K q theorem is_contr_eq {A : Type} [H : is_contr A] (x y : A) : is_contr (x = y) := is_contr.mk !eq_of_is_contr (λ p, !prop_eq_of_is_contr) local attribute is_contr_eq [instance] /- truncation is upward close -/ -- n-types are also (n+1)-types theorem is_trunc_succ [instance] [priority 900] (A : Type) (n : ℕ₋₂) [H : is_trunc n A] : is_trunc (n.+1) A := trunc_index.rec_on n (λ A (H : is_contr A), !is_trunc_succ_intro) (λ n IH A (H : is_trunc (n.+1) A), @is_trunc_succ_intro _ _ (λ x y, IH _ _)) A H --in the proof the type of H is given explicitly to make it available for class inference theorem is_trunc_of_le.{l} (A : Type.{l}) {n m : ℕ₋₂} (Hnm : n ≤ m) [Hn : is_trunc n A] : is_trunc m A := begin induction Hnm with m Hnm IH, { exact Hn}, { exact _} end definition is_trunc_of_imp_is_trunc {n : ℕ₋₂} (H : A → is_trunc (n.+1) A) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λx y, @is_trunc_eq _ _ (H x) x y) definition is_trunc_of_imp_is_trunc_of_le {n : ℕ₋₂} (Hn : -1 ≤ n) (H : A → is_trunc n A) : is_trunc n A := begin cases Hn with n' Hn': apply is_trunc_of_imp_is_trunc H end -- these must be definitions, because we need them to compute sometimes definition is_trunc_of_is_contr (A : Type) (n : ℕ₋₂) [H : is_contr A] : is_trunc n A := trunc_index.rec_on n H (λn H, _) definition is_trunc_succ_of_is_prop (A : Type) (n : ℕ₋₂) [H : is_prop A] : is_trunc (n.+1) A := is_trunc_of_le A (show -1 ≤ n.+1, from succ_le_succ (minus_two_le n)) definition is_trunc_succ_succ_of_is_set (A : Type) (n : ℕ₋₂) [H : is_set A] : is_trunc (n.+2) A := is_trunc_of_le A (show 0 ≤ n.+2, from succ_le_succ (succ_le_succ (minus_two_le n))) /- props -/ definition is_prop.elim [H : is_prop A] (x y : A) : x = y := !center definition is_contr_of_inhabited_prop {A : Type} [H : is_prop A] (x : A) : is_contr A := is_contr.mk x (λy, !is_prop.elim) theorem is_prop_of_imp_is_contr {A : Type} (H : A → is_contr A) : is_prop A := @is_trunc_succ_intro A -2 (λx y, have H2 : is_contr A, from H x, !is_contr_eq) theorem is_prop.mk {A : Type} (H : ∀x y : A, x = y) : is_prop A := is_prop_of_imp_is_contr (λ x, is_contr.mk x (H x)) theorem is_prop_elim_self {A : Type} {H : is_prop A} (x : A) : is_prop.elim x x = idp := !is_prop.elim /- sets -/ theorem is_set.mk (A : Type) (H : ∀(x y : A) (p q : x = y), p = q) : is_set A := @is_trunc_succ_intro _ _ (λ x y, is_prop.mk (H x y)) definition is_set.elim [H : is_set A] ⦃x y : A⦄ (p q : x = y) : p = q := !is_prop.elim /- instances -/ definition is_contr_sigma_eq [instance] [priority 800] {A : Type} (a : A) : is_contr (Σ(x : A), a = x) := is_contr.mk (sigma.mk a idp) (λp, sigma.rec_on p (λ b q, eq.rec_on q idp)) definition is_contr_sigma_eq' [instance] [priority 800] {A : Type} (a : A) : is_contr (Σ(x : A), x = a) := is_contr.mk (sigma.mk a idp) (λp, sigma.rec_on p (λ b q, eq.rec_on q idp)) definition ap_pr1_center_eq_sigma_eq {A : Type} {a x : A} (p : a = x) : ap pr₁ (center_eq ⟨x, p⟩) = p := by induction p; reflexivity definition ap_pr1_center_eq_sigma_eq' {A : Type} {a x : A} (p : x = a) : ap pr₁ (center_eq ⟨x, p⟩) = p⁻¹ := by induction p; reflexivity definition is_contr_unit : is_contr unit := is_contr.mk star (λp, unit.rec_on p idp) definition is_prop_empty : is_prop empty := is_prop.mk (λx, !empty.elim x) local attribute is_contr_unit is_prop_empty [instance] definition is_trunc_unit [instance] (n : ℕ₋₂) : is_trunc n unit := !is_trunc_of_is_contr definition is_trunc_empty [instance] (n : ℕ₋₂) : is_trunc (n.+1) empty := !is_trunc_succ_of_is_prop /- interaction with equivalences -/ section open is_equiv equiv definition is_contr_is_equiv_closed (f : A → B) [Hf : is_equiv f] [HA: is_contr A] : (is_contr B) := is_contr.mk (f (center A)) (λp, eq_of_eq_inv !center_eq) definition is_contr_equiv_closed (H : A ≃ B) [HA: is_contr A] : is_contr B := is_contr_is_equiv_closed (to_fun H) definition equiv_of_is_contr_of_is_contr [HA : is_contr A] [HB : is_contr B] : A ≃ B := equiv.mk (λa, center B) (is_equiv.adjointify (λa, center B) (λb, center A) center_eq center_eq) theorem is_trunc_is_equiv_closed (n : ℕ₋₂) (f : A → B) [H : is_equiv f] [HA : is_trunc n A] : is_trunc n B := begin revert A HA B f H, induction n with n IH: intros, { exact is_contr_is_equiv_closed f}, { apply is_trunc_succ_intro, intro x y, exact IH (f⁻¹ x = f⁻¹ y) _ (x = y) (ap f⁻¹)⁻¹ !is_equiv_inv} end definition is_trunc_is_equiv_closed_rev (n : ℕ₋₂) (f : A → B) [H : is_equiv f] [HA : is_trunc n B] : is_trunc n A := is_trunc_is_equiv_closed n f⁻¹ definition is_trunc_equiv_closed (n : ℕ₋₂) (f : A ≃ B) [HA : is_trunc n A] : is_trunc n B := is_trunc_is_equiv_closed n (to_fun f) definition is_trunc_equiv_closed_rev (n : ℕ₋₂) (f : A ≃ B) [HA : is_trunc n B] : is_trunc n A := is_trunc_is_equiv_closed n (to_inv f) definition is_equiv_of_is_prop [constructor] [HA : is_prop A] [HB : is_prop B] (f : A → B) (g : B → A) : is_equiv f := is_equiv.mk f g (λb, !is_prop.elim) (λa, !is_prop.elim) (λa, !is_set.elim) definition is_equiv_of_is_contr [constructor] [HA : is_contr A] [HB : is_contr B] (f : A → B) : is_equiv f := is_equiv.mk f (λx, !center) (λb, !is_prop.elim) (λa, !is_prop.elim) (λa, !is_set.elim) definition equiv_of_is_prop [constructor] [HA : is_prop A] [HB : is_prop B] (f : A → B) (g : B → A) : A ≃ B := equiv.mk f (is_equiv_of_is_prop f g) definition equiv_of_iff_of_is_prop [unfold 5] [HA : is_prop A] [HB : is_prop B] (H : A ↔ B) : A ≃ B := equiv_of_is_prop (iff.elim_left H) (iff.elim_right H) /- truncatedness of lift -/ definition is_trunc_lift [instance] [priority 1450] (A : Type) (n : ℕ₋₂) [H : is_trunc n A] : is_trunc n (lift A) := is_trunc_equiv_closed _ !equiv_lift end /- interaction with the Unit type -/ open equiv /- A contractible type is equivalent to unit. -/ variable (A) definition equiv_unit_of_is_contr [constructor] [H : is_contr A] : A ≃ unit := equiv.MK (λ (x : A), ⋆) (λ (u : unit), center A) (λ (u : unit), unit.rec_on u idp) (λ (x : A), center_eq x) /- interaction with pathovers -/ variable {A} variables {C : A → Type} {a a₂ : A} (p : a = a₂) (c : C a) (c₂ : C a₂) definition is_trunc_pathover [instance] (n : ℕ₋₂) [H : is_trunc (n.+1) (C a)] : is_trunc n (c =[p] c₂) := is_trunc_equiv_closed_rev n !pathover_equiv_eq_tr definition is_prop.elimo [H : is_prop (C a)] : c =[p] c₂ := pathover_of_eq_tr !is_prop.elim definition is_prop_elimo_self {A : Type} (B : A → Type) {a : A} (b : B a) {H : is_prop (B a)} : @is_prop.elimo A B a a idp b b H = idpo := !is_prop.elim variables {p c c₂} theorem is_set.elimo (q q' : c =[p] c₂) [H : is_set (C a)] : q = q' := !is_prop.elim -- TODO: port "Truncated morphisms" /- truncated universe -/ end is_trunc structure trunctype (n : ℕ₋₂) := (carrier : Type) (struct : is_trunc n carrier) notation n `-Type` := trunctype n abbreviation Prop := -1-Type abbreviation Set := 0-Type attribute trunctype.carrier [coercion] attribute trunctype.struct [instance] [priority 1400] protected abbreviation Prop.mk := @trunctype.mk -1 protected abbreviation Set.mk := @trunctype.mk (-1.+1) protected definition trunctype.mk' [constructor] (n : ℕ₋₂) (A : Type) [H : is_trunc n A] : n-Type := trunctype.mk A H namespace is_trunc definition tlift.{u v} [constructor] {n : ℕ₋₂} (A : trunctype.{u} n) : trunctype.{max u v} n := trunctype.mk (lift A) !is_trunc_lift end is_trunc
6a02e107bf1a90ee51c7889a08331d7a5d5de43d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/polynomial/content_auto.lean
c46fea0f8fabe37552750a34e50839bf9117576c
[]
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
9,283
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.finset.gcd import Mathlib.data.polynomial.default import Mathlib.data.polynomial.erase_lead import Mathlib.data.polynomial.cancel_leads import Mathlib.PostPort universes u_1 namespace Mathlib /-! # GCD structures on polynomials Definitions and basic results about polynomials over GCD domains, particularly their contents and primitive polynomials. ## Main Definitions Let `p : polynomial R`. - `p.content` is the `gcd` of the coefficients of `p`. - `p.is_primitive` indicates that `p.content = 1`. ## Main Results - `polynomial.content_mul`: If `p q : polynomial R`, then `(p * q).content = p.content * q.content`. - `polynomial.gcd_monoid`: The polynomial ring of a GCD domain is itself a GCD domain. -/ namespace polynomial /-- `p.content` is the `gcd` of the coefficients of `p`. -/ def content {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) : R := finset.gcd (finsupp.support p) (coeff p) theorem content_dvd_coeff {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} (n : ℕ) : content p ∣ coeff p n := sorry @[simp] theorem content_C {R : Type u_1} [integral_domain R] [gcd_monoid R] {r : R} : content (coe_fn C r) = coe_fn normalize r := sorry @[simp] theorem content_zero {R : Type u_1} [integral_domain R] [gcd_monoid R] : content 0 = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (content 0 = 0)) (Eq.symm C_0))) (eq.mpr (id (Eq._oldrec (Eq.refl (content (coe_fn C 0) = 0)) content_C)) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn normalize 0 = 0)) normalize_zero)) (Eq.refl 0))) @[simp] theorem content_one {R : Type u_1} [integral_domain R] [gcd_monoid R] : content 1 = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (content 1 = 1)) (Eq.symm C_1))) (eq.mpr (id (Eq._oldrec (Eq.refl (content (coe_fn C 1) = 1)) content_C)) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn normalize 1 = 1)) normalize_one)) (Eq.refl 1))) theorem content_X_mul {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} : content (X * p) = content p := sorry @[simp] theorem content_X_pow {R : Type u_1} [integral_domain R] [gcd_monoid R] {k : ℕ} : content (X ^ k) = 1 := sorry @[simp] theorem content_X {R : Type u_1} [integral_domain R] [gcd_monoid R] : content X = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (content X = 1)) (Eq.symm (mul_one X)))) (eq.mpr (id (Eq._oldrec (Eq.refl (content (X * 1) = 1)) content_X_mul)) (eq.mpr (id (Eq._oldrec (Eq.refl (content 1 = 1)) content_one)) (Eq.refl 1))) theorem content_C_mul {R : Type u_1} [integral_domain R] [gcd_monoid R] (r : R) (p : polynomial R) : content (coe_fn C r * p) = coe_fn normalize r * content p := sorry @[simp] theorem content_monomial {R : Type u_1} [integral_domain R] [gcd_monoid R] {r : R} {k : ℕ} : content (coe_fn (monomial k) r) = coe_fn normalize r := sorry theorem content_eq_zero_iff {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} : content p = 0 ↔ p = 0 := sorry @[simp] theorem normalize_content {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} : coe_fn normalize (content p) = content p := finset.normalize_gcd theorem content_eq_gcd_range_of_lt {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) (n : ℕ) (h : nat_degree p < n) : content p = finset.gcd (finset.range n) (coeff p) := sorry theorem content_eq_gcd_range_succ {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) : content p = finset.gcd (finset.range (Nat.succ (nat_degree p))) (coeff p) := content_eq_gcd_range_of_lt p (Nat.succ (nat_degree p)) (nat.lt_succ_self (nat_degree p)) theorem content_eq_gcd_leading_coeff_content_erase_lead {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) : content p = gcd (leading_coeff p) (content (erase_lead p)) := sorry theorem dvd_content_iff_C_dvd {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} {r : R} : r ∣ content p ↔ coe_fn C r ∣ p := sorry theorem C_content_dvd {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) : coe_fn C (content p) ∣ p := iff.mp dvd_content_iff_C_dvd (dvd_refl (content p)) /-- A polynomial over a GCD domain is primitive when the `gcd` of its coefficients is 1 -/ def is_primitive {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) := content p = 1 @[simp] theorem is_primitive_one {R : Type u_1} [integral_domain R] [gcd_monoid R] : is_primitive 1 := sorry theorem monic.is_primitive {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} (hp : monic p) : is_primitive p := sorry theorem is_primitive.ne_zero {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} (hp : is_primitive p) : p ≠ 0 := sorry theorem is_primitive.content_eq_one {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} (hp : is_primitive p) : content p = 1 := hp theorem is_primitive_iff_is_unit_of_C_dvd {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} : is_primitive p ↔ ∀ (r : R), coe_fn C r ∣ p → is_unit r := sorry /-- The primitive part of a polynomial `p` is the primitive polynomial gained by dividing `p` by `p.content`. If `p = 0`, then `p.prim_part = 1`. -/ def prim_part {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) : polynomial R := ite (p = 0) 1 (classical.some (C_content_dvd p)) theorem eq_C_content_mul_prim_part {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) : p = coe_fn C (content p) * prim_part p := sorry @[simp] theorem prim_part_zero {R : Type u_1} [integral_domain R] [gcd_monoid R] : prim_part 0 = 1 := if_pos rfl theorem is_primitive_prim_part {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) : is_primitive (prim_part p) := sorry theorem content_prim_part {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) : content (prim_part p) = 1 := is_primitive_prim_part p theorem prim_part_ne_zero {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) : prim_part p ≠ 0 := is_primitive.ne_zero (is_primitive_prim_part p) theorem nat_degree_prim_part {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) : nat_degree (prim_part p) = nat_degree p := sorry @[simp] theorem is_primitive.prim_part_eq {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} (hp : is_primitive p) : prim_part p = p := sorry theorem is_unit_prim_part_C {R : Type u_1} [integral_domain R] [gcd_monoid R] (r : R) : is_unit (prim_part (coe_fn C r)) := sorry theorem prim_part_dvd {R : Type u_1} [integral_domain R] [gcd_monoid R] (p : polynomial R) : prim_part p ∣ p := dvd.intro_left (coe_fn C (content p)) (Eq.symm (eq_C_content_mul_prim_part p)) theorem gcd_content_eq_of_dvd_sub {R : Type u_1} [integral_domain R] [gcd_monoid R] {a : R} {p : polynomial R} {q : polynomial R} (h : coe_fn C a ∣ p - q) : gcd a (content p) = gcd a (content q) := sorry theorem content_mul_aux {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} {q : polynomial R} : gcd (content (erase_lead (p * q))) (leading_coeff p) = gcd (content (erase_lead p * q)) (leading_coeff p) := sorry @[simp] theorem content_mul {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} {q : polynomial R} : content (p * q) = content p * content q := sorry theorem is_primitive.mul {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} {q : polynomial R} (hp : is_primitive p) (hq : is_primitive q) : is_primitive (p * q) := sorry @[simp] theorem prim_part_mul {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} {q : polynomial R} (h0 : p * q ≠ 0) : prim_part (p * q) = prim_part p * prim_part q := sorry theorem is_primitive.is_primitive_of_dvd {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} {q : polynomial R} (hp : is_primitive p) (hdvd : q ∣ p) : is_primitive q := sorry theorem is_primitive.dvd_prim_part_iff_dvd {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} {q : polynomial R} (hp : is_primitive p) (hq : q ≠ 0) : p ∣ prim_part q ↔ p ∣ q := sorry theorem exists_primitive_lcm_of_is_primitive {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} {q : polynomial R} (hp : is_primitive p) (hq : is_primitive q) : ∃ (r : polynomial R), is_primitive r ∧ ∀ (s : polynomial R), p ∣ s ∧ q ∣ s ↔ r ∣ s := sorry theorem dvd_iff_content_dvd_content_and_prim_part_dvd_prim_part {R : Type u_1} [integral_domain R] [gcd_monoid R] {p : polynomial R} {q : polynomial R} (hq : q ≠ 0) : p ∣ q ↔ content p ∣ content q ∧ prim_part p ∣ prim_part q := sorry protected instance gcd_monoid {R : Type u_1} [integral_domain R] [gcd_monoid R] : gcd_monoid (polynomial R) := gcd_monoid_of_exists_lcm sorry end Mathlib
5d364fe294b159344a7dcaa282a338663a228b8f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1037.lean
df87681beb31d8ff44814ff5dbfd13fb2bffc825
[ "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
410
lean
example (p q r s: Prop) (h1: p -> s) (h2: q -> s) (h3: r -> s) : ((p \/ q) -> s) /\ (r -> s) := by { constructor <;> intro h <;> (try (apply Or.elim h <;> intro h)) <;> revert h <;> assumption; } example (p q r s: Prop) (h1: p -> s) (h2: q -> s) (h3: r -> s) : ((p \/ q) -> s) /\ (r -> s) := by { constructor <;> intro h <;> (try (apply h.elim <;> intro h)) <;> revert h <;> assumption; }
e99b4726c30d4778368552e28755baf5e05ac0f9
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Util/MonadBacktrack.lean
d0532d5a83a402c3b01893327c30532693e19140
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,596
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 -/ namespace Lean /-- Similar to `MonadState`, but it retrieves/restores only the "backtrackable" part of the state -/ class MonadBacktrack (s : outParam Type) (m : Type → Type) where saveState : m s restoreState : s → m Unit export MonadBacktrack (saveState restoreState) @[specialize] def commitWhenSome? [Monad m] [MonadBacktrack s m] [MonadExcept ε m] (x? : m (Option α)) : m (Option α) := do let s ← saveState try match (← x?) with | some a => pure (some a) | none => restoreState s pure none catch ex => restoreState s throw ex @[specialize] def commitWhen [Monad m] [MonadBacktrack s m] [MonadExcept ε m] (x : m Bool) : m Bool := do let s ← saveState try match (← x) with | true => pure true | false => restoreState s pure false catch ex => restoreState s throw ex @[specialize] def withoutModifyingState [Monad m] [MonadFinally m] [MonadBacktrack s m] (x : m α) : m α := do let s ← saveState try x finally restoreState s @[specialize] def observing? [Monad m] [MonadBacktrack s m] [MonadExcept ε m] (x : m α) : m (Option α) := do let s ← saveState try x catch _ => restoreState s return none instance [MonadBacktrack s m] [Monad m] : MonadBacktrack s (ExceptT ε m) where saveState := ExceptT.lift saveState restoreState s := ExceptT.lift <| restoreState s end Lean
e5336b649de9b38cea94e5e689903c797d4f1055
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/big_operators/ring.lean
191ba358c799aa3e72e7051ac610fe71ba97abdc
[ "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
11,180
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.basic import algebra.field.defs import data.finset.pi import data.finset.powerset /-! # Results about big operators with values in a (semi)ring We prove results about big operators that involve some interaction between multiplicative and additive structures on the values being combined. -/ universes u v w open_locale big_operators variables {α : Type u} {β : Type v} {γ : Type w} namespace finset variables {s s₁ s₂ : finset α} {a : α} {b : β} {f g : α → β} section comm_monoid variables [comm_monoid β] open_locale classical lemma prod_pow_eq_pow_sum {x : β} {f : α → ℕ} : ∀ {s : finset α}, (∏ i in s, x ^ (f i)) = x ^ (∑ x in s, f x) := begin apply finset.induction, { simp }, { assume a s has H, rw [finset.prod_insert has, finset.sum_insert has, pow_add, H] } end end comm_monoid section semiring variables [non_unital_non_assoc_semiring β] lemma sum_mul : (∑ x in s, f x) * b = ∑ x in s, f x * b := add_monoid_hom.map_sum (add_monoid_hom.mul_right b) _ s lemma mul_sum : b * (∑ x in s, f x) = ∑ x in s, b * f x := add_monoid_hom.map_sum (add_monoid_hom.mul_left b) _ s lemma sum_mul_sum {ι₁ : Type*} {ι₂ : Type*} (s₁ : finset ι₁) (s₂ : finset ι₂) (f₁ : ι₁ → β) (f₂ : ι₂ → β) : (∑ x₁ in s₁, f₁ x₁) * (∑ x₂ in s₂, f₂ x₂) = ∑ p in s₁ ×ˢ s₂, f₁ p.1 * f₂ p.2 := by { rw [sum_product, sum_mul, sum_congr rfl], intros, rw mul_sum } end semiring section semiring variables [non_assoc_semiring β] lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∑ x in s, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 := by simp lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∑ x in s, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 := by simp end semiring lemma sum_div [division_semiring β] {s : finset α} {f : α → β} {b : β} : (∑ x in s, f x) / b = ∑ x in s, f x / b := by simp only [div_eq_mul_inv, sum_mul] section comm_semiring variables [comm_semiring β] /-- The product over a sum can be written as a sum over the product of sets, `finset.pi`. `finset.prod_univ_sum` is an alternative statement when the product is over `univ`. -/ lemma prod_sum {δ : α → Type*} [decidable_eq α] [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : (∏ a in s, ∑ b in (t a), f a b) = ∑ p in (s.pi t), ∏ x in s.attach, f x.1 (p x.1 x.2) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)), { assume x hx y hy h, simp only [disjoint_iff_ne, mem_image], rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq₂, eq₃, eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bUnion h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, pi_cons_injective ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr' with ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end open_locale classical /-- The product of `f a + g a` over all of `s` is the sum over the powerset of `s` of the product of `f` over a subset `t` times the product of `g` over the complement of `t` -/ lemma prod_add (f g : α → β) (s : finset α) : ∏ a in s, (f a + g a) = ∑ t in s.powerset, ((∏ a in t, f a) * (∏ a in (s \ t), g a)) := calc ∏ a in s, (f a + g a) = ∏ a in s, ∑ p in ({true, false} : finset Prop), if p then f a else g a : by simp ... = ∑ p in (s.pi (λ _, {true, false}) : finset (Π a ∈ s, Prop)), ∏ a in s.attach, if p a.1 a.2 then f a.1 else g a.1 : prod_sum ... = ∑ t in s.powerset, (∏ a in t, f a) * (∏ a in (s \ t), g a) : begin refine eq.symm (sum_bij (λ t _ a _, a ∈ t) _ _ _ _), { simp [subset_iff]; tauto }, { intros t ht, erw [prod_ite (λ a : {a // a ∈ s}, f a.1) (λ a : {a // a ∈ s}, g a.1)], refine congr_arg2 _ (prod_bij (λ (a : α) (ha : a ∈ t), ⟨a, mem_powerset.1 ht ha⟩) _ _ _ (λ b hb, ⟨b, by cases b; simpa only [true_and, exists_prop, mem_filter, and_true, mem_attach, eq_self_iff_true, subtype.coe_mk] using hb⟩)) (prod_bij (λ (a : α) (ha : a ∈ s \ t), ⟨a, by simp * at *⟩) _ _ _ (λ b hb, ⟨b, by cases b; begin simp only [true_and, mem_filter, mem_attach, subtype.coe_mk] at hb, simpa only [true_and, exists_prop, and_true, mem_sdiff, eq_self_iff_true, subtype.coe_mk, b_property], end⟩)); intros; simp * at *; simp * at * }, { assume a₁ a₂ h₁ h₂ H, ext x, simp only [function.funext_iff, subset_iff, mem_powerset, eq_iff_iff] at h₁ h₂ H, exact ⟨λ hx, (H x (h₁ hx)).1 hx, λ hx, (H x (h₂ hx)).2 hx⟩ }, { assume f hf, exact ⟨s.filter (λ a : α, ∃ h : a ∈ s, f a h), by simp, by funext; intros; simp *⟩ } end /-- `∏ i, (f i + g i) = (∏ i, f i) + ∑ i, g i * (∏ j < i, f j + g j) * (∏ j > i, f j)`. -/ lemma prod_add_ordered {ι R : Type*} [comm_semiring R] [linear_order ι] (s : finset ι) (f g : ι → R) : (∏ i in s, (f i + g i)) = (∏ i in s, f i) + ∑ i in s, g i * (∏ j in s.filter (< i), (f j + g j)) * ∏ j in s.filter (λ j, i < j), f j := begin refine finset.induction_on_max s (by simp) _, clear s, intros a s ha ihs, have ha' : a ∉ s, from λ ha', (ha a ha').false, rw [prod_insert ha', prod_insert ha', sum_insert ha', filter_insert, if_neg (lt_irrefl a), filter_true_of_mem ha, ihs, add_mul, mul_add, mul_add, add_assoc], congr' 1, rw add_comm, congr' 1, { rw [filter_false_of_mem, prod_empty, mul_one], exact (forall_mem_insert _ _ _).2 ⟨lt_irrefl a, λ i hi, (ha i hi).not_lt⟩ }, { rw mul_sum, refine sum_congr rfl (λ i hi, _), rw [filter_insert, if_neg (ha i hi).not_lt, filter_insert, if_pos (ha i hi), prod_insert, mul_left_comm], exact mt (λ ha, (mem_filter.1 ha).1) ha' } end /-- `∏ i, (f i - g i) = (∏ i, f i) - ∑ i, g i * (∏ j < i, f j - g j) * (∏ j > i, f j)`. -/ lemma prod_sub_ordered {ι R : Type*} [comm_ring R] [linear_order ι] (s : finset ι) (f g : ι → R) : (∏ i in s, (f i - g i)) = (∏ i in s, f i) - ∑ i in s, g i * (∏ j in s.filter (< i), (f j - g j)) * ∏ j in s.filter (λ j, i < j), f j := begin simp only [sub_eq_add_neg], convert prod_add_ordered s f (λ i, -g i), simp, end /-- `∏ i, (1 - f i) = 1 - ∑ i, f i * (∏ j < i, 1 - f j)`. This formula is useful in construction of a partition of unity from a collection of “bump” functions. -/ lemma prod_one_sub_ordered {ι R : Type*} [comm_ring R] [linear_order ι] (s : finset ι) (f : ι → R) : (∏ i in s, (1 - f i)) = 1 - ∑ i in s, f i * ∏ j in s.filter (< i), (1 - f j) := by { rw prod_sub_ordered, simp } /-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a `finset` gives `(a + b)^s.card`.-/ lemma sum_pow_mul_eq_add_pow {α R : Type*} [comm_semiring R] (a b : R) (s : finset α) : (∑ t in s.powerset, a ^ t.card * b ^ (s.card - t.card)) = (a + b) ^ s.card := begin rw [← prod_const, prod_add], refine finset.sum_congr rfl (λ t ht, _), rw [prod_const, prod_const, ← card_sdiff (mem_powerset.1 ht)] end theorem dvd_sum {b : β} {s : finset α} {f : α → β} (h : ∀ x ∈ s, b ∣ f x) : b ∣ ∑ x in s, f x := multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx) @[norm_cast] lemma prod_nat_cast (s : finset α) (f : α → ℕ) : ↑(∏ x in s, f x : ℕ) = (∏ x in s, (f x : β)) := (nat.cast_ring_hom β).map_prod f s end comm_semiring section comm_ring variables {R : Type*} [comm_ring R] lemma prod_range_cast_nat_sub (n k : ℕ) : ∏ i in range k, (n - i : R) = (∏ i in range k, (n - i) : ℕ) := begin rw prod_nat_cast, cases le_or_lt k n with hkn hnk, { exact prod_congr rfl (λ i hi, (nat.cast_sub $ (mem_range.1 hi).le.trans hkn).symm) }, { rw ← mem_range at hnk, rw [prod_eq_zero hnk, prod_eq_zero hnk]; simp } end end comm_ring /-- A product over all subsets of `s ∪ {x}` is obtained by multiplying the product over all subsets of `s`, and over all subsets of `s` to which one adds `x`. -/ @[to_additive "A sum over all subsets of `s ∪ {x}` is obtained by summing the sum over all subsets of `s`, and over all subsets of `s` to which one adds `x`."] lemma prod_powerset_insert [decidable_eq α] [comm_monoid β] {s : finset α} {x : α} (h : x ∉ s) (f : finset α → β) : (∏ a in (insert x s).powerset, f a) = (∏ a in s.powerset, f a) * (∏ t in s.powerset, f (insert x t)) := begin rw [powerset_insert, finset.prod_union, finset.prod_image], { assume t₁ h₁ t₂ h₂ heq, rw [← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₁ h), ← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₂ h), heq] }, { rw finset.disjoint_iff_ne, assume t₁ h₁ t₂ h₂, rcases finset.mem_image.1 h₂ with ⟨t₃, h₃, H₃₂⟩, rw ← H₃₂, exact ne_insert_of_not_mem _ _ (not_mem_of_mem_powerset_of_not_mem h₁ h) } end /-- A product over `powerset s` is equal to the double product over sets of subsets of `s` with `card s = k`, for `k = 1, ..., card s`. -/ @[to_additive "A sum over `powerset s` is equal to the double sum over sets of subsets of `s` with `card s = k`, for `k = 1, ..., card s`"] lemma prod_powerset [comm_monoid β] (s : finset α) (f : finset α → β) : ∏ t in powerset s, f t = ∏ j in range (card s + 1), ∏ t in powerset_len j s, f t := begin classical, rw [powerset_card_bUnion, prod_bUnion], intros i hi j hj hij, rw [function.on_fun, powerset_len_eq_filter, powerset_len_eq_filter, disjoint_filter], intros x hx hc hnc, apply hij, rwa ← hc, end lemma sum_range_succ_mul_sum_range_succ [non_unital_non_assoc_semiring β] (n k : ℕ) (f g : ℕ → β) : (∑ i in range (n+1), f i) * (∑ i in range (k+1), g i) = (∑ i in range n, f i) * (∑ i in range k, g i) + f n * (∑ i in range k, g i) + (∑ i in range n, f i) * g k + f n * g k := by simp only [add_mul, mul_add, add_assoc, sum_range_succ] end finset
166f583d2904d5d72e2d50e29e509ae612258689
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/module/submodule.lean
6b1bd4f42e70543db4fb023bc9ed8c3f430960c1
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
11,468
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.module.linear_map import group_theory.group_action.sub_mul_action /-! # Submodules of a module In this file we define * `submodule R M` : a subset of a `module` `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`. ## Tags submodule, subspace, linear map -/ open function open_locale big_operators universes u' u v w variables {S : Type u'} {R : Type u} {M : Type v} {ι : Type w} set_option old_structure_cmd true /-- 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) [semiring R] [add_comm_monoid M] [module R M] extends add_submonoid M, sub_mul_action R M : Type v. /-- Reinterpret a `submodule` as an `add_submonoid`. -/ add_decl_doc submodule.to_add_submonoid /-- Reinterpret a `submodule` as an `sub_mul_action`. -/ add_decl_doc submodule.to_sub_mul_action namespace submodule variables [semiring R] [add_comm_monoid M] [module R M] instance : set_like (submodule R M) M := ⟨submodule.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] theorem mem_to_add_submonoid (p : submodule R M) (x : M) : x ∈ p.to_add_submonoid ↔ x ∈ p := iff.rfl variables {p q : submodule R M} @[simp] lemma mk_coe (S : set M) (h₁ h₂ h₃) : ((⟨S, h₁, h₂, h₃⟩ : submodule R M) : set M) = S := rfl @[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h /-- Copy of a submodule with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (p : submodule R M) (s : set M) (hs : s = ↑p) : submodule R M := { carrier := s, zero_mem' := hs.symm ▸ p.zero_mem', add_mem' := hs.symm ▸ p.add_mem', smul_mem' := hs.symm ▸ p.smul_mem' } theorem to_add_submonoid_injective : injective (to_add_submonoid : submodule R M → add_submonoid M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_add_submonoid_eq : p.to_add_submonoid = q.to_add_submonoid ↔ p = q := to_add_submonoid_injective.eq_iff @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : submodule R M → add_submonoid M) := λ _ _, id @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : submodule R M → add_submonoid M) := to_add_submonoid_strict_mono.monotone @[simp] theorem coe_to_add_submonoid (p : submodule R M) : (p.to_add_submonoid : set M) = p := rfl theorem to_sub_mul_action_injective : injective (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_sub_mul_action_eq : p.to_sub_mul_action = q.to_sub_mul_action ↔ p = q := to_sub_mul_action_injective.eq_iff @[mono] lemma to_sub_mul_action_strict_mono : strict_mono (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ _ _, id @[mono] lemma to_sub_mul_action_mono : monotone (to_sub_mul_action : submodule R M → sub_mul_action R M) := to_sub_mul_action_strict_mono.monotone @[simp] theorem coe_to_sub_mul_action (p : submodule R M) : (p.to_sub_mul_action : set M) = p := rfl end submodule namespace submodule section add_comm_monoid variables [semiring S] [semiring R] [add_comm_monoid M] -- 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} variables [has_scalar S R] [module S M] [is_scalar_tower S R M] variables (p) @[simp] lemma mem_carrier : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl @[simp] lemma zero_mem : (0 : M) ∈ p := p.zero_mem' lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add_mem' h₁ h₂ lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h lemma smul_of_tower_mem (r : S) (h : x ∈ p) : r • x ∈ p := p.to_sub_mul_action.smul_of_tower_mem r h lemma sum_mem {t : finset ι} {f : ι → M} : (∀c∈t, f c ∈ p) → (∑ i in t, f i) ∈ p := p.to_add_submonoid.sum_mem lemma sum_smul_mem {t : finset ι} {f : ι → M} (r : ι → R) (hyp : ∀ c ∈ t, f c ∈ p) : (∑ i in t, r i • f i) ∈ p := submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (hyp i hi)) @[simp] lemma smul_mem_iff' (u : units S) : (u:S) • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff' 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_scalar S p := ⟨λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩⟩ protected lemma nonempty : (p : set M).nonempty := ⟨0, p.zero_mem⟩ @[simp] lemma mk_eq_zero {x} (h : x ∈ p) : (⟨x, h⟩ : p) = 0 ↔ x = 0 := subtype.ext_iff_val variables {p} @[simp, norm_cast] lemma coe_eq_zero {x : p} : (x : M) = 0 ↔ x = 0 := (set_like.coe_eq_coe : (x : M) = (0 : p) ↔ x = 0) @[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 @[norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_smul_of_tower (r : S) (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] lemma coe_mem (x : p) : (x : M) ∈ p := x.2 variables (p) instance : add_comm_monoid p := { add := (+), zero := 0, .. p.to_add_submonoid.to_add_comm_monoid } instance module' : module S p := by refine {smul := (•), ..p.to_sub_mul_action.mul_action', ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } instance : module R p := p.module' instance : is_scalar_tower S R p := p.to_sub_mul_action.is_scalar_tower instance no_zero_smul_divisors [no_zero_smul_divisors R M] : no_zero_smul_divisors R p := ⟨λ c x h, have c = 0 ∨ (x : M) = 0, from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h), this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩ /-- 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 /-- Note the `add_submonoid` version of this lemma is called `add_submonoid.coe_finset_sum`. -/ @[simp] lemma coe_sum (x : ι → p) (s : finset ι) : ↑(∑ i in s, x i) = ∑ i in s, (x i : M) := p.subtype.map_sum end add_comm_monoid section add_comm_group variables [ring R] [add_comm_group M] variables {module_M : module R M} variables (p p' : submodule R M) variables {r : R} {x y : M} lemma neg_mem (hx : x ∈ p) : -x ∈ p := p.to_sub_mul_action.neg_mem hx /-- Reinterpret a submodule as an additive subgroup. -/ def to_add_subgroup : add_subgroup M := { neg_mem' := λ _, p.neg_mem , .. p.to_add_submonoid } @[simp] lemma coe_to_add_subgroup : (p.to_add_subgroup : set M) = p := rfl @[simp] lemma mem_to_add_subgroup : x ∈ p.to_add_subgroup ↔ x ∈ p := iff.rfl include module_M theorem to_add_subgroup_injective : injective (to_add_subgroup : submodule R M → add_subgroup M) | p q h := set_like.ext (set_like.ext_iff.1 h : _) @[simp] theorem to_add_subgroup_eq : p.to_add_subgroup = p'.to_add_subgroup ↔ p = p' := to_add_subgroup_injective.eq_iff @[mono] lemma to_add_subgroup_strict_mono : strict_mono (to_add_subgroup : submodule R M → add_subgroup M) := λ _ _, id @[mono] lemma to_add_subgroup_mono : monotone (to_add_subgroup : submodule R M → add_subgroup M) := to_add_subgroup_strict_mono.monotone omit module_M lemma sub_mem : x ∈ p → y ∈ p → x - y ∈ p := p.to_add_subgroup.sub_mem @[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := p.to_add_subgroup.neg_mem_iff lemma add_mem_iff_left : y ∈ p → (x + y ∈ p ↔ x ∈ p) := p.to_add_subgroup.add_mem_cancel_right lemma add_mem_iff_right : x ∈ p → (x + y ∈ p ↔ y ∈ p) := p.to_add_subgroup.add_mem_cancel_left instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ @[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl instance : add_comm_group p := { add := (+), zero := 0, neg := has_neg.neg, ..p.to_add_subgroup.to_add_comm_group } @[simp, norm_cast] lemma coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := rfl end add_comm_group section ordered_monoid variables [semiring R] /-- A submodule of an `ordered_add_comm_monoid` is an `ordered_add_comm_monoid`. -/ instance to_ordered_add_comm_monoid {M} [ordered_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_add_comm_monoid S := subtype.coe_injective.ordered_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_monoid` is a `linear_ordered_add_comm_monoid`. -/ instance to_linear_ordered_add_comm_monoid {M} [linear_ordered_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_add_comm_monoid S := subtype.coe_injective.linear_ordered_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of an `ordered_cancel_add_comm_monoid` is an `ordered_cancel_add_comm_monoid`. -/ instance to_ordered_cancel_add_comm_monoid {M} [ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_cancel_add_comm_monoid S := subtype.coe_injective.ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of a `linear_ordered_cancel_add_comm_monoid` is a `linear_ordered_cancel_add_comm_monoid`. -/ instance to_linear_ordered_cancel_add_comm_monoid {M} [linear_ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_cancel_add_comm_monoid S := subtype.coe_injective.linear_ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) end ordered_monoid section ordered_group variables [ring R] /-- A submodule of an `ordered_add_comm_group` is an `ordered_add_comm_group`. -/ instance to_ordered_add_comm_group {M} [ordered_add_comm_group M] [module R M] (S : submodule R M) : ordered_add_comm_group S := subtype.coe_injective.ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_group` is a `linear_ordered_add_comm_group`. -/ instance to_linear_ordered_add_comm_group {M} [linear_ordered_add_comm_group M] [module R M] (S : submodule R M) : linear_ordered_add_comm_group S := subtype.coe_injective.linear_ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) end ordered_group end submodule namespace submodule variables [division_ring S] [semiring R] [add_comm_monoid M] [module R M] variables [has_scalar S R] [module S M] [is_scalar_tower S R M] variables (p : submodule R M) {s : S} {x y : M} theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff s0 end submodule /-- Subspace of a vector space. Defined to equal `submodule`. -/ abbreviation subspace (R : Type u) (M : Type v) [field R] [add_comm_group M] [module R M] := submodule R M
635977d79a2f3e6eeef8abb9f62ea2b7cb33dabf
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/category_theory/monoidal/Mon_.lean
805be5b77e17a681afea41afd298ab9f9b1e5042
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
9,409
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 category_theory.monoidal.discrete import category_theory.monoidal.unitors import category_theory.limits.shapes.terminal import algebra.punit_instances /-! # The category of monoids in a monoidal category. -/ universes v₁ v₂ u₁ u₂ open category_theory open category_theory.monoidal_category variables (C : Type u₁) [category.{v₁} C] [monoidal_category.{v₁} C] /-- A monoid object internal to a monoidal category. When the monoidal category is preadditive, this is also sometimes called an "algebra object". -/ structure Mon_ := (X : C) (one : 𝟙_ C ⟶ X) (mul : X ⊗ X ⟶ X) (one_mul' : (one ⊗ 𝟙 X) ≫ mul = (λ_ X).hom . obviously) (mul_one' : (𝟙 X ⊗ one) ≫ mul = (ρ_ X).hom . obviously) -- Obviously there is some flexibility stating this axiom. -- This one has left- and right-hand sides matching the statement of `monoid.mul_assoc`, -- and chooses to place the associator on the right-hand side. -- The heuristic is that unitors and associators "don't have much weight". (mul_assoc' : (mul ⊗ 𝟙 X) ≫ mul = (α_ X X X).hom ≫ (𝟙 X ⊗ mul) ≫ mul . obviously) restate_axiom Mon_.one_mul' restate_axiom Mon_.mul_one' restate_axiom Mon_.mul_assoc' attribute [reassoc] Mon_.one_mul Mon_.mul_one -- We prove a more general `@[simp]` lemma below. attribute [simp, reassoc] Mon_.mul_assoc namespace Mon_ /-- The trivial monoid object. We later show this is initial in `Mon_ C`. -/ @[simps] def trivial : Mon_ C := { X := 𝟙_ C, one := 𝟙 _, mul := (λ_ _).hom, mul_assoc' := by simp_rw [triangle_assoc, iso.cancel_iso_hom_right, tensor_right_iff, unitors_equal], mul_one' := by simp [unitors_equal] } instance : inhabited (Mon_ C) := ⟨trivial C⟩ variables {C} {M : Mon_ C} @[simp] lemma one_mul_hom {Z : C} (f : Z ⟶ M.X) : (M.one ⊗ f) ≫ M.mul = (λ_ Z).hom ≫ f := by rw [←id_tensor_comp_tensor_id, category.assoc, M.one_mul, left_unitor_naturality] @[simp] lemma mul_one_hom {Z : C} (f : Z ⟶ M.X) : (f ⊗ M.one) ≫ M.mul = (ρ_ Z).hom ≫ f := by rw [←tensor_id_comp_id_tensor, category.assoc, M.mul_one, right_unitor_naturality] lemma assoc_flip : (𝟙 M.X ⊗ M.mul) ≫ M.mul = (α_ M.X M.X M.X).inv ≫ (M.mul ⊗ 𝟙 M.X) ≫ M.mul := by simp /-- A morphism of monoid objects. -/ @[ext] structure hom (M N : Mon_ C) := (hom : M.X ⟶ N.X) (one_hom' : M.one ≫ hom = N.one . obviously) (mul_hom' : M.mul ≫ hom = (hom ⊗ hom) ≫ N.mul . obviously) restate_axiom hom.one_hom' restate_axiom hom.mul_hom' attribute [simp, reassoc] hom.one_hom hom.mul_hom /-- The identity morphism on a monoid object. -/ @[simps] def id (M : Mon_ C) : hom M M := { hom := 𝟙 M.X, } instance hom_inhabited (M : Mon_ C) : inhabited (hom M M) := ⟨id M⟩ /-- Composition of morphisms of monoid objects. -/ @[simps] def comp {M N O : Mon_ C} (f : hom M N) (g : hom N O) : hom M O := { hom := f.hom ≫ g.hom, } instance : category (Mon_ C) := { hom := λ M N, hom M N, id := id, comp := λ M N O f g, comp f g, } @[simp] lemma id_hom' (M : Mon_ C) : (𝟙 M : hom M M).hom = 𝟙 M.X := rfl @[simp] lemma comp_hom' {M N K : Mon_ C} (f : M ⟶ N) (g : N ⟶ K) : (f ≫ g : hom M K).hom = f.hom ≫ g.hom := rfl section variables (C) /-- The forgetful functor from monoid objects to the ambient category. -/ @[simps] def forget : Mon_ C ⥤ C := { obj := λ A, A.X, map := λ A B f, f.hom, } end instance forget_faithful : faithful (@forget C _ _) := { } instance {A B : Mon_ C} (f : A ⟶ B) [e : is_iso ((forget C).map f)] : is_iso f.hom := e /-- The forgetful functor from monoid objects to the ambient category reflects isomorphisms. -/ instance : reflects_isomorphisms (forget C) := { reflects := λ X Y f e, by exactI { inv := { hom := inv f.hom, mul_hom' := begin simp only [is_iso.comp_inv_eq, hom.mul_hom, category.assoc, ←tensor_comp_assoc, is_iso.inv_hom_id, tensor_id, category.id_comp], end } } } instance unique_hom_from_trivial (A : Mon_ C) : unique (trivial C ⟶ A) := { default := { hom := A.one, one_hom' := by { dsimp, simp, }, mul_hom' := by { dsimp, simp [A.one_mul, unitors_equal], } }, uniq := λ f, begin ext, simp, rw [←category.id_comp f.hom], erw f.one_hom, end } open category_theory.limits instance : has_initial (Mon_ C) := has_initial_of_unique (trivial C) end Mon_ namespace category_theory.lax_monoidal_functor variables {C} {D : Type u₂} [category.{v₂} D] [monoidal_category.{v₂} D] /-- A lax monoidal functor takes monoid objects to monoid objects. That is, a lax monoidal functor `F : C ⥤ D` induces a functor `Mon_ C ⥤ Mon_ D`. -/ -- TODO: map_Mod F A : Mod A ⥤ Mod (F.map_Mon A) @[simps] def map_Mon (F : lax_monoidal_functor C D) : Mon_ C ⥤ Mon_ D := { obj := λ A, { X := F.obj A.X, one := F.ε ≫ F.map A.one, mul := F.μ _ _ ≫ F.map A.mul, one_mul' := begin conv_lhs { rw [comp_tensor_id, ←F.to_functor.map_id], }, slice_lhs 2 3 { rw [F.μ_natural], }, slice_lhs 3 4 { rw [←F.to_functor.map_comp, A.one_mul], }, rw [F.to_functor.map_id], rw [F.left_unitality], end, mul_one' := begin conv_lhs { rw [id_tensor_comp, ←F.to_functor.map_id], }, slice_lhs 2 3 { rw [F.μ_natural], }, slice_lhs 3 4 { rw [←F.to_functor.map_comp, A.mul_one], }, rw [F.to_functor.map_id], rw [F.right_unitality], end, mul_assoc' := begin conv_lhs { rw [comp_tensor_id, ←F.to_functor.map_id], }, slice_lhs 2 3 { rw [F.μ_natural], }, slice_lhs 3 4 { rw [←F.to_functor.map_comp, A.mul_assoc], }, conv_lhs { rw [F.to_functor.map_id] }, conv_lhs { rw [F.to_functor.map_comp, F.to_functor.map_comp] }, conv_rhs { rw [id_tensor_comp, ←F.to_functor.map_id], }, slice_rhs 3 4 { rw [F.μ_natural], }, conv_rhs { rw [F.to_functor.map_id] }, slice_rhs 1 3 { rw [←F.associativity], }, simp only [category.assoc], end, }, map := λ A B f, { hom := F.map f.hom, one_hom' := by { dsimp, rw [category.assoc, ←F.to_functor.map_comp, f.one_hom], }, mul_hom' := begin dsimp, rw [category.assoc, F.μ_natural_assoc, ←F.to_functor.map_comp, ←F.to_functor.map_comp, f.mul_hom], end }, map_id' := λ A, by { ext, simp, }, map_comp' := λ A B C f g, by { ext, simp, }, } variables (C D) /-- `map_Mon` is functorial in the lax monoidal functor. -/ def map_Mon_functor : (lax_monoidal_functor C D) ⥤ (Mon_ C ⥤ Mon_ D) := { obj := map_Mon, map := λ F G α, { app := λ A, { hom := α.app A.X, } } } end category_theory.lax_monoidal_functor namespace Mon_ open category_theory.lax_monoidal_functor namespace equiv_lax_monoidal_functor_punit /-- Implementation of `Mon_.equiv_lax_monoidal_functor_punit`. -/ @[simps] def lax_monoidal_to_Mon : lax_monoidal_functor (discrete punit) C ⥤ Mon_ C := { obj := λ F, (F.map_Mon : Mon_ _ ⥤ Mon_ C).obj (trivial (discrete punit)), map := λ F G α, ((map_Mon_functor (discrete punit) C).map α).app _ } /-- Implementation of `Mon_.equiv_lax_monoidal_functor_punit`. -/ @[simps] def Mon_to_lax_monoidal : Mon_ C ⥤ lax_monoidal_functor (discrete punit) C := { obj := λ A, { obj := λ _, A.X, map := λ _ _ _, 𝟙 _, ε := A.one, μ := λ _ _, A.mul, map_id' := λ _, rfl, map_comp' := λ _ _ _ _ _, (category.id_comp (𝟙 A.X)).symm, }, map := λ A B f, { app := λ _, f.hom, naturality' := λ _ _ _, by { dsimp, rw [category.id_comp, category.comp_id], }, unit' := f.one_hom, tensor' := λ _ _, f.mul_hom, }, } /-- Implementation of `Mon_.equiv_lax_monoidal_functor_punit`. -/ @[simps] def unit_iso : 𝟭 (lax_monoidal_functor (discrete punit) C) ≅ lax_monoidal_to_Mon C ⋙ Mon_to_lax_monoidal C := nat_iso.of_components (λ F, monoidal_nat_iso.of_components (λ _, F.to_functor.map_iso (eq_to_iso (by ext))) (by tidy) (by tidy) (by tidy)) (by tidy) /-- Implementation of `Mon_.equiv_lax_monoidal_functor_punit`. -/ @[simps] def counit_iso : Mon_to_lax_monoidal C ⋙ lax_monoidal_to_Mon C ≅ 𝟭 (Mon_ C) := nat_iso.of_components (λ F, { hom := { hom := 𝟙 _, }, inv := { hom := 𝟙 _, } }) (by tidy) end equiv_lax_monoidal_functor_punit open equiv_lax_monoidal_functor_punit /-- Monoid objects in `C` are "just" lax monoidal functors from the trivial monoidal category to `C`. -/ @[simps] def equiv_lax_monoidal_functor_punit : lax_monoidal_functor (discrete punit) C ≌ Mon_ C := { functor := lax_monoidal_to_Mon C, inverse := Mon_to_lax_monoidal C, unit_iso := unit_iso C, counit_iso := counit_iso C, } end Mon_ /-! Projects: * Check that `Mon_ Mon ≌ CommMon`, via the Eckmann-Hilton argument. (You'll have to hook up the cartesian monoidal structure on `Mon` first, available in #3463) * Check that `Mon_ Top ≌ [bundled topological monoids]`. * Check that `Mon_ AddCommGroup ≌ Ring`. (We've already got `Mon_ (Module R) ≌ Algebra R`, in `category_theory.monoidal.internal.Module`.) * Can you transport this monoidal structure to `Ring` or `Algebra R`? How does it compare to the "native" one? * Show that if `C` is braided then `Mon_ C` is naturally monoidal. -/
4e695d13f04c281e90a98fcc3f60a5e385b5795f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/tcloop.lean
9b95556de32ab1d2e11e7e0b977fd69a0a366e40
[ "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
218
lean
class A (α : Type u) where a : Unit class B (α : Type u) where a : Unit instance [s : B (Array α)] : A α where a := () instance [s : A (Array α)] : B α where a := () def f : B Nat := inferInstance
7fe30849aa17ad4c2ac8cff2ee35cefee515079d
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/algebra/category/default.lean
7c35a9c4edcb5a1d40bd0b5ed7b2c91e7f369806
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
190
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn -/ import .morphism .constructions
e32de4c8d0028abac048558bbe93375a72b17e52
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/array1.lean
74ccb3423eb476f9f3ffd852302a11d21c2b659c
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
563
lean
#check @array.mk #eval mk_array 4 1 def v : array nat 10 := @array.mk nat 10 (λ ⟨i, _⟩, i) #eval array.map (+10) v def w : array nat 10 := (mk_array 9 1)^.push_back 3 def f : fin 10 → nat := array.cases_on w (λ f, f) #eval f ⟨9, dec_trivial⟩ #eval f ⟨2, dec_trivial⟩ #eval (((mk_array 1 1)^.push_back 2)^.push_back 3)^.foldl 0 (+) def array_sum {n} (a : array nat n) : nat := a^.foldl 0 (+) #eval array_sum (mk_array 10 1) #eval (mk_array 10 1)^.data ⟨1, dec_trivial⟩ + 20 #eval (mk_array 10 1)^.data 2 #eval (mk_array 10 3)^.data 2
e235ffab4448ecf2ed18b4e2f01b80b1c1d80eac
a206acf8ac244f25d5523b86bea8e677ea3c6b91
/2.lean
281e8d1e7c24c1d7ee3b200a0f73503bf258ecb9
[]
no_license
quasimik/tp-lean
cebfd6adf1b7905a411fbb5e7dc3aec87a28e418
bdf59f3d2fe22b95ed0944252a5019ca0081f96c
refs/heads/master
1,615,744,339,038
1,584,612,369,000
1,584,682,398,000
246,781,014
0
0
null
null
null
null
UTF-8
Lean
false
false
3,419
lean
/- Exercise 1. Define the function Do_Twice, as described in Section 2.4. Exercise 2. Define the functions curry and uncurry, as described in Section 2.4. -/ def do_twice (f : ℕ → ℕ) (x : ℕ) : ℕ := f (f x) def double (x : ℕ) : ℕ := x * 2 def quadruple (x : ℕ) : ℕ := do_twice double x def octuple (x : ℕ) : ℕ := double (do_twice double x) def Do_Twice (g : (ℕ → ℕ) → ℕ → ℕ) (f : ℕ → ℕ) : ℕ → ℕ := g (g f) #reduce double 2 #reduce do_twice double 2 #reduce quadruple 2 #reduce octuple 2 #reduce Do_Twice do_twice double 2 #check do_twice #check Do_Twice #check Do_Twice do_twice double -- curry : (α × β) → γ → α → β → γ -- uncurry : α → β → γ → (α × β) → γ def curry (α β γ : Type) (f : α × β → γ) : α → β → γ := λ (a : α) (b : β), f (a, b) def uncurry (α β γ : Type) (f : α → β → γ) : α × β → γ := λ (ab : α × β), f ab.1 ab.2 #check curry #check uncurry /- ...try to understand why the definition of foo below type checks, but the definition of bar does not. -/ def foo := let a := nat in λ x : a, x + 2 /- def bar := (λ a, (λ x : a, x + 2)) nat this does not type check because at check time, Lean does not know that the operation '+' is valid for type 'a', even though 'a' is later resolved to 'nat'. -/ def bar2 := (λ a, (λ x : a, x)) nat -- to illustrate, this is ok. #check foo #check bar2 -- this means that let bindings are evaluated before type checks. /- Exercise 3. Above, we used the example vec α n for vectors of elements of type α of length n. Declare a constant vec_add that could represent a function that adds two vectors of natural numbers of the same length, and a constant vec_reverse that can represent a function that reverses its argument. Use implicit arguments for parameters that can be inferred. Declare some variables and check some expressions involving the constants that you have declared. -/ universe u variable α : Type u variables m n o : ℕ constant vec : Type u → ℕ → Type u constant vec_add : Π {n}, vec ℕ n → vec ℕ n → vec ℕ n constant vec_reverse : Π {n}, vec ℕ n → vec ℕ n variable v2 : vec ℕ 2 variable v3 : vec ℕ 3 #check vec_add v2 v2 #check vec_add v3 v3 -- #check vec_add v2 v3 -- error #check vec_reverse v2 #check vec_reverse v3 /- Exercise 4. Similarly, declare a constant matrix so that matrix α m n could represent the type of m by n matrices. Declare some constants to represent functions on this type, such as matrix addition and multiplication, and (using vec) multiplication of a matrix by a vector. Once again, declare some variables and check some expressions involving the constants that you have declared. -/ constant matrix : Type u → ℕ → ℕ → Type u constant mat_add : Π {α m n}, matrix α m n → matrix α m n → matrix α m n constant mat_mul : Π {α m n o}, matrix α m n → matrix α n o → matrix α m o constant mat_vec_mul : Π {α m n}, matrix α m n → vec α n → vec α m variable m35 : matrix ℕ 3 5 variable m57 : matrix ℕ 5 7 variable v5 : vec ℕ 5 variable v7 : vec ℕ 7 #check mat_add m35 m35 -- #check mat_add m35 m57 -- error #check mat_mul m35 m57 -- #check mat_mul m35 m35 -- error #check mat_vec_mul m35 v5 -- #check mat_vec_mul m35 v7 -- error
fa5e9fe55c71fd4b626eca05cc480fc9292efd38
ac89c256db07448984849346288e0eeffe8b20d0
/src/Init/Notation.lean
552dfe623e092264119ee66cc9071eedc9af815d
[ "Apache-2.0" ]
permissive
chepinzhang/lean4
002cc667f35417a418f0ebc9cb4a44559bb0ccac
24fe2875c68549b5481f07c57eab4ad4a0ae5305
refs/heads/master
1,688,942,838,326
1,628,801,942,000
1,628,801,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,789
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 Notation for operators defined at Prelude.lean -/ prelude import Init.Prelude -- DSL for specifying parser precedences and priorities namespace Lean.Parser.Syntax syntax:65 (name := addPrec) prec " + " prec:66 : prec syntax:65 (name := subPrec) prec " - " prec:66 : prec syntax:65 (name := addPrio) prio " + " prio:66 : prio syntax:65 (name := subPrio) prio " - " prio:66 : prio end Lean.Parser.Syntax macro "max" : prec => `(1024) -- maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...) macro "arg" : prec => `(1023) -- precedence used for application arguments (`do`, `by`, ...) macro "lead" : prec => `(1022) -- precedence used for terms not supposed to be used as arguments (`let`, `have`, ...) macro "(" p:prec ")" : prec => p macro "min" : prec => `(10) -- minimum precedence used in term parsers macro "min1" : prec => `(11) -- `(min+1) we can only `min+1` after `Meta.lean` /- `max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`. We use `max_prec` to workaround bootstrapping issues. -/ macro "max_prec" : term => `(1024) macro "default" : prio => `(1000) macro "low" : prio => `(100) macro "mid" : prio => `(1000) macro "high" : prio => `(10000) macro "(" p:prio ")" : prio => p -- Basic notation for defining parsers -- NOTE: precedence must be at least `arg` to be used in `macro` without parentheses syntax:arg stx:max "+" : stx syntax:arg stx:max "*" : stx syntax:arg stx:max "?" : stx syntax:2 stx:2 " <|> " stx:1 : stx macro_rules | `(stx| $p +) => `(stx| many1($p)) | `(stx| $p *) => `(stx| many($p)) | `(stx| $p ?) => `(stx| optional($p)) | `(stx| $p₁ <|> $p₂) => `(stx| orelse($p₁, $p₂)) /- Comma-separated sequence. -/ macro:arg x:stx:max ",*" : stx => `(stx| sepBy($x, ",", ", ")) macro:arg x:stx:max ",+" : stx => `(stx| sepBy1($x, ",", ", ")) /- Comma-separated sequence with optional trailing comma. -/ macro:arg x:stx:max ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep)) macro:arg x:stx:max ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep)) macro:arg "!" x:stx:max : stx => `(stx| notFollowedBy($x)) syntax (name := rawNatLit) "nat_lit " num : term infixr:90 " ∘ " => Function.comp infixr:35 " × " => Prod infixl:55 " ||| " => HOr.hOr infixl:58 " ^^^ " => HXor.hXor infixl:60 " &&& " => HAnd.hAnd infixl:65 " + " => HAdd.hAdd infixl:65 " - " => HSub.hSub infixl:70 " * " => HMul.hMul infixl:70 " / " => HDiv.hDiv infixl:70 " % " => HMod.hMod infixl:75 " <<< " => HShiftLeft.hShiftLeft infixl:75 " >>> " => HShiftRight.hShiftRight infixr:80 " ^ " => HPow.hPow prefix:100 "-" => Neg.neg prefix:100 "~~~" => Complement.complement /- Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binop%` elaboration helper for binary operators. It addresses issue #382. -/ macro_rules | `($x ||| $y) => `(binop% HOr.hOr $x $y) macro_rules | `($x ^^^ $y) => `(binop% HXor.hXor $x $y) macro_rules | `($x &&& $y) => `(binop% HAnd.hAnd $x $y) macro_rules | `($x + $y) => `(binop% HAdd.hAdd $x $y) macro_rules | `($x - $y) => `(binop% HSub.hSub $x $y) macro_rules | `($x * $y) => `(binop% HMul.hMul $x $y) macro_rules | `($x / $y) => `(binop% HDiv.hDiv $x $y) macro_rules | `($x % $y) => `(binop% HMod.hMod $x $y) macro_rules | `($x <<< $y) => `(binop% HShiftLeft.hShiftLeft $x $y) macro_rules | `($x >>> $y) => `(binop% HShiftRight.hShiftRight $x $y) macro_rules | `($x ^ $y) => `(binop% HPow.hPow $x $y) -- declare ASCII alternatives first so that the latter Unicode unexpander wins infix:50 " <= " => LE.le infix:50 " ≤ " => LE.le infix:50 " < " => LT.lt infix:50 " >= " => GE.ge infix:50 " ≥ " => GE.ge infix:50 " > " => GT.gt infix:50 " = " => Eq infix:50 " == " => BEq.beq infix:50 " ~= " => HEq infix:50 " ≅ " => HEq /- Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binrel%` elaboration helper for binary relations. It has better support for applying coercions. For example, suppose we have `binrel% Eq n i` where `n : Nat` and `i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but `binrel%` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/ macro_rules | `($x <= $y) => `(binrel% LE.le $x $y) macro_rules | `($x ≤ $y) => `(binrel% LE.le $x $y) macro_rules | `($x < $y) => `(binrel% LT.lt $x $y) macro_rules | `($x > $y) => `(binrel% GT.gt $x $y) macro_rules | `($x >= $y) => `(binrel% GE.ge $x $y) macro_rules | `($x ≥ $y) => `(binrel% GE.ge $x $y) macro_rules | `($x = $y) => `(binrel% Eq $x $y) macro_rules | `($x == $y) => `(binrel% BEq.beq $x $y) infixr:35 " /\\ " => And infixr:35 " ∧ " => And infixr:30 " \\/ " => Or infixr:30 " ∨ " => Or notation:max "¬" p:40 => Not p infixl:35 " && " => and infixl:30 " || " => or notation:max "!" b:40 => not b infixl:65 " ++ " => HAppend.hAppend infixr:67 " :: " => List.cons infixr:20 " <|> " => HOrElse.hOrElse infixr:60 " >> " => HAndThen.hAndThen infixl:55 " >>= " => Bind.bind infixl:60 " <*> " => Seq.seq infixl:60 " <* " => SeqLeft.seqLeft infixr:60 " *> " => SeqRight.seqRight infixr:100 " <$> " => Functor.map syntax (name := termDepIfThenElse) ppGroup(ppDedent("if " ident " : " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $h:ident : $c then $t:term else $e:term) => ``(dite $c (fun $h:ident => $t) (fun $h:ident => $e)) syntax (name := termIfThenElse) ppGroup(ppDedent("if " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $c then $t:term else $e:term) => ``(ite $c $t $e) macro "if " "let " pat:term " := " d:term " then " t:term " else " e:term : term => `(match $d:term with | $pat:term => $t | _ => $e) syntax:min term "<|" term:min : term macro_rules | `($f $args* <| $a) => let args := args.push a; `($f $args*) | `($f <| $a) => `($f $a) syntax:min term "|>" term:min1 : term macro_rules | `($a |> $f $args*) => let args := args.push a; `($f $args*) | `($a |> $f) => `($f $a) -- Haskell-like pipe <| -- Note that we have a whitespace after `$` to avoid an ambiguity with the antiquotations. syntax:min term atomic("$" ws) term:min : term macro_rules | `($f $args* $ $a) => let args := args.push a; `($f $args*) | `($f $ $a) => `($f $a) syntax "{ " ident (" : " term)? " // " term " }" : term macro_rules | `({ $x : $type // $p }) => ``(Subtype (fun ($x:ident : $type) => $p)) | `({ $x // $p }) => ``(Subtype (fun ($x:ident : _) => $p)) /- `without_expected_type t` instructs Lean to elaborate `t` without an expected type. Recall that terms such as `match ... with ...` and `⟨...⟩` will postpone elaboration until expected type is known. So, `without_expected_type` is not effective in this case. -/ macro "without_expected_type " x:term : term => `(let aux := $x; aux) syntax "[" term,* "]" : term syntax "%[" term,* "|" term "]" : term -- auxiliary notation for creating big list literals namespace Lean macro_rules | `([ $elems,* ]) => do let rec expandListLit (i : Nat) (skip : Bool) (result : Syntax) : MacroM Syntax := do match i, skip with | 0, _ => pure result | i+1, true => expandListLit i false result | i+1, false => expandListLit i true (← ``(List.cons $(elems.elemsAndSeps[i]) $result)) if elems.elemsAndSeps.size < 64 then expandListLit elems.elemsAndSeps.size false (← ``(List.nil)) else `(%[ $elems,* | List.nil ]) notation:50 e:51 " matches " p:51 => match e with | p => true | _ => false namespace Parser.Tactic /-- Introduce one or more hypotheses, optionally naming and/or pattern-matching them. For each hypothesis to be introduced, the remaining main goal's target type must be a `let` or function type. * `intro` by itself introduces one anonymous hypothesis, which can be accessed by e.g. `assumption`. * `intro x y` introduces two hypotheses and names them. Individual hypotheses can be anonymized via `_`, or matched against a pattern: ```lean -- ... ⊢ α × β → ... intro (a, b) -- ..., a : α, b : β ⊢ ... ``` * Alternatively, `intro` can be combined with pattern matching much like `fun`: ```lean intro | n + 1, 0 => tac | ... ``` -/ syntax (name := intro) "intro " notFollowedBy("|") (colGt term:max)* : tactic /-- `intros x...` behaves like `intro x...`, but then keeps introducing (anonymous) hypotheses until goal is not of a function type. -/ syntax (name := intros) "intros " (colGt (ident <|> "_"))* : tactic /-- `rename t => x` renames the most recent hypothesis whose type matches `t` (which may contain placeholders) to `x`, or fails if no such hypothesis could be found. -/ syntax (name := rename) "rename " term " => " ident : tactic /-- `revert x...` is the inverse of `intro x...`: it moves the given hypotheses into the main goal's target type. -/ syntax (name := revert) "revert " (colGt ident)+ : tactic /-- `clear x...` removes the given hypotheses, or fails if there are remaining references to a hypothesis. -/ syntax (name := clear) "clear " (colGt ident)+ : tactic /-- `subst x...` substitutes each `x` with `e` in the goal if there is a hypothesis of type `x = e` or `e = x`. If `x` is itself a hypothesis of type `y = e` or `e = y`, `y` is substituted instead. -/ syntax (name := subst) "subst " (colGt ident)+ : tactic /-- `assumption` tries to solve the main goal using a hypothesis of compatible type, or else fails. Note also the `‹t›` term notation, which is a shorthand for `show t by assumption`. -/ syntax (name := assumption) "assumption" : tactic /-- `contradiction` closes the main goal if its hypotheses are "trivially contradictory". ```lean example (h : False) : p := by contradiction -- inductive type/family with no applicable constructors example (h : none = some true) : p := by contradiction -- injectivity of constructors example (h : 2 + 2 = 3) : p := by contradiction -- decidable false proposition example (h : p) (h' : ¬ p) : q := by contradiction example (x : Nat) (h : x ≠ x) : p := by contradiction ``` -/ syntax (name := contradiction) "contradiction" : tactic /-- `apply e` tries to match the current goal against the conclusion of `e`'s type. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones. The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ syntax (name := apply) "apply " term : tactic /-- `exact e` closes the main goal if its target type matches that of `e`. -/ syntax (name := exact) "exact " term : tactic /-- `refine e` behaves like `exact e`, except that named (`?x`) or unnamed (`?_`) holes in `e` that are not solved by unification with the main goal's target type are converted into new goals, using the hole's name, if any, as the goal case name. -/ syntax (name := refine) "refine " term : tactic /-- `refine' e` behaves like `refine e`, except that unsolved placeholders (`_`) and implicit parameters are also converted into new goals. -/ syntax (name := refine') "refine' " term : tactic /-- If the main goal's target type is an inductive type, `constructor` solves it with the first matching constructor, or else fails. -/ syntax (name := constructor) "constructor" : tactic /-- `case tag => tac` focuses on the goal with case name `tag` and solves it using `tac`, or else fails. `case tag x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/ syntax (name := case) "case " ident (ident <|> "_")* " => " tacticSeq : tactic /-- `allGoals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/ syntax (name := allGoals) "allGoals " tacticSeq : tactic /-- `focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it. Usually `· tac`, which enforces that the goal is closed by `tac`, should be preferred. -/ syntax (name := focus) "focus " tacticSeq : tactic /-- `skip` does nothing. -/ syntax (name := skip) "skip" : tactic /-- `done` succeeds iff there are no remaining goals. -/ syntax (name := done) "done" : tactic syntax (name := traceState) "traceState" : tactic syntax (name := failIfSuccess) "failIfSuccess " tacticSeq : tactic /-- `generalize [h :] e = x` replaces all occurrences of the term `e` in the main goal with a fresh hypothesis `x`. If `h` is given, `h : e = x` is introduced as well. -/ syntax (name := generalize) "generalize " atomic(ident " : ")? term:51 " = " ident : tactic syntax (name := paren) "(" tacticSeq ")" : tactic syntax (name := withReducible) "withReducible " tacticSeq : tactic syntax (name := withReducibleAndInstances) "withReducibleAndInstances " tacticSeq : tactic /-- `first | tac | ...` runs each `tac` until one succeeds, or else fails. -/ syntax (name := first) "first " withPosition((group(colGe "|" tacticSeq))+) : tactic syntax (name := rotateLeft) "rotateLeft" (num)? : tactic syntax (name := rotateRight) "rotateRight" (num)? : tactic /-- `try tac` runs `tac` and succeeds even if `tac` failed. -/ macro "try " t:tacticSeq : tactic => `(first | $t | skip) /-- `tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal, concatenating all goals produced by `tac'`. -/ macro:1 x:tactic " <;> " y:tactic:0 : tactic => `(tactic| focus ($x:tactic; allGoals $y:tactic)) /-- `· tac` focuses on the main goal and tries to solve it using `tac`, or else fails. -/ macro dot:("·" <|> ".") ts:tacticSeq : tactic => `(tactic| {%$dot ($ts:tacticSeq) }) /-- `rfl` is a shorthand for `exact rfl`. -/ macro "rfl" : tactic => `(exact rfl) /-- `admit` is a shorthand for `exact sorry`. -/ macro "admit" : tactic => `(exact sorry) macro "inferInstance" : tactic => `(exact inferInstance) syntax locationWildcard := "*" syntax locationHyp := (colGt ident)+ ("⊢" <|> "|-")? -- TODO: delete syntax locationTargets := (colGt ident)+ ("⊢" <|> "|-")? syntax location := withPosition("at " locationWildcard <|> locationHyp) syntax (name := change) "change " term (location)? : tactic syntax (name := changeWith) "change " term " with " term (location)? : tactic syntax rwRule := ("←" <|> "<-")? term syntax rwRuleSeq := "[" rwRule,+,? "]" syntax (name := rewriteSeq) "rewrite " rwRuleSeq (location)? : tactic syntax (name := erewriteSeq) "erewrite " rwRuleSeq (location)? : tactic syntax (name := rwSeq) "rw " rwRuleSeq (location)? : tactic syntax (name := erwSeq) "erw " rwRuleSeq (location)? : tactic def rwWithRfl (kind : SyntaxNodeKind) (atom : String) (stx : Syntax) : MacroM Syntax := do -- We show the `rfl` state on `]` let seq := stx[1] let rbrak := seq[2] -- Replace `]` token with one without position information in the expanded tactic let seq := seq.setArg 2 (mkAtom "]") let tac := stx.setKind kind |>.setArg 0 (mkAtomFrom stx atom) |>.setArg 1 seq `(tactic| $tac; try (withReducible rfl%$rbrak)) @[macro rwSeq] def expandRwSeq : Macro := rwWithRfl ``Lean.Parser.Tactic.rewriteSeq "rewrite" @[macro erwSeq] def expandERwSeq : Macro := rwWithRfl ``Lean.Parser.Tactic.erewriteSeq "erewrite" syntax (name := injection) "injection " term (" with " (colGt (ident <|> "_"))+)? : tactic syntax simpPre := "↓" syntax simpPost := "↑" syntax simpLemma := (simpPre <|> simpPost)? term syntax simpErase := "-" ident syntax (name := simp) "simp " ("(" &"config" " := " term ")")? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? (location)? : tactic syntax (name := simpAll) "simp_all " ("(" &"config" " := " term ")")? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? : tactic -- Auxiliary macro for lifting have/suffices/let/... -- It makes sure the "continuation" `?_` is the main goal after refining macro "refineLift " e:term : tactic => `(focus (refine noImplicitLambda% $e; rotateRight)) macro "have " d:haveDecl : tactic => `(refineLift have $d:haveDecl; ?_) /- We use a priority > default, to avoid ambiguity with previous `have` notation -/ macro (priority := high) "have" x:ident " := " p:term : tactic => `(have $x:ident : _ := $p) macro "suffices " d:sufficesDecl : tactic => `(refineLift suffices $d:sufficesDecl; ?_) macro "let " d:letDecl : tactic => `(refineLift let $d:letDecl; ?_) macro "show " e:term : tactic => `(refineLift show $e:term from ?_) syntax (name := letrec) withPosition(atomic(group("let " &"rec ")) letRecDecls) : tactic macro_rules | `(tactic| let rec $d:letRecDecls) => `(tactic| refineLift let rec $d:letRecDecls; ?_) -- Similar to `refineLift`, but using `refine'` macro "refineLift' " e:term : tactic => `(focus (refine' noImplicitLambda% $e; rotateRight)) macro "have' " d:haveDecl : tactic => `(refineLift' have $d:haveDecl; ?_) macro (priority := high) "have'" x:ident " := " p:term : tactic => `(have' $x:ident : _ := $p) macro "let' " d:letDecl : tactic => `(refineLift' let $d:letDecl; ?_) syntax inductionAlt := "| " (group("@"? ident) <|> "_") (ident <|> "_")* " => " (hole <|> syntheticHole <|> tacticSeq) syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) syntax (name := induction) "induction " term,+ (" using " ident)? ("generalizing " ident+)? (inductionAlts)? : tactic syntax casesTarget := atomic(ident " : ")? term syntax (name := cases) "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic syntax (name := existsIntro) "exists " term : tactic syntax "repeat " tacticSeq : tactic macro_rules | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip) syntax "trivial" : tactic macro_rules | `(tactic| trivial) => `(tactic| assumption) macro_rules | `(tactic| trivial) => `(tactic| rfl) macro_rules | `(tactic| trivial) => `(tactic| contradiction) macro_rules | `(tactic| trivial) => `(tactic| apply True.intro) macro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial) macro "unhygienic " t:tacticSeq : tactic => `(set_option tactic.hygienic false in $t:tacticSeq) end Tactic namespace Attr -- simp attribute syntax syntax (name := simp) "simp" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr end Attr end Parser end Lean macro "‹" type:term "›" : term => `((by assumption : $type))
50810e96ade854ba4920658aad65bbafa0faded8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/list/duplicate.lean
e142708891e1e2f5447c4c7d23846a24f7d62dd7
[ "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,437
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky, Chris Hughes -/ import data.list.nodup /-! # List duplicates > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions * `list.duplicate x l : Prop` is an inductive property that holds when `x` is a duplicate in `l` ## Implementation details In this file, `x ∈+ l` notation is shorthand for `list.duplicate x l`. -/ variable {α : Type*} namespace list /-- Property that an element `x : α` of `l : list α` can be found in the list more than once. -/ inductive duplicate (x : α) : list α → Prop | cons_mem {l : list α} : x ∈ l → duplicate (x :: l) | cons_duplicate {y : α} {l : list α} : duplicate l → duplicate (y :: l) local infix ` ∈+ `:50 := list.duplicate variables {l : list α} {x : α} lemma mem.duplicate_cons_self (h : x ∈ l) : x ∈+ x :: l := duplicate.cons_mem h lemma duplicate.duplicate_cons (h : x ∈+ l) (y : α) : x ∈+ y :: l := duplicate.cons_duplicate h lemma duplicate.mem (h : x ∈+ l) : x ∈ l := begin induction h with l' h y l' h hm, { exact mem_cons_self _ _ }, { exact mem_cons_of_mem _ hm } end lemma duplicate.mem_cons_self (h : x ∈+ x :: l) : x ∈ l := begin cases h with _ h _ _ h, { exact h }, { exact h.mem } end @[simp] lemma duplicate_cons_self_iff : x ∈+ x :: l ↔ x ∈ l := ⟨duplicate.mem_cons_self, mem.duplicate_cons_self⟩ lemma duplicate.ne_nil (h : x ∈+ l) : l ≠ [] := λ H, (mem_nil_iff x).mp (H ▸ h.mem) @[simp] lemma not_duplicate_nil (x : α) : ¬ x ∈+ [] := λ H, H.ne_nil rfl lemma duplicate.ne_singleton (h : x ∈+ l) (y : α) : l ≠ [y] := begin induction h with l' h z l' h hm, { simp [ne_nil_of_mem h] }, { simp [ne_nil_of_mem h.mem] } end @[simp] lemma not_duplicate_singleton (x y : α) : ¬ x ∈+ [y] := λ H, H.ne_singleton _ rfl lemma duplicate.elim_nil (h : x ∈+ []) : false := not_duplicate_nil x h lemma duplicate.elim_singleton {y : α} (h : x ∈+ [y]) : false := not_duplicate_singleton x y h lemma duplicate_cons_iff {y : α} : x ∈+ y :: l ↔ (y = x ∧ x ∈ l) ∨ x ∈+ l := begin refine ⟨λ h, _, λ h, _⟩, { cases h with _ hm _ _ hm, { exact or.inl ⟨rfl, hm⟩ }, { exact or.inr hm } }, { rcases h with ⟨rfl|h⟩|h, { simpa }, { exact h.cons_duplicate } } end lemma duplicate.of_duplicate_cons {y : α} (h : x ∈+ y :: l) (hx : x ≠ y) : x ∈+ l := by simpa [duplicate_cons_iff, hx.symm] using h lemma duplicate_cons_iff_of_ne {y : α} (hne : x ≠ y) : x ∈+ y :: l ↔ x ∈+ l := by simp [duplicate_cons_iff, hne.symm] lemma duplicate.mono_sublist {l' : list α} (hx : x ∈+ l) (h : l <+ l') : x ∈+ l' := begin induction h with l₁ l₂ y h IH l₁ l₂ y h IH, { exact hx }, { exact (IH hx).duplicate_cons _ }, { rw duplicate_cons_iff at hx ⊢, rcases hx with ⟨rfl, hx⟩|hx, { simp [h.subset hx] }, { simp [IH hx] } } end /-- The contrapositive of `list.nodup_iff_sublist`. -/ lemma duplicate_iff_sublist : x ∈+ l ↔ [x, x] <+ l := begin induction l with y l IH, { simp }, { by_cases hx : x = y, { simp [hx, cons_sublist_cons_iff, singleton_sublist] }, { rw [duplicate_cons_iff_of_ne hx, IH], refine ⟨sublist_cons_of_sublist y, λ h, _⟩, cases h, { assumption }, { contradiction } } } end lemma nodup_iff_forall_not_duplicate : nodup l ↔ ∀ (x : α), ¬ x ∈+ l := by simp_rw [nodup_iff_sublist, duplicate_iff_sublist] lemma exists_duplicate_iff_not_nodup : (∃ (x : α), x ∈+ l) ↔ ¬ nodup l := by simp [nodup_iff_forall_not_duplicate] lemma duplicate.not_nodup (h : x ∈+ l) : ¬ nodup l := λ H, nodup_iff_forall_not_duplicate.mp H _ h lemma duplicate_iff_two_le_count [decidable_eq α] : (x ∈+ l) ↔ 2 ≤ count x l := by simp [duplicate_iff_sublist, le_count_iff_replicate_sublist] instance decidable_duplicate [decidable_eq α] (x : α) : ∀ (l : list α), decidable (x ∈+ l) | [] := is_false (not_duplicate_nil x) | (y :: l) := match decidable_duplicate l with | is_true h := is_true (h.duplicate_cons y) | is_false h := if hx : y = x ∧ x ∈ l then is_true (hx.left.symm ▸ hx.right.duplicate_cons_self) else is_false (by simpa [duplicate_cons_iff, h] using hx) end end list
92eb17f597edf710cd0825abe475701aa2790a53
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/predicate_logic/true.lean
1c6119aa408e901a5f27ae6bac35e39ff8409ba4
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
456
lean
/- In Lean, true is a proposition that is always true, in the sense that there is a proof of it that doesn't depend on anything else being true. -/ #check true /- inductive true : Prop | intro : true -/ /- Introduction rule for true -/ lemma true_is_true : true := true.intro /- A function from true to true -/ lemma true_to_true' : true → true := λ (t : true), t /- A proof that true → true -/ lemma true_to_true : true → true := λ t, t
97e5cbc0b827d662204e37dd18ea02e418616016
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/analysis/normed_space/point_reflection.lean
ecb340065255a74514230f62b47b54d0819e1a7e
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
3,447
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov -/ import algebra.midpoint import topology.metric_space.isometry /-! # Point reflection in a point as an `isometric` homeomorphism Given a `normed_group E` and `x : E`, we define `isometric.point_reflection x` to be the point reflection in `x` interpreted as an `isometric` homeomorphism. Point reflection is defined as an `equiv.perm` in `data.equiv.mul_add`. In this file we restate results about `equiv.point_reflection` for an `isometric.point_reflection`, and add a few results about `dist`. ## Tags point reflection, isometric -/ variables (R : Type*) {E : Type*} lemma equiv.point_reflection_fixed_iff_of_module [ring R] [invertible (2:R)] [add_comm_group E] [module R E] {x y : E} : (equiv.point_reflection x : E → E) y = y ↔ y = x := equiv.point_reflection_fixed_iff_of_bit0_injective $ λ x y h, by rw [← one_smul R x, ← one_smul R y, ← inv_of_mul_self (2:R), mul_smul, mul_smul, two_smul, two_smul, ← bit0, ← bit0, h] namespace isometric section normed_group variables [normed_group E] /-- Point reflection in `x` as an `isometric` homeomorphism. -/ def point_reflection (x : E) : E ≃ᵢ E := (isometric.neg E).trans (isometric.add_left (x + x)) lemma point_reflection_apply (x y : E) : (point_reflection x : E → E) y = x + x - y := rfl @[simp] lemma point_reflection_to_equiv (x : E) : (point_reflection x).to_equiv = equiv.point_reflection x := rfl @[simp] lemma point_reflection_self (x : E) : (point_reflection x : E → E) x = x := add_sub_cancel _ _ lemma point_reflection_involutive (x : E) : function.involutive (point_reflection x : E → E) := equiv.point_reflection_involutive x @[simp] lemma point_reflection_symm (x : E) : (point_reflection x).symm = point_reflection x := to_equiv_inj $ equiv.point_reflection_symm x @[simp] lemma point_reflection_dist_fixed (x y : E) : dist ((point_reflection x : E → E) y) x = dist y x := by rw [← (point_reflection x).dist_eq y x, point_reflection_self] lemma point_reflection_dist_self' (x y : E) : dist ((point_reflection x : E → E) y) y = dist (x + x) (y + y) := by { simp only [point_reflection_apply, dist_eq_norm], congr' 1, abel } end normed_group section module variables [ring R] [invertible (2:R)] [normed_group E] [module R E] @[simp] lemma point_reflection_midpoint_left (x y : E) : (point_reflection (midpoint R x y) : E → E) x = y := equiv.point_reflection_midpoint_left R x y @[simp] lemma point_reflection_midpoint_right (x y : E) : (point_reflection (midpoint R x y) : E → E) y = x := equiv.point_reflection_midpoint_right R x y variable (R) include R lemma point_reflection_fixed_iff {x y : E} : (point_reflection x : E → E) y = y ↔ y = x := equiv.point_reflection_fixed_iff_of_module R end module section normed_space variables (R) [normed_field R] [normed_group E] [normed_space R E] lemma point_reflection_dist_self (x y : E) : dist ((point_reflection x : E → E) y) y = ∥(2:R)∥ * dist x y := by simp only [point_reflection_dist_self', ← two_smul R x, ← two_smul R y, dist_smul] end normed_space lemma point_reflection_dist_self_real [normed_group E] [normed_space ℝ E] (x y : E) : dist ((point_reflection x : E → E) y) y = 2 * dist x y := by simp [point_reflection_dist_self ℝ x y, real.norm_two] end isometric
93e36604dee46e442f3df73690b7f6a521687090
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/algebra/associated.lean
0f745e302b2e165f89fbe4ffa33c55d651b7cbc8
[ "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
25,505
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 Associated and irreducible elements. -/ import algebra.group data.multiset variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} open lattice /-- is unit -/ def is_unit [monoid α] (a : α) : Prop := ∃u:units α, a = u @[simp] lemma is_unit_unit [monoid α] (u : units α) : is_unit (u : α) := ⟨u, rfl⟩ @[simp] theorem is_unit_zero_iff [semiring α] : is_unit (0 : α) ↔ (0:α) = 1 := ⟨λ ⟨⟨_, a, (a0 : 0 * a = 1), _⟩, rfl⟩, by rwa zero_mul at a0, λ h, begin haveI := subsingleton_of_zero_eq_one _ h, refine ⟨⟨0, 0, _, _⟩, rfl⟩; apply subsingleton.elim end⟩ @[simp] theorem not_is_unit_zero [nonzero_comm_ring α] : ¬ is_unit (0 : α) := mt is_unit_zero_iff.1 zero_ne_one @[simp] theorem is_unit_one [monoid α] : is_unit (1:α) := ⟨1, rfl⟩ theorem is_unit_of_mul_one [comm_monoid α] (a b : α) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ theorem is_unit_iff_exists_inv [comm_monoid α] {a : α} : is_unit a ↔ ∃ b, a * b = 1 := ⟨by rintro ⟨⟨a, b, hab, _⟩, rfl⟩; exact ⟨b, hab⟩, λ ⟨b, hab⟩, is_unit_of_mul_one _ b hab⟩ theorem is_unit_iff_exists_inv' [comm_monoid α] {a : α} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] lemma is_unit_pow [monoid α] {a : α} (n : ℕ) : is_unit a → is_unit (a ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ @[simp] theorem units.is_unit_mul_units [monoid α] (a : α) (u : units α) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (assume ⟨v, hv⟩, hv.symm ▸ ⟨v * u, (units.coe_mul v u).symm⟩) theorem is_unit_of_mul_is_unit_left {α} [comm_monoid α] {x y : α} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ theorem is_unit_of_mul_is_unit_right {α} [comm_monoid α] {x y : α} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm theorem is_unit_iff_dvd_one [comm_semiring α] {x : α} : is_unit x ↔ x ∣ 1 := ⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩, λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩ theorem is_unit_iff_forall_dvd [comm_semiring α] {x : α} : is_unit x ↔ ∀ y, x ∣ y := is_unit_iff_dvd_one.trans ⟨λ h y, dvd.trans h (one_dvd _), λ h, h _⟩ theorem mul_dvd_of_is_unit_left [comm_semiring α] {x y z : α} (h : is_unit x) : x * y ∣ z ↔ y ∣ z := ⟨dvd_trans (dvd_mul_left _ _), dvd_trans $ by simpa using mul_dvd_mul_right (is_unit_iff_dvd_one.1 h) y⟩ theorem mul_dvd_of_is_unit_right [comm_semiring α] {x y z : α} (h : is_unit y) : x * y ∣ z ↔ x ∣ z := by rw [mul_comm, mul_dvd_of_is_unit_left h] @[simp] lemma unit_mul_dvd_iff [comm_semiring α] {a b : α} {u : units α} : (u : α) * a ∣ b ↔ a ∣ b := mul_dvd_of_is_unit_left (is_unit_unit _) @[simp] lemma mul_unit_dvd_iff [comm_semiring α] {a b : α} {u : units α} : a * u ∣ b ↔ a ∣ b := mul_dvd_of_is_unit_right (is_unit_unit _) theorem is_unit_of_dvd_unit {α} [comm_semiring α] {x y : α} (xy : x ∣ y) (hu : is_unit y) : is_unit x := is_unit_iff_dvd_one.2 $ dvd_trans xy $ is_unit_iff_dvd_one.1 hu @[simp] theorem is_unit_nat {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) theorem is_unit_int {n : ℤ} : is_unit n ↔ n.nat_abs = 1 := ⟨λ ⟨u, hu⟩, (int.units_eq_one_or u).elim (by simp *) (by simp *), λ h, is_unit_iff_dvd_one.2 ⟨n, by rw [← int.nat_abs_mul_self, h]; refl⟩⟩ lemma is_unit_of_dvd_one [comm_semiring α] : ∀a ∣ 1, is_unit (a:α) | a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩ lemma dvd_and_not_dvd_iff [integral_domain α] {x y : α} : x ∣ y ∧ ¬y ∣ x ↔ x ≠ 0 ∧ ∃ d : α, ¬ is_unit d ∧ y = x * d := ⟨λ ⟨⟨d, hd⟩, hyx⟩, ⟨λ hx0, by simpa [hx0] using hyx, ⟨d, mt is_unit_iff_dvd_one.1 (λ ⟨e, he⟩, hyx ⟨e, by rw [hd, mul_assoc, ← he, mul_one]⟩), hd⟩⟩, λ ⟨hx0, d, hdu, hdx⟩, ⟨⟨d, hdx⟩, λ ⟨e, he⟩, hdu (is_unit_of_dvd_one _ ⟨e, (domain.mul_left_inj hx0).1 $ by conv {to_lhs, rw [he, hdx]};simp [mul_assoc]⟩)⟩⟩ /-- prime element of a semiring -/ def prime [comm_semiring α] (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ (∀a b, p ∣ a * b → p ∣ a ∨ p ∣ b) @[simp] lemma not_prime_zero [integral_domain α] : ¬ prime (0 : α) | ⟨h, _⟩ := h rfl @[simp] lemma not_prime_one [comm_semiring α] : ¬ prime (1 : α) := λ h, h.2.1 is_unit_one lemma exists_mem_multiset_dvd_of_prime [comm_semiring α] {s : multiset α} {p : α} (hp : prime p) : p ∣ s.prod → ∃a∈s, p ∣ a := multiset.induction_on s (assume h, (hp.2.1 $ is_unit_of_dvd_one _ h).elim) $ assume a s ih h, have p ∣ a * s.prod, by simpa using h, match hp.2.2 a s.prod this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end /-- `irreducible p` states that `p` is non-unit and only factors into units. We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a monoid allows us to reuse irreducible for associated elements. -/ @[class] def irreducible [monoid α] (p : α) : Prop := ¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b @[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) := by simp [irreducible] @[simp] theorem not_irreducible_zero [semiring α] : ¬ irreducible (0 : α) | ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm), this.elim hn0 hn0 theorem nonzero_of_irreducible [semiring α] : ∀ {p:α}, irreducible p → p ≠ 0 | _ hp rfl := not_irreducible_zero hp theorem of_irreducible_mul {α} [monoid α] {x y : α} : irreducible (x * y) → is_unit x ∨ is_unit y | ⟨_, h⟩ := h _ _ rfl theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) : irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x := begin haveI := classical.dec, refine or_iff_not_imp_right.2 (λ H, _), simp [h, irreducible] at H ⊢, refine λ a b h, classical.by_contradiction $ λ o, _, simp [not_or_distrib] at o, exact H _ o.1 _ o.2 h.symm end lemma irreducible_of_prime [integral_domain α] {p : α} (hp : prime p) : irreducible p := ⟨hp.2.1, λ a b hab, (show a * b ∣ a ∨ a * b ∣ b, from hab ▸ hp.2.2 a b (hab ▸ (dvd_refl _))).elim (λ ⟨x, hx⟩, or.inr (is_unit_iff_dvd_one.2 ⟨x, (domain.mul_left_inj (show a ≠ 0, from λ h, by simp [*, prime] at *)).1 $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩)) (λ ⟨x, hx⟩, or.inl (is_unit_iff_dvd_one.2 ⟨x, (domain.mul_left_inj (show b ≠ 0, from λ h, by simp [*, prime] at *)).1 $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul [integral_domain α] {p : α} (hp : prime p) {a b : α} {k l : ℕ} : p ^ k ∣ a → p ^ l ∣ b → p ^ ((k + l) + 1) ∣ a * b → p ^ (k + 1) ∣ a ∨ p ^ (l + 1) ∣ b := λ ⟨x, hx⟩ ⟨y, hy⟩ ⟨z, hz⟩, have h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z), by simpa [mul_comm, _root_.pow_add, hx, hy, mul_assoc, mul_left_comm] using hz, have hp0: p ^ (k + l) ≠ 0, from pow_ne_zero _ hp.1, have hpd : p ∣ x * y, from ⟨z, by rwa [domain.mul_left_inj hp0] at h⟩, (hp.2.2 x y hpd).elim (λ ⟨d, hd⟩, or.inl ⟨d, by simp [*, _root_.pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) (λ ⟨d, hd⟩, or.inr ⟨d, by simp [*, _root_.pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y local infix ` ~ᵤ ` : 50 := associated namespace associated @[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩ @[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x | x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩ @[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z | x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.coe_mul, mul_assoc]⟩ protected def setoid (α : Type*) [monoid α] : setoid α := { r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ } end associated local attribute [instance] associated.setoid theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩ theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a := iff.intro (assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, one_mul _⟩) (assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩) theorem associated_zero_iff_eq_zero [comm_semiring α] (a : α) : a ~ᵤ 0 ↔ a = 0 := iff.intro (assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm) (assume h, h ▸ associated.refl a) theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 := show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} : a * b ~ᵤ 1 → a ~ᵤ 1 | ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h lemma associated_mul_mul [comm_monoid α] {a₁ a₂ b₁ b₂ : α} : a₁ ~ᵤ b₁ → a₂ ~ᵤ b₂ → (a₁ * a₂) ~ᵤ (b₁ * b₂) | ⟨c₁, h₁⟩ ⟨c₂, h₂⟩ := ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩ theorem associated_of_dvd_dvd [integral_domain α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b := begin haveI := classical.dec_eq α, rcases hab with ⟨c, rfl⟩, rcases hba with ⟨d, a_eq⟩, by_cases ha0 : a = 0, { simp [*] at * }, have : a * 1 = a * (c * d), { simpa [mul_assoc] using a_eq }, have : 1 = (c * d), from eq_of_mul_eq_mul_left ha0 this, exact ⟨units.mk_of_mul_eq_one c d (this.symm), by rw [units.mk_of_mul_eq_one, units.val_coe]⟩ end lemma exists_associated_mem_of_dvd_prod [integral_domain α] {p : α} (hp : prime p) {s : multiset α} : (∀ r ∈ s, prime r) → p ∣ s.prod → ∃ q ∈ s, p ~ᵤ q := multiset.induction_on s (by simp [mt is_unit_iff_dvd_one.2 hp.2.1]) (λ a s ih hs hps, begin rw [multiset.prod_cons] at hps, cases hp.2.2 _ _ hps with h h, { use [a, by simp], cases h with u hu, cases ((irreducible_of_prime (hs a (multiset.mem_cons.2 (or.inl rfl)))).2 p u hu).resolve_left hp.2.1 with v hv, exact ⟨v, by simp [hu, hv]⟩ }, { rcases ih (λ r hr, hs _ (multiset.mem_cons.2 (or.inr hr))) h with ⟨q, hq₁, hq₂⟩, exact ⟨q, multiset.mem_cons.2 (or.inr hq₁), hq₂⟩ } end) lemma dvd_iff_dvd_of_rel_left [comm_semiring α] {a b c : α} (h : a ~ᵤ b) : a ∣ c ↔ b ∣ c := let ⟨u, hu⟩ := h in hu ▸ mul_unit_dvd_iff.symm @[simp] lemma dvd_mul_unit_iff [comm_semiring α] {a b : α} {u : units α} : a ∣ b * u ↔ a ∣ b := ⟨λ ⟨d, hd⟩, ⟨d * (u⁻¹ : units α), by simp [(mul_assoc _ _ _).symm, hd.symm]⟩, λ h, dvd.trans h (by simp)⟩ lemma dvd_iff_dvd_of_rel_right [comm_semiring α] {a b c : α} (h : b ~ᵤ c) : a ∣ b ↔ a ∣ c := let ⟨u, hu⟩ := h in hu ▸ dvd_mul_unit_iff.symm lemma eq_zero_iff_of_associated [comm_semiring α] {a b : α} (h : a ~ᵤ b) : a = 0 ↔ b = 0 := ⟨λ ha, let ⟨u, hu⟩ := h in by simp [hu.symm, ha], λ hb, let ⟨u, hu⟩ := h.symm in by simp [hu.symm, hb]⟩ lemma ne_zero_iff_of_associated [comm_semiring α] {a b : α} (h : a ~ᵤ b) : a ≠ 0 ↔ b ≠ 0 := by haveI := classical.dec; exact not_iff_not.2 (eq_zero_iff_of_associated h) lemma prime_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) (hp : prime p) : prime q := ⟨(ne_zero_iff_of_associated h).1 hp.1, let ⟨u, hu⟩ := h in ⟨λ ⟨v, hv⟩, hp.2.1 ⟨v * u⁻¹, by simp [hv.symm, hu.symm]⟩, hu ▸ by simp [mul_unit_dvd_iff]; exact hp.2.2⟩⟩ lemma prime_iff_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) : prime p ↔ prime q := ⟨prime_of_associated h, prime_of_associated h.symm⟩ lemma is_unit_iff_of_associated [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a ↔ is_unit b := ⟨let ⟨u, hu⟩ := h in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩, let ⟨u, hu⟩ := h.symm in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩⟩ lemma irreducible_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) (hp : irreducible p) : irreducible q := ⟨mt (is_unit_iff_of_associated h).2 hp.1, let ⟨u, hu⟩ := h in λ a b hab, have hpab : p = a * (b * (u⁻¹ : units α)), from calc p = (p * u) * (u ⁻¹ : units α) : by simp ... = _ : by rw hu; simp [hab, mul_assoc], (hp.2 _ _ hpab).elim or.inl (λ ⟨v, hv⟩, or.inr ⟨v * u, by simp [hv.symm]⟩)⟩ lemma irreducible_iff_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) : irreducible p ↔ irreducible q := ⟨irreducible_of_associated h, irreducible_of_associated h.symm⟩ lemma associated_mul_left_cancel [integral_domain α] {a b c d : α} (h : a * b ~ᵤ c * d) (h₁ : a ~ᵤ c) (ha : a ≠ 0) : b ~ᵤ d := let ⟨u, hu⟩ := h in let ⟨v, hv⟩ := associated.symm h₁ in ⟨u * (v : units α), (domain.mul_left_inj ha).1 begin rw [← hv, mul_assoc c (v : α) d, mul_left_comm c, ← hu], simp [hv.symm, mul_assoc, mul_comm, mul_left_comm] end⟩ lemma associated_mul_right_cancel [integral_domain α] {a b c d : α} : a * b ~ᵤ c * d → b ~ᵤ d → b ≠ 0 → a ~ᵤ c := by rw [mul_comm a, mul_comm c]; exact associated_mul_left_cancel def associates (α : Type*) [monoid α] : Type* := quotient (associated.setoid α) namespace associates open associated protected def mk {α : Type*} [monoid α] (a : α) : associates α := ⟦ a ⟧ theorem mk_eq_mk_iff_associated [monoid α] {a b : α} : associates.mk a = associates.mk b ↔ a ~ᵤ b := iff.intro quotient.exact quot.sound theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl theorem forall_associated [monoid α] {p : associates α → Prop} : (∀a, p a) ↔ (∀a, p (associates.mk a)) := iff.intro (assume h a, h _) (assume h a, quotient.induction_on a h) instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩ theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl instance [monoid α] : has_bot (associates α) := ⟨1⟩ section comm_monoid variable [comm_monoid α] instance : has_mul (associates α) := ⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $ assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩, quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩ theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) := rfl instance : comm_monoid (associates α) := { one := 1, mul := (*), mul_one := assume a', quotient.induction_on a' $ assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp, one_mul := assume a', quotient.induction_on a' $ assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp, mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $ assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc], mul_comm := assume a' b', quotient.induction_on₂ a' b' $ assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] } instance : preorder (associates α) := { le := λa b, ∃c, a * c = b, le_refl := assume a, ⟨1, by simp⟩, le_trans := assume a b c ⟨f₁, h₁⟩ ⟨f₂, h₂⟩, ⟨f₁ * f₂, h₂ ▸ h₁ ▸ (mul_assoc _ _ _).symm⟩} instance [comm_monoid α] : has_dvd (associates α) := ⟨(≤)⟩ @[simp] lemma mk_one : associates.mk (1 : α) = 1 := rfl lemma mk_pow (a : α) (n : ℕ) : associates.mk (a ^ n) = (associates.mk a) ^ n := by induction n; simp [*, pow_succ, associates.mk_mul_mk.symm] lemma dvd_eq_le [comm_monoid α] : ((∣) : associates α → associates α → Prop) = (≤) := rfl theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod := multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl theorem rel_associated_iff_map_eq_map {p q : multiset α} : multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk := by rw [← multiset.rel_eq]; simp [multiset.rel_map_left, multiset.rel_map_right, mk_eq_mk_iff_associated] theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b ~ᵤ 1, from quotient.exact h, ⟨quotient.sound $ associated_one_of_associated_mul_one this, quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩) (by simp {contextual := tt}) theorem prod_eq_one_iff {p : multiset (associates α)} : p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) := multiset.induction_on p (by simp) (by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt}) theorem coe_unit_eq_one : ∀u:units (associates α), (u : associates α) = 1 | ⟨u, v, huv, hvu⟩ := by rw [mul_eq_one_iff] at huv; exact huv.1 theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 := iff.intro (assume ⟨u, h⟩, h.symm ▸ coe_unit_eq_one _) (assume h, h.symm ▸ is_unit_one) theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a := calc is_unit (associates.mk a) ↔ a ~ᵤ 1 : by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated] ... ↔ is_unit a : associated_one_iff_is_unit section order theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in ⟨x * y, by simp [hx.symm, hy.symm, mul_comm, mul_assoc, mul_left_comm]⟩ theorem one_le {a : associates α} : 1 ≤ a := ⟨a, one_mul a⟩ theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod := begin haveI := classical.dec_eq (associates α), haveI := classical.dec_eq α, suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this }, suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa }, exact mul_mono (le_refl p.prod) one_le end theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩ theorem le_mul_left {a b : associates α} : a ≤ b * a := by rw [mul_comm]; exact le_mul_right end order end comm_monoid instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩ instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩ section comm_semiring variables [comm_semiring α] @[simp] theorem mk_zero_eq (a : α) : associates.mk a = 0 ↔ a = 0 := ⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩ @[simp] theorem mul_zero : ∀(a : associates α), a * 0 = 0 := by rintros ⟨a⟩; show associates.mk (a * 0) = associates.mk 0; rw [mul_zero] @[simp] protected theorem zero_mul : ∀(a : associates α), 0 * a = 0 := by rintros ⟨a⟩; show associates.mk (0 * a) = associates.mk 0; rw [zero_mul] theorem mk_eq_zero_iff_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 := calc associates.mk a = 0 ↔ (a ~ᵤ 0) : mk_eq_mk_iff_associated ... ↔ a = 0 : associated_zero_iff_eq_zero a theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b | ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc, let ⟨d, hd⟩ := (quotient.exact hc).symm in ⟨(↑d⁻¹) * c, calc b = (a * c) * ↑d⁻¹ : by rw [← hd, mul_assoc, units.mul_inv, mul_one] ... = a * (↑d⁻¹ * c) : by ac_refl⟩) hc' theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b := assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩ theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd def prime (p : associates α) : Prop := p ≠ 0 ∧ p ≠ 1 ∧ (∀a b, p ≤ a * b → p ≤ a ∨ p ≤ b) lemma exists_mem_multiset_le_of_prime {s : multiset (associates α)} {p : associates α} (hp : prime p) : p ≤ s.prod → ∃a∈s, p ≤ a := multiset.induction_on s (assume ⟨d, eq⟩, (hp.2.1 (mul_eq_one_iff.1 eq).1).elim) $ assume a s ih h, have p ≤ a * s.prod, by simpa using h, match hp.2.2 a s.prod this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end lemma prime_mk (p : α) : prime (associates.mk p) ↔ _root_.prime p := begin rw [associates.prime, _root_.prime, forall_associated], transitivity, { apply and_congr, refl, apply and_congr, refl, apply forall_congr, assume a, exact forall_associated }, apply and_congr, { rw [(≠), mk_zero_eq] }, apply and_congr, { rw [(≠), ← is_unit_iff_eq_one, is_unit_mk], }, apply forall_congr, assume a, apply forall_congr, assume b, rw [mk_mul_mk, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff] end end comm_semiring section integral_domain variable [integral_domain α] instance : partial_order (associates α) := { le_antisymm := assume a' b', quotient.induction_on₂ a' b' $ assume a b ⟨f₁', h₁⟩ ⟨f₂', h₂⟩, (quotient.induction_on₂ f₁' f₂' $ assume f₁ f₂ h₁ h₂, let ⟨c₁, h₁⟩ := quotient.exact h₁, ⟨c₂, h₂⟩ := quotient.exact h₂ in quotient.sound $ associated_of_dvd_dvd (h₁ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) (h₂ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)) h₁ h₂ .. associates.preorder } instance : lattice.order_bot (associates α) := { bot := 1, bot_le := assume a, one_le, .. associates.partial_order } instance : lattice.order_top (associates α) := { top := 0, le_top := assume a, ⟨0, mul_zero a⟩, .. associates.partial_order } theorem zero_ne_one : (0 : associates α) ≠ 1 := assume h, have (0 : α) ~ᵤ 1, from quotient.exact h, have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm, zero_ne_one this theorem mul_eq_zero_iff {x y : associates α} : x * y = 0 ↔ x = 0 ∨ y = 0 := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h), have a = 0 ∨ b = 0, from mul_eq_zero_iff_eq_zero_or_eq_zero.1 this, this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl)) (by simp [or_imp_distrib] {contextual := tt}) theorem prod_eq_zero_iff {s : multiset (associates α)} : s.prod = 0 ↔ (0 : associates α) ∈ s := multiset.induction_on s (by simp; exact zero_ne_one.symm) $ assume a s, by simp [mul_eq_zero_iff, @eq_comm _ 0 a] {contextual := tt} theorem irreducible_mk_iff (a : α) : irreducible (associates.mk a) ↔ irreducible a := begin simp [irreducible, is_unit_mk], apply and_congr (iff.refl _), split, { assume h x y eq, have : is_unit (associates.mk x) ∨ is_unit (associates.mk y), from h _ _ (by rw [eq]; refl), simpa [is_unit_mk] }, { refine assume h x y, quotient.induction_on₂ x y (assume x y eq, _), rcases quotient.exact eq.symm with ⟨u, eq⟩, have : a = x * (y * u), by rwa [mul_assoc, eq_comm] at eq, show is_unit (associates.mk x) ∨ is_unit (associates.mk y), simpa [is_unit_mk] using h _ _ this } end lemma eq_of_mul_eq_mul_left [integral_domain α] : ∀(a b c : associates α), a ≠ 0 → a * b = a * c → b = c := begin rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h, rcases quotient.exact' h with ⟨u, hu⟩, have hu : a * (b * ↑u) = a * c, { rwa [← mul_assoc] }, exact quotient.sound' ⟨u, eq_of_mul_eq_mul_left (mt (mk_zero_eq a).2 ha) hu⟩ end lemma le_of_mul_le_mul_left [integral_domain α] (a b c : associates α) (ha : a ≠ 0) : a * b ≤ a * c → b ≤ c | ⟨d, hd⟩ := ⟨d, eq_of_mul_eq_mul_left a _ _ ha $ by rwa ← mul_assoc⟩ lemma one_or_eq_of_le_of_prime [integral_domain α] : ∀(p m : associates α), prime p → m ≤ p → (m = 1 ∨ m = p) | _ m ⟨hp0, hp1, h⟩ ⟨d, rfl⟩ := match h m d (le_refl _) with | or.inl h := classical.by_cases (assume : m = 0, by simp [this]) $ assume : m ≠ 0, have m * d ≤ m * 1, by simpa using h, have d ≤ 1, from associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this, have d = 1, from lattice.bot_unique this, by simp [this] | or.inr h := classical.by_cases (assume : d = 0, by simp [this] at hp0; contradiction) $ assume : d ≠ 0, have d * m ≤ d * 1, by simpa [mul_comm] using h, or.inl $ lattice.bot_unique $ associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this end end integral_domain end associates
266e2f35a82ee8fa897bf91539eb1667413abd34
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/monoidal/subcategory.lean
8fef005cad002f024b4dfb79a9a64ba9b840a9b7
[ "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
5,881
lean
/- Copyright (c) 2022 Antoine Labelle. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Antoine Labelle -/ import category_theory.monoidal.braided import category_theory.concrete_category.basic /-! # Full monoidal subcategories Given a monidal category `C` and a monoidal predicate on `C`, that is a function `P : C → Prop` closed under `𝟙_` and `⊗`, we can put a monoidal structure on `{X : C // P X}` (the category structure is defined in `category_theory.full_subcategory`). When `C` is also braided/symmetric, the full monoidal subcategory also inherits the braided/symmetric structure. ## TODO * Add monoidal/braided versions of `category_theory.full_subcategory.lift` -/ universes u v namespace category_theory namespace monoidal_category open iso variables {C : Type u} [category.{v} C] [monoidal_category C] (P : C → Prop) /-- A property `C → Prop` is a monoidal predicate if it is closed under `𝟙_` and `⊗`. -/ class monoidal_predicate := (prop_id' : P (𝟙_ C) . obviously) (prop_tensor' : ∀ {X Y}, P X → P Y → P (X ⊗ Y) . obviously) restate_axiom monoidal_predicate.prop_id' restate_axiom monoidal_predicate.prop_tensor' open monoidal_predicate variables [monoidal_predicate P] /-- When `P` is a monoidal predicate, the full subcategory `{X : C // P X}` inherits the monoidal structure of `C` -/ instance full_monoidal_subcategory : monoidal_category {X : C // P X} := { tensor_obj := λ X Y, ⟨X ⊗ Y, prop_tensor X.2 Y.2⟩, tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, by { change X₁.1 ⊗ X₂.1 ⟶ Y₁.1 ⊗ Y₂.1, change X₁.1 ⟶ Y₁.1 at f, change X₂.1 ⟶ Y₂.1 at g, exact f ⊗ g }, tensor_unit := ⟨𝟙_ C, prop_id⟩, associator := λ X Y Z, ⟨(α_ X.1 Y.1 Z.1).hom, (α_ X.1 Y.1 Z.1).inv, hom_inv_id (α_ X.1 Y.1 Z.1), inv_hom_id (α_ X.1 Y.1 Z.1)⟩, left_unitor := λ X, ⟨(λ_ X.1).hom, (λ_ X.1).inv, hom_inv_id (λ_ X.1), inv_hom_id (λ_ X.1)⟩, right_unitor := λ X, ⟨(ρ_ X.1).hom, (ρ_ X.1).inv, hom_inv_id (ρ_ X.1), inv_hom_id (ρ_ X.1)⟩, tensor_id' := λ X Y, tensor_id X.1 Y.1, tensor_comp' := λ X₁ Y₁ Z₁ X₂ Y₂ Z₂ f₁ f₂ g₁ g₂, tensor_comp f₁ f₂ g₁ g₂, associator_naturality' := λ X₁ X₂ X₃ Y₁ Y₂ Y₃ f₁ f₂ f₃, associator_naturality f₁ f₂ f₃, left_unitor_naturality' := λ X Y f, left_unitor_naturality f, right_unitor_naturality' := λ X Y f, right_unitor_naturality f, pentagon' := λ W X Y Z, pentagon W.1 X.1 Y.1 Z.1, triangle' := λ X Y, triangle X.1 Y.1 } /-- The forgetful monoidal functor from a full monoidal subcategory into the original category ("forgetting" the condition). -/ @[simps] def full_monoidal_subcategory_inclusion : monoidal_functor {X : C // P X} C := { to_functor := full_subcategory_inclusion P, ε := 𝟙 _, μ := λ X Y, 𝟙 _ } instance full_monoidal_subcategory.full : full (full_monoidal_subcategory_inclusion P).to_functor := full_subcategory.full P instance full_monoidal_subcategory.faithful : faithful (full_monoidal_subcategory_inclusion P).to_functor := full_subcategory.faithful P variables {P} {P' : C → Prop} [monoidal_predicate P'] /-- An implication of predicates `P → P'` induces a monoidal functor between full monoidal subcategories. -/ @[simps] def full_monoidal_subcategory.map (h : ∀ ⦃X⦄, P X → P' X) : monoidal_functor {X : C // P X} {X : C // P' X} := { to_functor := full_subcategory.map h, ε := 𝟙 _, μ := λ X Y, 𝟙 _ } instance full_monoidal_subcategory.map_full (h : ∀ ⦃X⦄, P X → P' X) : full (full_monoidal_subcategory.map h).to_functor := { preimage := λ X Y f, f } instance full_monoidal_subcategory.map_faithful (h : ∀ ⦃X⦄, P X → P' X) : faithful (full_monoidal_subcategory.map h).to_functor := {} section braided variables (P) [braided_category C] /-- The braided structure on `{X : C // P X}` inherited by the braided structure on `C`. -/ instance full_braided_subcategory : braided_category {X : C // P X} := braided_category_of_faithful (full_monoidal_subcategory_inclusion P) (λ X Y, ⟨(β_ X.1 Y.1).hom, (β_ X.1 Y.1).inv, (β_ X.1 Y.1).hom_inv_id, (β_ X.1 Y.1).inv_hom_id⟩) (λ X Y, by tidy) /-- The forgetful braided functor from a full braided subcategory into the original category ("forgetting" the condition). -/ @[simps] def full_braided_subcategory_inclusion : braided_functor {X : C // P X} C := { to_monoidal_functor := full_monoidal_subcategory_inclusion P, braided' := λ X Y, by { rw [is_iso.eq_inv_comp], tidy } } instance full_braided_subcategory.full : full (full_braided_subcategory_inclusion P).to_functor := full_monoidal_subcategory.full P instance full_braided_subcategory.faithful : faithful (full_braided_subcategory_inclusion P).to_functor := full_monoidal_subcategory.faithful P variables {P} /-- An implication of predicates `P → P'` induces a braided functor between full braided subcategories. -/ @[simps] def full_braided_subcategory.map (h : ∀ ⦃X⦄, P X → P' X) : braided_functor {X : C // P X} {X : C // P' X} := { to_monoidal_functor := full_monoidal_subcategory.map h, braided' := λ X Y, by { rw [is_iso.eq_inv_comp], tidy } } instance full_braided_subcategory.map_full (h : ∀ ⦃X⦄, P X → P' X) : full (full_braided_subcategory.map h).to_functor := full_monoidal_subcategory.map_full h instance full_braided_subcategory.map_faithful (h : ∀ ⦃X⦄, P X → P' X) : faithful (full_braided_subcategory.map h).to_functor := full_monoidal_subcategory.map_faithful h end braided section symmetric variables (P) [symmetric_category C] instance full_symmetric_subcategory : symmetric_category {X : C // P X} := symmetric_category_of_faithful (full_braided_subcategory_inclusion P) end symmetric end monoidal_category end category_theory
375f8e493875de7942cd47db49aaacb9791fbdac
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finset/fold.lean
1f728224a9520abf7196e2f5a5e5a6815765b17c
[ "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
9,017
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.order.monoid.with_top import data.finset.basic import data.multiset.fold /-! # The fold operation for a commutative associative operation over a finset. -/ namespace finset open multiset variables {α β γ : Type*} /-! ### fold -/ section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation (name := op) a ` * ` b := op a b include hc ha /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_cons (h : a ∉ s) : (cons a s h).fold op b f = f a * s.fold op b f := by { dunfold fold, rw [cons_val, multiset.map_cons, fold_cons_left], } @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, multiset.map_cons, fold_cons_left] @[simp] theorem fold_singleton : ({a} : finset α).fold op b f = f a * b := rfl @[simp] theorem fold_map {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr rfl H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] lemma fold_const [decidable (s = ∅)] (c : β) (h : op c (op b c) = op b c) : finset.fold op b (λ _, c) s = if s = ∅ then b else op b c := begin classical, unfreezingI { induction s using finset.induction_on with x s hx IH }, { simp }, { simp only [finset.fold_insert hx, IH, if_false, finset.insert_ne_empty], split_ifs, { rw hc.comm }, { exact h } } end theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_disj_union {s₁ s₂ : finset α} {b₁ b₂ : β} (h) : (s₁.disj_union s₂ h).fold op (b₁ * b₂) f = s₁.fold op b₁ f * s₂.fold op b₂ f := (congr_arg _ $ multiset.map_add _ _ _).trans (multiset.fold_add _ _ _ _ _) theorem fold_disj_Union {ι : Type*} {s : finset ι} {t : ι → finset α} {b : ι → β} {b₀ : β} (h) : (s.disj_Union t h).fold op (s.fold op b₀ b) f = s.fold op b₀ (λ i, (t i).fold op (b i) f) := (congr_arg _ $ multiset.map_bind _ _ _).trans (multiset.fold_bind _ _ _ _ _) theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← multiset.map_add, union_val, inter_val, union_add_inter, multiset.map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := begin by_cases (a ∈ s), { rw [← insert_erase h], simp [← ha.assoc, hi.idempotent] }, { apply fold_insert h }, end theorem fold_image_idem [decidable_eq α] {g : γ → α} {s : finset γ} [hi : is_idempotent β op] : (image g s).fold op b f = s.fold op b (f ∘ g) := begin induction s using finset.cons_induction with x xs hx ih, { rw [fold_empty, image_empty, fold_empty] }, { haveI := classical.dec_eq γ, rw [fold_cons, cons_eq_insert, image_insert, fold_insert_idem, ih], } end /-- A stronger version of `finset.fold_ite`, but relies on an explicit proof of idempotency on the seed element, rather than relying on typeclass idempotency over the whole type. -/ lemma fold_ite' {g : α → β} (hb : op b b = b) (p : α → Prop) [decidable_pred p] : finset.fold op b (λ i, ite (p i) (f i) (g i)) s = op (finset.fold op b f (s.filter p)) (finset.fold op b g (s.filter (λ i, ¬ p i))) := begin classical, induction s using finset.induction_on with x s hx IH, { simp [hb] }, { simp only [finset.filter_congr_decidable, finset.fold_insert hx], split_ifs with h h, { have : x ∉ finset.filter p s, { simp [hx] }, simp [finset.filter_insert, h, finset.fold_insert this, ha.assoc, IH] }, { have : x ∉ finset.filter (λ i, ¬ p i) s, { simp [hx] }, simp [finset.filter_insert, h, finset.fold_insert this, IH, ←ha.assoc, hc.comm] } } end /-- A weaker version of `finset.fold_ite'`, relying on typeclass idempotency over the whole type, instead of solely on the seed element. However, this is easier to use because it does not generate side goals. -/ lemma fold_ite [is_idempotent β op] {g : α → β} (p : α → Prop) [decidable_pred p] : finset.fold op b (λ i, ite (p i) (f i) (g i)) s = op (finset.fold op b f (s.filter p)) (finset.fold op b g (s.filter (λ i, ¬ p i))) := fold_ite' (is_idempotent.idempotent _) _ lemma fold_op_rel_iff_and {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∧ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∧ ∀ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← and_assoc, and_comm (r c (f a)), and_assoc], apply and_congr iff.rfl, split, { rintro ⟨h₁, h₂⟩, intros b hb, rw finset.mem_insert at hb, rcases hb with rfl|hb; solve_by_elim }, { intro h, split, { exact h a (finset.mem_insert_self _ _), }, { intros b hb, apply h b, rw finset.mem_insert, right, exact hb } } end lemma fold_op_rel_iff_or {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∨ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∨ ∃ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← or_assoc, or_comm (r c (f a)), or_assoc], apply or_congr iff.rfl, split, { rintro (h₁|⟨x, hx, h₂⟩), { use a, simp [h₁] }, { refine ⟨x, by simp [hx], h₂⟩ } }, { rintro ⟨x, hx, h⟩, rw mem_insert at hx, cases hx, { left, rwa hx at h }, { right, exact ⟨x, hx, h⟩ } } end omit hc ha @[simp] lemma fold_union_empty_singleton [decidable_eq α] (s : finset α) : finset.fold (∪) ∅ singleton s = s := begin apply finset.induction_on s, { simp only [fold_empty], }, { intros a s has ih, rw [fold_insert has, ih, insert_eq], } end lemma fold_sup_bot_singleton [decidable_eq α] (s : finset α) : finset.fold (⊔) ⊥ singleton s = s := fold_union_empty_singleton s section order variables [linear_order β] (c : β) lemma le_fold_min : c ≤ s.fold min b f ↔ (c ≤ b ∧ ∀ x∈s, c ≤ f x) := fold_op_rel_iff_and $ λ x y z, le_min_iff lemma fold_min_le : s.fold min b f ≤ c ↔ (b ≤ c ∨ ∃ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ ≤ _ ↔ _, exact min_le_iff end lemma lt_fold_min : c < s.fold min b f ↔ (c < b ∧ ∀ x∈s, c < f x) := fold_op_rel_iff_and $ λ x y z, lt_min_iff lemma fold_min_lt : s.fold min b f < c ↔ (b < c ∨ ∃ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ < _ ↔ _, exact min_lt_iff end lemma fold_max_le : s.fold max b f ≤ c ↔ (b ≤ c ∧ ∀ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ ≤ _ ↔ _, exact max_le_iff end lemma le_fold_max : c ≤ s.fold max b f ↔ (c ≤ b ∨ ∃ x∈s, c ≤ f x) := fold_op_rel_iff_or $ λ x y z, le_max_iff lemma fold_max_lt : s.fold max b f < c ↔ (b < c ∧ ∀ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ < _ ↔ _, exact max_lt_iff end lemma lt_fold_max : c < s.fold max b f ↔ (c < b ∨ ∃ x∈s, c < f x) := fold_op_rel_iff_or $ λ x y z, lt_max_iff lemma fold_max_add [has_add β] [covariant_class β β (function.swap (+)) (≤)] (n : with_bot β) (s : finset α) : s.fold max ⊥ (λ (x : α), ↑(f x) + n) = s.fold max ⊥ (coe ∘ f) + n := by { classical, apply s.induction_on; simp [max_add_add_right] {contextual := tt} } end order end fold end finset
0895b96f9378eaec0c01e78e72e3327668c816db
4c630d016e43ace8c5f476a5070a471130c8a411
/category/functor.lean
09b84fecc0a7f8811e51d3b3f34856fbfe6488fe
[ "Apache-2.0" ]
permissive
ngamt/mathlib
9a510c391694dc43eec969914e2a0e20b272d172
58909bd424209739a2214961eefaa012fb8a18d2
refs/heads/master
1,585,942,993,674
1,540,739,585,000
1,540,916,815,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,367
lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Standard identity and composition functors -/ import tactic.ext tactic.cache category.basic universe variables u v w section functor variables {F : Type u → Type v} variables {α β γ : Type u} variables [functor F] [is_lawful_functor F] lemma functor.map_id : (<$>) id = (id : F α → F α) := by apply funext; apply id_map lemma functor.map_comp_map (f : α → β) (g : β → γ) : ((<$>) g ∘ (<$>) f : F α → F γ) = (<$>) (g ∘ f) := by apply funext; intro; rw comp_map theorem functor.ext {F} : ∀ {F1 : functor F} {F2 : functor F} [@is_lawful_functor F F1] [@is_lawful_functor F F2] (H : ∀ α β (f : α → β) (x : F α), @functor.map _ F1 _ _ f x = @functor.map _ F2 _ _ f x), F1 = F2 | ⟨m, mc⟩ ⟨m', mc'⟩ H1 H2 H := begin cases show @m = @m', by funext α β f x; apply H, congr, funext α β, have E1 := @map_const_eq _ ⟨@m, @mc⟩ H1, have E2 := @map_const_eq _ ⟨@m, @mc'⟩ H2, exact E1.trans E2.symm end end functor def id.mk {α : Sort u} : α → id α := id namespace functor /-- `functor.comp` is a wrapper around `function.comp` for types. It prevents Lean's type class resolution mechanism from trying a `functor (comp F id)` when `functor F` would do. -/ def comp (F : Type u → Type w) (G : Type v → Type u) (α : Type v) : Type w := F $ G α @[pattern] def comp.mk {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : F (G α)) : comp F G α := x def comp.run {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : comp F G α) : F (G α) := x namespace comp variables {F : Type u → Type w} {G : Type v → Type u} protected lemma ext {α} {x y : comp F G α} : x.run = y.run → x = y := id variables [functor F] [functor G] protected def map {α β : Type v} (h : α → β) : comp F G α → comp F G β | (comp.mk x) := comp.mk ((<$>) h <$> x) instance : functor (comp F G) := { map := @comp.map F G _ _ } @[functor_norm] lemma map_mk {α β} (h : α → β) (x : F (G α)) : h <$> comp.mk x = comp.mk ((<$>) h <$> x) := rfl variables [is_lawful_functor F] [is_lawful_functor G] variables {α β γ : Type v} protected lemma id_map : ∀ (x : comp F G α), comp.map id x = x | (comp.mk x) := by simp [comp.map, functor.map_id] protected lemma comp_map (g' : α → β) (h : β → γ) : ∀ (x : comp F G α), comp.map (h ∘ g') x = comp.map h (comp.map g' x) | (comp.mk x) := by simp [comp.map, functor.map_comp_map g' h] with functor_norm @[simp] protected lemma run_map (h : α → β) (x : comp F G α) : (h <$> x).run = (<$>) h <$> x.run := rfl instance : is_lawful_functor (comp F G) := { id_map := @comp.id_map F G _ _ _ _, comp_map := @comp.comp_map F G _ _ _ _ } theorem functor_comp_id {F} [AF : functor F] [is_lawful_functor F] : @comp.functor F id _ _ = AF := @functor.ext F _ AF (@comp.is_lawful_functor F id _ _ _ _) _ (λ α β f x, rfl) theorem functor_id_comp {F} [AF : functor F] [is_lawful_functor F] : @comp.functor id F _ _ = AF := @functor.ext F _ AF (@comp.is_lawful_functor id F _ _ _ _) _ (λ α β f x, rfl) end comp end functor namespace ulift instance : functor ulift := { map := λ α β f, up ∘ f ∘ down } end ulift
e3b1a0b0b518931bcbcfb7aa4812927d5038e762
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/field/basic.lean
51f74dd247549f391f6703c0a8da286d65a3e22a
[ "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
14,906
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import algebra.ring.basic /-! # Fields and division rings This file introduces fields and division rings (also known as skewfields) and proves some basic statements about them. For a more extensive theory of fields, see the `field_theory` folder. ## Main definitions * `division_ring`: introduces the notion of a division ring as a `ring` such that `0 ≠ 1` and `a * a⁻¹ = 1` for `a ≠ 0` * `field`: a division ring which is also a commutative ring. * `is_field`: a predicate on a ring that it is a field, i.e. that the multiplication is commutative, that it has more than one element and that all non-zero elements have a multiplicative inverse. In contrast to `field`, which contains the data of a function associating to an element of the field its multiplicative inverse, this predicate only assumes the existence and can therefore more easily be used to e.g. transfer along ring isomorphisms. ## Implementation details By convention `0⁻¹ = 0` in a field or division ring. This is due to the fact that working with total functions has the advantage of not constantly having to check that `x ≠ 0` when writing `x⁻¹`. With this convention in place, some statements like `(a + b) * c⁻¹ = a * c⁻¹ + b * c⁻¹` still remain true, while others like the defining property `a * a⁻¹ = 1` need the assumption `a ≠ 0`. If you are a beginner in using Lean and are confused by that, you can read more about why this convention is taken in Kevin Buzzard's [blogpost](https://xenaproject.wordpress.com/2020/07/05/division-by-zero-in-type-theory-a-faq/) A division ring or field is an example of a `group_with_zero`. If you cannot find a division ring / field lemma that does not involve `+`, you can try looking for a `group_with_zero` lemma instead. ## Tags field, division ring, skew field, skew-field, skewfield -/ open set set_option old_structure_cmd true universe u variables {K : Type u} /-- A `division_ring` is a `ring` with multiplicative inverses for nonzero elements -/ @[protect_proj, ancestor ring div_inv_monoid nontrivial] class division_ring (K : Type u) extends ring K, div_inv_monoid K, nontrivial K := (mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : K)⁻¹ = 0) section division_ring variables [division_ring K] {a b : K} /-- Every division ring is a `group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance division_ring.to_group_with_zero : group_with_zero K := { .. ‹division_ring K›, .. (infer_instance : semiring K) } local attribute [simp] division_def mul_comm mul_assoc mul_left_comm mul_inv_cancel inv_mul_cancel lemma one_div_neg_one_eq_neg_one : (1:K) / (-1) = -1 := have (-1) * (-1) = (1:K), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one_right this) lemma one_div_neg_eq_neg_one_div (a : K) : 1 / (- a) = - (1 / a) := calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw one_div_mul_one_div_rev ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg, mul_one] lemma div_neg_eq_neg_div (a b : K) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b / a) : by rw mul_one_div lemma neg_div (a b : K) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul] @[field_simps] lemma neg_div' (a b : K) : - (b / a) = (-b) / a := by simp [neg_div] lemma neg_div_neg_eq (a b : K) : (-a) / (-b) = a / b := by rw [div_neg_eq_neg_div, neg_div, neg_neg] @[simp] lemma div_neg_self {a : K} (h : a ≠ 0) : a / -a = -1 := by rw [div_neg_eq_neg_div, div_self h] @[simp] lemma neg_div_self {a : K} (h : a ≠ 0) : (-a) / a = -1 := by rw [neg_div, div_self h] @[field_simps] lemma div_add_div_same (a b c : K) : a / c + b / c = (a + b) / c := by simpa only [div_eq_mul_inv] using (right_distrib a b (c⁻¹)).symm lemma same_add_div {a b : K} (h : b ≠ 0) : (b + a) / b = 1 + a / b := by simpa only [← @div_self _ _ b h] using (div_add_div_same b a b).symm lemma one_add_div {a b : K} (h : b ≠ 0 ) : 1 + a / b = (b + a) / b := (same_add_div h).symm lemma div_add_same {a b : K} (h : b ≠ 0) : (a + b) / b = a / b + 1 := by simpa only [← @div_self _ _ b h] using (div_add_div_same a b b).symm lemma div_add_one {a b : K} (h : b ≠ 0) : a / b + 1 = (a + b) / b := (div_add_same h).symm lemma div_sub_div_same (a b c : K) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg] lemma same_sub_div {a b : K} (h : b ≠ 0) : (b - a) / b = 1 - a / b := by simpa only [← @div_self _ _ b h] using (div_sub_div_same b a b).symm lemma one_sub_div {a b : K} (h : b ≠ 0) : 1 - a / b = (b - a) / b := (same_sub_div h).symm lemma div_sub_same {a b : K} (h : b ≠ 0) : (a - b) / b = a / b - 1 := by simpa only [← @div_self _ _ b h] using (div_sub_div_same a b b).symm lemma div_sub_one {a b : K} (h : b ≠ 0) : a / b - 1 = (a - b) / b := (div_sub_same h).symm lemma neg_inv : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma add_div (a b c : K) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma sub_div (a b c : K) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma div_neg (a : K) : a / -b = -(a / b) := by rw [← div_neg_eq_neg_div] lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := by rw neg_inv lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] lemma add_div_eq_mul_add_div (a b : K) {c : K} (hc : c ≠ 0) : a + b / c = (a * c + b) / c := (eq_div_iff_mul_eq hc).2 $ by rw [right_distrib, (div_mul_cancel _ hc)] @[priority 100] -- see Note [lower instance priority] instance division_ring.is_domain : is_domain K := { ..‹division_ring K›, ..(by apply_instance : no_zero_divisors K) } end division_ring /-- A `field` is a `comm_ring` with multiplicative inverses for nonzero elements -/ @[protect_proj, ancestor comm_ring div_inv_monoid nontrivial] class field (K : Type u) extends comm_ring K, div_inv_monoid K, nontrivial K := (mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : K)⁻¹ = 0) section field variable [field K] @[priority 100] -- see Note [lower instance priority] instance field.to_division_ring : division_ring K := { ..show field K, by apply_instance } /-- Every field is a `comm_group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance field.to_comm_group_with_zero : comm_group_with_zero K := { .. (_ : group_with_zero K), .. ‹field K› } local attribute [simp] mul_assoc mul_comm mul_left_comm lemma div_add_div (a : K) {b : K} (c : K) {d : K} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [← mul_div_mul_right _ b hd, ← mul_div_mul_left c d hb, div_add_div_same] lemma one_div_add_one_div {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := by rw [div_add_div _ _ ha hb, one_mul, mul_one, add_comm] @[field_simps] lemma div_sub_div (a : K) {b : K} (c : K) {d : K} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp only [sub_eq_add_neg], rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd, ← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul] end lemma inv_add_inv {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] @[field_simps] lemma add_div' (a b c : K) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma sub_div' (a b c : K) (hc : c ≠ 0) : b - a / c = (b * c - a) / c := by simpa using div_sub_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : K) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] @[field_simps] lemma div_sub' (a b c : K) (hc : c ≠ 0) : a / c - b = (a - c * b) / c := by simpa using div_sub_div a b hc one_ne_zero @[priority 100] -- see Note [lower instance priority] instance field.is_domain : is_domain K := { ..division_ring.is_domain } end field section is_field /-- A predicate to express that a ring is a field. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. Additionaly, this is useful when trying to prove that a particular ring structure extends to a field. -/ structure is_field (R : Type u) [ring R] : Prop := (exists_pair_ne : ∃ (x y : R), x ≠ y) (mul_comm : ∀ (x y : R), x * y = y * x) (mul_inv_cancel : ∀ {a : R}, a ≠ 0 → ∃ b, a * b = 1) /-- Transferring from field to is_field -/ lemma field.to_is_field (R : Type u) [field R] : is_field R := { mul_inv_cancel := λ a ha, ⟨a⁻¹, field.mul_inv_cancel ha⟩, ..‹field R› } @[simp] lemma is_field.nontrivial {R : Type u} [ring R] (h : is_field R) : nontrivial R := ⟨h.exists_pair_ne⟩ @[simp] lemma not_is_field_of_subsingleton (R : Type u) [ring R] [subsingleton R] : ¬is_field R := λ h, let ⟨x, y, h⟩ := h.exists_pair_ne in h (subsingleton.elim _ _) open_locale classical /-- Transferring from is_field to field -/ noncomputable def is_field.to_field {R : Type u} [ring R] (h : is_field R) : field R := { inv := λ a, if ha : a = 0 then 0 else classical.some (is_field.mul_inv_cancel h ha), inv_zero := dif_pos rfl, mul_inv_cancel := λ a ha, begin convert classical.some_spec (is_field.mul_inv_cancel h ha), exact dif_neg ha end, .. ‹ring R›, ..h } /-- For each field, and for each nonzero element of said field, there is a unique inverse. Since `is_field` doesn't remember the data of an `inv` function and as such, a lemma that there is a unique inverse could be useful. -/ lemma uniq_inv_of_is_field (R : Type u) [ring R] (hf : is_field R) : ∀ (x : R), x ≠ 0 → ∃! (y : R), x * y = 1 := begin intros x hx, apply exists_unique_of_exists_of_unique, { exact hf.mul_inv_cancel hx }, { intros y z hxy hxz, calc y = y * (x * z) : by rw [hxz, mul_one] ... = (x * y) * z : by rw [← mul_assoc, hf.mul_comm y x] ... = z : by rw [hxy, one_mul] } end end is_field namespace ring_hom section variables {R : Type*} [semiring R] [division_ring K] (f : R →+* K) @[simp] lemma map_units_inv (u : Rˣ) : f ↑u⁻¹ = (f ↑u)⁻¹ := (f : R →* K).map_units_inv u end section variables {R K' : Type*} [division_ring K] [semiring R] [nontrivial R] [division_ring K'] (f : K →+* R) (g : K →+* K') {x y : K} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := f.to_monoid_with_zero_hom.map_ne_zero @[simp] lemma map_eq_zero : f x = 0 ↔ x = 0 := f.to_monoid_with_zero_hom.map_eq_zero variables (x y) lemma map_inv : g x⁻¹ = (g x)⁻¹ := g.to_monoid_with_zero_hom.map_inv x lemma map_div : g (x / y) = g x / g y := g.to_monoid_with_zero_hom.map_div x y protected lemma injective : function.injective f := (injective_iff_map_eq_zero f).2 $ λ x, f.map_eq_zero.1 end end ring_hom section noncomputable_defs variables {R : Type*} [nontrivial R] /-- Constructs a `division_ring` structure on a `ring` consisting only of units and 0. -/ noncomputable def division_ring_of_is_unit_or_eq_zero [hR : ring R] (h : ∀ (a : R), is_unit a ∨ a = 0) : division_ring R := { .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR } /-- Constructs a `field` structure on a `comm_ring` consisting only of units and 0. See note [reducible non-instances]. -/ @[reducible] noncomputable def field_of_is_unit_or_eq_zero [hR : comm_ring R] (h : ∀ (a : R), is_unit a ∨ a = 0) : field R := { .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR } end noncomputable_defs /-- Pullback a `division_ring` along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.division_ring [division_ring K] {K'} [has_zero K'] [has_mul K'] [has_add K'] [has_neg K'] [has_sub K'] [has_one K'] [has_inv K'] [has_div K'] [has_scalar ℕ K'] [has_scalar ℤ K'] [has_pow K' ℕ] [has_pow K' ℤ] (f : K' → K) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) : division_ring K' := { .. hf.group_with_zero f zero one mul inv div npow zpow, .. hf.ring f zero one add mul neg sub nsmul zsmul npow } /-- Pullback a `field` along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.field [field K] {K'} [has_zero K'] [has_mul K'] [has_add K'] [has_neg K'] [has_sub K'] [has_one K'] [has_inv K'] [has_div K'] [has_scalar ℕ K'] [has_scalar ℤ K'] [has_pow K' ℕ] [has_pow K' ℤ] (f : K' → K) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) : field K' := { .. hf.comm_group_with_zero f zero one mul inv div npow zpow, .. hf.comm_ring f zero one add mul neg sub nsmul zsmul npow }
a002b3499156c346be68c7507da5e0fc427f22d4
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/CancellativeMagma.lean
82ec736f0f02690bd7ad3ce5737b0596323d52c3
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
6,427
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section CancellativeMagma structure CancellativeMagma (A : Type) : Type := (op : (A → (A → A))) (leftCancellative : (∀ {x y z : A} , ((op z x) = (op z y) → x = y))) (rightCancellative : (∀ {x y z : A} , ((op x z) = (op y z) → x = y))) open CancellativeMagma structure Sig (AS : Type) : Type := (opS : (AS → (AS → AS))) structure Product (A : Type) : Type := (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (leftCancellativeP : (∀ {xP yP zP : (Prod A A)} , ((opP zP xP) = (opP zP yP) → xP = yP))) (rightCancellativeP : (∀ {xP yP zP : (Prod A A)} , ((opP xP zP) = (opP yP zP) → xP = yP))) structure Hom {A1 : Type} {A2 : Type} (Ca1 : (CancellativeMagma A1)) (Ca2 : (CancellativeMagma A2)) : Type := (hom : (A1 → A2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Ca1) x1 x2)) = ((op Ca2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Ca1 : (CancellativeMagma A1)) (Ca2 : (CancellativeMagma A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Ca1) x1 x2) ((op Ca2) y1 y2)))))) inductive CancellativeMagmaTerm : Type | opL : (CancellativeMagmaTerm → (CancellativeMagmaTerm → CancellativeMagmaTerm)) open CancellativeMagmaTerm inductive ClCancellativeMagmaTerm (A : Type) : Type | sing : (A → ClCancellativeMagmaTerm) | opCl : (ClCancellativeMagmaTerm → (ClCancellativeMagmaTerm → ClCancellativeMagmaTerm)) open ClCancellativeMagmaTerm inductive OpCancellativeMagmaTerm (n : ℕ) : Type | v : ((fin n) → OpCancellativeMagmaTerm) | opOL : (OpCancellativeMagmaTerm → (OpCancellativeMagmaTerm → OpCancellativeMagmaTerm)) open OpCancellativeMagmaTerm inductive OpCancellativeMagmaTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpCancellativeMagmaTerm2) | sing2 : (A → OpCancellativeMagmaTerm2) | opOL2 : (OpCancellativeMagmaTerm2 → (OpCancellativeMagmaTerm2 → OpCancellativeMagmaTerm2)) open OpCancellativeMagmaTerm2 def simplifyCl {A : Type} : ((ClCancellativeMagmaTerm A) → (ClCancellativeMagmaTerm A)) | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpCancellativeMagmaTerm n) → (OpCancellativeMagmaTerm n)) | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpCancellativeMagmaTerm2 n A) → (OpCancellativeMagmaTerm2 n A)) | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((CancellativeMagma A) → (CancellativeMagmaTerm → A)) | Ca (opL x1 x2) := ((op Ca) (evalB Ca x1) (evalB Ca x2)) def evalCl {A : Type} : ((CancellativeMagma A) → ((ClCancellativeMagmaTerm A) → A)) | Ca (sing x1) := x1 | Ca (opCl x1 x2) := ((op Ca) (evalCl Ca x1) (evalCl Ca x2)) def evalOpB {A : Type} {n : ℕ} : ((CancellativeMagma A) → ((vector A n) → ((OpCancellativeMagmaTerm n) → A))) | Ca vars (v x1) := (nth vars x1) | Ca vars (opOL x1 x2) := ((op Ca) (evalOpB Ca vars x1) (evalOpB Ca vars x2)) def evalOp {A : Type} {n : ℕ} : ((CancellativeMagma A) → ((vector A n) → ((OpCancellativeMagmaTerm2 n A) → A))) | Ca vars (v2 x1) := (nth vars x1) | Ca vars (sing2 x1) := x1 | Ca vars (opOL2 x1 x2) := ((op Ca) (evalOp Ca vars x1) (evalOp Ca vars x2)) def inductionB {P : (CancellativeMagmaTerm → Type)} : ((∀ (x1 x2 : CancellativeMagmaTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : CancellativeMagmaTerm) , (P x))) | popl (opL x1 x2) := (popl _ _ (inductionB popl x1) (inductionB popl x2)) def inductionCl {A : Type} {P : ((ClCancellativeMagmaTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClCancellativeMagmaTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClCancellativeMagmaTerm A)) , (P x)))) | psing popcl (sing x1) := (psing x1) | psing popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl x1) (inductionCl psing popcl x2)) def inductionOpB {n : ℕ} {P : ((OpCancellativeMagmaTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpCancellativeMagmaTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpCancellativeMagmaTerm n)) , (P x)))) | pv popol (v x1) := (pv x1) | pv popol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol x1) (inductionOpB pv popol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpCancellativeMagmaTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpCancellativeMagmaTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpCancellativeMagmaTerm2 n A)) , (P x))))) | pv2 psing2 popol2 (v2 x1) := (pv2 x1) | pv2 psing2 popol2 (sing2 x1) := (psing2 x1) | pv2 psing2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 x1) (inductionOp pv2 psing2 popol2 x2)) def stageB : (CancellativeMagmaTerm → (Staged CancellativeMagmaTerm)) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClCancellativeMagmaTerm A) → (Staged (ClCancellativeMagmaTerm A))) | (sing x1) := (Now (sing x1)) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpCancellativeMagmaTerm n) → (Staged (OpCancellativeMagmaTerm n))) | (v x1) := (const (code (v x1))) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpCancellativeMagmaTerm2 n A) → (Staged (OpCancellativeMagmaTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (opT : ((Repr A) → ((Repr A) → (Repr A)))) end CancellativeMagma
be7d8d1f4bc45bc048ee40e893f6f26e1c373575
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/convPatternMatchIssue.lean
8da8c6251a509ccf176a0d6ae31992e66078299a
[ "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
188
lean
def test : (λ x => x) = (λ x : Nat => let_fun foo := λ y => id (id y) foo x) := by conv => pattern (id _) trace_state skip
ba7169a184e6aa67746b619616ce8120de89dfdc
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/theories/group_theory/action.lean
5985aada4c9c0b9bfd69517bbbcb5eb5f17785d6
[ "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
23,110
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ import algebra.group data .hom .perm .finsubg namespace group open finset algebra function local attribute perm.f [coercion] private lemma and_left_true {a b : Prop} (Pa : a) : a ∧ b ↔ b := by rewrite [iff_true_intro Pa, true_and] section def variables {G S : Type} [ambientG : group G] [finS : fintype S] [deceqS : decidable_eq S] include ambientG finS definition is_fixed_point (hom : G → perm S) (H : finset G) (a : S) : Prop := ∀ h, h ∈ H → hom h a = a include deceqS definition orbit (hom : G → perm S) (H : finset G) (a : S) : finset S := image (move_by a) (image hom H) definition fixed_points [reducible] (hom : G → perm S) (H : finset G) : finset S := {a ∈ univ | orbit hom H a = singleton a} variable [deceqG : decidable_eq G] include deceqG -- required by {x ∈ H |p x} filtering definition moverset (hom : G → perm S) (H : finset G) (a b : S) : finset G := {f ∈ H | hom f a = b} definition stab (hom : G → perm S) (H : finset G) (a : S) : finset G := {f ∈ H | hom f a = a} end def section orbit_stabilizer variables {G S : Type} variable [ambientG : group G] include ambientG variable [finS : fintype S] include finS variable [deceqS : decidable_eq S] include deceqS section variables {hom : G → perm S} {H : finset G} {a : S} [Hom : is_hom_class hom] include Hom lemma exists_of_orbit {b : S} : b ∈ orbit hom H a → ∃ h, h ∈ H ∧ hom h a = b := assume Pb, obtain p (Pp₁ : p ∈ image hom H) (Pp₂ : move_by a p = b), from exists_of_mem_image Pb, obtain h (Ph₁ : h ∈ H) (Ph₂ : hom h = p), from exists_of_mem_image Pp₁, assert Phab : hom h a = b, from calc hom h a = p a : Ph₂ ... = b : Pp₂, exists.intro h (and.intro Ph₁ Phab) lemma orbit_of_exists {b : S} : (∃ h, h ∈ H ∧ hom h a = b) → b ∈ orbit hom H a := assume Pex, obtain h PinH Phab, from Pex, mem_image (mem_image_of_mem hom PinH) Phab lemma is_fixed_point_of_mem_fixed_points : a ∈ fixed_points hom H → is_fixed_point hom H a := assume Pain, take h, assume Phin, eq_of_mem_singleton (of_mem_sep Pain ▸ orbit_of_exists (exists.intro h (and.intro Phin rfl))) lemma mem_fixed_points_of_exists_of_is_fixed_point : (∃ h, h ∈ H) → is_fixed_point hom H a → a ∈ fixed_points hom H := assume Pex Pfp, mem_sep_of_mem !mem_univ (ext take x, iff.intro (assume Porb, obtain h Phin Pha, from exists_of_orbit Porb, by rewrite [mem_singleton_eq, -Pha, Pfp h Phin]) (obtain h Phin, from Pex, by rewrite mem_singleton_eq; intro Peq; rewrite Peq; apply orbit_of_exists; existsi h; apply and.intro Phin (Pfp h Phin))) lemma is_fixed_point_iff_mem_fixed_points_of_exists : (∃ h, h ∈ H) → (a ∈ fixed_points hom H ↔ is_fixed_point hom H a) := assume Pex, iff.intro is_fixed_point_of_mem_fixed_points (mem_fixed_points_of_exists_of_is_fixed_point Pex) lemma is_fixed_point_iff_mem_fixed_points [finsubgH : is_finsubg H] : a ∈ fixed_points hom H ↔ is_fixed_point hom H a := is_fixed_point_iff_mem_fixed_points_of_exists (exists.intro 1 !finsubg_has_one) lemma is_fixed_point_of_one : is_fixed_point hom (singleton 1) a := take h, assume Ph, by rewrite [eq_of_mem_singleton Ph, hom_map_one] lemma fixed_points_of_one : fixed_points hom (singleton 1) = univ := ext take s, iff.intro (assume Pl, mem_univ s) (assume Pr, mem_fixed_points_of_exists_of_is_fixed_point (exists.intro 1 !mem_singleton) is_fixed_point_of_one) open fintype lemma card_fixed_points_of_one : card (fixed_points hom (singleton 1)) = card S := by rewrite [fixed_points_of_one] end variable [deceqG : decidable_eq G] include deceqG -- these are already specified by stab hom H a variables {hom : G → perm S} {H : finset G} {a : S} variable [Hom : is_hom_class hom] include Hom lemma perm_f_mul (f g : G): perm.f ((hom f) * (hom g)) a = ((hom f) ∘ (hom g)) a := rfl lemma stab_lmul {f g : G} : g ∈ stab hom H a → hom (f*g) a = hom f a := assume Pgstab, assert hom g a = a, from of_mem_sep Pgstab, calc hom (f*g) a = perm.f ((hom f) * (hom g)) a : is_hom hom ... = ((hom f) ∘ (hom g)) a : by rewrite perm_f_mul ... = (hom f) a : by unfold compose; rewrite this lemma stab_subset : stab hom H a ⊆ H := begin apply subset_of_forall, intro f Pfstab, apply mem_of_mem_sep Pfstab end lemma reverse_move {h g : G} : g ∈ moverset hom H a (hom h a) → hom (h⁻¹*g) a = a := assume Pg, assert hom g a = hom h a, from of_mem_sep Pg, calc hom (h⁻¹*g) a = perm.f ((hom h⁻¹) * (hom g)) a : by rewrite (is_hom hom) ... = ((hom h⁻¹) ∘ hom g) a : by rewrite perm_f_mul ... = perm.f ((hom h)⁻¹ * hom h) a : by unfold compose; rewrite [this, perm_f_mul, hom_map_inv hom h] ... = perm.f (1 : perm S) a : by rewrite (mul.left_inv (hom h)) ... = a : by esimp lemma moverset_inj_on_orbit : set.inj_on (moverset hom H a) (ts (orbit hom H a)) := take b1 b2, assume Pb1, obtain h1 Ph1₁ Ph1₂, from exists_of_orbit Pb1, assert Ph1b1 : h1 ∈ moverset hom H a b1, from mem_sep_of_mem Ph1₁ Ph1₂, assume Psetb2 Pmeq, begin subst b1, rewrite Pmeq at Ph1b1, apply of_mem_sep Ph1b1 end variable [subgH : is_finsubg H] include subgH lemma subg_stab_of_move {h g : G} : h ∈ H → g ∈ moverset hom H a (hom h a) → h⁻¹*g ∈ stab hom H a := assume Ph Pg, assert Phinvg : h⁻¹*g ∈ H, from begin apply finsubg_mul_closed H, apply finsubg_has_inv H, assumption, apply mem_of_mem_sep Pg end, mem_sep_of_mem Phinvg (reverse_move Pg) lemma subg_stab_closed : finset_mul_closed_on (stab hom H a) := take f g, assume Pfstab, assert Pf : hom f a = a, from of_mem_sep Pfstab, assume Pgstab, assert Pfg : hom (f*g) a = a, from calc hom (f*g) a = (hom f) a : stab_lmul Pgstab ... = a : Pf, assert PfginH : (f*g) ∈ H, from finsubg_mul_closed H (mem_of_mem_sep Pfstab) (mem_of_mem_sep Pgstab), mem_sep_of_mem PfginH Pfg lemma subg_stab_has_one : 1 ∈ stab hom H a := assert P : hom 1 a = a, from calc hom 1 a = perm.f (1 : perm S) a : {hom_map_one hom} ... = a : rfl, assert PoneinH : 1 ∈ H, from finsubg_has_one H, mem_sep_of_mem PoneinH P lemma subg_stab_has_inv : finset_has_inv (stab hom H a) := take f, assume Pfstab, assert Pf : hom f a = a, from of_mem_sep Pfstab, assert Pfinv : hom f⁻¹ a = a, from calc hom f⁻¹ a = hom f⁻¹ ((hom f) a) : by rewrite Pf ... = perm.f ((hom f⁻¹) * (hom f)) a : by rewrite perm_f_mul ... = hom (f⁻¹ * f) a : by rewrite (is_hom hom) ... = hom 1 a : by rewrite mul.left_inv ... = perm.f (1 : perm S) a : by rewrite (hom_map_one hom), assert PfinvinH : f⁻¹ ∈ H, from finsubg_has_inv H (mem_of_mem_sep Pfstab), mem_sep_of_mem PfinvinH Pfinv definition subg_stab_is_finsubg [instance] : is_finsubg (stab hom H a) := is_finsubg.mk subg_stab_has_one subg_stab_closed subg_stab_has_inv lemma subg_lcoset_eq_moverset {h : G} : h ∈ H → fin_lcoset (stab hom H a) h = moverset hom H a (hom h a) := assume Ph, ext (take g, iff.intro (assume Pl, obtain f (Pf₁ : f ∈ stab hom H a) (Pf₂ : h*f = g), from exists_of_mem_image Pl, assert Pfstab : hom f a = a, from of_mem_sep Pf₁, assert PginH : g ∈ H, begin subst Pf₂, apply finsubg_mul_closed H, assumption, apply mem_of_mem_sep Pf₁ end, assert Pga : hom g a = hom h a, from calc hom g a = hom (h*f) a : by subst g ... = hom h a : stab_lmul Pf₁, mem_sep_of_mem PginH Pga) (assume Pr, begin rewrite [↑fin_lcoset, mem_image_iff], existsi h⁻¹*g, split, exact subg_stab_of_move Ph Pr, apply mul_inv_cancel_left end)) lemma subg_moverset_of_orbit_is_lcoset_of_stab (b : S) : b ∈ orbit hom H a → ∃ h, h ∈ H ∧ fin_lcoset (stab hom H a) h = moverset hom H a b := assume Porb, obtain p (Pp₁ : p ∈ image hom H) (Pp₂ : move_by a p = b), from exists_of_mem_image Porb, obtain h (Ph₁ : h ∈ H) (Ph₂ : hom h = p), from exists_of_mem_image Pp₁, assert Phab : hom h a = b, from by subst p; assumption, exists.intro h (and.intro Ph₁ (Phab ▸ subg_lcoset_eq_moverset Ph₁)) lemma subg_lcoset_of_stab_is_moverset_of_orbit (h : G) : h ∈ H → ∃ b, b ∈ orbit hom H a ∧ moverset hom H a b = fin_lcoset (stab hom H a) h := assume Ph, have Pha : (hom h a) ∈ orbit hom H a, by apply mem_image_of_mem; apply mem_image_of_mem; exact Ph, exists.intro (hom h a) (and.intro Pha (eq.symm (subg_lcoset_eq_moverset Ph))) lemma subg_moversets_of_orbit_eq_stab_lcosets : image (moverset hom H a) (orbit hom H a) = fin_lcosets (stab hom H a) H := ext (take s, iff.intro (assume Pl, obtain b Pb₁ Pb₂, from exists_of_mem_image Pl, obtain h Ph, from subg_moverset_of_orbit_is_lcoset_of_stab b Pb₁, begin rewrite [↑fin_lcosets, mem_image_eq], existsi h, subst Pb₂, assumption end) (assume Pr, obtain h Ph₁ Ph₂, from exists_of_mem_image Pr, obtain b Pb, from @subg_lcoset_of_stab_is_moverset_of_orbit G S ambientG finS deceqS deceqG hom H a Hom subgH h Ph₁, begin rewrite [mem_image_eq], existsi b, subst Ph₂, assumption end)) open nat nat.finset theorem orbit_stabilizer_theorem : card H = card (orbit hom H a) * card (stab hom H a) := calc card H = card (fin_lcosets (stab hom H a) H) * card (stab hom H a) : lagrange_theorem stab_subset ... = card (image (moverset hom H a) (orbit hom H a)) * card (stab hom H a) : subg_moversets_of_orbit_eq_stab_lcosets ... = card (orbit hom H a) * card (stab hom H a) : card_image_eq_of_inj_on moverset_inj_on_orbit end orbit_stabilizer section orbit_partition variables {G S : Type} [ambientG : group G] [finS : fintype S] variables [deceqS : decidable_eq S] include ambientG finS deceqS variables {hom : G → perm S} [Hom : is_hom_class hom] {H : finset G} [subgH : is_finsubg H] include Hom subgH lemma in_orbit_refl {a : S} : a ∈ orbit hom H a := mem_image (mem_image (finsubg_has_one H) (hom_map_one hom)) rfl lemma in_orbit_trans {a b c : S} : a ∈ orbit hom H b → b ∈ orbit hom H c → a ∈ orbit hom H c := assume Painb Pbinc, obtain h PhinH Phba, from exists_of_orbit Painb, obtain g PginH Pgcb, from exists_of_orbit Pbinc, orbit_of_exists (exists.intro (h*g) (and.intro (finsubg_mul_closed H PhinH PginH) (calc hom (h*g) c = perm.f ((hom h) * (hom g)) c : is_hom hom ... = ((hom h) ∘ (hom g)) c : by rewrite perm_f_mul ... = (hom h) b : Pgcb ... = a : Phba))) lemma in_orbit_symm {a b : S} : a ∈ orbit hom H b → b ∈ orbit hom H a := assume Painb, obtain h PhinH Phba, from exists_of_orbit Painb, assert perm.f (hom h)⁻¹ a = b, by rewrite [-Phba, -perm_f_mul, mul.left_inv], assert (hom h⁻¹) a = b, by rewrite [hom_map_inv, this], orbit_of_exists (exists.intro h⁻¹ (and.intro (finsubg_has_inv H PhinH) this)) lemma orbit_is_partition : is_partition (orbit hom H) := take a b, propext (iff.intro (assume Painb, obtain h PhinH Phba, from exists_of_orbit Painb, ext take c, iff.intro (assume Pcina, in_orbit_trans Pcina Painb) (assume Pcinb, obtain g PginH Pgbc, from exists_of_orbit Pcinb, in_orbit_trans Pcinb (in_orbit_symm Painb))) (assume Peq, Peq ▸ in_orbit_refl)) variables (hom) (H) open nat nat.finset finset.partition fintype definition orbit_partition : @partition S _ := mk univ (orbit hom H) orbit_is_partition (restriction_imp_union (orbit hom H) orbit_is_partition (λ a Pa, !subset_univ)) definition orbits : finset (finset S) := equiv_classes (orbit_partition hom H) definition fixed_point_orbits : finset (finset S) := {cls ∈ orbits hom H | card cls = 1} variables {hom} {H} lemma exists_iff_mem_orbits (orb : finset S) : orb ∈ orbits hom H ↔ ∃ a : S, orbit hom H a = orb := begin esimp [orbits, equiv_classes, orbit_partition], rewrite [mem_image_iff], apply iff.intro, intro Pl, cases Pl with a Pa, rewrite (and_left_true !mem_univ) at Pa, existsi a, exact Pa, intro Pr, cases Pr with a Pa, rewrite -true_and at Pa, rewrite -(iff_true_intro (mem_univ a)) at Pa, existsi a, exact Pa end lemma exists_of_mem_orbits {orb : finset S} : orb ∈ orbits hom H → ∃ a : S, orbit hom H a = orb := iff.elim_left (exists_iff_mem_orbits orb) lemma fixed_point_orbits_eq : fixed_point_orbits hom H = image (orbit hom H) (fixed_points hom H) := ext take s, iff.intro (assume Pin, obtain Psin Ps, from iff.elim_left !mem_sep_iff Pin, obtain a Pa, from exists_of_mem_orbits Psin, mem_image (mem_sep_of_mem !mem_univ (eq.symm (eq_of_card_eq_of_subset (by rewrite [card_singleton, Pa, Ps]) (subset_of_forall take x, assume Pxin, eq_of_mem_singleton Pxin ▸ in_orbit_refl)))) Pa) (assume Pin, obtain a Pain Porba, from exists_of_mem_image Pin, mem_sep_of_mem (begin esimp [orbits, equiv_classes, orbit_partition], rewrite [mem_image_iff], existsi a, exact and.intro !mem_univ Porba end) (begin substvars, rewrite [of_mem_sep Pain] end)) lemma orbit_inj_on_fixed_points : set.inj_on (orbit hom H) (ts (fixed_points hom H)) := take a₁ a₂, begin rewrite [-*mem_eq_mem_to_set, ↑fixed_points, *mem_sep_iff], intro Pa₁ Pa₂, rewrite [and.right Pa₁, and.right Pa₂], exact eq_of_singleton_eq end lemma card_fixed_point_orbits_eq : card (fixed_point_orbits hom H) = card (fixed_points hom H) := by rewrite fixed_point_orbits_eq; apply card_image_eq_of_inj_on orbit_inj_on_fixed_points lemma orbit_class_equation : card S = Sum (orbits hom H) card := class_equation (orbit_partition hom H) lemma card_fixed_point_orbits : Sum (fixed_point_orbits hom H) card = card (fixed_point_orbits hom H) := calc Sum _ _ = Sum (fixed_point_orbits hom H) (λ x, 1) : Sum_ext (take c Pin, of_mem_sep Pin) ... = card (fixed_point_orbits hom H) * 1 : Sum_const_eq_card_mul ... = card (fixed_point_orbits hom H) : mul_one (card (fixed_point_orbits hom H)) local attribute nat.comm_semiring [instance] lemma orbit_class_equation' : card S = card (fixed_points hom H) + Sum {cls ∈ orbits hom H | card cls ≠ 1} card := calc card S = Sum (orbits hom H) finset.card : orbit_class_equation ... = Sum (fixed_point_orbits hom H) finset.card + Sum {cls ∈ orbits hom H | card cls ≠ 1} card : Sum_binary_union ... = card (fixed_point_orbits hom H) + Sum {cls ∈ orbits hom H | card cls ≠ 1} card : by rewrite -card_fixed_point_orbits ... = card (fixed_points hom H) + Sum {cls ∈ orbits hom H | card cls ≠ 1} card : by rewrite card_fixed_point_orbits_eq end orbit_partition section cayley variables {G : Type} variable [ambientG : group G] include ambientG variable [finG : fintype G] include finG definition action_by_lmul : G → perm G := take g, perm.mk (lmul_by g) (lmul_inj g) variable [deceqG : decidable_eq G] include deceqG lemma action_by_lmul_hom : homomorphic (@action_by_lmul G _ _) := take g₁ (g₂ : G), eq.symm (calc action_by_lmul g₁ * action_by_lmul g₂ = perm.mk ((lmul_by g₁)∘(lmul_by g₂)) _ : rfl ... = perm.mk (lmul_by (g₁*g₂)) _ : by congruence; apply coset.lmul_compose) lemma action_by_lmul_inj : injective (@action_by_lmul G _ _) := take g₁ g₂, assume Peq, perm.no_confusion Peq (λ Pfeq Pqeq, have Pappeq : g₁*1 = g₂*1, from congr_fun Pfeq _, calc g₁ = g₁ * 1 : mul_one ... = g₂ * 1 : Pappeq ... = g₂ : mul_one) definition action_by_lmul_is_iso [instance] : is_iso_class (@action_by_lmul G _ _) := is_iso_class.mk action_by_lmul_hom action_by_lmul_inj end cayley section lcosets open fintype subtype variables {G : Type} [ambientG : group G] [finG : fintype G] [deceqG : decidable_eq G] include ambientG deceqG finG variables H : finset G definition action_on_lcoset : G → perm (lcoset_type univ H) := take g, perm.mk (lcoset_lmul (mem_univ g)) lcoset_lmul_inj private definition lcoset_of (g : G) : lcoset_type univ H := tag (fin_lcoset H g) (exists.intro g (and.intro !mem_univ rfl)) variable {H} lemma action_on_lcoset_eq (g : G) (J : lcoset_type univ H) : elt_of (action_on_lcoset H g J) = fin_lcoset (elt_of J) g := rfl lemma action_on_lcoset_hom : homomorphic (action_on_lcoset H) := take g₁ g₂, eq_of_feq (funext take S, subtype.eq (by rewrite [↑action_on_lcoset, ↑lcoset_lmul, -fin_lcoset_compose])) definition action_on_lcoset_is_hom [instance] : is_hom_class (action_on_lcoset H) := is_hom_class.mk action_on_lcoset_hom variable [finsubgH : is_finsubg H] include finsubgH lemma aol_fixed_point_subset_normalizer (J : lcoset_type univ H) : is_fixed_point (action_on_lcoset H) H J → elt_of J ⊆ normalizer H := obtain j Pjin Pj, from exists_of_lcoset_type J, assume Pfp, assert PH : ∀ {h}, h ∈ H → fin_lcoset (fin_lcoset H j) h = fin_lcoset H j, from take h, assume Ph, by rewrite [Pj, -action_on_lcoset_eq, Pfp h Ph], subset_of_forall take g, begin rewrite [-Pj, fin_lcoset_same, -inv_inv at {2}], intro Pg, rewrite -Pg at PH, apply finsubg_has_inv, apply mem_sep_of_mem !mem_univ, intro h Ph, assert Phg : fin_lcoset (fin_lcoset H g) h = fin_lcoset H g, exact PH Ph, revert Phg, rewrite [↑conj_by, inv_inv, mul.assoc, fin_lcoset_compose, -fin_lcoset_same, ↑fin_lcoset, mem_image_iff, ↑lmul_by], intro Pex, cases Pex with k Pand, cases Pand with Pkin Pk, rewrite [-Pk, inv_mul_cancel_left], exact Pkin end lemma aol_fixed_point_of_mem_normalizer {g : G} : g ∈ normalizer H → is_fixed_point (action_on_lcoset H) H (lcoset_of H g) := assume Pgin, take h, assume Phin, subtype.eq (by rewrite [action_on_lcoset_eq, ↑lcoset_of, lrcoset_same_of_mem_normalizer Pgin, fin_lrcoset_comm, finsubg_lcoset_id Phin]) lemma aol_fixed_points_eq_normalizer : Union (fixed_points (action_on_lcoset H) H) elt_of = normalizer H := ext take g, begin rewrite [mem_Union_iff], apply iff.intro, intro Pl, cases Pl with L PL, revert PL, rewrite [is_fixed_point_iff_mem_fixed_points], intro Pg, apply mem_of_subset_of_mem, apply aol_fixed_point_subset_normalizer L, exact and.left Pg, exact and.right Pg, intro Pr, existsi (lcoset_of H g), apply and.intro, rewrite [is_fixed_point_iff_mem_fixed_points], exact aol_fixed_point_of_mem_normalizer Pr, exact fin_mem_lcoset g end open nat lemma card_aol_fixed_points_eq_card_cosets : card (fixed_points (action_on_lcoset H) H) = card (lcoset_type (normalizer H) H) := have Peq : card (fixed_points (action_on_lcoset H) H) * card H = card (lcoset_type (normalizer H) H) * card H, from calc card _ * card H = card (Union (fixed_points (action_on_lcoset H) H) elt_of) : card_Union_lcosets ... = card (normalizer H) : aol_fixed_points_eq_normalizer ... = card (lcoset_type (normalizer H) H) * card H : lagrange_theorem' subset_normalizer, eq_of_mul_eq_mul_right (card_pos_of_mem !finsubg_has_one) Peq end lcosets section perm_fin open fin nat eq.ops variable {n : nat} definition lift_perm (p : perm (fin n)) : perm (fin (succ n)) := perm.mk (lift_fun p) (lift_fun_of_inj (perm.inj p)) definition lower_perm (p : perm (fin (succ n))) (P : p maxi = maxi) : perm (fin n) := perm.mk (lower_inj p (perm.inj p) P) (take i j, begin rewrite [-eq_iff_veq, *lower_inj_apply, eq_iff_veq], apply injective_compose (perm.inj p) lift_succ_inj end) lemma lift_lower_eq : ∀ {p : perm (fin (succ n))} (P : p maxi = maxi), lift_perm (lower_perm p P) = p | (perm.mk pf Pinj) := assume Pmax, begin rewrite [↑lift_perm], congruence, apply funext, intro i, assert Pfmax : pf maxi = maxi, apply Pmax, assert Pd : decidable (i = maxi), exact _, cases Pd with Pe Pne, rewrite [Pe, Pfmax], apply lift_fun_max, rewrite [lift_fun_of_ne_max Pne, ↑lower_perm, ↑lift_succ], rewrite [-eq_iff_veq, -val_lift, lower_inj_apply, eq_iff_veq], congruence, rewrite [-eq_iff_veq] end lemma lift_perm_inj : injective (@lift_perm n) := take p1 p2, assume Peq, eq_of_feq (lift_fun_inj (feq_of_eq Peq)) lemma lift_perm_inj_on_univ : set.inj_on (@lift_perm n) (ts univ) := eq.symm to_set_univ ▸ iff.elim_left set.injective_iff_inj_on_univ lift_perm_inj lemma lift_to_stab : image (@lift_perm n) univ = stab id univ maxi := ext (take (pp : perm (fin (succ n))), iff.intro (assume Pimg, obtain p P_ Pp, from exists_of_mem_image Pimg, assert Ppp : pp maxi = maxi, from calc pp maxi = lift_perm p maxi : {eq.symm Pp} ... = lift_fun p maxi : rfl ... = maxi : lift_fun_max, mem_sep_of_mem !mem_univ Ppp) (assume Pstab, assert Ppp : pp maxi = maxi, from of_mem_sep Pstab, mem_image !mem_univ (lift_lower_eq Ppp))) definition move_from_max_to (i : fin (succ n)) : perm (fin (succ n)) := perm.mk (madd (i - maxi)) madd_inj lemma orbit_max : orbit (@id (perm (fin (succ n)))) univ maxi = univ := ext (take i, iff.intro (assume P, !mem_univ) (assume P, begin apply mem_image, apply mem_image, apply mem_univ (move_from_max_to i), apply rfl, apply sub_add_cancel end)) lemma card_orbit_max : card (orbit (@id (perm (fin (succ n)))) univ maxi) = succ n := calc card (orbit (@id (perm (fin (succ n)))) univ maxi) = card univ : by rewrite orbit_max ... = succ n : card_fin (succ n) open fintype lemma card_lift_to_stab : card (stab (@id (perm (fin (succ n)))) univ maxi) = card (perm (fin n)) := calc finset.card (stab (@id (perm (fin (succ n)))) univ maxi) = finset.card (image (@lift_perm n) univ) : by rewrite lift_to_stab ... = card univ : by rewrite (card_image_eq_of_inj_on lift_perm_inj_on_univ) lemma card_perm_step : card (perm (fin (succ n))) = (succ n) * card (perm (fin n)) := calc card (perm (fin (succ n))) = card (orbit id univ maxi) * card (stab id univ maxi) : orbit_stabilizer_theorem ... = (succ n) * card (stab id univ maxi) : {card_orbit_max} ... = (succ n) * card (perm (fin n)) : by rewrite -card_lift_to_stab end perm_fin end group
09cfac0500ec83491e84199bf7417fb1c4a40537
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.22.lean
6f82a305a6291ce4326642f21461934ed4655926
[]
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
392
lean
import standard example (p q : Prop) (H : p ∧ q) : p ∧ q ∧ p := assert Hp : p, from and.left H, assert Hq : q, from and.right H, begin apply (and.intro Hp), apply (and.intro Hq), exact Hp end example (p q : Prop) (H : p ∧ q) : p ∧ q ∧ p := assert Hp : p, from and.left H, assert Hq : q, from and.right H, begin apply and.intro, assumption, apply and.intro, repeat assumption end
8da91bbcd162b1f0edb5097dd38cbff20d4ed210
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/1766.lean
6a0bca53286ed6333d26e063d09583f57fd8af9f
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
738
lean
inductive is_some (x : option nat) : Prop | mk : ∀ value : nat, x = some value → is_some def value_1 (x : option nat) (H : is_some x) : nat := begin destruct x; intros, {destruct H, -- ERROR: `is_some` can only eliminate into Prop intros, clear a_2, rw a at a_1, contradiction}, {assumption} end def value_2 (x : option nat) (H : is_some x) : x = x := begin destruct x; intros, {destruct H, intros, rw a at a_1}, {refl} end inductive is_some' (x : option nat) : Type | mk : ∀ value : nat, x = some value → is_some' def value_3 (x : option nat) (H : is_some' x) : nat := begin destruct x; intros, {destruct H, intros, clear a_2, rw a at a_1, contradiction}, {assumption} end
af66c45dbaab5674b441a0450215414adb51fd94
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/interactive/eq2.lean
5000440e983c7d6c45718e5bf0e44c9bfcca7e98
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,033
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -- logic.connectives.eq -- ==================== -- Equality. prelude definition Prop := Type.{0} -- eq -- -- inductive eq {A : Type} (a : A) : A → Prop := refl : eq a a infix `=`:50 := eq definition rfl {A : Type} {a : A} := eq.refl a -- proof irrelevance is built in theorem proof_irrel {a : Prop} {H1 H2 : a} : H1 = H2 := rfl namespace eq theorem id_refl {A : Type} {a : A} (H1 : a = a) : H1 = (eq.refl a) := proof_irrel theorem irrel {A : Type} {a b : A} (H1 H2 : a = b) : H1 = H2 := proof_irrel theorem subst {A : Type} {a b : A} {P : A → Prop} (H1 : a = b) (H2 : P a) : P b := rec H2 H1 theorem trans {A : Type} {a b c : A} (H1 : a = b) (H2 : b = c) : a = c := subst H2 H1 theorem symm {A : Type} {a b : A} (H : a = b) : b = a := subst H (refl a) end eq calc_subst eq.subst calc_refl eq.refl calc_trans eq.trans namespace eq_ops postfix `⁻¹`:1024 := eq.symm infixr `⬝`:75 := eq.trans infixr `▸`:75 := eq.subst end eq_ops open eq_ops namespace eq -- eq_rec with arguments swapped, for transporting an element of a dependent type -- definition rec_on {A : Type} {a1 a2 : A} {B : A → Type} (H1 : a1 = a2) (H2 : B a1) : B a2 := -- eq.rec H2 H1 definition drec_on {A : Type} {a a' : A} {B : Πa' : A, a = a' → Type} (H1 : a = a') (H2 : B a (refl a)) : B a' H1 := eq.rec (λH1 : a = a, show B a H1, from H2) H1 H1 theorem drec_on_id {A : Type} {a : A} {B : Πa' : A, a = a' → Type} (H : a = a) (b : B a H) : drec_on H b = b := refl (drec_on rfl b) theorem drec_on_constant {A : Type} {a a' : A} {B : Type} (H : a = a') (b : B) : drec_on H b = b := drec_on H (λ(H' : a = a), drec_on_id H' b) H theorem drec_on_constant2 {A : Type} {a₁ a₂ a₃ a₄ : A} {B : Type} (H₁ : a₁ = a₂) (H₂ : a₃ = a₄) (b : B) : drec_on H₁ b = drec_on H₂ b := drec_on_constant H₁ b ⬝ drec_on_constant H₂ b ⁻¹ theorem drec_on_irrel {A B : Type} {a a' : A} {f : A → B} {D : B → Type} (H : a = a') (H' : f a = f a') (b : D (f a)) : drec_on H b = drec_on H' b := drec_on H (λ(H : a = a) (H' : f a = f a), drec_on_id H b ⬝ drec_on_id H' b⁻¹) H H' theorem rec_id {A : Type} {a : A} {B : A → Type} (H : a = a) (b : B a) : rec b H = b := id_refl H⁻¹ ▸ refl (eq.rec b (refl a)) theorem drec_on_compose {A : Type} {a b c : A} {P : A → Type} (H1 : a = b) (H2 : b = c) (u : P a) : drec_on H2 (drec_on H1 u) = drec_on (trans H1 H2) u := (show ∀(H2 : b = c), drec_on H2 (drec_on H1 u) = drec_on (trans H1 H2) u, from drec_on H2 (fun (H2 : b = b), drec_on_id H2 _)) H2 end eq open eq theorem congr_fun {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) (a : A) : f a = g a := H ▸ rfl theorem congr_arg {A : Type} {B : Type} {a b : A} (f : A → B) (H : a = b) : f a = f b := H ▸ rfl theorem congr {A : Type} {B : Type} {f g : A → B} {a b : A} (H1 : f = g) (H2 : a = b) : f a = g b := H1 ▸ H2 ▸ rfl theorem congr_arg2 {A B C : Type} {a a' : A} {b b' : B} (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' := congr (congr_arg f Ha) Hb theorem congr_arg3 {A B C D : Type} {a a' : A} {b b' : B} {c c' : C} (f : A → B → C → D) (Ha : a = a') (Hb : b = b') (Hc : c = c') : f a b c = f a' b' c' := congr (congr_arg2 f Ha Hb) Hc theorem congr_arg4 {A B C D E : Type} {a a' : A} {b b' : B} {c c' : C} {d d' : D} (f : A → B → C → D → E) (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') : f a b c d = f a' b' c' d' := congr (congr_arg3 f Ha Hb Hc) Hd theorem congr_arg5 {A B C D E F : Type} {a a' : A} {b b' : B} {c c' : C} {d d' : D} {e e' : E} (f : A → B → C → D → E → F) (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') (He : e = e') : f a b c d e = f a' b' c' d' e' := congr (congr_arg4 f Ha Hb Hc Hd) He theorem congr2 {A B C : Type} {a a' : A} {b b' : B} (f f' : A → B → C) (Hf : f = f') (Ha : a = a') (Hb : b = b') : f a b = f' a' b' := Hf ▸ congr_arg2 f Ha Hb theorem congr3 {A B C D : Type} {a a' : A} {b b' : B} {c c' : C} (f f' : A → B → C → D) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') : f a b c = f' a' b' c' := Hf ▸ congr_arg3 f Ha Hb Hc theorem congr4 {A B C D E : Type} {a a' : A} {b b' : B} {c c' : C} {d d' : D} (f f' : A → B → C → D → E) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') : f a b c d = f' a' b' c' d' := Hf ▸ congr_arg4 f Ha Hb Hc Hd theorem congr5 {A B C D E F : Type} {a a' : A} {b b' : B} {c c' : C} {d d' : D} {e e' : E} (f f' : A → B → C → D → E → F) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') (He : e = e') : f a b c d e = f' a' b' c' d' e' := Hf ▸ congr_arg5 f Ha Hb Hc Hd He theorem congr_arg2_dep {A : Type} {B : A → Type} {C : Type} {a₁ a₂ : A} {b₁ : B a₁} {b₂ : B a₂} (f : Πa, B a → C) (H₁ : a₁ = a₂) (H₂ : eq.drec_on H₁ b₁ = b₂) : f a₁ b₁ = f a₂ b₂ := eq.drec_on H₁ (λ (b₂ : B a₁) (H₁ : a₁ = a₁) (H₂ : eq.drec_on H₁ b₁ = b₂), calc f a₁ b₁ = f a₁ (eq.drec_on H₁ b₁) : {(eq.drec_on_id H₁ b₁)⁻¹} ... = f a₁ b₂ : {H₂}) b₂ H₁ H₂ theorem congr_arg3_dep {A : Type} {B : A → Type} {C : Πa, B a → Type} {D : Type} {a₁ a₂ : A} {b₁ : B a₁} {b₂ : B a₂} {c₁ : C a₁ b₁} {c₂ : C a₂ b₂} (f : Πa b, C a b → D) (H₁ : a₁ = a₂) (H₂ : eq.drec_on H₁ b₁ = b₂) (H₃ : eq.drec_on (congr_arg2_dep C H₁ H₂) c₁ = c₂) : f a₁ b₁ c₁ = f a₂ b₂ c₂ := eq.drec_on H₁ (λ (b₂ : B a₁) (H₂ : b₁ = b₂) (c₂ : C a₁ b₂) (H₃ : _ = c₂), have H₃' : eq.drec_on H₂ c₁ = c₂, from (drec_on_irrel H₂ (congr_arg2_dep C (refl a₁) H₂) c₁⁻¹) ▸ H₃, congr_arg2_dep (f a₁) H₂ H₃') b₂ H₂ c₂ H₃ theorem congr_arg3_ndep_dep {A B : Type} {C : A → B → Type} {D : Type} {a₁ a₂ : A} {b₁ b₂ : B} {c₁ : C a₁ b₁} {c₂ : C a₂ b₂} (f : Πa b, C a b → D) (H₁ : a₁ = a₂) (H₂ : b₁ = b₂) (H₃ : eq.drec_on (congr_arg2 C H₁ H₂) c₁ = c₂) : f a₁ b₁ c₁ = f a₂ b₂ c₂ := congr_arg3_dep f H₁ (drec_on_constant H₁ b₁ ⬝ H₂) H₃ theorem equal_f {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) : ∀x, f x = g x := fun x, congr_fun H x theorem eqmp {a b : Prop} (H1 : a = b) (H2 : a) : b := H1 ▸ H2 theorem eqmpr {a b : Prop} (H1 : a = b) (H2 : b) : a := H1⁻¹ ▸ H2 theorem imp_trans {a b c : Prop} (H1 : a → b) (H2 : b → c) : a → c := fun Ha, H2 (H1 Ha) theorem imp_eq_trans {a b c : Prop} (H1 : a → b) (H2 : b = c) : a → c := fun Ha, H2 ▸ (H1 Ha) theorem eq_imp_trans {a b c : Prop} (H1 : a = b) (H2 : b → c) : a → c := fun Ha, H2 (H1 ▸ Ha)
873250e563e37365a8dcf72299dcaeeeab940d45
91b8df3b248df89472cc0b753fbe2bac750aefea
/experiments/lean/src/ddl/host/default.lean
545ae7042cec8f88d84751b0d6ad1bc630b0a150
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yeslogic/fathom
eabe5c4112d3b4d5ec9096a57bb502254ddbdf15
3960a9466150d392c2cb103c5cb5fcffa0200814
refs/heads/main
1,685,349,769,736
1,675,998,621,000
1,675,998,621,000
28,993,871
214
11
Apache-2.0
1,694,044,276,000
1,420,764,938,000
Rust
UTF-8
Lean
false
false
95
lean
import ddl.host.basic import ddl.host.evaluation import ddl.host.typing import ddl.host.lemmas
b46f3d6be03df4b17d037575bd5636c139aff42a
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/measure_theory/integral/set_integral.lean
37eb88792a7d123db4bcc5d0a901dc21ea9d57b1
[ "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
50,163
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.integral.integrable_on import measure_theory.integral.bochner import order.filter.indicator_function import topology.metric_space.thickened_indicator /-! # Set integral In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable function `f` and a measurable set `s` this definition coincides with another natural definition: `∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s` and is zero otherwise. Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ` directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g. `integral_union`, `integral_empty`, `integral_univ`. We use the property `integrable_on f s μ := integrable f (μ.restrict s)`, defined in `measure_theory.integrable_on`. We also defined in that same file a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l`. Finally, we prove a version of the [Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries. Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)` as `s` tends to `l.small_sets`, i.e. for any `ε>0` there exists `t ∈ l` such that `∥∫ x in s, f x ∂μ - μ s • c∥ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`. ## Notation We provide the following notations for expressing the integral of a function on a set : * `∫ a in s, f a ∂μ` is `measure_theory.integral (μ.restrict s) f` * `∫ a in s, f a` is `∫ a in s, f a ∂volume` Note that the set notations are defined in the file `measure_theory/integral/bochner`, but we reference them here because all theorems about set integrals are in this file. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topological_space interval big_operators filter ennreal nnreal measure_theory variables {α β E F : Type*} [measurable_space α] namespace measure_theory section normed_add_comm_group variables [normed_add_comm_group E] {f g : α → E} {s t : set α} {μ ν : measure α} {l l' : filter α} variables [complete_space E] [normed_space ℝ E] lemma set_integral_congr_ae (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := integral_congr_ae ((ae_restrict_iff' hs).2 h) lemma set_integral_congr (hs : measurable_set s) (h : eq_on f g s) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := set_integral_congr_ae hs $ eventually_of_forall h lemma set_integral_congr_set_ae (hst : s =ᵐ[μ] t) : ∫ x in s, f x ∂μ = ∫ x in t, f x ∂μ := by rw measure.restrict_congr_set hst lemma integral_union_ae (hst : ae_disjoint μ s t) (ht : null_measurable_set t μ) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := by simp only [integrable_on, measure.restrict_union₀ hst ht, integral_add_measure hfs hft] lemma integral_union (hst : disjoint s t) (ht : measurable_set t) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := integral_union_ae hst.ae_disjoint ht.null_measurable_set hfs hft lemma integral_diff (ht : measurable_set t) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) (hts : t ⊆ s) : ∫ x in s \ t, f x ∂μ = ∫ x in s, f x ∂μ - ∫ x in t, f x ∂μ := begin rw [eq_sub_iff_add_eq, ← integral_union, diff_union_of_subset hts], exacts [disjoint_diff.symm, ht, hfs.mono_set (diff_subset _ _), hft] end lemma integral_finset_bUnion {ι : Type*} (t : finset ι) {s : ι → set α} (hs : ∀ i ∈ t, measurable_set (s i)) (h's : set.pairwise ↑t (disjoint on s)) (hf : ∀ i ∈ t, integrable_on f (s i) μ) : ∫ x in (⋃ i ∈ t, s i), f x ∂ μ = ∑ i in t, ∫ x in s i, f x ∂ μ := begin induction t using finset.induction_on with a t hat IH hs h's, { simp }, { simp only [finset.coe_insert, finset.forall_mem_insert, set.pairwise_insert, finset.set_bUnion_insert] at hs hf h's ⊢, rw [integral_union _ _ hf.1 (integrable_on_finset_Union.2 hf.2)], { rw [finset.sum_insert hat, IH hs.2 h's.1 hf.2] }, { simp only [disjoint_Union_right], exact (λ i hi, (h's.2 i hi (ne_of_mem_of_not_mem hi hat).symm).1) }, { exact finset.measurable_set_bUnion _ hs.2 } } end lemma integral_fintype_Union {ι : Type*} [fintype ι] {s : ι → set α} (hs : ∀ i, measurable_set (s i)) (h's : pairwise (disjoint on s)) (hf : ∀ i, integrable_on f (s i) μ) : ∫ x in (⋃ i, s i), f x ∂ μ = ∑ i, ∫ x in s i, f x ∂ μ := begin convert integral_finset_bUnion finset.univ (λ i hi, hs i) _ (λ i _, hf i), { simp }, { simp [pairwise_univ, h's] } end lemma integral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, integral_zero_measure] lemma integral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [measure.restrict_univ] lemma integral_add_compl (hs : measurable_set s) (hfi : integrable f μ) : ∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ := by rw [← integral_union (@disjoint_compl_right (set α) _ _) hs.compl hfi.integrable_on hfi.integrable_on, union_compl_self, integral_univ] /-- For a function `f` and a measurable set `s`, the integral of `indicator s f` over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/ lemma integral_indicator (hs : measurable_set s) : ∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ := begin by_cases hfi : integrable_on f s μ, swap, { rwa [integral_undef, integral_undef], rwa integrable_indicator_iff hs }, calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ : (integral_add_compl hs (hfi.indicator hs)).symm ... = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ : congr_arg2 (+) (integral_congr_ae (indicator_ae_eq_restrict hs)) (integral_congr_ae (indicator_ae_eq_restrict_compl hs)) ... = ∫ x in s, f x ∂μ : by simp end lemma set_integral_indicator (ht : measurable_set t) : ∫ x in s, t.indicator f x ∂μ = ∫ x in s ∩ t, f x ∂μ := by rw [integral_indicator ht, measure.restrict_restrict ht, set.inter_comm] lemma of_real_set_integral_one_of_measure_ne_top {α : Type*} {m : measurable_space α} {μ : measure α} {s : set α} (hs : μ s ≠ ∞) : ennreal.of_real (∫ x in s, (1 : ℝ) ∂μ) = μ s := calc ennreal.of_real (∫ x in s, (1 : ℝ) ∂μ) = ennreal.of_real (∫ x in s, ∥(1 : ℝ)∥ ∂μ) : by simp only [norm_one] ... = ∫⁻ x in s, 1 ∂μ : begin rw of_real_integral_norm_eq_lintegral_nnnorm (integrable_on_const.2 (or.inr hs.lt_top)), simp only [nnnorm_one, ennreal.coe_one], end ... = μ s : set_lintegral_one _ lemma of_real_set_integral_one {α : Type*} {m : measurable_space α} (μ : measure α) [is_finite_measure μ] (s : set α) : ennreal.of_real (∫ x in s, (1 : ℝ) ∂μ) = μ s := of_real_set_integral_one_of_measure_ne_top (measure_ne_top μ s) lemma integral_piecewise [decidable_pred (∈ s)] (hs : measurable_set s) {f g : α → E} (hf : integrable_on f s μ) (hg : integrable_on g sᶜ μ) : ∫ x, s.piecewise f g x ∂μ = ∫ x in s, f x ∂μ + ∫ x in sᶜ, g x ∂μ := by rw [← set.indicator_add_compl_eq_piecewise, integral_add' (hf.indicator hs) (hg.indicator hs.compl), integral_indicator hs, integral_indicator hs.compl] lemma tendsto_set_integral_of_monotone {ι : Type*} [encodable ι] [semilattice_sup ι] {s : ι → set α} {f : α → E} (hsm : ∀ i, measurable_set (s i)) (h_mono : monotone s) (hfi : integrable_on f (⋃ n, s n) μ) : tendsto (λ i, ∫ a in s i, f a ∂μ) at_top (𝓝 (∫ a in (⋃ n, s n), f a ∂μ)) := begin have hfi' : ∫⁻ x in ⋃ n, s n, ∥f x∥₊ ∂μ < ∞ := hfi.2, set S := ⋃ i, s i, have hSm : measurable_set S := measurable_set.Union hsm, have hsub : ∀ {i}, s i ⊆ S, from subset_Union s, rw [← with_density_apply _ hSm] at hfi', set ν := μ.with_density (λ x, ∥f x∥₊) with hν, refine metric.nhds_basis_closed_ball.tendsto_right_iff.2 (λ ε ε0, _), lift ε to ℝ≥0 using ε0.le, have : ∀ᶠ i in at_top, ν (s i) ∈ Icc (ν S - ε) (ν S + ε), from tendsto_measure_Union h_mono (ennreal.Icc_mem_nhds hfi'.ne (ennreal.coe_pos.2 ε0).ne'), refine this.mono (λ i hi, _), rw [mem_closed_ball_iff_norm', ← integral_diff (hsm i) hfi (hfi.mono_set hsub) hsub, ← coe_nnnorm, nnreal.coe_le_coe, ← ennreal.coe_le_coe], refine (ennnorm_integral_le_lintegral_ennnorm _).trans _, rw [← with_density_apply _ (hSm.diff (hsm _)), ← hν, measure_diff hsub (hsm _)], exacts [tsub_le_iff_tsub_le.mp hi.1, (hi.2.trans_lt $ ennreal.add_lt_top.2 ⟨hfi', ennreal.coe_lt_top⟩).ne] end lemma has_sum_integral_Union_ae {ι : Type*} [encodable ι] {s : ι → set α} {f : α → E} (hm : ∀ i, null_measurable_set (s i) μ) (hd : pairwise (ae_disjoint μ on s)) (hfi : integrable_on f (⋃ i, s i) μ) : has_sum (λ n, ∫ a in s n, f a ∂ μ) (∫ a in ⋃ n, s n, f a ∂μ) := begin simp only [integrable_on, measure.restrict_Union_ae hd hm] at hfi ⊢, exact has_sum_integral_measure hfi end lemma has_sum_integral_Union {ι : Type*} [encodable ι] {s : ι → set α} {f : α → E} (hm : ∀ i, measurable_set (s i)) (hd : pairwise (disjoint on s)) (hfi : integrable_on f (⋃ i, s i) μ) : has_sum (λ n, ∫ a in s n, f a ∂ μ) (∫ a in ⋃ n, s n, f a ∂μ) := has_sum_integral_Union_ae (λ i, (hm i).null_measurable_set) (hd.mono (λ i j h, h.ae_disjoint)) hfi lemma integral_Union {ι : Type*} [encodable ι] {s : ι → set α} {f : α → E} (hm : ∀ i, measurable_set (s i)) (hd : pairwise (disjoint on s)) (hfi : integrable_on f (⋃ i, s i) μ) : (∫ a in (⋃ n, s n), f a ∂μ) = ∑' n, ∫ a in s n, f a ∂ μ := (has_sum.tsum_eq (has_sum_integral_Union hm hd hfi)).symm lemma integral_Union_ae {ι : Type*} [encodable ι] {s : ι → set α} {f : α → E} (hm : ∀ i, null_measurable_set (s i) μ) (hd : pairwise (ae_disjoint μ on s)) (hfi : integrable_on f (⋃ i, s i) μ) : (∫ a in (⋃ n, s n), f a ∂μ) = ∑' n, ∫ a in s n, f a ∂ μ := (has_sum.tsum_eq (has_sum_integral_Union_ae hm hd hfi)).symm lemma set_integral_eq_zero_of_forall_eq_zero {f : α → E} (hf : strongly_measurable f) (ht_eq : ∀ x ∈ t, f x = 0) : ∫ x in t, f x ∂μ = 0 := begin refine integral_eq_zero_of_ae _, rw [eventually_eq, ae_restrict_iff (hf.measurable_set_eq_fun strongly_measurable_zero)], refine eventually_of_forall (λ x hx, _), rw pi.zero_apply, exact ht_eq x hx, end lemma set_integral_union_eq_left {f : α → E} (hf : strongly_measurable f) (hfi : integrable f μ) (hs : measurable_set s) (ht_eq : ∀ x ∈ t, f x = 0) : ∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ := begin rw [← set.union_diff_self, union_comm, integral_union, set_integral_eq_zero_of_forall_eq_zero _ (λ x hx, ht_eq x (diff_subset _ _ hx)), zero_add], exacts [hf, disjoint_diff.symm, hs, hfi.integrable_on, hfi.integrable_on] end lemma set_integral_neg_eq_set_integral_nonpos [linear_order E] [order_closed_topology E] {f : α → E} (hf : strongly_measurable f) (hfi : integrable f μ) : ∫ x in {x | f x < 0}, f x ∂μ = ∫ x in {x | f x ≤ 0}, f x ∂μ := begin have h_union : {x | f x ≤ 0} = {x | f x < 0} ∪ {x | f x = 0}, by { ext, simp_rw [set.mem_union_eq, set.mem_set_of_eq], exact le_iff_lt_or_eq, }, rw h_union, exact (set_integral_union_eq_left hf hfi (hf.measurable_set_lt strongly_measurable_const) (λ x hx, hx)).symm, end lemma integral_norm_eq_pos_sub_neg {f : α → ℝ} (hf : strongly_measurable f) (hfi : integrable f μ) : ∫ x, ∥f x∥ ∂μ = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ := have h_meas : measurable_set {x | 0 ≤ f x}, from strongly_measurable_const.measurable_set_le hf, calc ∫ x, ∥f x∥ ∂μ = ∫ x in {x | 0 ≤ f x}, ∥f x∥ ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ∥f x∥ ∂μ : by rw ← integral_add_compl h_meas hfi.norm ... = ∫ x in {x | 0 ≤ f x}, f x ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ∥f x∥ ∂μ : begin congr' 1, refine set_integral_congr h_meas (λ x hx, _), dsimp only, rw [real.norm_eq_abs, abs_eq_self.mpr _], exact hx, end ... = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | 0 ≤ f x}ᶜ, f x ∂μ : begin congr' 1, rw ← integral_neg, refine set_integral_congr h_meas.compl (λ x hx, _), dsimp only, rw [real.norm_eq_abs, abs_eq_neg_self.mpr _], rw [set.mem_compl_iff, set.nmem_set_of_eq] at hx, linarith, end ... = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ : by { rw ← set_integral_neg_eq_set_integral_nonpos hf hfi, congr, ext1 x, simp, } lemma set_integral_const (c : E) : ∫ x in s, c ∂μ = (μ s).to_real • c := by rw [integral_const, measure.restrict_apply_univ] @[simp] lemma integral_indicator_const (e : E) ⦃s : set α⦄ (s_meas : measurable_set s) : ∫ (a : α), s.indicator (λ (x : α), e) a ∂μ = (μ s).to_real • e := by rw [integral_indicator s_meas, ← set_integral_const] @[simp] lemma integral_indicator_one ⦃s : set α⦄ (hs : measurable_set s) : ∫ a, s.indicator 1 a ∂μ = (μ s).to_real := (integral_indicator_const 1 hs).trans ((smul_eq_mul _).trans (mul_one _)) lemma set_integral_indicator_const_Lp {p : ℝ≥0∞} (hs : measurable_set s) (ht : measurable_set t) (hμt : μ t ≠ ∞) (x : E) : ∫ a in s, indicator_const_Lp p ht hμt x a ∂μ = (μ (t ∩ s)).to_real • x := calc ∫ a in s, indicator_const_Lp p ht hμt x a ∂μ = (∫ a in s, t.indicator (λ _, x) a ∂μ) : by rw set_integral_congr_ae hs (indicator_const_Lp_coe_fn.mono (λ x hx hxs, hx)) ... = (μ (t ∩ s)).to_real • x : by rw [integral_indicator_const _ ht, measure.restrict_apply ht] lemma integral_indicator_const_Lp {p : ℝ≥0∞} (ht : measurable_set t) (hμt : μ t ≠ ∞) (x : E) : ∫ a, indicator_const_Lp p ht hμt x a ∂μ = (μ t).to_real • x := calc ∫ a, indicator_const_Lp p ht hμt x a ∂μ = ∫ a in univ, indicator_const_Lp p ht hμt x a ∂μ : by rw integral_univ ... = (μ (t ∩ univ)).to_real • x : set_integral_indicator_const_Lp measurable_set.univ ht hμt x ... = (μ t).to_real • x : by rw inter_univ lemma set_integral_map {β} [measurable_space β] {g : α → β} {f : β → E} {s : set β} (hs : measurable_set s) (hf : ae_strongly_measurable f (measure.map g μ)) (hg : ae_measurable g μ) : ∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ := begin rw [measure.restrict_map_of_ae_measurable hg hs, integral_map (hg.mono_measure measure.restrict_le_self) (hf.mono_measure _)], exact measure.map_mono_of_ae_measurable measure.restrict_le_self hg end lemma _root_.measurable_embedding.set_integral_map {β} {_ : measurable_space β} {f : α → β} (hf : measurable_embedding f) (g : β → E) (s : set β) : ∫ y in s, g y ∂(measure.map f μ) = ∫ x in f ⁻¹' s, g (f x) ∂μ := by rw [hf.restrict_map, hf.integral_map] lemma _root_.closed_embedding.set_integral_map [topological_space α] [borel_space α] {β} [measurable_space β] [topological_space β] [borel_space β] {g : α → β} {f : β → E} (s : set β) (hg : closed_embedding g) : ∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ := hg.measurable_embedding.set_integral_map _ _ lemma measure_preserving.set_integral_preimage_emb {β} {_ : measurable_space β} {f : α → β} {ν} (h₁ : measure_preserving f μ ν) (h₂ : measurable_embedding f) (g : β → E) (s : set β) : ∫ x in f ⁻¹' s, g (f x) ∂μ = ∫ y in s, g y ∂ν := (h₁.restrict_preimage_emb h₂ s).integral_comp h₂ _ lemma measure_preserving.set_integral_image_emb {β} {_ : measurable_space β} {f : α → β} {ν} (h₁ : measure_preserving f μ ν) (h₂ : measurable_embedding f) (g : β → E) (s : set α) : ∫ y in f '' s, g y ∂ν = ∫ x in s, g (f x) ∂μ := eq.symm $ (h₁.restrict_image_emb h₂ s).integral_comp h₂ _ lemma set_integral_map_equiv {β} [measurable_space β] (e : α ≃ᵐ β) (f : β → E) (s : set β) : ∫ y in s, f y ∂(measure.map e μ) = ∫ x in e ⁻¹' s, f (e x) ∂μ := e.measurable_embedding.set_integral_map f s lemma norm_set_integral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ∞) (hC : ∀ᵐ x ∂μ.restrict s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := begin rw ← measure.restrict_apply_univ at *, haveI : is_finite_measure (μ.restrict s) := ⟨‹_›⟩, exact norm_integral_le_of_norm_le_const hC end lemma norm_set_integral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ∞) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) (hfm : ae_strongly_measurable f (μ.restrict s)) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := begin apply norm_set_integral_le_of_norm_le_const_ae hs, have A : ∀ᵐ (x : α) ∂μ, x ∈ s → ∥ae_strongly_measurable.mk f hfm x∥ ≤ C, { filter_upwards [hC, hfm.ae_mem_imp_eq_mk] with _ h1 h2 h3, rw [← h2 h3], exact h1 h3 }, have B : measurable_set {x | ∥(hfm.mk f) x∥ ≤ C} := hfm.strongly_measurable_mk.norm.measurable measurable_set_Iic, filter_upwards [hfm.ae_eq_mk, (ae_restrict_iff B).2 A] with _ h1 _, rwa h1, end lemma norm_set_integral_le_of_norm_le_const_ae'' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae hs $ by rwa [ae_restrict_eq hsm, eventually_inf_principal] lemma norm_set_integral_le_of_norm_le_const {C : ℝ} (hs : μ s < ∞) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) (hfm : ae_strongly_measurable f (μ.restrict s)) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae' hs (eventually_of_forall hC) hfm lemma norm_set_integral_le_of_norm_le_const' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae'' hs hsm $ eventually_of_forall hC lemma set_integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : integrable_on f s μ) : ∫ x in s, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict s] 0 := integral_eq_zero_iff_of_nonneg_ae hf hfi lemma set_integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : integrable_on f s μ) : 0 < ∫ x in s, f x ∂μ ↔ 0 < μ (support f ∩ s) := begin rw [integral_pos_iff_support_of_nonneg_ae hf hfi, measure.restrict_apply₀], rw support_eq_preimage, exact hfi.ae_strongly_measurable.ae_measurable.null_measurable (measurable_set_singleton 0).compl end lemma set_integral_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → E} (hf_meas : strongly_measurable[m] f) {s : set α} (hs : measurable_set[m] s) : ∫ x in s, f x ∂μ = ∫ x in s, f x ∂(μ.trim hm) := by rwa [integral_trim hm hf_meas, restrict_trim hm μ] lemma integral_Icc_eq_integral_Ioc' [partial_order α] {f : α → E} {a b : α} (ha : μ {a} = 0) : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ := set_integral_congr_set_ae (Ioc_ae_eq_Icc' ha).symm lemma integral_Ioc_eq_integral_Ioo' [partial_order α] {f : α → E} {a b : α} (hb : μ {b} = 0) : ∫ t in Ioc a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ := set_integral_congr_set_ae (Ioo_ae_eq_Ioc' hb).symm lemma integral_Icc_eq_integral_Ioc [partial_order α] {f : α → E} {a b : α} [has_no_atoms μ] : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ := integral_Icc_eq_integral_Ioc' $ measure_singleton a lemma integral_Ioc_eq_integral_Ioo [partial_order α] {f : α → E} {a b : α} [has_no_atoms μ] : ∫ t in Ioc a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ := integral_Ioc_eq_integral_Ioo' $ measure_singleton b end normed_add_comm_group section mono variables {μ : measure α} {f g : α → ℝ} {s t : set α} (hf : integrable_on f s μ) (hg : integrable_on g s μ) lemma set_integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict s] g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := integral_mono_ae hf hg h lemma set_integral_mono_ae (h : f ≤ᵐ[μ] g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := set_integral_mono_ae_restrict hf hg (ae_restrict_of_ae h) lemma set_integral_mono_on (hs : measurable_set s) (h : ∀ x ∈ s, f x ≤ g x) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := set_integral_mono_ae_restrict hf hg (by simp [hs, eventually_le, eventually_inf_principal, ae_of_all _ h]) include hf hg -- why do I need this include, but we don't need it in other lemmas? lemma set_integral_mono_on_ae (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x ≤ g x) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := by { refine set_integral_mono_ae_restrict hf hg _, rwa [eventually_le, ae_restrict_iff' hs], } omit hf hg lemma set_integral_mono (h : f ≤ g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := integral_mono hf hg h lemma set_integral_mono_set (hfi : integrable_on f t μ) (hf : 0 ≤ᵐ[μ.restrict t] f) (hst : s ≤ᵐ[μ] t) : ∫ x in s, f x ∂μ ≤ ∫ x in t, f x ∂μ := integral_mono_measure (measure.restrict_mono_ae hst) hf hfi lemma set_integral_ge_of_const_le {c : ℝ} (hs : measurable_set s) (hμs : μ s ≠ ∞) (hf : ∀ x ∈ s, c ≤ f x) (hfint : integrable_on (λ (x : α), f x) s μ) : c * (μ s).to_real ≤ ∫ x in s, f x ∂μ := begin rw [mul_comm, ← smul_eq_mul, ← set_integral_const c], exact set_integral_mono_on (integrable_on_const.2 (or.inr hμs.lt_top)) hfint hs hf, end end mono section nonneg variables {μ : measure α} {f : α → ℝ} {s : set α} lemma set_integral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict s] f) : 0 ≤ ∫ a in s, f a ∂μ := integral_nonneg_of_ae hf lemma set_integral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ a in s, f a ∂μ := set_integral_nonneg_of_ae_restrict (ae_restrict_of_ae hf) lemma set_integral_nonneg (hs : measurable_set s) (hf : ∀ a, a ∈ s → 0 ≤ f a) : 0 ≤ ∫ a in s, f a ∂μ := set_integral_nonneg_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf)) lemma set_integral_nonneg_ae (hs : measurable_set s) (hf : ∀ᵐ a ∂μ, a ∈ s → 0 ≤ f a) : 0 ≤ ∫ a in s, f a ∂μ := set_integral_nonneg_of_ae_restrict $ by rwa [eventually_le, ae_restrict_iff' hs] lemma set_integral_le_nonneg {s : set α} (hs : measurable_set s) (hf : strongly_measurable f) (hfi : integrable f μ) : ∫ x in s, f x ∂μ ≤ ∫ x in {y | 0 ≤ f y}, f x ∂μ := begin rw [← integral_indicator hs, ← integral_indicator (strongly_measurable_const.measurable_set_le hf)], exact integral_mono (hfi.indicator hs) (hfi.indicator (strongly_measurable_const.measurable_set_le hf)) (indicator_le_indicator_nonneg s f), end lemma set_integral_nonpos_of_ae_restrict (hf : f ≤ᵐ[μ.restrict s] 0) : ∫ a in s, f a ∂μ ≤ 0 := integral_nonpos_of_ae hf lemma set_integral_nonpos_of_ae (hf : f ≤ᵐ[μ] 0) : ∫ a in s, f a ∂μ ≤ 0 := set_integral_nonpos_of_ae_restrict (ae_restrict_of_ae hf) lemma set_integral_nonpos (hs : measurable_set s) (hf : ∀ a, a ∈ s → f a ≤ 0) : ∫ a in s, f a ∂μ ≤ 0 := set_integral_nonpos_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf)) lemma set_integral_nonpos_ae (hs : measurable_set s) (hf : ∀ᵐ a ∂μ, a ∈ s → f a ≤ 0) : ∫ a in s, f a ∂μ ≤ 0 := set_integral_nonpos_of_ae_restrict $ by rwa [eventually_le, ae_restrict_iff' hs] lemma set_integral_nonpos_le {s : set α} (hs : measurable_set s) (hf : strongly_measurable f) (hfi : integrable f μ) : ∫ x in {y | f y ≤ 0}, f x ∂μ ≤ ∫ x in s, f x ∂μ := begin rw [← integral_indicator hs, ← integral_indicator (hf.measurable_set_le strongly_measurable_const)], exact integral_mono (hfi.indicator (hf.measurable_set_le strongly_measurable_const)) (hfi.indicator hs) (indicator_nonpos_le_indicator s f), end end nonneg section tendsto_mono variables {μ : measure α} [normed_add_comm_group E] [complete_space E] [normed_space ℝ E] {s : ℕ → set α} {f : α → E} lemma _root_.antitone.tendsto_set_integral (hsm : ∀ i, measurable_set (s i)) (h_anti : antitone s) (hfi : integrable_on f (s 0) μ) : tendsto (λi, ∫ a in s i, f a ∂μ) at_top (𝓝 (∫ a in (⋂ n, s n), f a ∂μ)) := begin let bound : α → ℝ := indicator (s 0) (λ a, ∥f a∥), have h_int_eq : (λ i, ∫ a in s i, f a ∂μ) = (λ i, ∫ a, (s i).indicator f a ∂μ), from funext (λ i, (integral_indicator (hsm i)).symm), rw h_int_eq, rw ← integral_indicator (measurable_set.Inter hsm), refine tendsto_integral_of_dominated_convergence bound _ _ _ _, { intro n, rw ae_strongly_measurable_indicator_iff (hsm n), exact (integrable_on.mono_set hfi (h_anti (zero_le n))).1 }, { rw integrable_indicator_iff (hsm 0), exact hfi.norm, }, { simp_rw norm_indicator_eq_indicator_norm, refine λ n, eventually_of_forall (λ x, _), exact indicator_le_indicator_of_subset (h_anti (zero_le n)) (λ a, norm_nonneg _) _ }, { filter_upwards with a using le_trans (h_anti.tendsto_indicator _ _ _) (pure_le_nhds _), }, end end tendsto_mono /-! ### Continuity of the set integral We prove that for any set `s`, the function `λ f : α →₁[μ] E, ∫ x in s, f x ∂μ` is continuous. -/ section continuous_set_integral variables [normed_add_comm_group E] {𝕜 : Type*} [normed_field 𝕜] [normed_add_comm_group F] [normed_space 𝕜 F] {p : ℝ≥0∞} {μ : measure α} /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.mem_ℒp f).restrict s).to_Lp f`. This map is additive. -/ lemma Lp_to_Lp_restrict_add (f g : Lp E p μ) (s : set α) : ((Lp.mem_ℒp (f + g)).restrict s).to_Lp ⇑(f + g) = ((Lp.mem_ℒp f).restrict s).to_Lp f + ((Lp.mem_ℒp g).restrict s).to_Lp g := begin ext1, refine (ae_restrict_of_ae (Lp.coe_fn_add f g)).mp _, refine (Lp.coe_fn_add (mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s)) (mem_ℒp.to_Lp g ((Lp.mem_ℒp g).restrict s))).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp g).restrict s)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp (f+g)).restrict s)).mono (λ x hx1 hx2 hx3 hx4 hx5, _), rw [hx4, hx1, pi.add_apply, hx2, hx3, hx5, pi.add_apply], end /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.mem_ℒp f).restrict s).to_Lp f`. This map commutes with scalar multiplication. -/ lemma Lp_to_Lp_restrict_smul (c : 𝕜) (f : Lp F p μ) (s : set α) : ((Lp.mem_ℒp (c • f)).restrict s).to_Lp ⇑(c • f) = c • (((Lp.mem_ℒp f).restrict s).to_Lp f) := begin ext1, refine (ae_restrict_of_ae (Lp.coe_fn_smul c f)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp (c • f)).restrict s)).mp _, refine (Lp.coe_fn_smul c (mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s))).mono (λ x hx1 hx2 hx3 hx4, _), rw [hx2, hx1, pi.smul_apply, hx3, hx4, pi.smul_apply], end /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.mem_ℒp f).restrict s).to_Lp f`. This map is non-expansive. -/ lemma norm_Lp_to_Lp_restrict_le (s : set α) (f : Lp E p μ) : ∥((Lp.mem_ℒp f).restrict s).to_Lp f∥ ≤ ∥f∥ := begin rw [Lp.norm_def, Lp.norm_def, ennreal.to_real_le_to_real (Lp.snorm_ne_top _) (Lp.snorm_ne_top _)], refine (le_of_eq _).trans (snorm_mono_measure _ measure.restrict_le_self), { exact s, }, exact snorm_congr_ae (mem_ℒp.coe_fn_to_Lp _), end variables (α F 𝕜) /-- Continuous linear map sending a function of `Lp F p μ` to the same function in `Lp F p (μ.restrict s)`. -/ def Lp_to_Lp_restrict_clm (μ : measure α) (p : ℝ≥0∞) [hp : fact (1 ≤ p)] (s : set α) : Lp F p μ →L[𝕜] Lp F p (μ.restrict s) := @linear_map.mk_continuous 𝕜 𝕜 (Lp F p μ) (Lp F p (μ.restrict s)) _ _ _ _ _ _ (ring_hom.id 𝕜) ⟨λ f, mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s), λ f g, Lp_to_Lp_restrict_add f g s, λ c f, Lp_to_Lp_restrict_smul c f s⟩ 1 (by { intro f, rw one_mul, exact norm_Lp_to_Lp_restrict_le s f, }) variables {α F 𝕜} variables (𝕜) lemma Lp_to_Lp_restrict_clm_coe_fn [hp : fact (1 ≤ p)] (s : set α) (f : Lp F p μ) : Lp_to_Lp_restrict_clm α F 𝕜 μ p s f =ᵐ[μ.restrict s] f := mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s) variables {𝕜} @[continuity] lemma continuous_set_integral [normed_space ℝ E] [complete_space E] (s : set α) : continuous (λ f : α →₁[μ] E, ∫ x in s, f x ∂μ) := begin haveI : fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_rfl⟩, have h_comp : (λ f : α →₁[μ] E, ∫ x in s, f x ∂μ) = (integral (μ.restrict s)) ∘ (λ f, Lp_to_Lp_restrict_clm α E ℝ μ 1 s f), { ext1 f, rw [function.comp_apply, integral_congr_ae (Lp_to_Lp_restrict_clm_coe_fn ℝ s f)], }, rw h_comp, exact continuous_integral.comp (Lp_to_Lp_restrict_clm α E ℝ μ 1 s).continuous, end end continuous_set_integral end measure_theory open measure_theory asymptotics metric variables {ι : Type*} [normed_add_comm_group E] /-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`, then `∫ x in s i, f x ∂μ = μ (s i) • b + o(μ (s i))` at a filter `li` provided that `s i` tends to `l.small_sets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma filter.tendsto.integral_sub_linear_is_o_ae [normed_space ℝ E] [complete_space E] {μ : measure α} {l : filter α} [l.is_measurably_generated] {f : α → E} {b : E} (h : tendsto f (l ⊓ μ.ae) (𝓝 b)) (hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {s : ι → set α} {li : filter ι} (hs : tendsto s li l.small_sets) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : (λ i, ∫ x in s i, f x ∂μ - m i • b) =o[li] m := begin suffices : (λ s, ∫ x in s, f x ∂μ - (μ s).to_real • b) =o[l.small_sets] (λ s, (μ s).to_real), from (this.comp_tendsto hs).congr' (hsμ.mono $ λ a ha, ha ▸ rfl) hsμ, refine is_o_iff.2 (λ ε ε₀, _), have : ∀ᶠ s in l.small_sets, ∀ᶠ x in μ.ae, x ∈ s → f x ∈ closed_ball b ε := eventually_small_sets_eventually.2 (h.eventually $ closed_ball_mem_nhds _ ε₀), filter_upwards [hμ.eventually, (hμ.integrable_at_filter_of_tendsto_ae hfm h).eventually, hfm.eventually, this], simp only [mem_closed_ball, dist_eq_norm], intros s hμs h_integrable hfm h_norm, rw [← set_integral_const, ← integral_sub h_integrable (integrable_on_const.2 $ or.inr hμs), real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], exact norm_set_integral_le_of_norm_le_const_ae' hμs h_norm (hfm.sub ae_strongly_measurable_const) end /-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a` within a measurable set `t`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at a filter `li` provided that `s i` tends to `(𝓝[t] a).small_sets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_within_at.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [complete_space E] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (ha : continuous_within_at f t a) (ht : measurable_set t) (hfm : strongly_measurable_at_filter f (𝓝[t] a) μ) {s : ι → set α} {li : filter ι} (hs : tendsto s li (𝓝[t] a).small_sets) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : (λ i, ∫ x in s i, f x ∂μ - m i • f a) =o[li] m := by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _; exact (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds_within a t) hs m hsμ /-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s` tends to `(𝓝 a).small_sets` along `li. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_at.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [complete_space E] {μ : measure α} [is_locally_finite_measure μ] {a : α} {f : α → E} (ha : continuous_at f a) (hfm : strongly_measurable_at_filter f (𝓝 a) μ) {s : ι → set α} {li : filter ι} (hs : tendsto s li (𝓝 a).small_sets) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : (λ i, ∫ x in s i, f x ∂μ - m i • f a) =o[li] m := (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds a) hs m hsμ /-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally finite measure, `f` is continuous on a measurable set `t`, and `a ∈ t`, then `∫ x in (s i), f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s i` tends to `(𝓝[t] a).small_sets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_on.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [complete_space E] [second_countable_topology_either α E] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ha : a ∈ t) (ht : measurable_set t) {s : ι → set α} {li : filter ι} (hs : tendsto s li (𝓝[t] a).small_sets) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : (λ i, ∫ x in s i, f x ∂μ - m i • f a) =o[li] m := (hft a ha).integral_sub_linear_is_o_ae ht ⟨t, self_mem_nhds_within, hft.ae_strongly_measurable ht⟩ hs m hsμ section /-! ### Continuous linear maps composed with integration The goal of this section is to prove that integration commutes with continuous linear maps. This holds for simple functions. The general result follows from the continuity of all involved operations on the space `L¹`. Note that composition by a continuous linear map on `L¹` is not just the composition, as we are dealing with classes of functions, but it has already been defined as `continuous_linear_map.comp_Lp`. We take advantage of this construction here. -/ open_locale complex_conjugate variables {μ : measure α} {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F] {p : ennreal} namespace continuous_linear_map variables [complete_space F] [normed_space ℝ F] lemma integral_comp_Lp (L : E →L[𝕜] F) (φ : Lp E p μ) : ∫ a, (L.comp_Lp φ) a ∂μ = ∫ a, L (φ a) ∂μ := integral_congr_ae $ coe_fn_comp_Lp _ _ lemma set_integral_comp_Lp (L : E →L[𝕜] F) (φ : Lp E p μ) {s : set α} (hs : measurable_set s) : ∫ a in s, (L.comp_Lp φ) a ∂μ = ∫ a in s, L (φ a) ∂μ := set_integral_congr_ae hs ((L.coe_fn_comp_Lp φ).mono (λ x hx hx2, hx)) lemma continuous_integral_comp_L1 (L : E →L[𝕜] F) : continuous (λ (φ : α →₁[μ] E), ∫ (a : α), L (φ a) ∂μ) := by { rw ← funext L.integral_comp_Lp, exact continuous_integral.comp (L.comp_LpL 1 μ).continuous, } variables [complete_space E] [normed_space ℝ E] lemma integral_comp_comm (L : E →L[𝕜] F) {φ : α → E} (φ_int : integrable φ μ) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := begin apply integrable.induction (λ φ, ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ)), { intros e s s_meas s_finite, rw [integral_indicator_const e s_meas, ← @smul_one_smul E ℝ 𝕜 _ _ _ _ _ (μ s).to_real e, continuous_linear_map.map_smul, @smul_one_smul F ℝ 𝕜 _ _ _ _ _ (μ s).to_real (L e), ← integral_indicator_const (L e) s_meas], congr' 1 with a, rw set.indicator_comp_of_zero L.map_zero }, { intros f g H f_int g_int hf hg, simp [L.map_add, integral_add f_int g_int, integral_add (L.integrable_comp f_int) (L.integrable_comp g_int), hf, hg] }, { exact is_closed_eq L.continuous_integral_comp_L1 (L.continuous.comp continuous_integral) }, { intros f g hfg f_int hf, convert hf using 1 ; clear hf, { exact integral_congr_ae (hfg.fun_comp L).symm }, { rw integral_congr_ae hfg.symm } }, all_goals { assumption } end lemma integral_apply {H : Type*} [normed_add_comm_group H] [normed_space 𝕜 H] {φ : α → H →L[𝕜] E} (φ_int : integrable φ μ) (v : H) : (∫ a, φ a ∂μ) v = ∫ a, φ a v ∂μ := ((continuous_linear_map.apply 𝕜 E v).integral_comp_comm φ_int).symm lemma integral_comp_comm' (L : E →L[𝕜] F) {K} (hL : antilipschitz_with K L) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := begin by_cases h : integrable φ μ, { exact integral_comp_comm L h }, have : ¬ (integrable (L ∘ φ) μ), by rwa lipschitz_with.integrable_comp_iff_of_antilipschitz L.lipschitz hL (L.map_zero), simp [integral_undef, h, this] end lemma integral_comp_L1_comm (L : E →L[𝕜] F) (φ : α →₁[μ] E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.integral_comp_comm (L1.integrable_coe_fn φ) end continuous_linear_map namespace linear_isometry variables [complete_space F] [normed_space ℝ F] [complete_space E] [normed_space ℝ E] lemma integral_comp_comm (L : E →ₗᵢ[𝕜] F) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.to_continuous_linear_map.integral_comp_comm' L.antilipschitz _ end linear_isometry variables [complete_space E] [normed_space ℝ E] [complete_space F] [normed_space ℝ F] @[norm_cast] lemma integral_of_real {f : α → ℝ} : ∫ a, (f a : 𝕜) ∂μ = ↑∫ a, f a ∂μ := (@is_R_or_C.of_real_li 𝕜 _).integral_comp_comm f lemma integral_re {f : α → 𝕜} (hf : integrable f μ) : ∫ a, is_R_or_C.re (f a) ∂μ = is_R_or_C.re ∫ a, f a ∂μ := (@is_R_or_C.re_clm 𝕜 _).integral_comp_comm hf lemma integral_im {f : α → 𝕜} (hf : integrable f μ) : ∫ a, is_R_or_C.im (f a) ∂μ = is_R_or_C.im ∫ a, f a ∂μ := (@is_R_or_C.im_clm 𝕜 _).integral_comp_comm hf lemma integral_conj {f : α → 𝕜} : ∫ a, conj (f a) ∂μ = conj ∫ a, f a ∂μ := (@is_R_or_C.conj_lie 𝕜 _).to_linear_isometry.integral_comp_comm f lemma integral_coe_re_add_coe_im {f : α → 𝕜} (hf : integrable f μ) : ∫ x, (is_R_or_C.re (f x) : 𝕜) ∂μ + ∫ x, is_R_or_C.im (f x) ∂μ * is_R_or_C.I = ∫ x, f x ∂μ := begin rw [mul_comm, ← smul_eq_mul, ← integral_smul, ← integral_add], { congr, ext1 x, rw [smul_eq_mul, mul_comm, is_R_or_C.re_add_im] }, { exact hf.re.of_real }, { exact hf.im.of_real.smul is_R_or_C.I } end lemma integral_re_add_im {f : α → 𝕜} (hf : integrable f μ) : ((∫ x, is_R_or_C.re (f x) ∂μ : ℝ) : 𝕜) + (∫ x, is_R_or_C.im (f x) ∂μ : ℝ) * is_R_or_C.I = ∫ x, f x ∂μ := by { rw [← integral_of_real, ← integral_of_real, integral_coe_re_add_coe_im hf] } lemma set_integral_re_add_im {f : α → 𝕜} {i : set α} (hf : integrable_on f i μ) : ((∫ x in i, is_R_or_C.re (f x) ∂μ : ℝ) : 𝕜) + (∫ x in i, is_R_or_C.im (f x) ∂μ : ℝ) * is_R_or_C.I = ∫ x in i, f x ∂μ := integral_re_add_im hf lemma fst_integral {f : α → E × F} (hf : integrable f μ) : (∫ x, f x ∂μ).1 = ∫ x, (f x).1 ∂μ := ((continuous_linear_map.fst ℝ E F).integral_comp_comm hf).symm lemma snd_integral {f : α → E × F} (hf : integrable f μ) : (∫ x, f x ∂μ).2 = ∫ x, (f x).2 ∂μ := ((continuous_linear_map.snd ℝ E F).integral_comp_comm hf).symm lemma integral_pair {f : α → E} {g : α → F} (hf : integrable f μ) (hg : integrable g μ) : ∫ x, (f x, g x) ∂μ = (∫ x, f x ∂μ, ∫ x, g x ∂μ) := have _ := hf.prod_mk hg, prod.ext (fst_integral this) (snd_integral this) lemma integral_smul_const {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] (f : α → 𝕜) (c : E) : ∫ x, f x • c ∂μ = (∫ x, f x ∂μ) • c := begin by_cases hf : integrable f μ, { exact ((1 : 𝕜 →L[𝕜] 𝕜).smul_right c).integral_comp_comm hf }, { by_cases hc : c = 0, { simp only [hc, integral_zero, smul_zero] }, rw [integral_undef hf, integral_undef, zero_smul], simp_rw [integrable_smul_const hc, hf, not_false_iff] } end section inner variables {E' : Type*} [inner_product_space 𝕜 E'] [complete_space E'] [normed_space ℝ E'] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E' _ x y lemma integral_inner {f : α → E'} (hf : integrable f μ) (c : E') : ∫ x, ⟪c, f x⟫ ∂μ = ⟪c, ∫ x, f x ∂μ⟫ := ((@innerSL 𝕜 E' _ _ c).restrict_scalars ℝ).integral_comp_comm hf lemma integral_eq_zero_of_forall_integral_inner_eq_zero (f : α → E') (hf : integrable f μ) (hf_int : ∀ (c : E'), ∫ x, ⟪c, f x⟫ ∂μ = 0) : ∫ x, f x ∂μ = 0 := by { specialize hf_int (∫ x, f x ∂μ), rwa [integral_inner hf, inner_self_eq_zero] at hf_int } end inner lemma integral_with_density_eq_integral_smul {f : α → ℝ≥0} (f_meas : measurable f) (g : α → E) : ∫ a, g a ∂(μ.with_density (λ x, f x)) = ∫ a, f a • g a ∂μ := begin by_cases hg : integrable g (μ.with_density (λ x, f x)), swap, { rw [integral_undef hg, integral_undef], rwa [← integrable_with_density_iff_integrable_smul f_meas]; apply_instance }, refine integrable.induction _ _ _ _ _ hg, { assume c s s_meas hs, rw integral_indicator s_meas, simp_rw [← indicator_smul_apply, integral_indicator s_meas], simp only [s_meas, integral_const, measure.restrict_apply', univ_inter, with_density_apply], rw [lintegral_coe_eq_integral, ennreal.to_real_of_real, ← integral_smul_const], { refl }, { exact integral_nonneg (λ x, nnreal.coe_nonneg _) }, { refine ⟨(f_meas.coe_nnreal_real).ae_measurable.ae_strongly_measurable, _⟩, rw with_density_apply _ s_meas at hs, rw has_finite_integral, convert hs, ext1 x, simp only [nnreal.nnnorm_eq] } }, { assume u u' h_disj u_int u'_int h h', change ∫ (a : α), (u a + u' a) ∂μ.with_density (λ (x : α), ↑(f x)) = ∫ (a : α), f a • (u a + u' a) ∂μ, simp_rw [smul_add], rw [integral_add u_int u'_int, h, h', integral_add], { exact (integrable_with_density_iff_integrable_smul f_meas).1 u_int }, { exact (integrable_with_density_iff_integrable_smul f_meas).1 u'_int } }, { have C1 : continuous (λ (u : Lp E 1 (μ.with_density (λ x, f x))), ∫ x, u x ∂(μ.with_density (λ x, f x))) := continuous_integral, have C2 : continuous (λ (u : Lp E 1 (μ.with_density (λ x, f x))), ∫ x, f x • u x ∂μ), { have : continuous ((λ (u : Lp E 1 μ), ∫ x, u x ∂μ) ∘ (with_density_smul_li μ f_meas)) := continuous_integral.comp (with_density_smul_li μ f_meas).continuous, convert this, ext1 u, simp only [function.comp_app, with_density_smul_li_apply], exact integral_congr_ae (mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp.symm }, exact is_closed_eq C1 C2 }, { assume u v huv u_int hu, rw [← integral_congr_ae huv, hu], apply integral_congr_ae, filter_upwards [(ae_with_density_iff f_meas.coe_nnreal_ennreal).1 huv] with x hx, rcases eq_or_ne (f x) 0 with h'x|h'x, { simp only [h'x, zero_smul]}, { rw [hx _], simpa only [ne.def, ennreal.coe_eq_zero] using h'x } } end lemma integral_with_density_eq_integral_smul₀ {f : α → ℝ≥0} (hf : ae_measurable f μ) (g : α → E) : ∫ a, g a ∂(μ.with_density (λ x, f x)) = ∫ a, f a • g a ∂μ := begin let f' := hf.mk _, calc ∫ a, g a ∂(μ.with_density (λ x, f x)) = ∫ a, g a ∂(μ.with_density (λ x, f' x)) : begin congr' 1, apply with_density_congr_ae, filter_upwards [hf.ae_eq_mk] with x hx, rw hx, end ... = ∫ a, f' a • g a ∂μ : integral_with_density_eq_integral_smul hf.measurable_mk _ ... = ∫ a, f a • g a ∂μ : begin apply integral_congr_ae, filter_upwards [hf.ae_eq_mk] with x hx, rw hx, end end lemma set_integral_with_density_eq_set_integral_smul {f : α → ℝ≥0} (f_meas : measurable f) (g : α → E) {s : set α} (hs : measurable_set s) : ∫ a in s, g a ∂(μ.with_density (λ x, f x)) = ∫ a in s, f a • g a ∂μ := by rw [restrict_with_density hs, integral_with_density_eq_integral_smul f_meas] lemma set_integral_with_density_eq_set_integral_smul₀ {f : α → ℝ≥0} {s : set α} (hf : ae_measurable f (μ.restrict s)) (g : α → E) (hs : measurable_set s) : ∫ a in s, g a ∂(μ.with_density (λ x, f x)) = ∫ a in s, f a • g a ∂μ := by rw [restrict_with_density hs, integral_with_density_eq_integral_smul₀ hf] end section thickened_indicator variables [pseudo_emetric_space α] lemma measure_le_lintegral_thickened_indicator_aux (μ : measure α) {E : set α} (E_mble : measurable_set E) (δ : ℝ) : μ E ≤ ∫⁻ a, (thickened_indicator_aux δ E a : ℝ≥0∞) ∂μ := begin convert_to lintegral μ (E.indicator (λ _, (1 : ℝ≥0∞))) ≤ lintegral μ (thickened_indicator_aux δ E), { rw [lintegral_indicator _ E_mble], simp only [lintegral_one, measure.restrict_apply, measurable_set.univ, univ_inter], }, { apply lintegral_mono, apply indicator_le_thickened_indicator_aux, }, end lemma measure_le_lintegral_thickened_indicator (μ : measure α) {E : set α} (E_mble : measurable_set E) {δ : ℝ} (δ_pos : 0 < δ) : μ E ≤ ∫⁻ a, (thickened_indicator δ_pos E a : ℝ≥0∞) ∂μ := begin convert measure_le_lintegral_thickened_indicator_aux μ E_mble δ, dsimp, simp only [thickened_indicator_aux_lt_top.ne, ennreal.coe_to_nnreal, ne.def, not_false_iff], end end thickened_indicator section bilinear_map namespace measure_theory variables {f : β → ℝ} {m m0 : measurable_space β} {μ : measure β} lemma integrable.simple_func_mul (g : simple_func β ℝ) (hf : integrable f μ) : integrable (g * f) μ := begin refine simple_func.induction (λ c s hs, _) (λ g₁ g₂ h_disj h_int₁ h_int₂, (h_int₁.add h_int₂).congr (by rw [simple_func.coe_add, add_mul])) g, simp only [simple_func.const_zero, simple_func.coe_piecewise, simple_func.coe_const, simple_func.coe_zero, set.piecewise_eq_indicator], have : set.indicator s (function.const β c) * f = s.indicator (c • f), { ext1 x, by_cases hx : x ∈ s, { simp only [hx, pi.mul_apply, set.indicator_of_mem, pi.smul_apply, algebra.id.smul_eq_mul] }, { simp only [hx, pi.mul_apply, set.indicator_of_not_mem, not_false_iff, zero_mul], }, }, rw [this, integrable_indicator_iff hs], exact (hf.smul c).integrable_on, end lemma integrable.simple_func_mul' (hm : m ≤ m0) (g : @simple_func β m ℝ) (hf : integrable f μ) : integrable (g * f) μ := by { rw ← simple_func.coe_to_larger_space_eq hm g, exact hf.simple_func_mul (g.to_larger_space hm) } end measure_theory end bilinear_map
cd0ffc18412f0270dbd7c8696f5bc3cee1d1c3b2
82e44445c70db0f03e30d7be725775f122d72f3e
/src/category_theory/monad/adjunction.lean
acf56216ef6604f6292a6492ed55044506b1c00d
[ "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,124
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₂ -- morphism levels before object levels. See note [category_theory universes]. variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] variables {L : C ⥤ D} {R : D ⥤ C} namespace adjunction /-- For a pair of functors `L : C ⥤ D`, `R : D ⥤ C`, an adjunction `h : L ⊣ R` induces a monad on the category `C`. -/ @[simps] def to_monad (h : L ⊣ R) : monad C := { to_functor := L ⋙ R, η' := h.unit, μ' := whisker_right (whisker_left L h.counit) R, assoc' := λ X, by { dsimp, rw [←R.map_comp], simp }, right_unit' := λ X, by { dsimp, rw [←R.map_comp], simp } } /-- For a pair of functors `L : C ⥤ D`, `R : D ⥤ C`, an adjunction `h : L ⊣ R` induces a comonad on the category `D`. -/ @[simps] def to_comonad (h : L ⊣ R) : comonad D := { to_functor := R ⋙ L, ε' := h.counit, δ' := whisker_right (whisker_left R h.unit) L, coassoc' := λ X, by { dsimp, rw ← L.map_comp, simp }, right_counit' := λ X, by { dsimp, rw ← L.map_comp, simp } } /-- The monad induced by the Eilenberg-Moore adjunction is the original monad. -/ @[simps] def adj_to_monad_iso (T : monad C) : T.adj.to_monad ≅ T := monad_iso.mk (nat_iso.of_components (λ X, iso.refl _) (by tidy)) (λ X, by { dsimp, simp }) (λ X, by { dsimp, simp }) /-- The comonad induced by the Eilenberg-Moore adjunction is the original comonad. -/ @[simps] def adj_to_comonad_iso (G : comonad C) : G.adj.to_comonad ≅ G := comonad_iso.mk (nat_iso.of_components (λ X, iso.refl _) (by tidy)) (λ X, by { dsimp, simp }) (λ X, by { dsimp, simp }) end adjunction /-- 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 monad.comparison (h : L ⊣ R) : D ⥤ h.to_monad.algebra := { obj := λ X, { A := R.obj X, a := R.map (h.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 monad.comparison_forget (h : L ⊣ R) : monad.comparison h ⋙ h.to_monad.forget ≅ R := { hom := { app := λ X, 𝟙 _, }, inv := { app := λ X, 𝟙 _, } } lemma monad.left_comparison (h : L ⊣ R) : L ⋙ monad.comparison h = h.to_monad.free := rfl instance [faithful R] (h : L ⊣ R) : faithful (monad.comparison h) := { map_injective' := λ X Y f g w, R.map_injective (congr_arg monad.algebra.hom.f w : _) } instance (T : monad C) : full (monad.comparison T.adj) := { preimage := λ X Y f, ⟨f.f, by simpa using f.h⟩ } instance (T : monad C) : ess_surj (monad.comparison T.adj) := { mem_ess_image := λ X, ⟨{ A := X.A, a := X.a, unit' := by simpa using X.unit, assoc' := by simpa using X.assoc }, ⟨monad.algebra.iso_mk (iso.refl _) (by simp)⟩⟩ } /-- 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 comonad.comparison (h : L ⊣ R) : C ⥤ h.to_comonad.coalgebra := { obj := λ X, { A := L.obj X, a := L.map (h.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 comonad.comparison_forget {L : C ⥤ D} {R : D ⥤ C} (h : L ⊣ R) : comonad.comparison h ⋙ h.to_comonad.forget ≅ L := { hom := { app := λ X, 𝟙 _, }, inv := { app := λ X, 𝟙 _, } } lemma comonad.left_comparison (h : L ⊣ R) : R ⋙ comonad.comparison h = h.to_comonad.cofree := rfl instance comonad.comparison_faithful_of_faithful [faithful L] (h : L ⊣ R) : faithful (comonad.comparison h) := { map_injective' := λ X Y f g w, L.map_injective (congr_arg comonad.coalgebra.hom.f w : _) } instance (G : comonad C) : full (comonad.comparison G.adj) := { preimage := λ X Y f, ⟨f.f, by simpa using f.h⟩ } instance (G : comonad C) : ess_surj (comonad.comparison G.adj) := { mem_ess_image := λ X, ⟨{ A := X.A, a := X.a, counit' := by simpa using X.counit, coassoc' := by simpa using X.coassoc }, ⟨comonad.coalgebra.iso_mk (iso.refl _) (by simp)⟩⟩ } /-- 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 (adjunction.of_right_adjoint 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 (adjunction.of_left_adjoint L))) noncomputable instance (T : monad C) : monadic_right_adjoint T.forget := ⟨(equivalence.of_fully_faithfully_ess_surj _ : is_equivalence (monad.comparison T.adj))⟩ noncomputable instance (G : comonad C) : comonadic_left_adjoint G.forget := ⟨(equivalence.of_fully_faithfully_ess_surj _ : is_equivalence (comonad.comparison G.adj))⟩ -- TODO: This holds more generally for idempotent adjunctions, not just reflective adjunctions. instance μ_iso_of_reflective [reflective R] : is_iso (adjunction.of_right_adjoint R).to_monad.μ := by { dsimp, apply_instance } attribute [instance] monadic_right_adjoint.eqv attribute [instance] comonadic_left_adjoint.eqv namespace reflective instance [reflective R] (X : (adjunction.of_right_adjoint R).to_monad.algebra) : is_iso ((adjunction.of_right_adjoint R).unit.app X.A) := ⟨⟨X.a, ⟨X.unit, begin dsimp only [functor.id_obj], rw ← (adjunction.of_right_adjoint R).unit_naturality, dsimp only [functor.comp_obj, adjunction.to_monad_coe], 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 (adjunction.of_right_adjoint 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, monad_to_functor_eq_coe, adjunction.to_monad_coe], 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 (adjunction.of_right_adjoint R)) := { preimage := λ X Y f, R.preimage f.f } 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.of_fully_faithfully_ess_surj _ } end category_theory
ff54752ec2a369b3667f21f302e90b7f3027d2d9
c062f1c97fdef9ac746f08754e7d766fd6789aa9
/tools/auto/mk_inhabitant.lean
9027cee3214451a24daefc8e63681da55f5be741
[]
no_license
emberian/library_dev
00c7a985b21bdebe912f4127a363f2874e1e7555
f3abd7db0238edc18a397540e361a1da2f51503c
refs/heads/master
1,624,153,474,804
1,490,147,180,000
1,490,147,180,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
533
lean
open tactic /- mk_inthabitant_using A t assumes A is an expression denoting a type. It creates a goal with type A, applies t, and returns the expression that results. -/ meta def mk_inhabitant_using (A : expr) (t : tactic unit) : tactic expr := do m ← mk_meta_var A, gs ← get_goals, set_goals [m], t, r ← instantiate_mvars m, set_goals gs, return r meta def my_tac : tactic expr := do A ← to_expr `(true ∧ true), mk_inhabitant_using A (trace_state >> repeat constructor) run_cmd my_tac >>= trace
b790880865c1d9a3e84ff3497f5869b71f399716
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/playground/lazylist.lean
46b0ac90ea8a9144878b68c99e6449676a16e261
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,623
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 -/ universes u v w inductive LazyList (α : Type u) | nil {} : LazyList | cons (hd : α) (tl : LazyList) : LazyList | delayed (t : Thunk LazyList) : LazyList @[extern cpp inline "#2"] def List.toLazy {α : Type u} : List α → LazyList α | [] := LazyList.nil | (h::t) := LazyList.cons h (List.toLazy t) namespace LazyList variables {α : Type u} {β : Type v} {δ : Type w} instance : Inhabited (LazyList α) := ⟨nil⟩ @[inline] protected def pure : α → LazyList α | a := cons a nil partial def get : LazyList α → LazyList α | (delayed as) := get as.get | other := other partial def isEmpty : LazyList α → Bool | nil := true | (cons _ _) := false | (delayed as) := isEmpty as.get partial def toList : LazyList α → List α | nil := [] | (cons a as) := a :: toList as | (delayed as) := toList as.get partial def head [Inhabited α] : LazyList α → α | nil := default α | (cons a as) := a | (delayed as) := head as.get partial def tail : LazyList α → LazyList α | nil := nil | (cons a as) := as | (delayed as) := tail as.get partial def append : LazyList α → LazyList α → LazyList α | nil bs := bs | (cons a as) bs := cons a (delayed (append as bs)) | (delayed as) bs := append as.get bs instance : Append (LazyList α) := ⟨LazyList.append⟩ partial def interleave : LazyList α → LazyList α → LazyList α | nil bs := bs | (cons a as) bs := cons a (delayed (interleave bs as)) | (delayed as) bs := interleave as.get bs @[specialize] partial def map (f : α → β) : LazyList α → LazyList β | nil := nil | (cons a as) := cons (f a) (delayed (map as)) | (delayed as) := map as.get @[specialize] partial def map₂ (f : α → β → δ) : LazyList α → LazyList β → LazyList δ | nil _ := nil | _ nil := nil | (cons a as) (cons b bs) := cons (f a b) (delayed (map₂ as bs)) | (delayed as) bs := map₂ as.get bs | as (delayed bs) := map₂ as bs.get @[inline] def zip : LazyList α → LazyList β → LazyList (α × β) := map₂ Prod.mk partial def join : LazyList (LazyList α) → LazyList α | nil := nil | (cons a as) := append a (delayed (join as)) | (delayed as) := join as.get @[inline] protected partial def bind (x : LazyList α) (f : α → LazyList β) : LazyList β := join (x.map f) instance isMonad : Monad LazyList := { pure := @LazyList.pure, bind := @LazyList.bind, map := @LazyList.map } instance : Alternative LazyList := { failure := λ _, nil, orelse := @LazyList.append, .. LazyList.isMonad } partial def approx : Nat → LazyList α → List α | 0 as := [] | _ nil := [] | (i+1) (cons a as) := a :: approx i as | (i+1) (delayed as) := approx (i+1) as.get @[specialize] partial def iterate (f : α → α) : α → LazyList α | x := cons x (delayed (iterate (f x))) @[specialize] partial def iterate₂ (f : α → α → α) : α → α → LazyList α | x y := cons x (delayed (iterate₂ y (f x y))) @[specialize] partial def filter (p : α → Bool) : LazyList α → LazyList α | nil := nil | (cons a as) := if p a then cons a (delayed (filter as)) else filter as | (delayed as) := filter as.get partial def cycle : LazyList α → LazyList α | xs := xs ++ delayed (cycle xs) partial def repeat : α → LazyList α | a := cons a (delayed (repeat a)) partial def inits : LazyList α → LazyList (LazyList α) | nil := cons nil nil | (cons a as) := cons nil (delayed (map (λ as, cons a as) (inits as))) | (delayed as) := inits as.get private def addOpenBracket (s : String) : String := if s.isEmpty then "[" else s partial def approxToStringAux [ToString α] : Nat → LazyList α → String → String | _ nil r := (if r.isEmpty then "[" else r) ++ "]" | 0 _ r := (if r.isEmpty then "[" else r) ++ ", ..]" | (n+1) (cons a as) r := approxToStringAux n as ((if r.isEmpty then "[" else r ++ ", ") ++ toString a) | n (delayed as) r := approxToStringAux n as.get r def approxToString [ToString α] (as : LazyList α) (n : Nat := 10) : String := as.approxToStringAux n "" instance [ToString α] : ToString (LazyList α) := ⟨approxToString⟩ end LazyList def fib : LazyList Nat := LazyList.iterate₂ (+) 0 1 def tst : LazyList String := do x ← [1, 2, 3].toLazy, y ← [2, 3, 4].toLazy, -- dbgTrace (toString x ++ " " ++ toString y) $ λ _, guard (x + y > 5), pure (toString x ++ " + " ++ toString y ++ " = " ++ toString (x+y)) open LazyList def iota (i : UInt32 := 0) : LazyList UInt32 := iterate (+1) i set_option pp.implicit true set_option trace.compiler.ir.result true partial def sieve : LazyList UInt32 → LazyList UInt32 | nil := nil | (cons a as) := cons a (delayed (sieve (filter (λ b, b % a != 0) as))) | (delayed as) := sieve as.get partial def primes : LazyList UInt32 := sieve (iota 2) def main : IO Unit := do let n := 10, -- IO.println $ tst.isEmpty, -- IO.println $ [1, 2, 3].toLazy.cycle, -- IO.println $ [1, 2, 3].toLazy.cycle.inits, -- IO.println $ ((iota.filter (λ v, v % 5 == 0)).approx 50000).foldl (+) 0, IO.println $ (primes.approx 2000).foldl (+) 0, -- IO.println $ tst.head, -- IO.println $ fib.interleave (iota.map (+100)), -- IO.println $ ((iota.map (+10)).filter (λ v, v % 2 == 0)), pure ()
243bdc236028100f21f3b6c633fbd9a2f7520229
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/category_theory/natural_isomorphism.lean
6e544304e41de1dda7b27f2b98b241ff3f3f6053
[ "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
5,516
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import category_theory.isomorphism import category_theory.functor_category open category_theory namespace category_theory.nat_iso 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] include 𝒞 𝒟 def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← functor.category.comp_app, iso.hom_inv_id], refl, end, inv_hom_id' := begin rw [← functor.category.comp_app, iso.inv_hom_id], refl, end } @[simp] lemma comp_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : app (α ≪≫ β) X = app α X ≪≫ app β X := rfl @[simp] lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (app α X).hom = α.hom.app X := rfl @[simp] lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (app α X).inv = α.inv.app X := rfl variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := { inv := α.inv.app X, hom_inv_id' := begin rw [←functor.category.comp_app, iso.hom_inv_id, ←functor.category.id_app] end, inv_hom_id' := begin rw [←functor.category.comp_app, iso.inv_hom_id, ←functor.category.id_app] end } instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := { inv := α.hom.app X, hom_inv_id' := begin rw [←functor.category.comp_app, iso.inv_hom_id, ←functor.category.id_app] end, inv_hom_id' := begin rw [←functor.category.comp_app, iso.hom_inv_id, ←functor.category.id_app] end } @[simp] lemma hom_vcomp_inv (α : F ≅ G) : (α.hom ⊟ α.inv) = nat_trans.id _ := begin have h : (α.hom ⊟ α.inv) = α.hom ≫ α.inv := rfl, rw h, rw iso.hom_inv_id, refl end @[simp] lemma inv_vcomp_hom (α : F ≅ G) : (α.inv ⊟ α.hom) = nat_trans.id _ := begin have h : (α.inv ⊟ α.hom) = α.inv ≫ α.hom := rfl, rw h, rw iso.inv_hom_id, refl end @[simp] lemma hom_app_inv_app_id (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 _ := begin rw ←nat_trans.vcomp_app, simp, end @[simp] lemma inv_app_hom_app_id (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 _ := begin rw ←nat_trans.vcomp_app, simp, end variables {X Y : C} @[simp] lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : (α.inv.app X) ≫ (F.map f) ≫ (α.hom.app Y) = G.map f := begin erw [nat_trans.naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end @[simp] lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : (α.hom.app X) ≫ (G.map f) ≫ (α.inv.app Y) = F.map f := begin erw [nat_trans.naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end instance is_iso_of_is_iso_app (α : F ⟶ G) [∀ X : C, is_iso (α.app X)] : is_iso α := { inv := { app := λ X, inv (α.app X), naturality' := λ X Y f, by simpa using congr_arg (λ f, inv (α.app X) ≫ (f ≫ inv (α.app Y))) (α.naturality f).symm } } def of_components (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality : ∀ {X Y : C} (f : X ⟶ Y), (F.map f) ≫ ((app Y).hom) = ((app X).hom) ≫ (G.map f)) : F ≅ G := as_iso { app := λ X, (app X).hom } @[simp] def of_components.app (app' : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : app (of_components app' naturality) X = app' X := by tidy @[simp] def of_components.hom_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).hom.app X = (app X).hom := rfl @[simp] def of_components.inv_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).inv.app X = (app X).inv := rfl end category_theory.nat_iso namespace category_theory.functor universes u₁ u₂ v₁ v₂ section variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 @[simp] protected def id_comp (F : C ⥤ D) : functor.id C ⋙ F ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } @[simp] protected def comp_id (F : C ⥤ D) : F ⋙ functor.id D ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } universes u₃ v₃ u₄ v₄ variables {A : Type u₃} [𝒜 : category.{v₃} A] {B : Type u₄} [ℬ : category.{v₄} B] include 𝒜 ℬ variables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) @[simp] protected def assoc : (F ⋙ G) ⋙ H ≅ F ⋙ (G ⋙ H ):= { hom := { app := λ X, 𝟙 (H.obj (G.obj (F.obj X))) }, inv := { app := λ X, 𝟙 (H.obj (G.obj (F.obj X))) } } -- When it's time to define monoidal categories and 2-categories, -- we'll need to add lemmas relating these natural isomorphisms, -- in particular the pentagon for the associator. end section variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 def ulift_down_up : ulift_down.{v₁} C ⋙ ulift_up C ≅ functor.id (ulift.{u₂} C) := { hom := { app := λ X, @category_struct.id (ulift.{u₂} C) _ X }, inv := { app := λ X, @category_struct.id (ulift.{u₂} C) _ X } } def ulift_up_down : ulift_up.{v₁} C ⋙ ulift_down C ≅ functor.id C := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } } end end category_theory.functor
fa43c8a8a822c51caa1ab51b9629f6f8bbde2134
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/cases_nested.lean
4d1daa0360caf478b17a4894be41fc279c415d0c
[ "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
511
lean
inductive term : Type | var : string → term | app : string → list term → term def cidx : term → nat | (term.var _) := 1 | (term.app _ _) := 2 def to_list : term → list term | (term.app _ ts) := ts | (term.var _) := [] def tid : term → string | (term.var id) := id | (term.app id _) := id lemma ex (t : term) (h : cidx t = 2) : term.app (tid t) (to_list t) = t := begin cases t, {simp [cidx] at h, assert h : 1 ≠ 2, tactic.comp_val, contradiction}, {simp [tid, to_list]} end
babd72a39981d287cd303fce10dbdf0ef9839b1f
82e44445c70db0f03e30d7be725775f122d72f3e
/src/deprecated/group.lean
0b8fb17c1af4ac149f107b3f25da8c55899a73cb
[ "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
13,133
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import algebra.group.type_tags import algebra.group.units_hom import algebra.ring.basic import data.equiv.mul_add /-! # Unbundled monoid and group homomorphisms This file defines predicates for unbundled monoid and group homomorphisms. Though bundled morphisms are preferred in mathlib, these unbundled predicates are still occasionally used in mathlib, and probably will not go away before Lean 4 because Lean 3 often fails to coerce a bundled homomorphism to a function. ## Main Definitions `is_monoid_hom` (deprecated), `is_group_hom` (deprecated) ## Tags is_group_hom, is_monoid_hom -/ universes u v variables {α : Type u} {β : Type v} /-- Predicate for maps which preserve an addition. -/ structure is_add_hom {α β : Type*} [has_add α] [has_add β] (f : α → β) : Prop := (map_add [] : ∀ x y, f (x + y) = f x + f y) /-- Predicate for maps which preserve a multiplication. -/ @[to_additive] structure is_mul_hom {α β : Type*} [has_mul α] [has_mul β] (f : α → β) : Prop := (map_mul [] : ∀ x y, f (x * y) = f x * f y) namespace is_mul_hom variables [has_mul α] [has_mul β] {γ : Type*} [has_mul γ] /-- The identity map preserves multiplication. -/ @[to_additive "The identity map preserves addition"] lemma id : is_mul_hom (id : α → α) := {map_mul := λ _ _, rfl} /-- The composition of maps which preserve multiplication, also preserves multiplication. -/ @[to_additive "The composition of addition preserving maps also preserves addition"] lemma comp {f : α → β} {g : β → γ} (hf : is_mul_hom f) (hg : is_mul_hom g) : is_mul_hom (g ∘ f) := { map_mul := λ x y, by simp only [function.comp, hf.map_mul, hg.map_mul] } /-- A product of maps which preserve multiplication, preserves multiplication when the target is commutative. -/ @[to_additive] lemma mul {α β} [semigroup α] [comm_semigroup β] {f g : α → β} (hf : is_mul_hom f) (hg : is_mul_hom g) : is_mul_hom (λ a, f a * g a) := { map_mul := λ a b, by simp only [hf.map_mul, hg.map_mul, mul_comm, mul_assoc, mul_left_comm] } /-- The inverse of a map which preserves multiplication, preserves multiplication when the target is commutative. -/ @[to_additive] lemma inv {α β} [has_mul α] [comm_group β] {f : α → β} (hf : is_mul_hom f) : is_mul_hom (λ a, (f a)⁻¹) := { map_mul := λ a b, (hf.map_mul a b).symm ▸ mul_inv _ _ } end is_mul_hom /-- Predicate for add_monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/ structure is_add_monoid_hom [add_zero_class α] [add_zero_class β] (f : α → β) extends is_add_hom f : Prop := (map_zero [] : f 0 = 0) /-- Predicate for monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/ @[to_additive] structure is_monoid_hom [mul_one_class α] [mul_one_class β] (f : α → β) extends is_mul_hom f : Prop := (map_one [] : f 1 = 1) namespace monoid_hom variables {M : Type*} {N : Type*} [mM : mul_one_class M] [mN : mul_one_class N] include mM mN /-- Interpret a map `f : M → N` as a homomorphism `M →* N`. -/ @[to_additive "Interpret a map `f : M → N` as a homomorphism `M →+ N`."] def of {f : M → N} (h : is_monoid_hom f) : M →* N := { to_fun := f, map_one' := h.2, map_mul' := h.1.1 } variables {mM mN} @[simp, to_additive] lemma coe_of {f : M → N} (hf : is_monoid_hom f) : ⇑ (monoid_hom.of hf) = f := rfl @[to_additive] lemma is_monoid_hom_coe (f : M →* N) : is_monoid_hom (f : M → N) := { map_mul := f.map_mul, map_one := f.map_one } end monoid_hom namespace mul_equiv variables {M : Type*} {N : Type*} [mul_one_class M] [mul_one_class N] /-- A multiplicative isomorphism preserves multiplication (deprecated). -/ @[to_additive] theorem is_mul_hom (h : M ≃* N) : is_mul_hom h := ⟨h.map_mul⟩ /-- A multiplicative bijection between two monoids is a monoid hom (deprecated -- use `mul_equiv.to_monoid_hom`). -/ @[to_additive] lemma is_monoid_hom (h : M ≃* N) : is_monoid_hom h := { map_mul := h.map_mul, map_one := h.map_one } end mul_equiv namespace is_monoid_hom variables [mul_one_class α] [mul_one_class β] {f : α → β} (hf : is_monoid_hom f) /-- A monoid homomorphism preserves multiplication. -/ @[to_additive] lemma map_mul (x y) : f (x * y) = f x * f y := hf.map_mul x y /-- The inverse of a map which preserves multiplication, preserves multiplication when the target is commutative. -/ @[to_additive] lemma inv {α β} [mul_one_class α] [comm_group β] {f : α → β} (hf : is_monoid_hom f) : is_monoid_hom (λ a, (f a)⁻¹) := { map_one := hf.map_one.symm ▸ one_inv, map_mul := λ a b, (hf.map_mul a b).symm ▸ mul_inv _ _ } end is_monoid_hom /-- A map to a group preserving multiplication is a monoid homomorphism. -/ @[to_additive] theorem is_mul_hom.to_is_monoid_hom [mul_one_class α] [group β] {f : α → β} (hf : is_mul_hom f) : is_monoid_hom f := { map_one := mul_right_eq_self.1 $ by rw [← hf.map_mul, one_mul], map_mul := hf.map_mul } namespace is_monoid_hom variables [mul_one_class α] [mul_one_class β] {f : α → β} /-- The identity map is a monoid homomorphism. -/ @[to_additive] lemma id : is_monoid_hom (@id α) := { map_one := rfl, map_mul := λ _ _, rfl } /-- The composite of two monoid homomorphisms is a monoid homomorphism. -/ @[to_additive] lemma comp (hf : is_monoid_hom f) {γ} [mul_one_class γ] {g : β → γ} (hg : is_monoid_hom g) : is_monoid_hom (g ∘ f) := { map_one := show g _ = 1, by rw [hf.map_one, hg.map_one], ..is_mul_hom.comp hf.to_is_mul_hom hg.to_is_mul_hom } end is_monoid_hom namespace is_add_monoid_hom /-- Left multiplication in a ring is an additive monoid morphism. -/ lemma is_add_monoid_hom_mul_left {γ : Type*} [non_unital_non_assoc_semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, x * y) := { map_zero := mul_zero x, map_add := λ y z, mul_add x y z } /-- Right multiplication in a ring is an additive monoid morphism. -/ lemma is_add_monoid_hom_mul_right {γ : Type*} [non_unital_non_assoc_semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, y * x) := { map_zero := zero_mul x, map_add := λ y z, add_mul y z x } end is_add_monoid_hom /-- Predicate for additive group homomorphism (deprecated -- use bundled `monoid_hom`). -/ structure is_add_group_hom [add_group α] [add_group β] (f : α → β) extends is_add_hom f : Prop /-- Predicate for group homomorphisms (deprecated -- use bundled `monoid_hom`). -/ @[to_additive] structure is_group_hom [group α] [group β] (f : α → β) extends is_mul_hom f : Prop @[to_additive] lemma monoid_hom.is_group_hom {G H : Type*} {_ : group G} {_ : group H} (f : G →* H) : is_group_hom (f : G → H) := { map_mul := f.map_mul } @[to_additive] lemma mul_equiv.is_group_hom {G H : Type*} {_ : group G} {_ : group H} (h : G ≃* H) : is_group_hom h := { map_mul := h.map_mul } /-- Construct `is_group_hom` from its only hypothesis. -/ @[to_additive] lemma is_group_hom.mk' [group α] [group β] {f : α → β} (hf : ∀ x y, f (x * y) = f x * f y) : is_group_hom f := { map_mul := hf } namespace is_group_hom variables [group α] [group β] {f : α → β} (hf : is_group_hom f) open is_mul_hom (map_mul) lemma map_mul : ∀ (x y), f (x * y) = f x * f y := hf.to_is_mul_hom.map_mul /-- A group homomorphism is a monoid homomorphism. -/ @[to_additive] lemma to_is_monoid_hom : is_monoid_hom f := hf.to_is_mul_hom.to_is_monoid_hom /-- A group homomorphism sends 1 to 1. -/ @[to_additive] lemma map_one : f 1 = 1 := hf.to_is_monoid_hom.map_one /-- A group homomorphism sends inverses to inverses. -/ @[to_additive] theorem map_inv (hf : is_group_hom f) (a : α) : f a⁻¹ = (f a)⁻¹ := eq_inv_of_mul_eq_one $ by rw [← hf.map_mul, inv_mul_self, hf.map_one] /-- The identity is a group homomorphism. -/ @[to_additive] lemma id : is_group_hom (@id α) := { map_mul := λ _ _, rfl} /-- The composition of two group homomorphisms is a group homomorphism. -/ @[to_additive] lemma comp (hf : is_group_hom f) {γ} [group γ] {g : β → γ} (hg : is_group_hom g) : is_group_hom (g ∘ f) := { ..is_mul_hom.comp hf.to_is_mul_hom hg.to_is_mul_hom } /-- A group homomorphism is injective iff its kernel is trivial. -/ @[to_additive] lemma injective_iff {f : α → β} (hf : is_group_hom f) : function.injective f ↔ (∀ a, f a = 1 → a = 1) := ⟨λ h _, by rw ← hf.map_one; exact @h _ _, λ h x y hxy, by rw [← inv_inv (f x), inv_eq_iff_mul_eq_one, ← hf.map_inv, ← hf.map_mul] at hxy; simpa using inv_eq_of_mul_eq_one (h _ hxy)⟩ /-- The product of group homomorphisms is a group homomorphism if the target is commutative. -/ @[to_additive] lemma mul {α β} [group α] [comm_group β] {f g : α → β} (hf : is_group_hom f) (hg : is_group_hom g) : is_group_hom (λa, f a * g a) := { map_mul := (hf.to_is_mul_hom.mul hg.to_is_mul_hom).map_mul } /-- The inverse of a group homomorphism is a group homomorphism if the target is commutative. -/ @[to_additive] lemma inv {α β} [group α] [comm_group β] {f : α → β} (hf : is_group_hom f) : is_group_hom (λa, (f a)⁻¹) := { map_mul := hf.to_is_mul_hom.inv.map_mul } end is_group_hom namespace ring_hom /-! These instances look redundant, because `deprecated.ring` provides `is_ring_hom` for a `→+*`. Nevertheless these are harmless, and helpful for stripping out dependencies on `deprecated.ring`. -/ variables {R : Type*} {S : Type*} section variables [non_assoc_semiring R] [non_assoc_semiring S] lemma to_is_monoid_hom (f : R →+* S) : is_monoid_hom f := { map_one := f.map_one, map_mul := f.map_mul } lemma to_is_add_monoid_hom (f : R →+* S) : is_add_monoid_hom f := { map_zero := f.map_zero, map_add := f.map_add } end section variables [ring R] [ring S] lemma to_is_add_group_hom (f : R →+* S) : is_add_group_hom f := { map_add := f.map_add } end end ring_hom /-- Inversion is a group homomorphism if the group is commutative. -/ @[to_additive neg.is_add_group_hom "Negation is an `add_group` homomorphism if the `add_group` is commutative."] lemma inv.is_group_hom [comm_group α] : is_group_hom (has_inv.inv : α → α) := { map_mul := mul_inv } namespace is_add_group_hom variables [add_group α] [add_group β] {f : α → β} (hf : is_add_group_hom f) /-- Additive group homomorphisms commute with subtraction. -/ lemma map_sub (a b) : f (a - b) = f a - f b := calc f (a - b) = f (a + -b) : congr_arg f (sub_eq_add_neg a b) ... = f a + f (-b) : hf.map_add _ _ ... = f a + -f b : by rw [hf.map_neg] ... = f a - f b : (sub_eq_add_neg _ _).symm end is_add_group_hom /-- The difference of two additive group homomorphisms is an additive group homomorphism if the target is commutative. -/ lemma is_add_group_hom.sub {α β} [add_group α] [add_comm_group β] {f g : α → β} (hf : is_add_group_hom f) (hg : is_add_group_hom g) : is_add_group_hom (λa, f a - g a) := by simpa only [sub_eq_add_neg] using hf.add hg.neg namespace units variables {M : Type*} {N : Type*} [monoid M] [monoid N] /-- The group homomorphism on units induced by a multiplicative morphism. -/ @[reducible] def map' {f : M → N} (hf : is_monoid_hom f) : units M →* units N := map (monoid_hom.of hf) @[simp] lemma coe_map' {f : M → N} (hf : is_monoid_hom f) (x : units M) : ↑((map' hf : units M → units N) x) = f x := rfl lemma coe_is_monoid_hom : is_monoid_hom (coe : units M → M) := (coe_hom M).is_monoid_hom_coe end units namespace is_unit variables {M : Type*} {N : Type*} [monoid M] [monoid N] {x : M} lemma map' {f : M → N} (hf :is_monoid_hom f) {x : M} (h : is_unit x) : is_unit (f x) := h.map (monoid_hom.of hf) end is_unit lemma additive.is_add_hom [has_mul α] [has_mul β] {f : α → β} (hf : is_mul_hom f) : @is_add_hom (additive α) (additive β) _ _ f := { map_add := is_mul_hom.map_mul hf } lemma multiplicative.is_mul_hom [has_add α] [has_add β] {f : α → β} (hf : is_add_hom f) : @is_mul_hom (multiplicative α) (multiplicative β) _ _ f := { map_mul := is_add_hom.map_add hf } -- defeq abuse lemma additive.is_add_monoid_hom [mul_one_class α] [mul_one_class β] {f : α → β} (hf : is_monoid_hom f) : @is_add_monoid_hom (additive α) (additive β) _ _ f := { map_zero := hf.map_one, ..additive.is_add_hom hf.to_is_mul_hom } lemma multiplicative.is_monoid_hom [add_zero_class α] [add_zero_class β] {f : α → β} (hf : is_add_monoid_hom f) : @is_monoid_hom (multiplicative α) (multiplicative β) _ _ f := { map_one := is_add_monoid_hom.map_zero hf, ..multiplicative.is_mul_hom hf.to_is_add_hom } lemma additive.is_add_group_hom [group α] [group β] {f : α → β} (hf : is_group_hom f) : @is_add_group_hom (additive α) (additive β) _ _ f := { map_add := hf.to_is_mul_hom.map_mul } lemma multiplicative.is_group_hom [add_group α] [add_group β] {f : α → β} (hf : is_add_group_hom f) : @is_group_hom (multiplicative α) (multiplicative β) _ _ f := { map_mul := hf.to_is_add_hom.map_add }
97c20de6251e847553da3d42878cc2baec17e0af
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/hints/thursday/afternoon/category_theory/exercise2/hint6.lean
5b7f9f4849eaf5ff69513116d94bb68b3b296c2b
[]
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
898
lean
import algebra.category.CommRing.basic import data.polynomial noncomputable theory -- the default implementation of polynomials is noncomputable local attribute [irreducible] polynomial.eval₂ def Ring.polynomial : Ring ⥤ Ring := { obj := λ R, Ring.of (polynomial R), map := λ R S f, ring_hom.of (polynomial.map f), } def CommRing.polynomial : CommRing ⥤ CommRing := { obj := λ R, CommRing.of (polynomial R), map := λ R S f, ring_hom.of (polynomial.map f), } open category_theory def commutes : (forget₂ CommRing Ring) ⋙ Ring.polynomial ≅ CommRing.polynomial ⋙ (forget₂ CommRing Ring) := -- We're trying to construct an isomorphism between functors here, -- so let's just set up a stub for the structure: { hom := { app := sorry, naturality' := sorry, }, inv := { app := sorry, naturality' := sorry }, hom_inv_id' := sorry, inv_hom_id' := sorry, }.
a6f4ea6b658c9ad6db4869174184f07a8353c775
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0502.lean
26df9706122226494c7b6c176f0fb9f2dbe4b9d3
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
238
lean
variable f : ℕ → ℕ variable h : ∀ x : ℕ, f x ≤ f (x + 1) example : f 0 ≤ f 3 := have f 0 ≤ f 1, from h 0, have f 0 ≤ f 2, from le_trans (by assumption) (h 1), show f 0 ≤ f 3, from le_trans (by assumption) (h 2)
de9b1df3d9fd588743751a5703c517507f8e7e34
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/bounded_lattice.lean
a4d1287b22baead5a16f9b52cf68beb1ed8cecfe
[ "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
46,934
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 order.lattice import data.option.basic import tactic.pi_instances import logic.nontrivial /-! # ⊤ and ⊥, bounded lattices and variants This file defines top and bottom elements (greatest and least elements) of a type, the bounded variants of different kinds of lattices, sets up the typeclass hierarchy between them and provides instances for `Prop` and `fun`. ## Main declarations * `has_<top/bot> α`: Typeclasses to declare the `⊤`/`⊥` notation. * `order_<top/bot> α`: Order with a top/bottom element. * `with_<top/bot> α`: Equips `option α` with the order on `α` plus `none` as the top/bottom element. * `semilattice_<sup/inf>_<top/bot>`: Semilattice with a join/meet and a top/bottom element (all four combinations). Typical examples include `ℕ`. * `bounded_lattice α`: Lattice with a top and bottom element. * `bounded_distrib_lattice α`: Bounded and distributive lattice. Typical examples include `Prop` and `set α`. * `is_compl x y`: In a bounded lattice, predicate for "`x` is a complement of `y`". Note that in a non distributive lattice, an element can have several complements. * `is_complemented α`: Typeclass stating that any element of a lattice has a complement. -/ /-! ### Top, bottom element -/ set_option old_structure_cmd true universes u v variables {α : Type u} {β : Type v} /-- Typeclass for the `⊤` (`\top`) notation -/ class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top notation `⊥` := has_bot.bot @[priority 100] instance has_top_nonempty (α : Type u) [has_top α] : nonempty α := ⟨⊤⟩ @[priority 100] instance has_bot_nonempty (α : Type u) [has_bot α] : nonempty α := ⟨⊥⟩ attribute [pattern] has_bot.bot has_top.top /-- An `order_top` is a partial order with a greatest element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α := (le_top : ∀ a : α, a ≤ ⊤) section order_top variables [order_top α] {a b : α} @[simp] theorem le_top : a ≤ ⊤ := order_top.le_top a theorem top_unique (h : ⊤ ≤ a) : a = ⊤ := le_top.antisymm h -- TODO: delete in favor of the next? theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨λ eq, eq.symm ▸ le_refl ⊤, top_unique⟩ @[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ @[simp] theorem not_top_lt : ¬ ⊤ < a := λ h, lt_irrefl a (lt_of_le_of_lt le_top h) theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_le_iff.1 $ h₂ ▸ h lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := le_top.lt_iff_ne lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := λ ha, hb $ top_unique $ ha ▸ hab lemma eq_top_of_maximal (h : ∀ b, ¬ a < b) : a = ⊤ := or.elim (lt_or_eq_of_le le_top) (λ hlt, absurd hlt (h ⊤)) (λ he, he) end order_top lemma strict_mono.top_preimage_top' [linear_order α] [order_top β] {f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) : x ≤ a := H.top_preimage_top (λ p, by { rw h_top, exact le_top }) x theorem order_top.ext_top {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_top.ext_top H, casesI A, casesI B, injection this; congr' end /-- An `order_bot` is a partial order with a least element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot variables [order_bot α] {a b : α} @[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique (h : a ≤ ⊥) : a = ⊥ := h.antisymm bot_le -- TODO: delete? theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨λ eq, eq.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, λ h, h.symm ▸ le_refl ⊥⟩ @[simp] theorem not_lt_bot : ¬ a < ⊥ := λ h, lt_irrefl a (lt_of_lt_of_le h bot_le) theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := λ ha, hb $ bot_unique $ ha ▸ hab theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := le_bot_iff.1 $ h₂ ▸ h lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := begin haveI := classical.dec_eq α, haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff, simp only [lt_iff_le_not_le, not_iff_not.mpr le_bot_iff, true_and, bot_le], end lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h lemma eq_bot_of_minimal (h : ∀ b, ¬ b < a) : a = ⊥ := or.elim (lt_or_eq_of_le bot_le) (λ hlt, absurd hlt (h ⊥)) (λ he, he.symm) end order_bot lemma strict_mono.bot_preimage_bot' [linear_order α] [order_bot β] {f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) : a ≤ x := H.bot_preimage_bot (λ p, by { rw h_bot, exact bot_le }) x theorem order_bot.ext_bot {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection this; congr' end /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α section semilattice_sup_top variables [semilattice_sup_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α section semilattice_sup_bot variables [semilattice_sup_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := { bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice } /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α section semilattice_inf_top variables [semilattice_inf_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α section semilattice_inf_bot variables [semilattice_inf_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /-! ### Bounded lattice -/ /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { le_top := λ x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bot_le := λ x, @bot_le α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { le_top := λ x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bot_le := λ x, @bot_le α _ x, ..bl } theorem bounded_lattice.ext {α} {A B : bounded_lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, have H2 := order_bot.ext H, have H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection H1; injection H2; injection H3; congr' end /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨λ h, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [h, inf_le_right], λ h, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by { rw inf_comm, exact inf_le_inf_left _ h } ... = ⊥ : h₂⟩ /-- Propositions form a bounded distributive lattice. -/ instance bounded_distrib_lattice_Prop : bounded_distrib_lattice Prop := { le := λ a b, a → b, le_refl := λ _, id, le_trans := λ a b c f g, g ∘ f, le_antisymm := λ a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := λ a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := λ a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), le_sup_inf := λ a b c H, or_iff_not_imp_left.2 $ λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩, top := true, le_top := λ a Ha, true.intro, bot := false, bot_le := @false.elim } noncomputable instance Prop.linear_order : linear_order Prop := { le_total := by intros p q; change (p → q) ∨ (q → p); tauto!, decidable_le := classical.dec_rel _, .. (_ : partial_order Prop) } @[simp] lemma le_Prop_eq : ((≤) : Prop → Prop → Prop) = (→) := rfl @[simp] lemma sup_Prop_eq : (⊔) = (∨) := rfl @[simp] lemma inf_Prop_eq : (⊓) = (∧) := rfl section logic variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λ x, p x ∧ q x) := λ a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λ x, p x ∨ q x) := λ a b h, or.imp (m_p h) (m_q h) end logic instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) := { bot := λ _, ⊥, bot_le := λ x a, bot_le, .. pi.partial_order } /-! ### Function lattices -/ instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) := ⟨λ i, ⊥⟩ @[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) : (⊥ : Π i, α i) i = ⊥ := rfl instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) := ⟨λ i, ⊤⟩ @[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) : (⊤ : Π i, α i) i = ⊤ := rfl instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] : semilattice_sup (Π i, α i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] : semilattice_inf (Π i, α i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] : semilattice_inf_bot (Π i, α i) := by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] : semilattice_inf_top (Π i, α i) := by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] : semilattice_sup_bot (Π i, α i) := by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] : semilattice_sup_top (Π i, α i) := by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] : bounded_lattice (Π i, α i) := { .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot } lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊥ : α) := eq_bot_mono le_top (eq.symm hα) lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊤ : α) := eq_top_mono bot_le hα lemma subsingleton_of_top_le_bot {α : Type*} [bounded_lattice α] (h : (⊤ : α) ≤ (⊥ : α)) : subsingleton α := ⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩ lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) : subsingleton α := subsingleton_of_top_le_bot (ge_of_eq hα) lemma subsingleton_iff_bot_eq_top {α : Type*} [bounded_lattice α] : (⊥ : α) = (⊤ : α) ↔ subsingleton α := ⟨subsingleton_of_bot_eq_top, λ h, by exactI subsingleton.elim ⊥ ⊤⟩ /-! ### `with_bot`, `with_top` -/ /-- Attach `⊥` to a type. -/ def with_bot (α : Type*) := option α namespace with_bot meta instance {α} [has_to_format α] : has_to_format (with_bot α) := { to_format := λ x, match x with | none := "⊥" | (some x) := to_fmt x end } instance : has_coe_t α (with_bot α) := ⟨some⟩ instance has_bot : has_bot (with_bot α) := ⟨none⟩ instance : inhabited (with_bot α) := ⟨⊥⟩ lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl /-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/ @[elab_as_eliminator] def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) : Π (n : with_bot α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[priority 10] instance has_lt [has_lt α] : has_lt (with_bot α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := by simp [(<)] lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a := ⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩ lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a instance : can_lift (with_bot α) α := { coe := coe, cond := λ r, r ≠ ⊥, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } instance [preorder α] : preorder (with_bot α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b, lt := (<), lt_iff_le_not_le := by intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<)]; split; refl, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩ } instance partial_order [partial_order α] : partial_order (with_bot α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_bot.preorder } instance order_bot [partial_order α] : order_bot (with_bot α) := { bot_le := λ a a' h, option.no_confusion h, ..with_bot.partial_order, ..with_bot.has_bot } @[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} : (a : with_bot α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩ @[simp] theorem some_le_some [preorder α] {a b : α} : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem coe_le [partial_order α] {a b : α} : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b | (some a) b := le_refl a | none b := λ _ h, option.no_confusion h @[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl lemma get_or_else_bot_le_iff [order_bot α] {a : with_bot α} {b : α} : a.get_or_else ⊥ ≤ b ↔ a ≤ b := by cases a; simp [none_eq_bot, some_eq_coe] instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤) | none x := is_true $ λ a h, option.no_confusion h | (some x) (some y) := if h : x ≤ y then is_true (some_le_some.2 h) else is_false $ by simp * | (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩ instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<) | none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩ | (some x) (some y) := if h : x < y then is_true $ by simp * else is_false $ by simp * | x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩ instance [partial_order α] [is_total α (≤)] : is_total (with_bot α) (≤) := { total := λ a b, match a, b with | none , _ := or.inl bot_le | _ , none := or.inr bot_le | some x, some y := by simp only [some_le_some, total_of] end } instance linear_order [linear_order α] : linear_order (with_bot α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inl bot_le}, cases o₂ with b, {exact or.inr bot_le}, simp [le_total] end, decidable_le := with_bot.decidable_le, decidable_lt := with_bot.decidable_lt, ..with_bot.partial_order } instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_bot α) = a ⊔ b := rfl instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_bot α) = a ⊓ b := rfl instance lattice [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_bot.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_bot α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_bot α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] @[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_bot α) = min x y := by simp [min, ite_cast] @[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_bot α) = max x y := by simp [max, ite_cast] instance order_top [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩, ..with_bot.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) := { ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot } lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_bot α → with_bot α → Prop) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] : densely_ordered (with_bot α) := ⟨ λ a b, match a, b with | a, none := λ h : a < ⊥, (not_lt_bot h).elim | none, some b := λ h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩ | some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot /-- Attach `⊤` to a type. -/ def with_top (α : Type*) := option α namespace with_top meta instance {α} [has_to_format α] : has_to_format (with_top α) := { to_format := λ x, match x with | none := "⊤" | (some x) := to_fmt x end } instance : has_coe_t α (with_top α) := ⟨some⟩ instance has_top : has_top (with_top α) := ⟨none⟩ instance : inhabited (with_top α) := ⟨⊤⟩ lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl /-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/ @[elab_as_eliminator] def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) : Π (n : with_top α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) . @[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ . @[priority 10] instance has_lt [has_lt α] : has_lt (with_top α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a } @[priority 10] instance has_le [has_le α] : has_le (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := by simp [(<)] @[simp] theorem some_le_some [has_le α] {a b : α} : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := by simp [(≤)] @[simp] theorem le_none [has_le α] {a : with_top α} : @has_le.le (with_top α) _ a none := by simp [(≤)] @[simp] theorem some_lt_none [has_lt α] {a : α} : @has_lt.lt (with_top α) _ (some a) none := by simp [(<)]; existsi a; refl instance : can_lift (with_top α) α := { coe := coe, cond := λ r, r ≠ ⊤, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } instance [preorder α] : preorder (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a, lt := (<), lt_iff_le_not_le := by { intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<),(≤)] }, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc, let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in ⟨a, ha, le_trans ab bc⟩, } instance partial_order [partial_order α] : partial_order (with_top α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₂ with b, { cases o₁ with a, {refl}, rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩, rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_top.preorder } instance order_top [partial_order α] : order_top (with_top α) := { le_top := λ a a' h, option.no_confusion h, ..with_top.partial_order, .. with_top.has_top } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_top α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩ theorem le_coe [partial_order α] {a b : α} : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b) | (some a) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b) | (some b) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b) | (some a) b := by simp [some_eq_coe, coe_eq_coe] | none b := by simp [none_eq_top] @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := some_lt_none theorem coe_lt_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b) | (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe] | none := by simp [none_eq_top, coe_lt_top] lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a := λ h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) := λ x y, @with_bot.decidable_le (order_dual α) _ _ y x instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) := λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x instance [partial_order α] [is_total α (≤)] : is_total (with_top α) (≤) := { total := λ a b, match a, b with | none , _ := or.inr le_top | _ , none := or.inl le_top | some x, some y := by simp only [some_le_some, total_of] end } instance linear_order [linear_order α] : linear_order (with_top α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inr le_top}, cases o₂ with b, {exact or.inl le_top}, simp [le_total] end, decidable_le := with_top.decidable_le, decidable_lt := with_top.decidable_lt, ..with_top.partial_order } instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.order_top } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.order_top } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl instance lattice [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_top.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_top α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_top α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] @[simp, norm_cast] lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_top α) = min x y := by simp [min, ite_cast] @[simp, norm_cast] lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_top α) = max x y := by simp [max, ite_cast] instance order_bot [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩, ..with_top.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) := { ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_top α → with_top α → Prop) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] : densely_ordered (with_top α) := ⟨ λ a b, match a, b with | none, a := λ h : ⊤ < a, (not_top_lt h).elim | some a, none := λ h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩ | some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α] {a b : with_top α} : (a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) := ⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩, λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩ end with_top /-! ### Subtype, order dual, product lattices -/ namespace subtype /-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/ protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop} (Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/ protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop} (Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a `⊔`-`⊤`-semilattice if `⊤` and `⊔` preserve the property. -/ protected def semilattice_sup_top [semilattice_sup_top α] {P : α → Prop} (Ptop : P ⊤) (Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)) : semilattice_sup_top {x : α // P x} := { top := ⟨⊤, Ptop⟩, le_top := λ x, @le_top α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. -/ protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop} (Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} := { top := ⟨⊤, Ptop⟩, le_top := λ x, @le_top α _ x, ..subtype.semilattice_inf Pinf } end subtype namespace order_dual variable (α) instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩ instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩ instance [order_bot α] : order_top (order_dual α) := { le_top := @bot_le α _, .. order_dual.partial_order α, .. order_dual.has_top α } instance [order_top α] : order_bot (order_dual α) := { bot_le := @le_top α _, .. order_dual.partial_order α, .. order_dual.has_bot α } instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_top α } instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_bot α } instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_top α } instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_bot α } instance [bounded_lattice α] : bounded_lattice (order_dual α) := { .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α } instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) := { .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α } end order_dual namespace prod variables (α β) instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩ instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩ instance [order_top α] [order_top β] : order_top (α × β) := { le_top := λ a, ⟨le_top, le_top⟩, .. prod.partial_order α β, .. prod.has_top α β } instance [order_bot α] [order_bot β] : order_bot (α × β) := { bot_le := λ a, ⟨bot_le, bot_le⟩, .. prod.partial_order α β, .. prod.has_bot α β } instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) := { .. prod.semilattice_sup α β, .. prod.order_top α β } instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) := { .. prod.semilattice_inf α β, .. prod.order_top α β } instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) := { .. prod.semilattice_sup α β, .. prod.order_bot α β } instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) := { .. prod.semilattice_inf α β, .. prod.order_bot α β } instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) := { .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β } instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] : bounded_distrib_lattice (α × β) := { .. prod.bounded_lattice α β, .. prod.distrib_lattice α β } end prod /-! ### Disjointness and complements -/ section disjoint section semilattice_inf_bot variable [semilattice_inf_bot α] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ := eq_bot_iff.2 h theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ := eq_bot_iff.symm theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] @[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a := disjoint.comm.1 @[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := inf_le_left @[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := inf_le_right theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h (le_refl _) theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint.mono (le_refl _) h @[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ := by simp [disjoint] lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := by { intro h, rw [←h, disjoint_self] at hab, exact ha hab } lemma disjoint.eq_bot_of_le {a b : α} (hab : disjoint a b) (h : a ≤ b) : a = ⊥ := eq_bot_iff.2 (by rwa ←inf_eq_left.2 h) lemma disjoint.of_disjoint_inf_of_le {a b c : α} (h : disjoint (a ⊓ b) c) (hle : a ≤ c) : disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_left.trans hle)] lemma disjoint.of_disjoint_inf_of_le' {a b c : α} (h : disjoint (a ⊓ b) c) (hle : b ≤ c) : disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_right.trans hle)] end semilattice_inf_bot section bounded_lattice variables [bounded_lattice α] {a : α} @[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff] @[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff] lemma eq_bot_of_disjoint_absorbs {a b : α} (w : disjoint a b) (h : a ⊔ b = a) : b = ⊥ := begin rw disjoint_iff at w, rw [←w, right_eq_inf], rwa sup_eq_left at h, end end bounded_lattice section bounded_distrib_lattice /- TODO: these lemmas don't require the existence of `⊤` and should be generalized to distrib_lattice_with_bot (which doesn't exist yet). -/ variables [bounded_distrib_lattice α] {a b c : α} @[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c := by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff] @[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c := by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff] lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c := disjoint_sup_left.2 ⟨ha, hb⟩ lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) := disjoint_sup_right.2 ⟨hb, hc⟩ lemma disjoint.left_le_of_le_sup_right {a b c : α} (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b := (λ x, le_of_inf_le_sup_le x (sup_le h le_sup_right)) ((disjoint_iff.mp hd).symm ▸ bot_le) lemma disjoint.left_le_of_le_sup_left {a b c : α} (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b := @le_of_inf_le_sup_le _ _ a b c ((disjoint_iff.mp hd).symm ▸ bot_le) ((@sup_comm _ _ c b) ▸ (sup_le h le_sup_left)) end bounded_distrib_lattice end disjoint section is_compl /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ structure is_compl [bounded_lattice α] (x y : α) : Prop := (inf_le_bot : x ⊓ y ≤ ⊥) (top_le_sup : ⊤ ≤ x ⊔ y) namespace is_compl section bounded_lattice variables [bounded_lattice α] {x y z : α} protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1 @[symm] protected lemma symm (h : is_compl x y) : is_compl y x := ⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩ lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := ⟨le_of_eq h₁, le_of_eq h₂.symm⟩ lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩ end bounded_lattice variables [bounded_distrib_lattice α] {x y z : α} lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z := inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y := h.symm.inf_left_eq_bot_iff lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z := by { rw disjoint_iff, exact h.inf_left_eq_bot_iff } lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y := h.symm.disjoint_left_iff lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y := h.disjoint_right_iff.symm lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x := h.symm.le_left_iff lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y := h.to_order_dual.le_left_iff lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x := h.symm.left_le_iff lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _) lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x) lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) : x = y := hxz.symm.right_unique hyz.symm lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm end is_compl lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq section variables [bounded_lattice α] {x : α} lemma eq_top_of_is_compl_bot (h : is_compl x ⊥) : x = ⊤ := sup_bot_eq.symm.trans h.sup_eq_top lemma eq_top_of_bot_is_compl (h : is_compl ⊥ x) : x = ⊤ := eq_top_of_is_compl_bot h.symm lemma eq_bot_of_is_compl_top (h : is_compl x ⊤) : x = ⊥ := eq_top_of_is_compl_bot h.to_order_dual lemma eq_bot_of_top_is_compl (h : is_compl ⊤ x) : x = ⊥ := eq_top_of_bot_is_compl h.to_order_dual end /-- A complemented bounded lattice is one where every element has a (not necessarily unique) complement. -/ class is_complemented (α) [bounded_lattice α] : Prop := (exists_is_compl : ∀ (a : α), ∃ (b : α), is_compl a b) export is_complemented (exists_is_compl) namespace is_complemented variables [bounded_lattice α] [is_complemented α] instance : is_complemented (order_dual α) := ⟨λ a, let ⟨b, hb⟩ := exists_is_compl (show α, from a) in ⟨b, hb.to_order_dual⟩⟩ end is_complemented end is_compl section nontrivial variables [bounded_lattice α] [nontrivial α] lemma bot_ne_top : (⊥ : α) ≠ ⊤ := λ H, not_nontrivial_iff_subsingleton.mpr (subsingleton_of_bot_eq_top H) ‹_› lemma top_ne_bot : (⊤ : α) ≠ ⊥ := ne.symm bot_ne_top end nontrivial namespace bool -- Could be generalised to `bounded_distrib_lattice` and `is_complemented` instance : bounded_lattice bool := { top := tt, le_top := λ x, le_tt, bot := ff, bot_le := λ x, ff_le, .. (infer_instance : lattice bool)} end bool section bool @[simp] lemma top_eq_tt : ⊤ = tt := rfl @[simp] lemma bot_eq_ff : ⊥ = ff := rfl end bool
377a46280291927da9fe3c11691d8500409f3736
4727251e0cd73359b15b664c3170e5d754078599
/src/control/traversable/lemmas.lean
2a4134ddcbfdc3a48dab2603bbdaaab32c01e443
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,857
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.applicative import control.traversable.basic /-! # Traversing collections This file proves basic properties of traversable and applicative functors and defines `pure_transformation F`, the natural applicative transformation from the identity functor to `F`. ## References Inspired by [The Essence of the Iterator Pattern][gibbons2009]. -/ universes u open is_lawful_traversable open function (hiding comp) open functor attribute [functor_norm] is_lawful_traversable.naturality attribute [simp] is_lawful_traversable.id_traverse namespace traversable variable {t : Type u → Type u} variables [traversable t] [is_lawful_traversable t] variables F G : Type u → Type u variables [applicative F] [is_lawful_applicative F] variables [applicative G] [is_lawful_applicative G] variables {α β γ : Type u} variables g : α → F β variables h : β → G γ variables f : β → γ /-- The natural applicative transformation from the identity functor to `F`, defined by `pure : Π {α}, α → F α`. -/ def pure_transformation : applicative_transformation id F := { app := @pure F _, preserves_pure' := λ α x, rfl, preserves_seq' := λ α β f x, by { simp only [map_pure, seq_pure], refl } } @[simp] theorem pure_transformation_apply {α} (x : id α) : pure_transformation F x = pure x := rfl variables {F G} (x : t β) lemma map_eq_traverse_id : map f = @traverse t _ _ _ _ _ (id.mk ∘ f) := funext $ λ y, (traverse_eq_map_id f y).symm theorem map_traverse (x : t α) : map f <$> traverse g x = traverse (map f ∘ g) x := begin rw @map_eq_traverse_id t _ _ _ _ f, refine (comp_traverse (id.mk ∘ f) g x).symm.trans _, congr, apply comp.applicative_comp_id end theorem traverse_map (f : β → F γ) (g : α → β) (x : t α) : traverse f (g <$> x) = traverse (f ∘ g) x := begin rw @map_eq_traverse_id t _ _ _ _ g, refine (comp_traverse f (id.mk ∘ g) x).symm.trans _, congr, apply comp.applicative_id_comp end lemma pure_traverse (x : t α) : traverse pure x = (pure x : F (t α)) := by have : traverse pure x = pure (traverse id.mk x) := (naturality (pure_transformation F) id.mk x).symm; rwa id_traverse at this lemma id_sequence (x : t α) : sequence (id.mk <$> x) = id.mk x := by simp [sequence, traverse_map, id_traverse]; refl lemma comp_sequence (x : t (F (G α))) : sequence (comp.mk <$> x) = comp.mk (sequence <$> sequence x) := by simp [sequence, traverse_map]; rw ← comp_traverse; simp [map_id] lemma naturality' (η : applicative_transformation F G) (x : t (F α)) : η (sequence x) = sequence (@η _ <$> x) := by simp [sequence, naturality, traverse_map] @[functor_norm] lemma traverse_id : traverse id.mk = (id.mk : t α → id (t α)) := by { ext, exact id_traverse _ } @[functor_norm] lemma traverse_comp (g : α → F β) (h : β → G γ) : traverse (comp.mk ∘ map h ∘ g) = (comp.mk ∘ map (traverse h) ∘ traverse g : t α → comp F G (t γ)) := by { ext, exact comp_traverse _ _ _ } lemma traverse_eq_map_id' (f : β → γ) : traverse (id.mk ∘ f) = id.mk ∘ (map f : t β → t γ) := by { ext, exact traverse_eq_map_id _ _ } -- @[functor_norm] lemma traverse_map' (g : α → β) (h : β → G γ) : traverse (h ∘ g) = (traverse h ∘ map g : t α → G (t γ)) := by { ext, rw [comp_app, traverse_map] } lemma map_traverse' (g : α → G β) (h : β → γ) : traverse (map h ∘ g) = (map (map h) ∘ traverse g : t α → G (t γ)) := by { ext, rw [comp_app, map_traverse] } lemma naturality_pf (η : applicative_transformation F G) (f : α → F β) : traverse (@η _ ∘ f) = @η _ ∘ (traverse f : t α → F (t β)) := by { ext, rw [comp_app, naturality] } end traversable
53d2c613a5e410f35d212fe624c82b6ad0944f9a
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/essentially_small.lean
82779c2c980b960f62fb9219792a17014f0a8a73
[ "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
7,376
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import logic.small import category_theory.skeletal /-! # Essentially small categories. A category given by `(C : Type u) [category.{v} C]` is `w`-essentially small if there exists a `small_model C : Type w` equipped with `[small_category (small_model C)]`. A category is `w`-locally small if every hom type is `w`-small. The main theorem here is that a category is `w`-essentially small iff the type `skeleton C` is `w`-small, and `C` is `w`-locally small. -/ universes w v v' u u' open category_theory variables (C : Type u) [category.{v} C] namespace category_theory /-- A category is `essentially_small.{w}` if there exists an equivalence to some `S : Type w` with `[small_category S]`. -/ class essentially_small (C : Type u) [category.{v} C] : Prop := (equiv_small_category : ∃ (S : Type w) (_ : small_category S), by exactI nonempty (C ≌ S)) /-- Constructor for `essentially_small C` from an explicit small category witness. -/ lemma essentially_small.mk' {C : Type u} [category.{v} C] {S : Type w} [small_category S] (e : C ≌ S) : essentially_small.{w} C := ⟨⟨S, _, ⟨e⟩⟩⟩ /-- An arbitrarily chosen small model for an essentially small category. -/ @[nolint has_inhabited_instance] def small_model (C : Type u) [category.{v} C] [essentially_small.{w} C] : Type w := classical.some (@essentially_small.equiv_small_category C _ _) noncomputable instance small_category_small_model (C : Type u) [category.{v} C] [essentially_small.{w} C] : small_category (small_model C) := classical.some (classical.some_spec (@essentially_small.equiv_small_category C _ _)) /-- The (noncomputable) categorical equivalence between an essentially small category and its small model. -/ noncomputable def equiv_small_model (C : Type u) [category.{v} C] [essentially_small.{w} C] : C ≌ small_model C := nonempty.some (classical.some_spec (classical.some_spec (@essentially_small.equiv_small_category C _ _))) lemma essentially_small_congr {C : Type u} [category.{v} C] {D : Type u'} [category.{v'} D] (e : C ≌ D) : essentially_small.{w} C ↔ essentially_small.{w} D := begin fsplit, { rintro ⟨S, 𝒮, ⟨f⟩⟩, resetI, exact essentially_small.mk' (e.symm.trans f), }, { rintro ⟨S, 𝒮, ⟨f⟩⟩, resetI, exact essentially_small.mk' (e.trans f), }, end lemma discrete.essentially_small_of_small {α : Type u} [small.{w} α] : essentially_small.{w} (discrete α) := ⟨⟨discrete (shrink α), ⟨infer_instance, ⟨discrete.equivalence (equiv_shrink _)⟩⟩⟩⟩ /-- A category is `w`-locally small if every hom set is `w`-small. See `shrink_homs C` for a category instance where every hom set has been replaced by a small model. -/ class locally_small (C : Type u) [category.{v} C] : Prop := (hom_small : ∀ X Y : C, small.{w} (X ⟶ Y) . tactic.apply_instance) instance (C : Type u) [category.{v} C] [locally_small.{w} C] (X Y : C) : small (X ⟶ Y) := locally_small.hom_small X Y lemma locally_small_congr {C : Type u} [category.{v} C] {D : Type u'} [category.{v'} D] (e : C ≌ D) : locally_small.{w} C ↔ locally_small.{w} D := begin fsplit, { rintro ⟨L⟩, fsplit, intros X Y, specialize L (e.inverse.obj X) (e.inverse.obj Y), refine (small_congr _).mpr L, exact equiv_of_fully_faithful e.inverse, }, { rintro ⟨L⟩, fsplit, intros X Y, specialize L (e.functor.obj X) (e.functor.obj Y), refine (small_congr _).mpr L, exact equiv_of_fully_faithful e.functor, }, end @[priority 100] instance locally_small_self (C : Type u) [category.{v} C] : locally_small.{v} C := {} @[priority 100] instance locally_small_of_essentially_small (C : Type u) [category.{v} C] [essentially_small.{w} C] : locally_small.{w} C := (locally_small_congr (equiv_small_model C)).mpr (category_theory.locally_small_self _) /-- We define a type alias `shrink_homs C` for `C`. When we have `locally_small.{w} C`, we'll put a `category.{w}` instance on `shrink_homs C`. -/ @[nolint has_inhabited_instance] def shrink_homs (C : Type u) := C namespace shrink_homs section variables {C' : Type*} -- a fresh variable with no category instance attached /-- Help the typechecker by explicitly translating from `C` to `shrink_homs C`. -/ def to_shrink_homs {C' : Type*} (X : C') : shrink_homs C' := X /-- Help the typechecker by explicitly translating from `shrink_homs C` to `C`. -/ def from_shrink_homs {C' : Type*} (X : shrink_homs C') : C' := X @[simp] lemma to_from (X : C') : from_shrink_homs (to_shrink_homs X) = X := rfl @[simp] lemma from_to (X : shrink_homs C') : to_shrink_homs (from_shrink_homs X) = X := rfl end variables (C) [locally_small.{w} C] @[simps] noncomputable instance : category.{w} (shrink_homs C) := { hom := λ X Y, shrink (from_shrink_homs X ⟶ from_shrink_homs Y), id := λ X, equiv_shrink _ (𝟙 (from_shrink_homs X)), comp := λ X Y Z f g, equiv_shrink _ (((equiv_shrink _).symm f) ≫ ((equiv_shrink _).symm g)), }. /-- Implementation of `shrink_homs.equivalence`. -/ @[simps] noncomputable def functor : C ⥤ shrink_homs C := { obj := λ X, to_shrink_homs X, map := λ X Y f, equiv_shrink (X ⟶ Y) f, } /-- Implementation of `shrink_homs.equivalence`. -/ @[simps] noncomputable def inverse : shrink_homs C ⥤ C := { obj := λ X, from_shrink_homs X, map := λ X Y f, (equiv_shrink (from_shrink_homs X ⟶ from_shrink_homs Y)).symm f, } /-- The categorical equivalence between `C` and `shrink_homs C`, when `C` is locally small. -/ @[simps] noncomputable def equivalence : C ≌ shrink_homs C := equivalence.mk (functor C) (inverse C) (nat_iso.of_components (λ X, iso.refl X) (by tidy)) (nat_iso.of_components (λ X, iso.refl X) (by tidy)) end shrink_homs /-- A category is essentially small if and only if the underlying type of its skeleton (i.e. the "set" of isomorphism classes) is small, and it is locally small. -/ theorem essentially_small_iff (C : Type u) [category.{v} C] : essentially_small.{w} C ↔ small.{w} (skeleton C) ∧ locally_small.{w} C := begin -- This theorem is the only bit of real work in this file. fsplit, { intro h, fsplit, { rcases h with ⟨S, 𝒮, ⟨e⟩⟩, resetI, refine ⟨⟨skeleton S, ⟨_⟩⟩⟩, exact e.skeleton_equiv, }, { resetI, apply_instance, }, }, { rintro ⟨⟨S, ⟨e⟩⟩, L⟩, resetI, let e' := (shrink_homs.equivalence C).skeleton_equiv.symm, refine ⟨⟨S, _, ⟨_⟩⟩⟩, apply induced_category.category (e'.trans e).symm, refine (shrink_homs.equivalence C).trans ((skeleton_equivalence _).symm.trans ((induced_functor (e'.trans e).symm).as_equivalence.symm)), }, end /-- Any thin category is locally small. -/ @[priority 100] instance locally_small_of_thin {C : Type u} [category.{v} C] [∀ X Y : C, subsingleton (X ⟶ Y)] : locally_small.{w} C := {} /-- A thin category is essentially small if and only if the underlying type of its skeleton is small. -/ theorem essentially_small_iff_of_thin {C : Type u} [category.{v} C] [∀ X Y : C, subsingleton (X ⟶ Y)] : essentially_small.{w} C ↔ small.{w} (skeleton C) := by simp [essentially_small_iff, category_theory.locally_small_of_thin] end category_theory
0ad169546f1cadbc38df6c11b536bd5c711f16e2
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/data/pnat/basic.lean
ccfc98b7bab7d5c97c1d19698cadf0feec137aa8
[ "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
14,267
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Neil Strickland -/ import data.nat.basic /-! # The positive natural numbers This file defines the type `ℕ+` or `pnat`, the subtype of natural numbers that are positive. -/ /-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype, and the VM representation of `ℕ+` is the same as `ℕ` because the proof is not stored. -/ def pnat := {n : ℕ // 0 < n} notation `ℕ+` := pnat instance coe_pnat_nat : has_coe ℕ+ ℕ := ⟨subtype.val⟩ instance : has_repr ℕ+ := ⟨λ n, repr n.1⟩ /-- Predecessor of a `ℕ+`, as a `ℕ`. -/ def pnat.nat_pred (i : ℕ+) : ℕ := i - 1 namespace nat /-- Convert a natural number to a positive natural number. The positivity assumption is inferred by `dec_trivial`. -/ def to_pnat (n : ℕ) (h : 0 < n . tactic.exact_dec_trivial) : ℕ+ := ⟨n, h⟩ /-- Write a successor as an element of `ℕ+`. -/ def succ_pnat (n : ℕ) : ℕ+ := ⟨succ n, succ_pos n⟩ @[simp] theorem succ_pnat_coe (n : ℕ) : (succ_pnat n : ℕ) = succ n := rfl theorem succ_pnat_inj {n m : ℕ} : succ_pnat n = succ_pnat m → n = m := λ h, by { let h' := congr_arg (coe : ℕ+ → ℕ) h, exact nat.succ.inj h' } /-- Convert a natural number to a pnat. `n+1` is mapped to itself, and `0` becomes `1`. -/ def to_pnat' (n : ℕ) : ℕ+ := succ_pnat (pred n) @[simp] theorem to_pnat'_coe : ∀ (n : ℕ), ((to_pnat' n) : ℕ) = ite (0 < n) n 1 | 0 := rfl | (m + 1) := by {rw [if_pos (succ_pos m)], refl} end nat namespace pnat open nat /-- We now define a long list of structures on ℕ+ induced by similar structures on ℕ. Most of these behave in a completely obvious way, but there are a few things to be said about subtraction, division and powers. -/ instance : decidable_eq ℕ+ := λ (a b : ℕ+), by apply_instance instance : linear_order ℕ+ := subtype.linear_order _ @[simp] lemma mk_le_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) ≤ ⟨k, hk⟩ ↔ n ≤ k := iff.rfl @[simp] lemma mk_lt_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) < ⟨k, hk⟩ ↔ n < k := iff.rfl @[simp, norm_cast] lemma coe_le_coe (n k : ℕ+) : (n:ℕ) ≤ k ↔ n ≤ k := iff.rfl @[simp, norm_cast] lemma coe_lt_coe (n k : ℕ+) : (n:ℕ) < k ↔ n < k := iff.rfl @[simp] theorem pos (n : ℕ+) : 0 < (n : ℕ) := n.2 theorem eq {m n : ℕ+} : (m : ℕ) = n → m = n := subtype.eq @[simp] lemma coe_inj {m n : ℕ+} : (m : ℕ) = n ↔ m = n := set_coe.ext_iff @[simp] theorem mk_coe (n h) : ((⟨n, h⟩ : ℕ+) : ℕ) = n := rfl instance : add_comm_semigroup ℕ+ := { add := λ a b, ⟨(a + b : ℕ), add_pos a.pos b.pos⟩, add_comm := λ a b, subtype.eq (add_comm a b), add_assoc := λ a b c, subtype.eq (add_assoc a b c) } @[simp] theorem add_coe (m n : ℕ+) : ((m + n : ℕ+) : ℕ) = m + n := rfl instance coe_add_hom : is_add_hom (coe : ℕ+ → ℕ) := ⟨add_coe⟩ instance : add_left_cancel_semigroup ℕ+ := { add_left_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [add_coe, add_coe] at h, exact eq ((add_right_inj (a : ℕ)).mp h)}, .. (pnat.add_comm_semigroup) } instance : add_right_cancel_semigroup ℕ+ := { add_right_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [add_coe, add_coe] at h, exact eq ((add_left_inj (b : ℕ)).mp h)}, .. (pnat.add_comm_semigroup) } @[simp] theorem ne_zero (n : ℕ+) : (n : ℕ) ≠ 0 := ne_of_gt n.2 theorem to_pnat'_coe {n : ℕ} : 0 < n → (n.to_pnat' : ℕ) = n := succ_pred_eq_of_pos @[simp] theorem coe_to_pnat' (n : ℕ+) : (n : ℕ).to_pnat' = n := eq (to_pnat'_coe n.pos) instance : comm_monoid ℕ+ := { mul := λ m n, ⟨m.1 * n.1, mul_pos m.2 n.2⟩, mul_assoc := λ a b c, subtype.eq (mul_assoc _ _ _), one := succ_pnat 0, one_mul := λ a, subtype.eq (one_mul _), mul_one := λ a, subtype.eq (mul_one _), mul_comm := λ a b, subtype.eq (mul_comm _ _) } theorem lt_add_one_iff : ∀ {a b : ℕ+}, a < b + 1 ↔ a ≤ b := λ a b, nat.lt_add_one_iff theorem add_one_le_iff : ∀ {a b : ℕ+}, a + 1 ≤ b ↔ a < b := λ a b, nat.add_one_le_iff @[simp] lemma one_le (n : ℕ+) : (1 : ℕ+) ≤ n := n.2 instance : order_bot ℕ+ := { bot := 1, bot_le := λ a, a.property, ..(by apply_instance : partial_order ℕ+) } @[simp] lemma bot_eq_zero : (⊥ : ℕ+) = 1 := rfl instance : inhabited ℕ+ := ⟨1⟩ -- Some lemmas that rewrite `pnat.mk n h`, for `n` an explicit numeral, into explicit numerals. @[simp] lemma mk_one {h} : (⟨1, h⟩ : ℕ+) = (1 : ℕ+) := rfl @[simp] lemma mk_bit0 (n) {h} : (⟨bit0 n, h⟩ : ℕ+) = (bit0 ⟨n, pos_of_bit0_pos h⟩ : ℕ+) := rfl @[simp] lemma mk_bit1 (n) {h} {k} : (⟨bit1 n, h⟩ : ℕ+) = (bit1 ⟨n, k⟩ : ℕ+) := rfl -- Some lemmas that rewrite inequalities between explicit numerals in `pnat` -- into the corresponding inequalities in `nat`. -- TODO: perhaps this should not be attempted by `simp`, -- and instead we should expect `norm_num` to take care of these directly? -- TODO: these lemmas are perhaps incomplete: -- * 1 is not represented as a bit0 or bit1 -- * strict inequalities? @[simp] lemma bit0_le_bit0 (n m : ℕ+) : (bit0 n) ≤ (bit0 m) ↔ (bit0 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit0_le_bit1 (n m : ℕ+) : (bit0 n) ≤ (bit1 m) ↔ (bit0 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit0 (n m : ℕ+) : (bit1 n) ≤ (bit0 m) ↔ (bit1 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit1 (n m : ℕ+) : (bit1 n) ≤ (bit1 m) ↔ (bit1 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] theorem one_coe : ((1 : ℕ+) : ℕ) = 1 := rfl @[simp] theorem mul_coe (m n : ℕ+) : ((m * n : ℕ+) : ℕ) = m * n := rfl instance coe_mul_hom : is_monoid_hom (coe : ℕ+ → ℕ) := {map_one := one_coe, map_mul := mul_coe} @[simp] lemma coe_eq_one_iff {m : ℕ+} : (m : ℕ) = 1 ↔ m = 1 := by { split; intro h; try { apply pnat.eq}; rw h; simp } @[simp] lemma coe_bit0 (a : ℕ+) : ((bit0 a : ℕ+) : ℕ) = bit0 (a : ℕ) := rfl @[simp] lemma coe_bit1 (a : ℕ+) : ((bit1 a : ℕ+) : ℕ) = bit1 (a : ℕ) := rfl @[simp] theorem pow_coe (m : ℕ+) (n : ℕ) : ((m ^ n : ℕ+) : ℕ) = (m : ℕ) ^ n := by induction n with n ih; [refl, rw [pow_succ', pow_succ, mul_coe, mul_comm, ih]] instance : left_cancel_semigroup ℕ+ := { mul_left_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, exact eq ((nat.mul_right_inj a.pos).mp h)}, .. (pnat.comm_monoid) } instance : right_cancel_semigroup ℕ+ := { mul_right_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, exact eq ((nat.mul_left_inj b.pos).mp h)}, .. (pnat.comm_monoid) } instance : ordered_cancel_comm_monoid ℕ+ := { mul_le_mul_left := by { intros, apply nat.mul_le_mul_left, assumption }, le_of_mul_le_mul_left := by { intros a b c h, apply nat.le_of_mul_le_mul_left h a.property, }, .. (pnat.left_cancel_semigroup), .. (pnat.right_cancel_semigroup), .. (pnat.linear_order), .. (pnat.comm_monoid)} instance : distrib ℕ+ := { left_distrib := λ a b c, eq (mul_add a b c), right_distrib := λ a b c, eq (add_mul a b c), ..(pnat.add_comm_semigroup), ..(pnat.comm_monoid) } /-- Subtraction a - b is defined in the obvious way when a > b, and by a - b = 1 if a ≤ b. -/ instance : has_sub ℕ+ := ⟨λ a b, to_pnat' (a - b : ℕ)⟩ theorem sub_coe (a b : ℕ+) : ((a - b : ℕ+) : ℕ) = ite (b < a) (a - b : ℕ) 1 := begin change ((to_pnat' ((a : ℕ) - (b : ℕ)) : ℕ)) = ite ((a : ℕ) > (b : ℕ)) ((a : ℕ) - (b : ℕ)) 1, split_ifs with h, { exact to_pnat'_coe (nat.sub_pos_of_lt h) }, { rw [nat.sub_eq_zero_iff_le.mpr (le_of_not_gt h)], refl } end theorem add_sub_of_lt {a b : ℕ+} : a < b → a + (b - a) = b := λ h, eq $ by { rw [add_coe, sub_coe, if_pos h], exact nat.add_sub_of_le (le_of_lt h) } instance : has_well_founded ℕ+ := ⟨(<), measure_wf coe⟩ /-- Strong induction on `pnat`. -/ lemma strong_induction_on {p : pnat → Prop} : ∀ (n : pnat) (h : ∀ k, (∀ m, m < k → p m) → p k), p n | n := λ IH, IH _ (λ a h, strong_induction_on a IH) using_well_founded { dec_tac := `[assumption] } /-- If `(n : pnat)` is different from `1`, then it is the successor of some `(k : pnat)`. -/ lemma exists_eq_succ_of_ne_one : ∀ {n : pnat} (h1 : n ≠ 1), ∃ (k : pnat), n = k + 1 | ⟨1, _⟩ h1 := false.elim $ h1 rfl | ⟨n+2, _⟩ _ := ⟨⟨n+1, by simp⟩, rfl⟩ lemma case_strong_induction_on {p : pnat → Prop} (a : pnat) (hz : p 1) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (n + 1)) : p a := begin apply strong_induction_on a, intros k hk, by_cases h1 : k = 1, { rwa h1 }, obtain ⟨b, rfl⟩ := exists_eq_succ_of_ne_one h1, simp only [lt_add_one_iff] at hk, exact hi b hk end /-- We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div_aux : ℕ+ → ℕ → ℕ → ℕ+ × ℕ | k 0 q := ⟨k, q.pred⟩ | k (r + 1) q := ⟨⟨r + 1, nat.succ_pos r⟩, q⟩ lemma mod_div_aux_spec : ∀ (k : ℕ+) (r q : ℕ) (h : ¬ (r = 0 ∧ q = 0)), (((mod_div_aux k r q).1 : ℕ) + k * (mod_div_aux k r q).2 = (r + k * q)) | k 0 0 h := (h ⟨rfl, rfl⟩).elim | k 0 (q + 1) h := by { change (k : ℕ) + (k : ℕ) * (q + 1).pred = 0 + (k : ℕ) * (q + 1), rw [nat.pred_succ, nat.mul_succ, zero_add, add_comm]} | k (r + 1) q h := rfl /-- `mod_div m k = (m % k, m / k)`. We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div (m k : ℕ+) : ℕ+ × ℕ := mod_div_aux k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) /-- We define `m % k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` This ensures that `m % k` is always positive. -/ def mod (m k : ℕ+) : ℕ+ := (mod_div m k).1 /-- We define `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m / k = n - 1`. This ensures that `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def div (m k : ℕ+) : ℕ := (mod_div m k).2 theorem mod_add_div (m k : ℕ+) : ((mod m k) + k * (div m k) : ℕ) = m := begin let h₀ := nat.mod_add_div (m : ℕ) (k : ℕ), have : ¬ ((m : ℕ) % (k : ℕ) = 0 ∧ (m : ℕ) / (k : ℕ) = 0), by { rintro ⟨hr, hq⟩, rw [hr, hq, mul_zero, zero_add] at h₀, exact (m.ne_zero h₀.symm).elim }, have := mod_div_aux_spec k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) this, exact (this.trans h₀), end theorem div_add_mod (m k : ℕ+) : (k * (div m k) + mod m k : ℕ) = m := (add_comm _ _).trans (mod_add_div _ _) theorem mod_coe (m k : ℕ+) : ((mod m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) (k : ℕ) ((m : ℕ) % (k : ℕ)) := begin dsimp [mod, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem div_coe (m k : ℕ+) : ((div m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) ((m : ℕ) / (k : ℕ)).pred ((m : ℕ) / (k : ℕ)) := begin dsimp [div, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem mod_le (m k : ℕ+) : mod m k ≤ m ∧ mod m k ≤ k := begin change ((mod m k) : ℕ) ≤ (m : ℕ) ∧ ((mod m k) : ℕ) ≤ (k : ℕ), rw [mod_coe], split_ifs, { have hm : (m : ℕ) > 0 := m.pos, rw [← nat.mod_add_div (m : ℕ) (k : ℕ), h, zero_add] at hm ⊢, by_cases h' : ((m : ℕ) / (k : ℕ)) = 0, { rw [h', mul_zero] at hm, exact (lt_irrefl _ hm).elim}, { let h' := nat.mul_le_mul_left (k : ℕ) (nat.succ_le_of_lt (nat.pos_of_ne_zero h')), rw [mul_one] at h', exact ⟨h', le_refl (k : ℕ)⟩ } }, { exact ⟨nat.mod_le (m : ℕ) (k : ℕ), le_of_lt (nat.mod_lt (m : ℕ) k.pos)⟩ } end theorem dvd_iff {k m : ℕ+} : k ∣ m ↔ (k : ℕ) ∣ (m : ℕ) := begin split; intro h, rcases h with ⟨_, rfl⟩, apply dvd_mul_right, rcases h with ⟨a, h⟩, cases a, { contrapose h, apply ne_zero, }, use a.succ, apply nat.succ_pos, rw [← coe_inj, h, mul_coe, mk_coe], end theorem dvd_iff' {k m : ℕ+} : k ∣ m ↔ mod m k = k := begin rw dvd_iff, rw [nat.dvd_iff_mod_eq_zero], split, { intro h, apply eq, rw [mod_coe, if_pos h] }, { intro h, by_cases h' : (m : ℕ) % (k : ℕ) = 0, { exact h'}, { replace h : ((mod m k) : ℕ) = (k : ℕ) := congr_arg _ h, rw [mod_coe, if_neg h'] at h, exact (ne_of_lt (nat.mod_lt (m : ℕ) k.pos) h).elim } } end lemma le_of_dvd {m n : ℕ+} : m ∣ n → m ≤ n := by { rw dvd_iff', intro h, rw ← h, apply (mod_le n m).left } /-- If `h : k | m`, then `k * (div_exact m k) = m`. Note that this is not equal to `m / k`. -/ def div_exact (m k : ℕ+) : ℕ+ := ⟨(div m k).succ, nat.succ_pos _⟩ theorem mul_div_exact {m k : ℕ+} (h : k ∣ m) : k * (div_exact m k) = m := begin apply eq, rw [mul_coe], change (k : ℕ) * (div m k).succ = m, rw [← mod_add_div m k, dvd_iff'.mp h, nat.mul_succ, add_comm], end theorem dvd_antisymm {m n : ℕ+} : m ∣ n → n ∣ m → m = n := λ hmn hnm, le_antisymm (le_of_dvd hmn) (le_of_dvd hnm) theorem dvd_one_iff (n : ℕ+) : n ∣ 1 ↔ n = 1 := ⟨λ h, dvd_antisymm h (one_dvd n), λ h, h.symm ▸ (dvd_refl 1)⟩ lemma pos_of_div_pos {n : ℕ+} {a : ℕ} (h : a ∣ n) : 0 < a := begin apply pos_iff_ne_zero.2, intro hzero, rw hzero at h, exact pnat.ne_zero n (eq_zero_of_zero_dvd h) end end pnat
4d27f845e12d361cb15f569fb4e2162ab5ef7785
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Elab/PreDefinition/Structural.lean
34f503434b3f7f183701418fa196d6911f5e620f
[ "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
22,351
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ForEachExpr import Lean.Meta.ForEachExpr import Lean.Meta.RecursorInfo import Lean.Meta.Match.Match import Lean.Elab.PreDefinition.Basic namespace Lean.Elab namespace Structural open Meta private def getFixedPrefix (declName : Name) (xs : Array Expr) (value : Expr) : Nat := let visitor {ω} : StateRefT Nat (ST ω) Unit := value.forEach' fun e => if e.isAppOf declName then do let args := e.getAppArgs modify fun numFixed => if args.size < numFixed then args.size else numFixed -- we continue searching if the e's arguments are not a prefix of `xs` pure !args.isPrefixOf xs else pure true runST fun _ => do let (_, numFixed) ← visitor.run xs.size; pure numFixed structure RecArgInfo := /- `fixedParams ++ ys` are the arguments of the function we are trying to justify termination using structural recursion. -/ (fixedParams : Array Expr) (ys : Array Expr) -- recursion arguments (pos : Nat) -- position in `ys` of the argument we are recursing on (indicesPos : Array Nat) -- position in `ys` of the inductive datatype indices we are recursing on (indName : Name) -- inductive datatype name of the argument we are recursing on (indLevels : List Level) -- inductice datatype universe levels of the argument we are recursing on (indParams : Array Expr) -- inductive datatype parameters of the argument we are recursing on (indIndices : Array Expr) -- inductive datatype indices of the argument we are recursing on, it is equal to `indicesPos.map fun i => ys.get! i` (reflexive : Bool) -- true if we are recursing over a reflexive inductive datatype private def getIndexMinPos (xs : Array Expr) (indices : Array Expr) : Nat := do let mut minPos := xs.size for index in indices do match xs.indexOf? index with | some pos => if pos.val < minPos then minPos := pos.val | _ => pure () return minPos -- Indices can only depend on other indices private def hasBadIndexDep? (ys : Array Expr) (indices : Array Expr) : MetaM (Option (Expr × Expr)) := do for index in indices do let indexType ← inferType index for y in ys do if !indices.contains y && (← dependsOn indexType y.fvarId!) then return some (index, y) return none -- Inductive datatype parameters cannot depend on ys private def hasBadParamDep? (ys : Array Expr) (indParams : Array Expr) : MetaM (Option (Expr × Expr)) := do for p in indParams do let pType ← inferType p for y in ys do if ← dependsOn pType y.fvarId! then return some (p, y) return none private def throwStructuralFailed {α} : MetaM α := throwError "structural recursion cannot be used" structure State := /- When compiling structural recursion we use the `brecOn` recursor automatically built by the `inductive` command. For an inductive datatype `C`, it has the form `C.brecOn As motive is c F` where `As` are the inductive datatype parameters, `is` are the inductive datatype indices, `c : C As is`, and `F : (js) → (d : C As js) → C.below d → motive d` The `C.below d` is used to eliminate recursive applications. We refine its type when we process a nested dependent pattern matcher using `MatcherApp.addArg`. See `replaceRecApps` for additional details. We store the names of the matcher where we used `MatcherApp.addArg` at `matcherBelowDep`. We use this information to generate the auxiliary `_sunfold` definition needed by the smart unfolding technique used at WHNF. -/ (matcherBelowDep : NameSet := {}) abbrev M := StateRefT State MetaM instance {α} : Inhabited (M α) := { default := throwError "failed" } private def run {α} (x : M α) (s : State := {}) : MetaM (α × State) := StateRefT'.run x s private def orelse' {α} (x y : M α) : M α := do let saveState ← get orelseMergeErrors x (do set saveState; y) private partial def findRecArg {α} (numFixed : Nat) (xs : Array Expr) (k : RecArgInfo → M α) : M α := let rec loop (i : Nat) : M α := do if h : i < xs.size then let x := xs.get ⟨i, h⟩ let localDecl ← getFVarLocalDecl x if localDecl.isLet then throwStructuralFailed else let xType ← whnfD localDecl.type matchConstInduct xType.getAppFn (fun _ => loop (i+1)) fun indInfo us => do if !(← hasConst (mkBRecOnName indInfo.name)) then loop (i+1) else if indInfo.isReflexive && !(← hasConst (mkBInductionOnName indInfo.name)) then loop (i+1) else let indArgs := xType.getAppArgs let indParams := indArgs.extract 0 indInfo.nparams let indIndices := indArgs.extract indInfo.nparams indArgs.size if !indIndices.all Expr.isFVar then orelse' (throwError! "argument #{i+1} was not used because its type is an inductive family and indices are not variables{indentExpr xType}") (loop (i+1)) else if !indIndices.allDiff then orelse' (throwError! "argument #{i+1} was not used because its type is an inductive family and indices are not pairwise distinct{indentExpr xType}") (loop (i+1)) else let indexMinPos := getIndexMinPos xs indIndices let numFixed := if indexMinPos < numFixed then indexMinPos else numFixed let fixedParams := xs.extract 0 numFixed let ys := xs.extract numFixed xs.size match ← hasBadIndexDep? ys indIndices with | some (index, y) => orelse' (throwError! "argument #{i+1} was not used because its type is an inductive family{indentExpr xType}\nand index{indentExpr index}\ndepends on the non index{indentExpr y}") (loop (i+1)) | none => match ← hasBadParamDep? ys indParams with | some (indParam, y) => orelse' (throwError! "argument #{i+1} was not used because its type is an inductive datatype{indentExpr xType}\nand parameter{indentExpr indParam}\ndepends on{indentExpr y}") (loop (i+1)) | none => let indicesPos := indIndices.map fun index => match ys.indexOf? index with | some i => i.val | none => unreachable! orelse' (mapError (k { fixedParams := fixedParams ys := ys pos := i - fixedParams.size indicesPos := indicesPos indName := indInfo.name indLevels := us indParams := indParams indIndices := indIndices reflexive := indInfo.isReflexive }) (fun msg => m!"argument #{i+1} was not used for structural recursion{indentD msg}")) (loop (i+1)) else throwStructuralFailed loop numFixed private def containsRecFn (recFnName : Name) (e : Expr) : Bool := (e.find? fun e => e.isConstOf recFnName).isSome private def ensureNoRecFn (recFnName : Name) (e : Expr) : MetaM Expr := do if containsRecFn recFnName e then Meta.forEachExpr e fun e => do if e.isAppOf recFnName then throwError! "unexpected occurrence of recursive application{indentExpr e}" pure e else pure e private def throwToBelowFailed {α} : MetaM α := throwError "toBelow failed" /- See toBelow -/ private partial def toBelowAux (C : Expr) : Expr → Expr → Expr → MetaM Expr | belowDict, arg, F => do let belowDict ← whnf belowDict trace[Elab.definition.structural]! "belowDict: {belowDict}, arg: {arg}" match belowDict with | Expr.app (Expr.app (Expr.const `PProd _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `PProd.fst #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `PProd.snd #[F])) | Expr.app (Expr.app (Expr.const `And _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `And.left #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `And.right #[F])) | _ => forallTelescopeReducing belowDict fun xs belowDict => do let argArgs := arg.getAppArgs unless argArgs.size >= xs.size do throwToBelowFailed let n := argArgs.size let argTailArgs := argArgs.extract (n - xs.size) n let belowDict := belowDict.replaceFVars xs argTailArgs match belowDict with | Expr.app belowDictFun belowDictArg _ => unless belowDictFun.getAppFn == C do throwToBelowFailed unless ← isDefEq belowDictArg arg do throwToBelowFailed pure (mkAppN F argTailArgs) | _ => throwToBelowFailed /- See toBelow -/ private def withBelowDict {α} (below : Expr) (numIndParams : Nat) (k : Expr → Expr → MetaM α) : MetaM α := do let belowType ← inferType below trace[Elab.definition.structural]! "belowType: {belowType}" belowType.withApp fun f args => do let motivePos := numIndParams + 1 unless motivePos < args.size do throwError! "unexpected 'below' type{indentExpr belowType}" let pre := mkAppN f (args.extract 0 numIndParams) let preType ← inferType pre forallBoundedTelescope preType (some 1) fun x _ => do let motiveType ← inferType x[0] let C ← mkFreshUserName `C withLocalDeclD C motiveType fun C => let belowDict := mkApp pre C let belowDict := mkAppN belowDict (args.extract (numIndParams + 1) args.size) k C belowDict /- `below` is a free variable with type of the form `I.below indParams motive indices major`, where `I` is the name of an inductive datatype. For example, when trying to show that the following function terminates using structural recursion ```lean def addAdjacent : List Nat → List Nat | [] => [] | [a] => [a] | a::b::as => (a+b) :: addAdjacent as ``` when we are visiting `addAdjacent as` at `replaceRecApps`, `below` has type `@List.below Nat (fun (x : List Nat) => List Nat) (a::b::as)` The motive `fun (x : List Nat) => List Nat` depends on the actual function we are trying to compute. So, we first replace it with a fresh variable `C` at `withBelowDict`. Recall that `brecOn` implements course-of-values recursion, and `below` can be viewed as a dictionary of the "previous values". We search this dictionary using the auxiliary function `toBelowAux`. The dictionary is built using the `PProd` (`And` for inductive predicates). We keep searching it until we find `C recArg`, where `C` is the auxiliary fresh variable created at `withBelowDict`. -/ private partial def toBelow (below : Expr) (numIndParams : Nat) (recArg : Expr) : MetaM Expr := do withBelowDict below numIndParams fun C belowDict => toBelowAux C belowDict recArg below /-- Return true iff `e` contains an application `recFnName .. t ..` where the term `t` is the argument we are trying to recurse on, and it contains loose bound variables. We use this test to decide whether we should process a matcher-application as a regular applicaton or not. That is, whether we should push the `below` argument should be affected by the matcher or not. If `e` does not contain an application of the form `recFnName .. t ..`, then we know the recursion doesn't depend on any pattern variable in this matcher. -/ private def recArgHasLooseBVarsAt (recFnName : Name) (recArgInfo : RecArgInfo) (e : Expr) : Bool := let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos let app? := e.find? fun e => e.isAppOf recFnName && e.getAppNumArgs > recArgPos && (e.getArg! recArgPos).hasLooseBVars app?.isSome private partial def replaceRecApps (recFnName : Name) (recArgInfo : RecArgInfo) (below : Expr) (e : Expr) : M Expr := let rec loop : Expr → Expr → M Expr | below, e@(Expr.lam n d b c) => do withLocalDecl n c.binderInfo (← loop below d) fun x => do mkLambdaFVars #[x] (← loop below (b.instantiate1 x)) | below, e@(Expr.forallE n d b c) => do withLocalDecl n c.binderInfo (← loop below d) fun x => do mkForallFVars #[x] (← loop below (b.instantiate1 x)) | below, Expr.letE n type val body _ => do withLetDecl n (← loop below type) (← loop below val) fun x => do mkLetFVars #[x] (← loop below (body.instantiate1 x)) | below, Expr.mdata d e _ => do pure $ mkMData d (← loop below e) | below, Expr.proj n i e _ => do pure $ mkProj n i (← loop below e) | below, e@(Expr.app _ _ _) => do let processApp (e : Expr) : M Expr := e.withApp fun f args => do if f.isConstOf recFnName then let numFixed := recArgInfo.fixedParams.size let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos if recArgPos >= args.size then throwError! "insufficient number of parameters at recursive application {indentExpr e}" let recArg := args[recArgPos] -- For reflexive type, we may have nested recursive applications in recArg let recArg ← loop below recArg let f ← try toBelow below recArgInfo.indParams.size recArg catch _ => throwError! "failed to eliminate recursive application{indentExpr e}" -- Recall that the fixed parameters are not in the scope of the `brecOn`. So, we skip them. let argsNonFixed := args.extract numFixed args.size -- The function `f` does not explicitly take `recArg` and its indices as arguments. So, we skip them too. let mut fArgs := #[] for i in [:argsNonFixed.size] do if recArgInfo.pos != i && !recArgInfo.indicesPos.contains i then let arg := argsNonFixed[i] let arg ← replaceRecApps recFnName recArgInfo below arg fArgs := fArgs.push arg pure $ mkAppN f fArgs else pure $ mkAppN (← loop below f) (← args.mapM (loop below)) let matcherApp? ← matchMatcherApp? e match matcherApp? with | some matcherApp => if !recArgHasLooseBVarsAt recFnName recArgInfo e then processApp e else /- Here is an example we currently not handle ``` def g (xs : List Nat) : Nat := match xs with | [] => 0 | y::ys => match ys with | [] => 1 | _::_::zs => g zs + 1 | zs => g ys + 2 ``` We are matching on `ys`, but still using `ys` in the third alternative. If we push the `below` argument over the dependent match it will be able to eliminate recursive call using `zs`. To make it work, users have to write the third alternative as `| zs => g zs + 2` If this is too annoying in practice, we may replace `ys` with the matching term, but this may generate weird error messages, when it doesn't work. -/ let matcherApp ← mapError (matcherApp.addArg below) (fun msg => "failed to add `below` argument to 'matcher' application" ++ indentD msg) modify fun s => { s with matcherBelowDep := s.matcherBelowDep.insert matcherApp.matcherName } let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do trace[Elab.definition.structural]! "altNumParams: {numParams}, xs: {xs}" unless xs.size >= numParams do throwError! "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" let belowForAlt := xs[numParams - 1] mkLambdaFVars xs (← loop belowForAlt altBody) pure { matcherApp with alts := altsNew }.toExpr | none => processApp e | _, e => ensureNoRecFn recFnName e loop below e private def mkBRecOn (recFnName : Name) (recArgInfo : RecArgInfo) (value : Expr) : M Expr := do let type := (← inferType value).headBeta let major := recArgInfo.ys[recArgInfo.pos] let otherArgs := recArgInfo.ys.filter fun y => y != major && !recArgInfo.indIndices.contains y let motive ← mkForallFVars otherArgs type let mut brecOnUniv ← getLevel motive trace[Elab.definition.structural]! "brecOn univ: {brecOnUniv}" let useBInductionOn := recArgInfo.reflexive && brecOnUniv == levelZero if recArgInfo.reflexive && brecOnUniv != levelZero then brecOnUniv ← decLevel brecOnUniv let motive ← mkLambdaFVars (recArgInfo.indIndices.push major) motive trace[Elab.definition.structural]! "brecOn motive: {motive}" let brecOn := if useBInductionOn then Lean.mkConst (mkBInductionOnName recArgInfo.indName) recArgInfo.indLevels else Lean.mkConst (mkBRecOnName recArgInfo.indName) (brecOnUniv :: recArgInfo.indLevels) let brecOn := mkAppN brecOn recArgInfo.indParams let brecOn := mkApp brecOn motive let brecOn := mkAppN brecOn recArgInfo.indIndices let brecOn := mkApp brecOn major check brecOn let brecOnType ← inferType brecOn trace[Elab.definition.structural]! "brecOn {brecOn}" trace[Elab.definition.structural]! "brecOnType {brecOnType}" forallBoundedTelescope brecOnType (some 1) fun F _ => do let F := F[0] let FType ← inferType F let numIndices := recArgInfo.indIndices.size forallBoundedTelescope FType (some $ numIndices + 1 /- major -/ + 1 /- below -/ + otherArgs.size) fun Fargs _ => do let indicesNew := Fargs.extract 0 numIndices let majorNew := Fargs[numIndices] let below := Fargs[numIndices+1] let otherArgsNew := Fargs.extract (numIndices+2) Fargs.size let valueNew := value.replaceFVars recArgInfo.indIndices indicesNew let valueNew := valueNew.replaceFVar major majorNew let valueNew := valueNew.replaceFVars otherArgs otherArgsNew let valueNew ← replaceRecApps recFnName recArgInfo below valueNew let Farg ← mkLambdaFVars Fargs valueNew let brecOn := mkApp brecOn Farg pure $ mkAppN brecOn otherArgs private def elimRecursion (preDef : PreDefinition) : M PreDefinition := withoutModifyingEnv do lambdaTelescope preDef.value fun xs value => do addAsAxiom preDef trace[Elab.definition.structural]! "{preDef.declName} {xs} :=\n{value}" let numFixed := getFixedPrefix preDef.declName xs value findRecArg numFixed xs fun recArgInfo => do -- when (recArgInfo.indName == `Nat) throwStructuralFailed -- HACK to skip Nat argument let valueNew ← mkBRecOn preDef.declName recArgInfo value let valueNew ← mkLambdaFVars xs valueNew trace[Elab.definition.structural]! "result: {valueNew}" -- Recursive applications may still occur in expressions that were not visited by replaceRecApps (e.g., in types) let valueNew ← ensureNoRecFn preDef.declName valueNew pure { preDef with value := valueNew } partial def addSmartUnfoldingDefAux (preDef : PreDefinition) (matcherBelowDep : NameSet) : MetaM PreDefinition := do let recFnName := preDef.declName let isMarkedMatcherName (n : Name) : Bool := matcherBelowDep.contains n let isMarkedMatcherConst (e : Expr) : Bool := e.isConst && isMarkedMatcherName e.constName! let isMarkedMatcherApp (e : Expr) : Bool := isMarkedMatcherConst e.getAppFn let containsMarkedMatcher (e : Expr) : Bool := e.find? isMarkedMatcherConst |>.isSome let rec visit (e : Expr) : MetaM Expr := do match e with | Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (← visit b) | Expr.forallE .. => forallTelescope e fun xs b => do mkForallFVars xs (← visit b) | Expr.letE n type val body _ => withLetDecl n type (← visit val) fun x => do mkLetFVars #[x] (← visit (body.instantiate1 x)) | Expr.mdata d b _ => return mkMData d (← visit b) | Expr.proj n i s _ => return mkProj n i (← visit s) | Expr.app .. => let processApp (e : Expr) : MetaM Expr := e.withApp fun f args => do return mkAppN (← visit f) (← args.mapM visit) match isMarkedMatcherApp e, (← matchMatcherApp? e) with | true, some matcherApp => let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do unless xs.size >= numParams do throwError! "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" if containsMarkedMatcher altBody then -- continue mkLambdaFVars xs (← visit altBody) else -- add idRhs marker let altBody ← mkLambdaFVars xs[numParams:xs.size] altBody let altBody ← mkIdRhs altBody mkLambdaFVars xs[0:numParams] altBody pure { matcherApp with alts := altsNew }.toExpr | _, _ => processApp e | _ => pure e return { preDef with declName := mkSmartUnfoldingNameFor preDef.declName, value := (← visit preDef.value), modifiers := {} } partial def addSmartUnfoldingDef (preDef : PreDefinition) (state : State) : TermElabM Unit := do if (← isProp preDef.type) then return () else let preDefSUnfold ← addSmartUnfoldingDefAux preDef state.matcherBelowDep addNonRec preDefSUnfold def structuralRecursion (preDefs : Array PreDefinition) : TermElabM Unit := if preDefs.size != 1 then throwError "structural recursion does not handle mutually recursive functions" else do let (preDefNonRec, state) ← run $ elimRecursion preDefs[0] mapError (addNonRec preDefNonRec) (fun msg => m!"structural recursion failed, produced type incorrect term{indentD msg}") addAndCompileUnsafeRec preDefs addSmartUnfoldingDef preDefs[0] state builtin_initialize registerTraceClass `Elab.definition.structural end Structural export Structural (structuralRecursion) end Lean.Elab
974aec3df6e91ec78e68a6fe2f13e9e382ddc0d2
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/simpPrio.lean
d005414fbb86085623a64a2ecbdd98d033ca65c8
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
183
lean
constant n : Nat @[simp] axiom prio_1000 : n = 1000 @[simp 10] axiom prio_10 : n = 10 -- simp should prefer the prio_1000 lemma with the higher priority example : n = 1000 := by simp
89fa822929c90a57263cc287b2cbfc055726de5c
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/filter/ultrafilter.lean
d845c9350166e07f5d8fb828daa8a02aac50b9d0
[ "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
12,822
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov -/ import order.filter.cofinite /-! # Ultrafilters An ultrafilter is a minimal (maximal in the set order) proper filter. In this file we define * `ultrafilter.of`: an ultrafilter that is less than or equal to a given filter; * `ultrafilter`: subtype of ultrafilters; * `ultrafilter.pure`: `pure x` as an `ultrafiler`; * `ultrafilter.map`, `ultrafilter.bind`, `ultrafilter.comap` : operations on ultrafilters; * `hyperfilter`: the ultrafilter extending the cofinite filter. -/ universes u v variables {α : Type u} {β : Type v} open set zorn filter function open_locale classical filter /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ @[protect_proj] structure ultrafilter (α : Type*) extends filter α := (ne_bot' : ne_bot to_filter) (le_of_le : ∀ g, filter.ne_bot g → g ≤ to_filter → to_filter ≤ g) namespace ultrafilter variables {f g : ultrafilter α} {s t : set α} {p q : α → Prop} instance : has_coe_t (ultrafilter α) (filter α) := ⟨ultrafilter.to_filter⟩ instance : has_mem (set α) (ultrafilter α) := ⟨λ s f, s ∈ (f : filter α)⟩ lemma unique (f : ultrafilter α) {g : filter α} (h : g ≤ f) (hne : ne_bot g . tactic.apply_instance) : g = f := le_antisymm h $ f.le_of_le g hne h instance ne_bot (f : ultrafilter α) : ne_bot (f : filter α) := f.ne_bot' @[simp, norm_cast] lemma mem_coe : s ∈ (f : filter α) ↔ s ∈ f := iff.rfl lemma coe_injective : injective (coe : ultrafilter α → filter α) | ⟨f, h₁, h₂⟩ ⟨g, h₃, h₄⟩ rfl := by congr @[simp, norm_cast] lemma coe_le_coe {f g : ultrafilter α} : (f : filter α) ≤ g ↔ f = g := ⟨λ h, coe_injective $ g.unique h, λ h, h ▸ le_rfl⟩ @[simp, norm_cast] lemma coe_inj : (f : filter α) = g ↔ f = g := coe_injective.eq_iff @[ext] lemma ext ⦃f g : ultrafilter α⦄ (h : ∀ s, s ∈ f ↔ s ∈ g) : f = g := coe_injective $ filter.ext h lemma le_of_inf_ne_bot (f : ultrafilter α) {g : filter α} (hg : ne_bot (↑f ⊓ g)) : ↑f ≤ g := le_of_inf_eq (f.unique inf_le_left hg) lemma le_of_inf_ne_bot' (f : ultrafilter α) {g : filter α} (hg : ne_bot (g ⊓ f)) : ↑f ≤ g := f.le_of_inf_ne_bot $ by rwa inf_comm @[simp] lemma compl_not_mem_iff : sᶜ ∉ f ↔ s ∈ f := ⟨λ hsc, le_principal_iff.1 $ f.le_of_inf_ne_bot ⟨λ h, hsc $ mem_of_eq_bot$ by rwa compl_compl⟩, compl_not_mem⟩ @[simp] lemma frequently_iff_eventually : (∃ᶠ x in f, p x) ↔ ∀ᶠ x in f, p x := compl_not_mem_iff alias frequently_iff_eventually ↔ filter.frequently.eventually _ lemma compl_mem_iff_not_mem : sᶜ ∈ f ↔ s ∉ f := by rw [← compl_not_mem_iff, compl_compl] lemma diff_mem_iff (f : ultrafilter α) : s \ t ∈ f ↔ s ∈ f ∧ t ∉ f := inter_mem_iff.trans $ and_congr iff.rfl compl_mem_iff_not_mem /-- If `sᶜ ∉ f ↔ s ∈ f`, then `f` is an ultrafilter. The other implication is given by `ultrafilter.compl_not_mem_iff`. -/ def of_compl_not_mem_iff (f : filter α) (h : ∀ s, sᶜ ∉ f ↔ s ∈ f) : ultrafilter α := { to_filter := f, ne_bot' := ⟨λ hf, by simpa [hf] using h⟩, le_of_le := λ g hg hgf s hs, (h s).1 $ λ hsc, by exactI compl_not_mem hs (hgf hsc) } lemma nonempty_of_mem (hs : s ∈ f) : s.nonempty := nonempty_of_mem hs lemma ne_empty_of_mem (hs : s ∈ f) : s ≠ ∅ := (nonempty_of_mem hs).ne_empty @[simp] lemma empty_not_mem : ∅ ∉ f := empty_not_mem f lemma mem_or_compl_mem (f : ultrafilter α) (s : set α) : s ∈ f ∨ sᶜ ∈ f := or_iff_not_imp_left.2 compl_mem_iff_not_mem.2 protected lemma em (f : ultrafilter α) (p : α → Prop) : (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, ¬p x := f.mem_or_compl_mem {x | p x} lemma eventually_or : (∀ᶠ x in f, p x ∨ q x) ↔ (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, q x := ⟨λ H, (f.em p).imp_right $ λ hp, (H.and hp).mono $ λ x ⟨hx, hnx⟩, hx.resolve_left hnx, λ H, H.elim (λ hp, hp.mono $ λ x, or.inl) (λ hp, hp.mono $ λ x, or.inr)⟩ lemma union_mem_iff : s ∪ t ∈ f ↔ s ∈ f ∨ t ∈ f := eventually_or lemma eventually_not : (∀ᶠ x in f, ¬p x) ↔ ¬∀ᶠ x in f, p x := compl_mem_iff_not_mem lemma eventually_imp : (∀ᶠ x in f, p x → q x) ↔ (∀ᶠ x in f, p x) → ∀ᶠ x in f, q x := by simp only [imp_iff_not_or, eventually_or, eventually_not] lemma finite_sUnion_mem_iff {s : set (set α)} (hs : finite s) : ⋃₀ s ∈ f ↔ ∃t∈s, t ∈ f := finite.induction_on hs (by simp) $ λ a s ha hs his, by simp [union_mem_iff, his, or_and_distrib_right, exists_or_distrib] lemma finite_bUnion_mem_iff {is : set β} {s : β → set α} (his : finite is) : (⋃i∈is, s i) ∈ f ↔ ∃i∈is, s i ∈ f := by simp only [← sUnion_image, finite_sUnion_mem_iff (his.image s), bex_image_iff] /-- Pushforward for ultrafilters. -/ def map (m : α → β) (f : ultrafilter α) : ultrafilter β := of_compl_not_mem_iff (map m f) $ λ s, @compl_not_mem_iff _ f (m ⁻¹' s) @[simp, norm_cast] lemma coe_map (m : α → β) (f : ultrafilter α) : (map m f : filter β) = filter.map m ↑f := rfl @[simp] lemma mem_map {m : α → β} {f : ultrafilter α} {s : set β} : s ∈ map m f ↔ m ⁻¹' s ∈ f := iff.rfl /-- The pullback of an ultrafilter along an injection whose range is large with respect to the given ultrafilter. -/ def comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) : ultrafilter α := { to_filter := comap m u, ne_bot' := u.ne_bot'.comap_of_range_mem large, le_of_le := λ g hg hgu, by { resetI, simp only [← u.unique (map_le_iff_le_comap.2 hgu), comap_map inj, le_rfl] } } @[simp] lemma mem_comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) {s : set α} : s ∈ u.comap inj large ↔ m '' s ∈ u := mem_comap_iff inj large @[simp] lemma coe_comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) : (u.comap inj large : filter α) = filter.comap m u := rfl /-- The principal ultrafilter associated to a point `x`. -/ instance : has_pure ultrafilter := ⟨λ α a, of_compl_not_mem_iff (pure a) $ λ s, by simp⟩ @[simp] lemma mem_pure {a : α} {s : set α} : s ∈ (pure a : ultrafilter α) ↔ a ∈ s := iff.rfl instance [inhabited α] : inhabited (ultrafilter α) := ⟨pure (default _)⟩ /-- Monadic bind for ultrafilters, coming from the one on filters defined in terms of map and join.-/ def bind (f : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β := of_compl_not_mem_iff (bind ↑f (λ x, ↑(m x))) $ λ s, by simp only [mem_bind', mem_coe, ← compl_mem_iff_not_mem, compl_set_of, compl_compl] instance ultrafilter.has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩ instance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map } instance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map } section local attribute [instance] filter.monad filter.is_lawful_monad instance ultrafilter.is_lawful_monad : is_lawful_monad ultrafilter := { id_map := assume α f, coe_injective (id_map f.1), pure_bind := assume α β a f, coe_injective (pure_bind a (coe ∘ f)), bind_assoc := assume α β γ f m₁ m₂, coe_injective (filter_eq rfl), bind_pure_comp_eq_map := assume α β f x, coe_injective (bind_pure_comp_eq_map f x.1) } end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ lemma exists_le (f : filter α) [h : ne_bot f] : ∃u : ultrafilter α, ↑u ≤ f := begin let τ := {f' // ne_bot f' ∧ f' ≤ f}, let r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, haveI := nonempty_of_ne_bot f, let top : τ := ⟨f, h, le_refl f⟩, let sup : Π(c:set τ), chain r c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.1, infi_ne_bot_of_directed (directed_of_chain $ chain_insert hc $ λ ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩, have : ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _), have : (∃ (u : τ), ∀ (a : τ), r u a → r a u), from exists_maximal_of_chains_bounded (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), cases this with uτ hmin, exact ⟨⟨uτ.val, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩, uτ.property.right⟩ end alias exists_le ← filter.exists_ultrafilter_le /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def of (f : filter α) [ne_bot f] : ultrafilter α := classical.some (exists_le f) lemma of_le (f : filter α) [ne_bot f] : ↑(of f) ≤ f := classical.some_spec (exists_le f) lemma of_coe (f : ultrafilter α) : of ↑f = f := coe_inj.1 $ f.unique (of_le f) lemma exists_ultrafilter_of_finite_inter_nonempty (S : set (set α)) (cond : ∀ T : finset (set α), (↑T : set (set α)) ⊆ S → (⋂₀ (↑T : set (set α))).nonempty) : ∃ F : ultrafilter α, S ⊆ F.sets := begin suffices : ∃ F : filter α, ne_bot F ∧ S ⊆ F.sets, { rcases this with ⟨F, cond, hF⟩, resetI, obtain ⟨G : ultrafilter α, h1 : ↑G ≤ F⟩ := exists_le F, exact ⟨G, λ T hT, h1 (hF hT)⟩ }, use filter.generate S, refine ⟨_, λ T hT, filter.generate_sets.basic hT⟩, rw ← forall_mem_nonempty_iff_ne_bot, intros T hT, rcases mem_generate_iff.mp hT with ⟨A, h1, h2, h3⟩, let B := set.finite.to_finset h2, rw (show A = ↑B, by simp) at *, rcases cond B h1 with ⟨x, hx⟩, exact ⟨x, h3 hx⟩, end end ultrafilter namespace filter open ultrafilter lemma mem_iff_ultrafilter {s : set α} {f : filter α} : s ∈ f ↔ ∀ g : ultrafilter α, ↑g ≤ f → s ∈ g := begin refine ⟨λ hf g hg, hg hf, λ H, by_contra $ λ hf, _⟩, set g : filter ↥sᶜ := comap coe f, haveI : ne_bot g := comap_ne_bot_iff_compl_range.2 (by simpa [compl_set_of]), simpa using H ((of g).map coe) (map_le_iff_le_comap.mpr (of_le g)) end lemma le_iff_ultrafilter {f₁ f₂ : filter α} : f₁ ≤ f₂ ↔ ∀ g : ultrafilter α, ↑g ≤ f₁ → ↑g ≤ f₂ := ⟨λ h g h₁, h₁.trans h, λ h s hs, mem_iff_ultrafilter.2 $ λ g hg, h g hg hs⟩ /-- A filter equals the intersection of all the ultrafilters which contain it. -/ lemma supr_ultrafilter_le_eq (f : filter α) : (⨆ (g : ultrafilter α) (hg : ↑g ≤ f), (g : filter α)) = f := eq_of_forall_ge_iff $ λ f', by simp only [supr_le_iff, ← le_iff_ultrafilter] /-- The `tendsto` relation can be checked on ultrafilters. -/ lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) : tendsto f l₁ l₂ ↔ ∀ g : ultrafilter α, ↑g ≤ l₁ → tendsto f g l₂ := by simpa only [tendsto_iff_comap] using le_iff_ultrafilter lemma exists_ultrafilter_iff {f : filter α} : (∃ (u : ultrafilter α), ↑u ≤ f) ↔ ne_bot f := ⟨λ ⟨u, uf⟩, ne_bot_of_le uf, λ h, @exists_ultrafilter_le _ _ h⟩ lemma forall_ne_bot_le_iff {g : filter α} {p : filter α → Prop} (hp : monotone p) : (∀ f : filter α, ne_bot f → f ≤ g → p f) ↔ ∀ f : ultrafilter α, ↑f ≤ g → p f := begin refine ⟨λ H f hf, H f f.ne_bot hf, _⟩, introsI H f hf hfg, exact hp (of_le f) (H _ ((of_le f).trans hfg)) end section hyperfilter variables (α) [infinite α] /-- The ultrafilter extending the cofinite filter. -/ noncomputable def hyperfilter : ultrafilter α := ultrafilter.of cofinite variable {α} lemma hyperfilter_le_cofinite : ↑(hyperfilter α) ≤ @cofinite α := ultrafilter.of_le cofinite @[simp] lemma bot_ne_hyperfilter : (⊥ : filter α) ≠ hyperfilter α := (by apply_instance : ne_bot ↑(hyperfilter α)).1.symm theorem nmem_hyperfilter_of_finite {s : set α} (hf : s.finite) : s ∉ hyperfilter α := λ hy, compl_not_mem hy $ hyperfilter_le_cofinite hf.compl_mem_cofinite alias nmem_hyperfilter_of_finite ← set.finite.nmem_hyperfilter theorem compl_mem_hyperfilter_of_finite {s : set α} (hf : set.finite s) : sᶜ ∈ hyperfilter α := compl_mem_iff_not_mem.2 hf.nmem_hyperfilter alias compl_mem_hyperfilter_of_finite ← set.finite.compl_mem_hyperfilter theorem mem_hyperfilter_of_finite_compl {s : set α} (hf : set.finite sᶜ) : s ∈ hyperfilter α := compl_compl s ▸ hf.compl_mem_hyperfilter end hyperfilter end filter
7c9bcbf038eb1466223363d85c6a29abb48d8a2f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/inner_product_space/euclidean_dist.lean
40ca085e11c73c9071c8107e16b03e6a8f4d0117
[ "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
4,691
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.inner_product_space.calculus import analysis.inner_product_space.pi_L2 /-! # Euclidean distance on a finite dimensional space When we define a smooth bump function on a normed space, it is useful to have a smooth distance on the space. Since the default distance is not guaranteed to be smooth, we define `to_euclidean` to be an equivalence between a finite dimensional normed space and the standard Euclidean space of the same dimension. Then we define `euclidean.dist x y = dist (to_euclidean x) (to_euclidean y)` and provide some definitions (`euclidean.ball`, `euclidean.closed_ball`) and simple lemmas about this distance. This way we hide the usage of `to_euclidean` behind an API. -/ open_locale topological_space open set variables {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] noncomputable theory /-- If `E` is a finite dimensional space over `ℝ`, then `to_euclidean` is a continuous `ℝ`-linear equivalence between `E` and the Euclidean space of the same dimension. -/ def to_euclidean : E ≃L[ℝ] euclidean_space ℝ (fin $ finite_dimensional.finrank ℝ E) := continuous_linear_equiv.of_finrank_eq finrank_euclidean_space_fin.symm namespace euclidean /-- If `x` and `y` are two points in a finite dimensional space over `ℝ`, then `euclidean.dist x y` is the distance between these points in the metric defined by some inner product space structure on `E`. -/ def dist (x y : E) : ℝ := dist (to_euclidean x) (to_euclidean y) /-- Closed ball w.r.t. the euclidean distance. -/ def closed_ball (x : E) (r : ℝ) : set E := {y | dist y x ≤ r} /-- Open ball w.r.t. the euclidean distance. -/ def ball (x : E) (r : ℝ) : set E := {y | dist y x < r} lemma ball_eq_preimage (x : E) (r : ℝ) : ball x r = to_euclidean ⁻¹' (metric.ball (to_euclidean x) r) := rfl lemma closed_ball_eq_preimage (x : E) (r : ℝ) : closed_ball x r = to_euclidean ⁻¹' (metric.closed_ball (to_euclidean x) r) := rfl lemma ball_subset_closed_ball {x : E} {r : ℝ} : ball x r ⊆ closed_ball x r := λ y (hy : _ < _), le_of_lt hy lemma is_open_ball {x : E} {r : ℝ} : is_open (ball x r) := metric.is_open_ball.preimage to_euclidean.continuous lemma mem_ball_self {x : E} {r : ℝ} (hr : 0 < r) : x ∈ ball x r := metric.mem_ball_self hr lemma closed_ball_eq_image (x : E) (r : ℝ) : closed_ball x r = to_euclidean.symm '' metric.closed_ball (to_euclidean x) r := by rw [to_euclidean.image_symm_eq_preimage, closed_ball_eq_preimage] lemma is_compact_closed_ball {x : E} {r : ℝ} : is_compact (closed_ball x r) := begin rw closed_ball_eq_image, exact (is_compact_closed_ball _ _).image to_euclidean.symm.continuous end lemma is_closed_closed_ball {x : E} {r : ℝ} : is_closed (closed_ball x r) := is_compact_closed_ball.is_closed lemma closure_ball (x : E) {r : ℝ} (h : 0 < r) : closure (ball x r) = closed_ball x r := by rw [ball_eq_preimage, ← to_euclidean.preimage_closure, closure_ball (to_euclidean x) h, closed_ball_eq_preimage] lemma exists_pos_lt_subset_ball {R : ℝ} {s : set E} {x : E} (hR : 0 < R) (hs : is_closed s) (h : s ⊆ ball x R) : ∃ r ∈ Ioo 0 R, s ⊆ ball x r := begin rw [ball_eq_preimage, ← image_subset_iff] at h, rcases exists_pos_lt_subset_ball hR (to_euclidean.is_closed_image.2 hs) h with ⟨r, hr, hsr⟩, exact ⟨r, hr, image_subset_iff.1 hsr⟩ end lemma nhds_basis_closed_ball {x : E} : (𝓝 x).has_basis (λ r : ℝ, 0 < r) (closed_ball x) := begin rw [to_euclidean.to_homeomorph.nhds_eq_comap], exact metric.nhds_basis_closed_ball.comap _ end lemma closed_ball_mem_nhds {x : E} {r : ℝ} (hr : 0 < r) : closed_ball x r ∈ 𝓝 x := nhds_basis_closed_ball.mem_of_mem hr lemma nhds_basis_ball {x : E} : (𝓝 x).has_basis (λ r : ℝ, 0 < r) (ball x) := begin rw [to_euclidean.to_homeomorph.nhds_eq_comap], exact metric.nhds_basis_ball.comap _ end lemma ball_mem_nhds {x : E} {r : ℝ} (hr : 0 < r) : ball x r ∈ 𝓝 x := nhds_basis_ball.mem_of_mem hr end euclidean variables {F : Type*} [normed_group F] [normed_space ℝ F] {f g : F → E} {n : with_top ℕ} lemma times_cont_diff.euclidean_dist (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g) (h : ∀ x, f x ≠ g x) : times_cont_diff ℝ n (λ x, euclidean.dist (f x) (g x)) := begin simp only [euclidean.dist], apply @times_cont_diff.dist ℝ, exacts [(@to_euclidean E _ _ _).times_cont_diff.comp hf, (@to_euclidean E _ _ _).times_cont_diff.comp hg, λ x, to_euclidean.injective.ne (h x)] end
686fe7735ed99172787ef5e1e79fd7bef66735d9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/hom/basic.lean
26cdd079ec5f599c00ae8c687874e6212a8626ec
[ "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
13,014
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 algebra.group_power.order /-! # Algebraic order homomorphism classes > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines hom classes for common properties at the intersection of order theory and algebra. ## Typeclasses Basic typeclasses * `nonneg_hom_class`: Homs are nonnegative: `∀ f a, 0 ≤ f a` * `subadditive_hom_class`: Homs are subadditive: `∀ f a b, f (a + b) ≤ f a + f b` * `submultiplicative_hom_class`: Homs are submultiplicative: `∀ f a b, f (a * b) ≤ f a * f b` * `mul_le_add_hom_class`: `∀ f a b, f (a * b) ≤ f a + f b` * `nonarchimedean_hom_class`: `∀ a b, f (a + b) ≤ max (f a) (f b)` Group norms * `add_group_seminorm_class`: Homs are nonnegative, subadditive, even and preserve zero. * `group_seminorm_class`: Homs are nonnegative, respect `f (a * b) ≤ f a + f b`, `f a⁻¹ = f a` and preserve zero. * `add_group_norm_class`: Homs are seminorms such that `f x = 0 → x = 0` for all `x`. * `group_norm_class`: Homs are seminorms such that `f x = 0 → x = 1` for all `x`. Ring norms * `ring_seminorm_class`: Homs are submultiplicative group norms. * `ring_norm_class`: Homs are ring seminorms that are also additive group norms. * `mul_ring_seminorm_class`: Homs are ring seminorms that are multiplicative. * `mul_ring_norm_class`: Homs are ring norms that are multiplicative. ## Notes Typeclasses for seminorms are defined here while types of seminorms are defined in `analysis.normed.group.seminorm` and `analysis.normed.ring.seminorm` because absolute values are multiplicative ring norms but outside of this use we only consider real-valued seminorms. ## TODO Finitary versions of the current lemmas. -/ /-- Diamond inheritance cannot depend on `out_param`s in the following circumstances: * there are three classes `top`, `middle`, `bottom` * all of these classes have a parameter `(α : out_param _)` * all of these classes have an instance parameter `[root α]` that depends on this `out_param` * the `root` class has two child classes: `left` and `right`, these are siblings in the hierarchy * the instance `bottom.to_middle` takes a `[left α]` parameter * the instance `middle.to_top` takes a `[right α]` parameter * there is a `leaf` class that inherits from both `left` and `right`. In that case, given instances `bottom α` and `leaf α`, Lean cannot synthesize a `top α` instance, even though the hypotheses of the instances `bottom.to_middle` and `middle.to_top` are satisfied. There are two workarounds: * You could replace the bundled inheritance implemented by the instance `middle.to_top` with unbundled inheritance implemented by adding a `[top α]` parameter to the `middle` class. This is the preferred option since it is also more compatible with Lean 4, at the cost of being more work to implement and more verbose to use. * You could weaken the `bottom.to_middle` instance by making it depend on a subclass of `middle.to_top`'s parameter, in this example replacing `[left α]` with `[leaf α]`. -/ library_note "out-param inheritance" set_option old_structure_cmd true open function variables {ι F α β γ δ : Type*} /-! ### Basics -/ /-- `nonneg_hom_class F α β` states that `F` is a type of nonnegative morphisms. -/ class nonneg_hom_class (F : Type*) (α β : out_param $ Type*) [has_zero β] [has_le β] extends fun_like F α (λ _, β) := (map_nonneg (f : F) : ∀ a, 0 ≤ f a) /-- `subadditive_hom_class F α β` states that `F` is a type of subadditive morphisms. -/ class subadditive_hom_class (F : Type*) (α β : out_param $ Type*) [has_add α] [has_add β] [has_le β] extends fun_like F α (λ _, β) := (map_add_le_add (f : F) : ∀ a b, f (a + b) ≤ f a + f b) /-- `submultiplicative_hom_class F α β` states that `F` is a type of submultiplicative morphisms. -/ @[to_additive subadditive_hom_class] class submultiplicative_hom_class (F : Type*) (α β : out_param $ Type*) [has_mul α] [has_mul β] [has_le β] extends fun_like F α (λ _, β) := (map_mul_le_mul (f : F) : ∀ a b, f (a * b) ≤ f a * f b) /-- `mul_le_add_hom_class F α β` states that `F` is a type of subadditive morphisms. -/ @[to_additive subadditive_hom_class] class mul_le_add_hom_class (F : Type*) (α β : out_param $ Type*) [has_mul α] [has_add β] [has_le β] extends fun_like F α (λ _, β) := (map_mul_le_add (f : F) : ∀ a b, f (a * b) ≤ f a + f b) /-- `nonarchimedean_hom_class F α β` states that `F` is a type of non-archimedean morphisms. -/ class nonarchimedean_hom_class (F : Type*) (α β : out_param $ Type*) [has_add α] [linear_order β] extends fun_like F α (λ _, β) := (map_add_le_max (f : F) : ∀ a b, f (a + b) ≤ max (f a) (f b)) export nonneg_hom_class (map_nonneg) export subadditive_hom_class (map_add_le_add) export submultiplicative_hom_class (map_mul_le_mul) export mul_le_add_hom_class (map_mul_le_add) export nonarchimedean_hom_class (map_add_le_max) attribute [simp] map_nonneg @[to_additive] lemma le_map_mul_map_div [group α] [comm_semigroup β] [has_le β] [submultiplicative_hom_class F α β] (f : F) (a b : α) : f a ≤ f b * f (a / b) := by simpa only [mul_comm, div_mul_cancel'] using map_mul_le_mul f (a / b) b @[to_additive] lemma le_map_add_map_div [group α] [add_comm_semigroup β] [has_le β] [mul_le_add_hom_class F α β] (f : F) (a b : α) : f a ≤ f b + f (a / b) := by simpa only [add_comm, div_mul_cancel'] using map_mul_le_add f (a / b) b @[to_additive] lemma le_map_div_mul_map_div [group α] [comm_semigroup β] [has_le β] [submultiplicative_hom_class F α β] (f : F) (a b c: α) : f (a / c) ≤ f (a / b) * f (b / c) := by simpa only [div_mul_div_cancel'] using map_mul_le_mul f (a / b) (b / c) @[to_additive] lemma le_map_div_add_map_div [group α] [add_comm_semigroup β] [has_le β] [mul_le_add_hom_class F α β] (f : F) (a b c: α) : f (a / c) ≤ f (a / b) + f (b / c) := by simpa only [div_mul_div_cancel'] using map_mul_le_add f (a / b) (b / c) /-! ### Group (semi)norms -/ /-- `add_group_seminorm_class F α` states that `F` is a type of `β`-valued seminorms on the additive group `α`. You should extend this class when you extend `add_group_seminorm`. -/ class add_group_seminorm_class (F : Type*) (α β : out_param $ Type*) [add_group α] [ordered_add_comm_monoid β] extends subadditive_hom_class F α β := (map_zero (f : F) : f 0 = 0) (map_neg_eq_map (f : F) (a : α) : f (-a) = f a) /-- `group_seminorm_class F α` states that `F` is a type of `β`-valued seminorms on the group `α`. You should extend this class when you extend `group_seminorm`. -/ @[to_additive] class group_seminorm_class (F : Type*) (α β : out_param $ Type*) [group α] [ordered_add_comm_monoid β] extends mul_le_add_hom_class F α β := (map_one_eq_zero (f : F) : f 1 = 0) (map_inv_eq_map (f : F) (a : α) : f a⁻¹ = f a) /-- `add_group_norm_class F α` states that `F` is a type of `β`-valued norms on the additive group `α`. You should extend this class when you extend `add_group_norm`. -/ class add_group_norm_class (F : Type*) (α β : out_param $ Type*) [add_group α] [ordered_add_comm_monoid β] extends add_group_seminorm_class F α β := (eq_zero_of_map_eq_zero (f : F) {a : α} : f a = 0 → a = 0) /-- `group_norm_class F α` states that `F` is a type of `β`-valued norms on the group `α`. You should extend this class when you extend `group_norm`. -/ @[to_additive] class group_norm_class (F : Type*) (α β : out_param $ Type*) [group α] [ordered_add_comm_monoid β] extends group_seminorm_class F α β := (eq_one_of_map_eq_zero (f : F) {a : α} : f a = 0 → a = 1) export add_group_seminorm_class (map_neg_eq_map) export group_seminorm_class (map_one_eq_zero map_inv_eq_map) export add_group_norm_class (eq_zero_of_map_eq_zero) export group_norm_class (eq_one_of_map_eq_zero) attribute [simp, to_additive map_zero] map_one_eq_zero attribute [simp] map_neg_eq_map attribute [simp, to_additive] map_inv_eq_map attribute [to_additive] group_seminorm_class.to_mul_le_add_hom_class attribute [to_additive] group_norm_class.to_group_seminorm_class @[priority 100] -- See note [lower instance priority] instance add_group_seminorm_class.to_zero_hom_class [add_group α] [ordered_add_comm_monoid β] [add_group_seminorm_class F α β] : zero_hom_class F α β := { ..‹add_group_seminorm_class F α β› } section group_seminorm_class variables [group α] [ordered_add_comm_monoid β] [group_seminorm_class F α β] (f : F) (x y : α) include α β @[to_additive] lemma map_div_le_add : f (x / y) ≤ f x + f y := by { rw [div_eq_mul_inv, ←map_inv_eq_map f y], exact map_mul_le_add _ _ _ } @[to_additive] lemma map_div_rev : f (x / y) = f (y / x) := by rw [←inv_div, map_inv_eq_map] @[to_additive] lemma le_map_add_map_div' : f x ≤ f y + f (y / x) := by simpa only [add_comm, map_div_rev, div_mul_cancel'] using map_mul_le_add f (x / y) y end group_seminorm_class example [ordered_add_comm_group β] : ordered_add_comm_monoid β := infer_instance @[to_additive] lemma abs_sub_map_le_div [group α] [linear_ordered_add_comm_group β] [group_seminorm_class F α β] (f : F) (x y : α) : |f x - f y| ≤ f (x / y) := begin rw [abs_sub_le_iff, sub_le_iff_le_add', sub_le_iff_le_add'], exact ⟨le_map_add_map_div _ _ _, le_map_add_map_div' _ _ _⟩ end @[to_additive, priority 100] -- See note [lower instance priority] instance group_seminorm_class.to_nonneg_hom_class [group α] [linear_ordered_add_comm_monoid β] [group_seminorm_class F α β] : nonneg_hom_class F α β := { map_nonneg := λ f a, (nsmul_nonneg_iff two_ne_zero).1 $ by { rw [two_nsmul, ←map_one_eq_zero f, ←div_self' a], exact map_div_le_add _ _ _ }, ..‹group_seminorm_class F α β› } section group_norm_class variables [group α] [ordered_add_comm_monoid β] [group_norm_class F α β] (f : F) {x : α} include α β @[simp, to_additive] lemma map_eq_zero_iff_eq_one : f x = 0 ↔ x = 1 := ⟨eq_one_of_map_eq_zero _, by { rintro rfl, exact map_one_eq_zero _ }⟩ @[to_additive] lemma map_ne_zero_iff_ne_one : f x ≠ 0 ↔ x ≠ 1 := (map_eq_zero_iff_eq_one _).not end group_norm_class @[to_additive] lemma map_pos_of_ne_one [group α] [linear_ordered_add_comm_monoid β] [group_norm_class F α β] (f : F) {x : α} (hx : x ≠ 1) : 0 < f x := (map_nonneg _ _).lt_of_ne $ ((map_ne_zero_iff_ne_one _).2 hx).symm /-! ### Ring (semi)norms -/ /-- `ring_seminorm_class F α` states that `F` is a type of `β`-valued seminorms on the ring `α`. You should extend this class when you extend `ring_seminorm`. -/ class ring_seminorm_class (F : Type*) (α β : out_param $ Type*) [non_unital_non_assoc_ring α] [ordered_semiring β] extends add_group_seminorm_class F α β, submultiplicative_hom_class F α β /-- `ring_norm_class F α` states that `F` is a type of `β`-valued norms on the ring `α`. You should extend this class when you extend `ring_norm`. -/ class ring_norm_class (F : Type*) (α β : out_param $ Type*) [non_unital_non_assoc_ring α] [ordered_semiring β] extends ring_seminorm_class F α β, add_group_norm_class F α β /-- `mul_ring_seminorm_class F α` states that `F` is a type of `β`-valued multiplicative seminorms on the ring `α`. You should extend this class when you extend `mul_ring_seminorm`. -/ class mul_ring_seminorm_class (F : Type*) (α β : out_param $ Type*) [non_assoc_ring α] [ordered_semiring β] extends add_group_seminorm_class F α β, monoid_with_zero_hom_class F α β /-- `mul_ring_norm_class F α` states that `F` is a type of `β`-valued multiplicative norms on the ring `α`. You should extend this class when you extend `mul_ring_norm`. -/ class mul_ring_norm_class (F : Type*) (α β : out_param $ Type*) [non_assoc_ring α] [ordered_semiring β] extends mul_ring_seminorm_class F α β, add_group_norm_class F α β -- See note [out-param inheritance] @[priority 100] -- See note [lower instance priority] instance ring_seminorm_class.to_nonneg_hom_class [non_unital_non_assoc_ring α] [linear_ordered_semiring β] [ring_seminorm_class F α β] : nonneg_hom_class F α β := add_group_seminorm_class.to_nonneg_hom_class @[priority 100] -- See note [lower instance priority] instance mul_ring_seminorm_class.to_ring_seminorm_class [non_assoc_ring α] [ordered_semiring β] [mul_ring_seminorm_class F α β] : ring_seminorm_class F α β := { map_mul_le_mul := λ f a b, (map_mul _ _ _).le, ..‹mul_ring_seminorm_class F α β› } @[priority 100] -- See note [lower instance priority] instance mul_ring_norm_class.to_ring_norm_class [non_assoc_ring α] [ordered_semiring β] [mul_ring_norm_class F α β] : ring_norm_class F α β := { ..‹mul_ring_norm_class F α β›, ..mul_ring_seminorm_class.to_ring_seminorm_class }
4b999ae69ae81399625603d8f2be25c6c495a5b6
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Meta/Tactic/Assert.lean
512c711eb5c5cd6ad993a057203d9770bda44c0e
[ "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
5,800
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.Tactic.Util import Lean.Meta.Tactic.FVarSubst import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Revert namespace Lean.Meta /-- Convert the given goal `Ctx |- target` into `Ctx |- type -> target`. It assumes `val` has type `type` -/ def _root_.Lean.MVarId.assert (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := mvarId.withContext do mvarId.checkNotAssigned `assert let tag ← mvarId.getTag let target ← mvarId.getType let newType := Lean.mkForall name BinderInfo.default type target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag mvarId.assign (mkApp newMVar val) return newMVar.mvarId! @[deprecated MVarId.assert] def assert (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := mvarId.assert name type val /-- Convert the given goal `Ctx |- target` into `Ctx |- let name : type := val; target`. It assumes `val` has type `type` -/ def _root_.Lean.MVarId.define (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := do mvarId.withContext do mvarId.checkNotAssigned `define let tag ← mvarId.getTag let target ← mvarId.getType let newType := Lean.mkLet name type val target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag mvarId.assign newMVar return newMVar.mvarId! @[deprecated MVarId.define] def define (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := do mvarId.define name type val /-- Convert the given goal `Ctx |- target` into `Ctx |- (hName : type) -> hName = val -> target`. It assumes `val` has type `type` -/ def _root_.Lean.MVarId.assertExt (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) (hName : Name := `h) : MetaM MVarId := do mvarId.withContext do mvarId.checkNotAssigned `assert let tag ← mvarId.getTag let target ← mvarId.getType let u ← getLevel type let hType := mkApp3 (mkConst `Eq [u]) type (mkBVar 0) val let newType := Lean.mkForall name BinderInfo.default type $ Lean.mkForall hName BinderInfo.default hType target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag let rflPrf ← mkEqRefl val mvarId.assign (mkApp2 newMVar val rflPrf) return newMVar.mvarId! @[deprecated MVarId.assertExt] def assertExt (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) (hName : Name := `h) : MetaM MVarId := do mvarId.assertExt name type val hName structure AssertAfterResult where fvarId : FVarId mvarId : MVarId subst : FVarSubst /-- Convert the given goal `Ctx |- target` into a goal containing `(userName : type)` after the local declaration with if `fvarId`. It assumes `val` has type `type`, and that `type` is well-formed after `fvarId`. Note that `val` does not need to be well-formed after `fvarId`. That is, it may contain variables that are defined after `fvarId`. -/ def _root_.Lean.MVarId.assertAfter (mvarId : MVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : MetaM AssertAfterResult := do mvarId.withContext do mvarId.checkNotAssigned `assertAfter let tag ← mvarId.getTag let target ← mvarId.getType let localDecl ← fvarId.getDecl let lctx ← getLCtx let localInsts ← getLocalInstances let fvarIds := lctx.foldl (init := #[]) (start := localDecl.index+1) fun fvarIds decl => fvarIds.push decl.fvarId let xs := fvarIds.map mkFVar let targetNew ← mkForallFVars xs target (usedLetOnly := false) let targetNew := Lean.mkForall userName BinderInfo.default type targetNew let lctxNew := fvarIds.foldl (init := lctx) fun lctxNew fvarId => lctxNew.erase fvarId let localInstsNew := localInsts.filter fun inst => !fvarIds.contains inst.fvar.fvarId! let mvarNew ← mkFreshExprMVarAt lctxNew localInstsNew targetNew MetavarKind.syntheticOpaque tag let args := (fvarIds.filter fun fvarId => !(lctx.get! fvarId).isLet).map mkFVar let args := #[val] ++ args mvarId.assign (mkAppN mvarNew args) let (fvarIdNew, mvarIdNew) ← mvarNew.mvarId!.intro1P let (fvarIdsNew, mvarIdNew) ← mvarIdNew.introNP fvarIds.size let subst := fvarIds.size.fold (init := {}) fun i subst => subst.insert fvarIds[i]! (mkFVar fvarIdsNew[i]!) return { fvarId := fvarIdNew, mvarId := mvarIdNew, subst := subst } @[deprecated MVarId.assertAfter] def assertAfter (mvarId : MVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : MetaM AssertAfterResult := do mvarId.assertAfter fvarId userName type val structure Hypothesis where userName : Name type : Expr value : Expr /-- Convert the given goal `Ctx |- target` into `Ctx, (hs[0].userName : hs[0].type) ... |-target`. It assumes `hs[i].val` has type `hs[i].type`. -/ def _root_.Lean.MVarId.assertHypotheses (mvarId : MVarId) (hs : Array Hypothesis) : MetaM (Array FVarId × MVarId) := do if hs.isEmpty then return (#[], mvarId) else mvarId.withContext do mvarId.checkNotAssigned `assertHypotheses let tag ← mvarId.getTag let target ← mvarId.getType let targetNew := hs.foldr (init := target) fun h targetNew => mkForall h.userName BinderInfo.default h.type targetNew let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag let val := hs.foldl (init := mvarNew) fun val h => mkApp val h.value mvarId.assign val mvarNew.mvarId!.introNP hs.size @[deprecated MVarId.assertHypotheses] def assertHypotheses (mvarId : MVarId) (hs : Array Hypothesis) : MetaM (Array FVarId × MVarId) := do mvarId.assertHypotheses hs end Lean.Meta
a2184561e7ee9432af2c435b89ab45cf2be1c07d
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/inner_product_space/lax_milgram.lean
c6f4f84191f2aab6fa769dfacfe1cf8d9ece23d9
[ "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
4,683
lean
/- Copyright (c) 2022 Daniel Roca González. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Roca González -/ import analysis.inner_product_space.projection import analysis.inner_product_space.dual import analysis.normed_space.banach import analysis.normed_space.operator_norm import topology.metric_space.antilipschitz /-! # The Lax-Milgram Theorem We consider an Hilbert space `V` over `ℝ` equipped with a bounded bilinear form `B : V →L[ℝ] V →L[ℝ] ℝ`. Recall that a bilinear form `B : V →L[ℝ] V →L[ℝ] ℝ` is *coercive* iff `∃ C, (0 < C) ∧ ∀ u, C * ‖u‖ * ‖u‖ ≤ B u u`. Under the hypothesis that `B` is coercive we prove the Lax-Milgram theorem: that is, the map `inner_product_space.continuous_linear_map_of_bilin` from `analysis.inner_product_space.dual` can be upgraded to a continuous equivalence `is_coercive.continuous_linear_equiv_of_bilin : V ≃L[ℝ] V`. ## References * We follow the notes of Peter Howard's Spring 2020 *M612: Partial Differential Equations* lecture, see[howard] ## Tags dual, Lax-Milgram -/ noncomputable theory open is_R_or_C linear_map continuous_linear_map inner_product_space linear_map (ker range) open_locale real_inner_product_space nnreal universe u namespace is_coercive variables {V : Type u} [normed_add_comm_group V] [inner_product_space ℝ V] [complete_space V] variables {B : V →L[ℝ] V →L[ℝ] ℝ} local postfix `♯`:1025 := @continuous_linear_map_of_bilin ℝ V _ _ _ _ lemma bounded_below (coercive : is_coercive B) : ∃ C, 0 < C ∧ ∀ v, C * ‖v‖ ≤ ‖B♯ v‖ := begin rcases coercive with ⟨C, C_ge_0, coercivity⟩, refine ⟨C, C_ge_0, _⟩, intro v, by_cases h : 0 < ‖v‖, { refine (mul_le_mul_right h).mp _, calc C * ‖v‖ * ‖v‖ ≤ B v v : coercivity v ... = ⟪B♯ v, v⟫_ℝ : (continuous_linear_map_of_bilin_apply ℝ B v v).symm ... ≤ ‖B♯ v‖ * ‖v‖ : real_inner_le_norm (B♯ v) v, }, { have : v = 0 := by simpa using h, simp [this], } end lemma antilipschitz (coercive : is_coercive B) : ∃ C : ℝ≥0, 0 < C ∧ antilipschitz_with C B♯ := begin rcases coercive.bounded_below with ⟨C, C_pos, below_bound⟩, refine ⟨(C⁻¹).to_nnreal, real.to_nnreal_pos.mpr (inv_pos.mpr C_pos), _⟩, refine continuous_linear_map.antilipschitz_of_bound B♯ _, simp_rw [real.coe_to_nnreal', max_eq_left_of_lt (inv_pos.mpr C_pos), ←inv_mul_le_iff (inv_pos.mpr C_pos)], simpa using below_bound, end lemma ker_eq_bot (coercive : is_coercive B) : ker B♯ = ⊥ := begin rw [linear_map_class.ker_eq_bot], rcases coercive.antilipschitz with ⟨_, _, antilipschitz⟩, exact antilipschitz.injective, end lemma closed_range (coercive : is_coercive B) : is_closed (range B♯ : set V) := begin rcases coercive.antilipschitz with ⟨_, _, antilipschitz⟩, exact antilipschitz.is_closed_range B♯.uniform_continuous, end lemma range_eq_top (coercive : is_coercive B) : range B♯ = ⊤ := begin haveI := coercive.closed_range.complete_space_coe, rw ← (range B♯).orthogonal_orthogonal, rw submodule.eq_top_iff', intros v w mem_w_orthogonal, rcases coercive with ⟨C, C_pos, coercivity⟩, obtain rfl : w = 0, { rw [←norm_eq_zero, ←mul_self_eq_zero, ←mul_right_inj' C_pos.ne', mul_zero, ←mul_assoc], apply le_antisymm, { calc C * ‖w‖ * ‖w‖ ≤ B w w : coercivity w ... = ⟪B♯ w, w⟫_ℝ : (continuous_linear_map_of_bilin_apply ℝ B w w).symm ... = 0 : mem_w_orthogonal _ ⟨w, rfl⟩ }, { exact mul_nonneg (mul_nonneg C_pos.le (norm_nonneg w)) (norm_nonneg w) } }, exact inner_zero_left _, end /-- The Lax-Milgram equivalence of a coercive bounded bilinear operator: for all `v : V`, `continuous_linear_equiv_of_bilin B v` is the unique element `V` such that `⟪continuous_linear_equiv_of_bilin B v, w⟫ = B v w`. The Lax-Milgram theorem states that this is a continuous equivalence. -/ def continuous_linear_equiv_of_bilin (coercive : is_coercive B) : V ≃L[ℝ] V := continuous_linear_equiv.of_bijective B♯ coercive.ker_eq_bot coercive.range_eq_top @[simp] lemma continuous_linear_equiv_of_bilin_apply (coercive : is_coercive B) (v w : V) : ⟪coercive.continuous_linear_equiv_of_bilin v, w⟫_ℝ = B v w := continuous_linear_map_of_bilin_apply ℝ B v w lemma unique_continuous_linear_equiv_of_bilin (coercive : is_coercive B) {v f : V} (is_lax_milgram : (∀ w, ⟪f, w⟫_ℝ = B v w)) : f = coercive.continuous_linear_equiv_of_bilin v := unique_continuous_linear_map_of_bilin ℝ B is_lax_milgram end is_coercive
a1fa430f13901420babaec8a6b8f36fceefbf8c7
3268ab3a126f0fef71459fbf170dc38efe5d0506
/cohomology/basic.hlean
5ce09d20126d5867822a2545052248213a4db29a
[ "Apache-2.0" ]
permissive
soraismus/Spectral
f043fed1a4e02ddfeba531769b2980eb817471f4
32512bf47db3a1b932856e7ed7c7830b1fc07ef0
refs/heads/master
1,585,628,705,579
1,538,609,948,000
1,538,609,974,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,876
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Ulrik Buchholtz Reduced cohomology of spectra and cohomology theories -/ import ..spectrum.basic ..algebra.arrow_group ..algebra.product_group ..choice ..homotopy.fwedge ..homotopy.pushout ..homotopy.EM ..homotopy.wedge open eq spectrum int trunc pointed EM group algebra circle sphere nat EM.ops equiv susp is_trunc function fwedge cofiber bool lift sigma is_equiv choice pushout algebra unit pi is_conn namespace cohomology /- The cohomology of X with coefficients in Y is trunc 0 (A →* Ω[2] (Y (n+2))) In the file arrow_group (in algebra) we construct the group structure on this type. Equivalently, it's πₛ[n] (sp_cotensor X Y) -/ definition cohomology (X : Type*) (Y : spectrum) (n : ℤ) : AbGroup := AbGroup_trunc_pmap X (Y (n+2)) definition ordinary_cohomology [reducible] (X : Type*) (G : AbGroup) (n : ℤ) : AbGroup := cohomology X (EM_spectrum G) n definition ordinary_cohomology_Z [reducible] (X : Type*) (n : ℤ) : AbGroup := ordinary_cohomology X agℤ n definition unreduced_cohomology (X : Type) (Y : spectrum) (n : ℤ) : AbGroup := cohomology X₊ Y n definition unreduced_ordinary_cohomology [reducible] (X : Type) (G : AbGroup) (n : ℤ) : AbGroup := unreduced_cohomology X (EM_spectrum G) n definition unreduced_ordinary_cohomology_Z [reducible] (X : Type) (n : ℤ) : AbGroup := unreduced_ordinary_cohomology X agℤ n definition parametrized_cohomology {X : Type*} (Y : X → spectrum) (n : ℤ) : AbGroup := AbGroup_trunc_ppi (λx, Y x (n+2)) definition ordinary_parametrized_cohomology [reducible] {X : Type*} (G : X → AbGroup) (n : ℤ) : AbGroup := parametrized_cohomology (λx, EM_spectrum (G x)) n definition unreduced_parametrized_cohomology {X : Type} (Y : X → spectrum) (n : ℤ) : AbGroup := parametrized_cohomology (add_point_spectrum Y) n definition unreduced_ordinary_parametrized_cohomology [reducible] {X : Type} (G : X → AbGroup) (n : ℤ) : AbGroup := unreduced_parametrized_cohomology (λx, EM_spectrum (G x)) n notation `H^` n `[`:0 X:0 `, ` Y:0 `]`:0 := cohomology X Y n notation `oH^` n `[`:0 X:0 `, ` G:0 `]`:0 := ordinary_cohomology X G n notation `H^` n `[`:0 X:0 `]`:0 := ordinary_cohomology_Z X n notation `uH^` n `[`:0 X:0 `, ` Y:0 `]`:0 := unreduced_cohomology X Y n notation `uoH^` n `[`:0 X:0 `, ` G:0 `]`:0 := unreduced_ordinary_cohomology X G n notation `uH^` n `[`:0 X:0 `]`:0 := unreduced_ordinary_cohomology_Z X n notation `pH^` n `[`:0 binders `, ` r:(scoped Y, parametrized_cohomology Y n) `]`:0 := r notation `opH^` n `[`:0 binders `, ` r:(scoped G, ordinary_parametrized_cohomology G n) `]`:0 := r notation `upH^` n `[`:0 binders `, ` r:(scoped Y, unreduced_parametrized_cohomology Y n) `]`:0 := r notation `uopH^` n `[`:0 binders `, ` r:(scoped G, unreduced_ordinary_parametrized_cohomology G n) `]`:0 := r /- an alternate definition of cohomology -/ definition parametrized_cohomology_isomorphism_shomotopy_group_spi {X : Type*} (Y : X → spectrum) {n m : ℤ} (p : -m = n) : pH^n[(x : X), Y x] ≃g πₛ[m] (spi X Y) := begin apply isomorphism.trans (trunc_ppi_loop_isomorphism (λx, Ω (Y x (n + 2))))⁻¹ᵍ, apply homotopy_group_isomorphism_of_pequiv 0, esimp, have q : sub 2 m = n + 2, from (int.add_comm (of_nat 2) (-m) ⬝ ap (λk, k + of_nat 2) p), rewrite q, symmetry, apply loop_pppi_pequiv end definition unreduced_parametrized_cohomology_isomorphism_shomotopy_group_supi {X : Type} (Y : X → spectrum) {n m : ℤ} (p : -m = n) : upH^n[(x : X), Y x] ≃g πₛ[m] (supi X Y) := begin refine parametrized_cohomology_isomorphism_shomotopy_group_spi (add_point_spectrum Y) p ⬝g _, apply shomotopy_group_isomorphism_of_pequiv, intro k, apply pppi_add_point_over end definition cohomology_isomorphism_shomotopy_group_sp_cotensor (X : Type*) (Y : spectrum) {n m : ℤ} (p : -m = n) : H^n[X, Y] ≃g πₛ[m] (sp_cotensor X Y) := begin refine parametrized_cohomology_isomorphism_shomotopy_group_spi (λx, Y) p ⬝g _, apply shomotopy_group_isomorphism_of_pequiv, intro k, apply pppi_pequiv_ppmap end definition unreduced_cohomology_isomorphism_shomotopy_group_sp_ucotensor (X : Type) (Y : spectrum) {n m : ℤ} (p : -m = n) : uH^n[X, Y] ≃g πₛ[m] (sp_ucotensor X Y) := begin refine cohomology_isomorphism_shomotopy_group_sp_cotensor X₊ Y p ⬝g _, apply shomotopy_group_isomorphism_of_pequiv, intro k, apply ppmap_add_point end /- functoriality -/ definition cohomology_functor [constructor] {X X' : Type*} (f : X' →* X) (Y : spectrum) (n : ℤ) : cohomology X Y n →g cohomology X' Y n := Group_trunc_pmap_homomorphism f notation `H^→` n `[`:0 f:0 `, ` Y:0 `]`:0 := cohomology_functor f Y n definition cohomology_functor_pid (X : Type*) (Y : spectrum) (n : ℤ) (f : H^n[X, Y]) : cohomology_functor (pid X) Y n f = f := !Group_trunc_pmap_pid definition cohomology_functor_pcompose {X X' X'' : Type*} (f : X' →* X) (g : X'' →* X') (Y : spectrum) (n : ℤ) (h : H^n[X, Y]) : cohomology_functor (f ∘* g) Y n h = cohomology_functor g Y n (cohomology_functor f Y n h) := !Group_trunc_pmap_pcompose definition cohomology_functor_phomotopy {X X' : Type*} {f g : X' →* X} (p : f ~* g) (Y : spectrum) (n : ℤ) : cohomology_functor f Y n ~ cohomology_functor g Y n := Group_trunc_pmap_phomotopy p notation `H^~` n `[`:0 h:0 `, ` Y:0 `]`:0 := cohomology_functor_phomotopy h Y n definition cohomology_functor_phomotopy_refl {X X' : Type*} (f : X' →* X) (Y : spectrum) (n : ℤ) (x : H^n[X, Y]) : cohomology_functor_phomotopy (phomotopy.refl f) Y n x = idp := Group_trunc_pmap_phomotopy_refl f x definition cohomology_functor_pconst {X X' : Type*} (Y : spectrum) (n : ℤ) (f : H^n[X, Y]) : cohomology_functor (pconst X' X) Y n f = 1 := !Group_trunc_pmap_pconst definition cohomology_isomorphism {X X' : Type*} (f : X' ≃* X) (Y : spectrum) (n : ℤ) : H^n[X, Y] ≃g H^n[X', Y] := Group_trunc_pmap_isomorphism f notation `H^≃` n `[`:0 e:0 `, ` Y:0 `]`:0 := cohomology_isomorphism e Y n definition cohomology_isomorphism_refl (X : Type*) (Y : spectrum) (n : ℤ) (x : H^n[X,Y]) : H^≃n[pequiv.refl X, Y] x = x := !Group_trunc_pmap_isomorphism_refl definition cohomology_isomorphism_right (X : Type*) {Y Y' : spectrum} (e : Πn, Y n ≃* Y' n) (n : ℤ) : H^n[X, Y] ≃g H^n[X, Y'] := cohomology_isomorphism_shomotopy_group_sp_cotensor X Y !neg_neg ⬝g shomotopy_group_isomorphism_of_pequiv (-n) (λk, ppmap_pequiv_ppmap_right (e k)) ⬝g (cohomology_isomorphism_shomotopy_group_sp_cotensor X Y' !neg_neg)⁻¹ᵍ definition unreduced_cohomology_isomorphism {X X' : Type} (f : X' ≃ X) (Y : spectrum) (n : ℤ) : uH^n[X, Y] ≃g uH^n[X', Y] := cohomology_isomorphism (add_point_pequiv f) Y n definition unreduced_cohomology_isomorphism_right (X : Type) {Y Y' : spectrum} (e : Πn, Y n ≃* Y' n) (n : ℤ) : uH^n[X, Y] ≃g uH^n[X, Y'] := cohomology_isomorphism_right X₊ e n definition unreduced_ordinary_cohomology_isomorphism {X X' : Type} (f : X' ≃ X) (G : AbGroup) (n : ℤ) : uoH^n[X, G] ≃g uoH^n[X', G] := unreduced_cohomology_isomorphism f (EM_spectrum G) n definition unreduced_ordinary_cohomology_isomorphism_right (X : Type) {G G' : AbGroup} (e : G ≃g G') (n : ℤ) : uoH^n[X, G] ≃g uoH^n[X, G'] := unreduced_cohomology_isomorphism_right X (EM_spectrum_pequiv e) n definition parametrized_cohomology_isomorphism_right {X : Type*} {Y Y' : X → spectrum} (e : Πx n, Y x n ≃* Y' x n) (n : ℤ) : pH^n[(x : X), Y x] ≃g pH^n[(x : X), Y' x] := parametrized_cohomology_isomorphism_shomotopy_group_spi Y !neg_neg ⬝g shomotopy_group_isomorphism_of_pequiv (-n) (λk, ppi_pequiv_right (λx, e x k)) ⬝g (parametrized_cohomology_isomorphism_shomotopy_group_spi Y' !neg_neg)⁻¹ᵍ definition unreduced_parametrized_cohomology_isomorphism_right {X : Type} {Y Y' : X → spectrum} (e : Πx n, Y x n ≃* Y' x n) (n : ℤ) : upH^n[(x : X), Y x] ≃g upH^n[(x : X), Y' x] := parametrized_cohomology_isomorphism_right (λx' k, add_point_over_pequiv (λx, e x k) x') n definition unreduced_ordinary_parametrized_cohomology_isomorphism_right {X : Type} {G G' : X → AbGroup} (e : Πx, G x ≃g G' x) (n : ℤ) : uopH^n[(x : X), G x] ≃g uopH^n[(x : X), G' x] := unreduced_parametrized_cohomology_isomorphism_right (λx, EM_spectrum_pequiv (e x)) n definition ordinary_cohomology_isomorphism_right (X : Type*) {G G' : AbGroup} (e : G ≃g G') (n : ℤ) : oH^n[X, G] ≃g oH^n[X, G'] := cohomology_isomorphism_right X (EM_spectrum_pequiv e) n definition ordinary_parametrized_cohomology_isomorphism_right {X : Type*} {G G' : X → AbGroup} (e : Πx, G x ≃g G' x) (n : ℤ) : opH^n[(x : X), G x] ≃g opH^n[(x : X), G' x] := parametrized_cohomology_isomorphism_right (λx, EM_spectrum_pequiv (e x)) n definition uopH_isomorphism_opH {X : Type} (G : X → AbGroup) (n : ℤ) : uopH^n[(x : X), G x] ≃g opH^n[(x : X₊), add_point_AbGroup G x] := parametrized_cohomology_isomorphism_right begin intro x n, induction x with x, { symmetry, apply EM_spectrum_trivial, }, { reflexivity } end n definition pH_isomorphism_H {X : Type*} (Y : spectrum) (n : ℤ) : pH^n[(x : X), Y] ≃g H^n[X, Y] := by reflexivity definition opH_isomorphism_oH {X : Type*} (G : AbGroup) (n : ℤ) : opH^n[(x : X), G] ≃g oH^n[X, G] := by reflexivity definition upH_isomorphism_uH {X : Type} (Y : spectrum) (n : ℤ) : upH^n[(x : X), Y] ≃g uH^n[X, Y] := unreduced_parametrized_cohomology_isomorphism_shomotopy_group_supi _ !neg_neg ⬝g (unreduced_cohomology_isomorphism_shomotopy_group_sp_ucotensor _ _ !neg_neg)⁻¹ᵍ definition uopH_isomorphism_uoH {X : Type} (G : AbGroup) (n : ℤ) : uopH^n[(x : X), G] ≃g uoH^n[X, G] := !upH_isomorphism_uH definition uopH_isomorphism_uoH_of_is_conn {X : Type*} (G : X → AbGroup) (n : ℤ) (H : is_conn 1 X) : uopH^n[(x : X), G x] ≃g uoH^n[X, G pt] := begin refine _ ⬝g !uopH_isomorphism_uoH, apply unreduced_ordinary_parametrized_cohomology_isomorphism_right, refine is_conn.elim 0 _ _, reflexivity end definition cohomology_change_int (X : Type*) (Y : spectrum) {n n' : ℤ} (p : n = n') : H^n[X, Y] ≃g H^n'[X, Y] := isomorphism_of_eq (ap (λn, H^n[X, Y]) p) definition parametrized_cohomology_change_int (X : Type*) (Y : X → spectrum) {n n' : ℤ} (p : n = n') : pH^n[(x : X), Y x] ≃g pH^n'[(x : X), Y x] := isomorphism_of_eq (ap (λn, pH^n[(x : X), Y x]) p) /- suspension axiom -/ definition cohomology_susp_2 (Y : spectrum) (n : ℤ) : Ω (Ω[2] (Y ((n+1)+2))) ≃* Ω[2] (Y (n+2)) := begin apply loopn_pequiv_loopn 2, exact loop_pequiv_loop (pequiv_of_eq (ap Y (add.right_comm n 1 2))) ⬝e* !equiv_glue⁻¹ᵉ* end definition cohomology_susp_1 (X : Type*) (Y : spectrum) (n : ℤ) : susp X →* Ω (Ω (Y (n + 1 + 2))) ≃ X →* Ω (Ω (Y (n+2))) := calc susp X →* Ω[2] (Y (n + 1 + 2)) ≃ X →* Ω (Ω[2] (Y (n + 1 + 2))) : susp_adjoint_loop_unpointed ... ≃ X →* Ω[2] (Y (n+2)) : equiv_of_pequiv (ppmap_pequiv_ppmap_right (cohomology_susp_2 Y n)) definition cohomology_susp_1_pmap_mul {X : Type*} {Y : spectrum} {n : ℤ} (f g : susp X →* Ω (Ω (Y (n + 1 + 2)))) : cohomology_susp_1 X Y n (pmap_mul f g) ~* pmap_mul (cohomology_susp_1 X Y n f) (cohomology_susp_1 X Y n g) := begin unfold [cohomology_susp_1], refine pwhisker_left _ !loop_susp_intro_pmap_mul ⬝* _, apply pcompose_pmap_mul end definition cohomology_susp_equiv (X : Type*) (Y : spectrum) (n : ℤ) : H^n+1[susp X, Y] ≃ H^n[X, Y] := trunc_equiv_trunc _ (cohomology_susp_1 X Y n) definition cohomology_susp (X : Type*) (Y : spectrum) (n : ℤ) : H^n+1[susp X, Y] ≃g H^n[X, Y] := isomorphism_of_equiv (cohomology_susp_equiv X Y n) begin intro f₁ f₂, induction f₁ with f₁, induction f₂ with f₂, apply ap tr, apply eq_of_phomotopy, exact cohomology_susp_1_pmap_mul f₁ f₂ end definition cohomology_susp_natural {X X' : Type*} (f : X →* X') (Y : spectrum) (n : ℤ) : cohomology_susp X Y n ∘ cohomology_functor (susp_functor f) Y (n+1) ~ cohomology_functor f Y n ∘ cohomology_susp X' Y n := begin refine (trunc_functor_compose _ _ _)⁻¹ʰᵗʸ ⬝hty _ ⬝hty trunc_functor_compose _ _ _, apply trunc_functor_homotopy, intro g, apply eq_of_phomotopy, refine _ ⬝* !passoc⁻¹*, apply pwhisker_left, apply loop_susp_intro_natural end /- exactness -/ definition cohomology_exact {X X' : Type*} (f : X →* X') (Y : spectrum) (n : ℤ) : is_exact_g (cohomology_functor (pcod f) Y n) (cohomology_functor f Y n) := is_exact_trunc_functor (cofiber_exact f) /- additivity -/ definition additive_hom [constructor] {I : Type} (X : I → Type*) (Y : spectrum) (n : ℤ) : H^n[⋁X, Y] →g Πᵍ i, H^n[X i, Y] := Group_pi_intro (λi, cohomology_functor (pinl i) Y n) definition additive_equiv.{u} {I : Type.{u}} (H : has_choice 0 I) (X : I → Type*) (Y : spectrum) (n : ℤ) : H^n[⋁X, Y] ≃ Πᵍ i, H^n[X i, Y] := trunc_fwedge_pmap_equiv H X (Ω[2] (Y (n+2))) definition spectrum_additive {I : Type} (H : has_choice 0 I) (X : I → Type*) (Y : spectrum) (n : ℤ) : is_equiv (additive_hom X Y n) := is_equiv_of_equiv_of_homotopy (additive_equiv H X Y n) begin intro f, induction f, reflexivity end definition cohomology_fwedge.{u} {I : Type.{u}} (H : has_choice 0 I) (X : I → Type*) (Y : spectrum) (n : ℤ) : H^n[⋁X, Y] ≃g Πᵍ i, H^n[X i, Y] := isomorphism.mk (additive_hom X Y n) (spectrum_additive H X Y n) /- dimension axiom for ordinary cohomology -/ open is_conn trunc_index theorem ordinary_cohomology_dimension (G : AbGroup) (n : ℤ) (H : n ≠ 0) : is_contr (oH^n[pbool, G]) := begin apply is_conn_equiv_closed 0 !pmap_pbool_equiv⁻¹ᵉ, apply is_conn_equiv_closed 0 !equiv_glue2⁻¹ᵉ, cases n with n n, { cases n with n, { exfalso, apply H, reflexivity }, { apply is_conn_of_le, apply zero_le_of_nat n, exact is_conn_EMadd1 G n, }}, { apply is_trunc_trunc_of_is_trunc, apply @is_contr_loop_of_is_trunc (n+1) (K G 0), apply is_trunc_of_le _ (zero_le_of_nat n) _ } end theorem ordinary_cohomology_dimension_plift (G : AbGroup) (n : ℤ) (H : n ≠ 0) : is_contr (oH^n[plift pbool, G]) := is_trunc_equiv_closed_rev -2 (equiv_of_isomorphism (cohomology_isomorphism (pequiv_plift pbool) _ _)) (ordinary_cohomology_dimension G n H) definition cohomology_iterate_susp (X : Type*) (Y : spectrum) (n : ℤ) (k : ℕ) : H^n+k[iterate_susp k X, Y] ≃g H^n[X, Y] := begin induction k with k IH, { exact cohomology_change_int X Y !add_zero }, { exact cohomology_change_int _ _ !add.assoc⁻¹ ⬝g cohomology_susp _ _ _ ⬝g IH } end definition ordinary_cohomology_pbool (G : AbGroup) : oH^0[pbool, G] ≃g G := begin refine cohomology_isomorphism_shomotopy_group_sp_cotensor _ _ !neg_neg ⬝g _, change πg[2] (pbool →** EM G 2) ≃g G, refine homotopy_group_isomorphism_of_pequiv 1 !ppmap_pbool_pequiv ⬝g ghomotopy_group_EM G 1 end definition ordinary_cohomology_sphere (G : AbGroup) (n : ℕ) : oH^n[sphere n, G] ≃g G := begin refine cohomology_isomorphism_shomotopy_group_sp_cotensor _ _ !neg_neg ⬝g _, change πg[2] (sphere n →** EM_spectrum G (2 - -n)) ≃g G, refine homotopy_group_isomorphism_of_pequiv 1 _ ⬝g ghomotopy_group_EMadd1 G 1, have p : 2 - (-n) = succ (1 + n), from !sub_eq_add_neg ⬝ ap (add 2) !neg_neg ⬝ ap of_nat !succ_add, refine !sphere_pmap_pequiv ⬝e* Ω≃[n] (pequiv_ap (EM_spectrum G) p) ⬝e* loopn_EMadd1_add G n 1, end definition ordinary_cohomology_sphere_of_neq (G : AbGroup) {n : ℤ} {k : ℕ} (p : n ≠ k) : is_contr (oH^n[sphere k, G]) := begin refine is_contr_equiv_closed_rev _ (ordinary_cohomology_dimension G (n-k) (λh, p (eq_of_sub_eq_zero h))), apply equiv_of_isomorphism, exact cohomology_change_int _ _ !neg_add_cancel_right⁻¹ ⬝g cohomology_iterate_susp pbool (EM_spectrum G) (n - k) k end definition cohomology_punit (Y : spectrum) (n : ℤ) : is_contr (H^n[punit, Y]) := @is_trunc_trunc_of_is_trunc _ _ _ !is_contr_punit_pmap definition cohomology_wedge (X X' : Type*) (Y : spectrum) (n : ℤ) : H^n[wedge X X', Y] ≃g H^n[X, Y] ×ag H^n[X', Y] := H^≃n[(wedge_pequiv_fwedge X X')⁻¹ᵉ*, Y] ⬝g cohomology_fwedge (has_choice_pbool 0) _ _ _ ⬝g Group_pi_isomorphism_Group_pi erfl begin intro b, induction b: reflexivity end ⬝g (product_isomorphism_Group_pi H^n[X, Y] H^n[X', Y])⁻¹ᵍ ⬝g proof !isomorphism.refl qed definition cohomology_isomorphism_of_equiv {X X' : Type*} (e : X ≃ X') (Y : spectrum) (n : ℤ) : H^n[X', Y] ≃g H^n[X, Y] := !cohomology_susp⁻¹ᵍ ⬝g H^≃n+1[susp_pequiv_of_equiv e, Y] ⬝g !cohomology_susp definition unreduced_cohomology_split (X : Type*) (Y : spectrum) (n : ℤ) : uH^n[X, Y] ≃g H^n[X, Y] ×ag H^n[pbool, Y] := cohomology_isomorphism_of_equiv (wedge.wedge_pbool_equiv_add_point X) Y n ⬝g cohomology_wedge X pbool Y n definition unreduced_ordinary_cohomology_nonzero (X : Type*) (G : AbGroup) (n : ℤ) (H : n ≠ 0) : uoH^n[X, G] ≃g oH^n[X, G] := unreduced_cohomology_split X (EM_spectrum G) n ⬝g product_trivial_right _ _ (ordinary_cohomology_dimension _ _ H) definition unreduced_ordinary_cohomology_zero (X : Type*) (G : AbGroup) : uoH^0[X, G] ≃g oH^0[X, G] ×ag G := unreduced_cohomology_split X (EM_spectrum G) 0 ⬝g (!isomorphism.refl ×≃g ordinary_cohomology_pbool G) definition unreduced_ordinary_cohomology_pbool (G : AbGroup) : uoH^0[pbool, G] ≃g G ×ag G := unreduced_ordinary_cohomology_zero pbool G ⬝g (ordinary_cohomology_pbool G ×≃g !isomorphism.refl) definition unreduced_ordinary_cohomology_pbool_nonzero (G : AbGroup) (n : ℤ) (H : n ≠ 0) : is_contr (uoH^n[pbool, G]) := is_contr_equiv_closed_rev (equiv_of_isomorphism (unreduced_ordinary_cohomology_nonzero pbool G n H)) (ordinary_cohomology_dimension G n H) definition unreduced_ordinary_cohomology_sphere_zero (G : AbGroup) (n : ℕ) (H : n ≠ 0) : uoH^0[sphere n, G] ≃g G := unreduced_ordinary_cohomology_zero (sphere n) G ⬝g product_trivial_left _ _ (ordinary_cohomology_sphere_of_neq _ (λh, H h⁻¹)) definition unreduced_ordinary_cohomology_sphere (G : AbGroup) (n : ℕ) (H : n ≠ 0) : uoH^n[sphere n, G] ≃g G := unreduced_ordinary_cohomology_nonzero (sphere n) G n H ⬝g ordinary_cohomology_sphere G n definition unreduced_ordinary_cohomology_sphere_of_neq (G : AbGroup) {n : ℤ} {k : ℕ} (p : n ≠ k) (q : n ≠ 0) : is_contr (uoH^n[sphere k, G]) := is_contr_equiv_closed_rev (equiv_of_isomorphism (unreduced_ordinary_cohomology_nonzero (sphere k) G n q)) (ordinary_cohomology_sphere_of_neq G p) theorem is_contr_cohomology_of_is_contr_spectrum (n : ℤ) (X : Type*) (Y : spectrum) (H : is_contr (Y n)) : is_contr (H^n[X, Y]) := begin apply is_trunc_trunc_of_is_trunc, apply is_trunc_pmap, refine is_contr_equiv_closed_rev _ H, exact loop_pequiv_loop (loop_pequiv_loop (pequiv_ap Y (add.assoc n 1 1)⁻¹) ⬝e* (equiv_glue Y (n+1))⁻¹ᵉ*) ⬝e (equiv_glue Y n)⁻¹ᵉ* end theorem is_contr_ordinary_cohomology (n : ℤ) (X : Type*) (G : AbGroup) (H : is_contr G) : is_contr (oH^n[X, G]) := begin apply is_contr_cohomology_of_is_contr_spectrum, exact is_contr_EM_spectrum _ _ H end theorem is_contr_unreduced_ordinary_cohomology (n : ℤ) (X : Type) (G : AbGroup) (H : is_contr G) : is_contr (uoH^n[X, G]) := is_contr_ordinary_cohomology _ _ _ H theorem is_contr_ordinary_cohomology_of_neg {n : ℤ} (X : Type*) (G : AbGroup) (H : n < 0) : is_contr (oH^n[X, G]) := begin apply is_contr_cohomology_of_is_contr_spectrum, cases n with n n, contradiction, apply is_contr_EM_spectrum_neg end /- cohomology theory -/ structure cohomology_theory.{u} : Type.{u+1} := (HH : ℤ → pType.{u} → AbGroup.{u}) (Hiso : Π(n : ℤ) {X Y : Type*} (f : X ≃* Y), HH n Y ≃g HH n X) (Hiso_refl : Π(n : ℤ) (X : Type*) (x : HH n X), Hiso n pequiv.rfl x = x) (Hh : Π(n : ℤ) {X Y : Type*} (f : X →* Y), HH n Y →g HH n X) (Hhomotopy : Π(n : ℤ) {X Y : Type*} {f g : X →* Y} (p : f ~* g), Hh n f ~ Hh n g) (Hhomotopy_refl : Π(n : ℤ) {X Y : Type*} (f : X →* Y) (x : HH n Y), Hhomotopy n (phomotopy.refl f) x = idp) (Hid : Π(n : ℤ) {X : Type*} (x : HH n X), Hh n (pid X) x = x) (Hcompose : Π(n : ℤ) {X Y Z : Type*} (g : Y →* Z) (f : X →* Y) (z : HH n Z), Hh n (g ∘* f) z = Hh n f (Hh n g z)) (Hsusp : Π(n : ℤ) (X : Type*), HH (succ n) (susp X) ≃g HH n X) (Hsusp_natural : Π(n : ℤ) {X Y : Type*} (f : X →* Y), Hsusp n X ∘ Hh (succ n) (susp_functor f) ~ Hh n f ∘ Hsusp n Y) (Hexact : Π(n : ℤ) {X Y : Type*} (f : X →* Y), is_exact_g (Hh n (pcod f)) (Hh n f)) (Hadditive : Π(n : ℤ) {I : Type.{u}} (X : I → Type*), has_choice 0 I → is_equiv (Group_pi_intro (λi, Hh n (pinl i)) : HH n (⋁ X) → Πᵍ i, HH n (X i))) structure ordinary_cohomology_theory.{u} extends cohomology_theory.{u} : Type.{u+1} := (Hdimension : Π(n : ℤ), n ≠ 0 → is_contr (HH n (plift pbool))) attribute cohomology_theory.HH [coercion] postfix `^→`:90 := cohomology_theory.Hh open cohomology_theory definition Hequiv (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X ≃* Y) : H n Y ≃ H n X := equiv_of_isomorphism (Hiso H n f) definition Hsusp_neg (H : cohomology_theory) (n : ℤ) (X : Type*) : H n (susp X) ≃g H (pred n) X := isomorphism_of_eq (ap (λn, H n _) proof (sub_add_cancel n 1)⁻¹ qed) ⬝g cohomology_theory.Hsusp H (pred n) X definition Hsusp_neg_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) : Hsusp_neg H n X ∘ H ^→ n (susp_functor f) ~ H ^→ (pred n) f ∘ Hsusp_neg H n Y := sorry definition Hsusp_inv_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) : H ^→ (succ n) (susp_functor f) ∘g (Hsusp H n Y)⁻¹ᵍ ~ (Hsusp H n X)⁻¹ᵍ ∘ H ^→ n f := sorry definition Hsusp_neg_inv_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) : H ^→ n (susp_functor f) ∘g (Hsusp_neg H n Y)⁻¹ᵍ ~ (Hsusp_neg H n X)⁻¹ᵍ ∘ H ^→ (pred n) f := sorry definition Hadditive_equiv (H : cohomology_theory) (n : ℤ) {I : Type} (X : I → Type*) (H2 : has_choice 0 I) : H n (⋁ X) ≃g Πᵍ i, H n (X i) := isomorphism.mk _ (Hadditive H n X H2) definition Hlift_empty.{u} (H : cohomology_theory.{u}) (n : ℤ) : is_contr (H n (plift punit)) := let P : lift empty → Type* := lift.rec empty.elim in let x := Hadditive H n P _ in begin note z := equiv.mk _ x, refine @(is_trunc_equiv_closed_rev -2 (_ ⬝e z ⬝e _)) !is_contr_unit, refine Hequiv H n (pequiv_punit_of_is_contr _ _ ⬝e* !pequiv_plift), apply is_contr_fwedge_of_neg, intro y, induction y with y, exact y, apply equiv_unit_of_is_contr, apply is_contr_pi_of_neg, intro y, induction y with y, exact y end definition Hempty (H : cohomology_theory.{0}) (n : ℤ) : is_contr (H n punit) := @(is_trunc_equiv_closed _ (Hequiv H n !pequiv_plift)) (Hlift_empty H n) definition Hconst (H : cohomology_theory) (n : ℤ) {X Y : Type*} (y : H n Y) : H ^→ n (pconst X Y) y = 1 := begin refine Hhomotopy H n (pconst_pcompose (pconst X (plift punit)))⁻¹* y ⬝ _, refine Hcompose H n _ _ y ⬝ _, refine ap (H ^→ n _) (@eq_of_is_contr _ (Hlift_empty H n) _ 1) ⬝ _, apply respect_one end -- definition Hwedge (H : cohomology_theory) (n : ℤ) (A B : Type*) : H n (A ∨ B) ≃g H n A ×ag H n B := -- begin -- refine Hiso H n (wedge_pequiv_fwedge A B)⁻¹ᵉ* ⬝g _, -- refine Hadditive_equiv H n _ _ ⬝g _ -- end definition cohomology_theory_spectrum.{u} [constructor] (Y : spectrum.{u}) : cohomology_theory.{u} := cohomology_theory.mk (λn A, H^n[A, Y]) (λn A B f, cohomology_isomorphism f Y n) (λn A, cohomology_isomorphism_refl A Y n) (λn A B f, cohomology_functor f Y n) (λn A B f g p, cohomology_functor_phomotopy p Y n) (λn A B f x, cohomology_functor_phomotopy_refl f Y n x) (λn A x, cohomology_functor_pid A Y n x) (λn A B C g f x, cohomology_functor_pcompose g f Y n x) (λn A, cohomology_susp A Y n) (λn A B f, cohomology_susp_natural f Y n) (λn A B f, cohomology_exact f Y n) (λn I A H, spectrum_additive H A Y n) -- set_option pp.universes true -- set_option pp.abbreviations false -- print cohomology_theory_spectrum -- print EM_spectrum -- print has_choice_lift -- print equiv_lift -- print has_choice_equiv_closed definition ordinary_cohomology_theory_EM [constructor] (G : AbGroup) : ordinary_cohomology_theory := ⦃ordinary_cohomology_theory, cohomology_theory_spectrum (EM_spectrum G), Hdimension := ordinary_cohomology_dimension_plift G ⦄ end cohomology
2537c9deb4adb06223ddb6eccbb8adcf2c6f71b6
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/number_theory/quadratic_reciprocity.lean
3b7f9214cf0f4661353596813cfd1136b7d1ab30
[ "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
24,984
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 field_theory.finite.basic import data.zmod.basic import data.nat.parity /-! # Quadratic reciprocity. This file contains results about quadratic residues modulo a prime number. The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the interpretations in terms of existence of square roots depending on the congruence mod 4, `exists_sq_eq_prime_iff_of_mod_four_eq_one`, and `exists_sq_eq_prime_iff_of_mod_four_eq_three`. Also proven are conditions for `-1` and `2` to be a square modulo a prime, `exists_sq_eq_neg_one_iff_mod_four_ne_three` and `exists_sq_eq_two_iff` ## Implementation notes The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma -/ open function finset nat finite_field zmod open_locale big_operators nat namespace zmod variables (p q : ℕ) [fact p.prime] [fact q.prime] /-- Euler's Criterion: A unit `x` of `zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion_units (x : units (zmod p)) : (∃ y : units (zmod p), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, refine iff_of_true ⟨1, _⟩ _; apply subsingleton.elim }, obtain ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmod p)), obtain ⟨n, hn⟩ : x ∈ submonoid.powers g, { rw mem_powers_iff_mem_zpowers, apply hg }, split, { rintro ⟨y, rfl⟩, rw [← pow_mul, two_mul_odd_div_two hp_odd, units_pow_card_sub_one_eq_one], }, { subst x, assume h, have key : 2 * (p / 2) ∣ n * (p / 2), { rw [← pow_mul] at h, rw [two_mul_odd_div_two hp_odd, ← card_units, ← order_of_eq_card_of_forall_mem_zpowers hg], apply order_of_dvd_of_pow_eq_one h }, have : 0 < p / 2 := nat.div_pos (fact.out (1 < p)) dec_trivial, obtain ⟨m, rfl⟩ := dvd_of_mul_dvd_mul_right this key, refine ⟨g ^ m, _⟩, rw [mul_comm, pow_mul], }, end /-- Euler's Criterion: a nonzero `a : zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion {a : zmod p} (ha : a ≠ 0) : (∃ y : zmod p, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := begin apply (iff_congr _ (by simp [units.ext_iff])).mp (euler_criterion_units p (units.mk0 a ha)), simp only [units.ext_iff, sq, units.coe_mk0, units.coe_mul], split, { rintro ⟨y, hy⟩, exact ⟨y, hy⟩ }, { rintro ⟨y, rfl⟩, have hy : y ≠ 0, { rintro rfl, simpa [zero_pow] using ha, }, refine ⟨units.mk0 y hy, _⟩, simp, } end lemma exists_sq_eq_neg_one_iff_mod_four_ne_three : (∃ y : zmod p, y ^ 2 = -1) ↔ p % 4 ≠ 3 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, exact dec_trivial }, haveI := fact.mk hp_odd, have neg_one_ne_zero : (-1 : zmod p) ≠ 0, from mt neg_eq_zero.1 one_ne_zero, rw [euler_criterion p neg_one_ne_zero, neg_one_pow_eq_pow_mod_two], cases mod_two_eq_zero_or_one (p / 2) with p_half_even p_half_odd, { rw [p_half_even, pow_zero, eq_self_iff_true, true_iff], contrapose! p_half_even with hp, rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp], exact dec_trivial }, { rw [p_half_odd, pow_one, iff_false_intro (ne_neg_self p one_ne_zero).symm, false_iff, not_not], rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at p_half_odd, rw [← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp_odd, have hp : p % 4 < 4, from nat.mod_lt _ dec_trivial, revert hp hp_odd p_half_odd, generalize : p % 4 = k, dec_trivial! } end lemma pow_div_two_eq_neg_one_or_one {a : zmod p} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, revert a ha, exact dec_trivial }, rw [← mul_self_eq_one_iff, ← pow_add, ← two_mul, two_mul_odd_div_two hp_odd], exact pow_card_sub_one_eq_one ha end /-- **Wilson's Lemma**: the product of `1`, ..., `p-1` is `-1` modulo `p`. -/ @[simp] lemma wilsons_lemma : ((p - 1)! : zmod p) = -1 := begin refine calc ((p - 1)! : zmod p) = (∏ x in Ico 1 (succ (p - 1)), x) : by rw [← finset.prod_Ico_id_eq_factorial, prod_nat_cast] ... = (∏ x : units (zmod p), x) : _ ... = -1 : by simp_rw [← units.coe_hom_apply, ← (units.coe_hom (zmod p)).map_prod, prod_univ_units_id_eq_neg_one, units.coe_hom_apply, units.coe_neg, units.coe_one], have hp : 0 < p := (fact.out p.prime).pos, symmetry, refine prod_bij (λ a _, (a : zmod p).val) _ _ _ _, { intros a ha, rw [mem_Ico, ← nat.succ_sub hp, nat.succ_sub_one], split, { apply nat.pos_of_ne_zero, rw ← @val_zero p, assume h, apply units.ne_zero a (val_injective p h) }, { exact val_lt _ } }, { intros a ha, simp only [cast_id, nat_cast_val], }, { intros _ _ _ _ h, rw units.ext_iff, exact val_injective p h }, { intros b hb, rw [mem_Ico, nat.succ_le_iff, ← succ_sub hp, succ_sub_one, pos_iff_ne_zero] at hb, refine ⟨units.mk0 b _, finset.mem_univ _, _⟩, { assume h, apply hb.1, apply_fun val at h, simpa only [val_cast_of_lt hb.right, val_zero] using h }, { simp only [val_cast_of_lt hb.right, units.coe_mk0], } } end @[simp] lemma prod_Ico_one_prime : (∏ x in Ico 1 p, (x : zmod p)) = -1 := begin conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub (fact.out p.prime).pos] }, rw [← prod_nat_cast, finset.prod_Ico_id_eq_factorial, wilsons_lemma] end end zmod /-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set of non zero natural numbers `x` such that `x ≤ p / 2` -/ lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id (p : ℕ) [hp : fact p.prime] (a : zmod p) (hap : a ≠ 0) : (Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) = (Ico 1 (p / 2).succ).1.map (λ a, a) := begin have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2, by simp [nat.lt_succ_iff, nat.succ_le_iff, pos_iff_ne_zero] {contextual := tt}, have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p, from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.1.pos dec_trivial), have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x, from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx), have hmem : ∀ (x : ℕ) (hx : x ∈ Ico 1 (p / 2).succ), (a * x : zmod p).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ, { assume x hx, simp [hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hx, lt_succ_iff, succ_le_iff, pos_iff_ne_zero, nat_abs_val_min_abs_le _], }, have hsurj : ∀ (b : ℕ) (hb : b ∈ Ico 1 (p / 2).succ), ∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmod p).val_min_abs.nat_abs, { assume b hb, refine ⟨(b / a : zmod p).val_min_abs.nat_abs, mem_Ico.mpr ⟨_, _⟩, _⟩, { apply nat.pos_of_ne_zero, simp only [div_eq_mul_inv, hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hb, not_false_iff, val_min_abs_eq_zero, inv_eq_zero, int.nat_abs_eq_zero, ne.def, mul_eq_zero, or_self] }, { apply lt_succ_of_le, apply nat_abs_val_min_abs_le }, { rw nat_cast_nat_abs_val_min_abs, split_ifs, { erw [mul_div_cancel' _ hap, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (mem_Ico.1 hb).2), int.nat_abs_of_nat], }, { erw [mul_neg_eq_neg_mul_symm, mul_div_cancel' _ hap, nat_abs_val_min_abs_neg, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (mem_Ico.1 hb).2), int.nat_abs_of_nat] } } }, exact multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _) (λ x _, (a * x : zmod p).val_min_abs.nat_abs) hmem (λ _ _, rfl) (inj_on_of_surj_on_of_card_le _ hmem hsurj (le_refl _)) hsurj end private lemma gauss_lemma_aux₁ (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) * (p / 2)! : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! := calc (a ^ (p / 2) * (p / 2)! : zmod p) = (∏ x in Ico 1 (p / 2).succ, a * x) : by rw [prod_mul_distrib, ← prod_nat_cast, ← prod_nat_cast, prod_Ico_id_eq_factorial, prod_const, card_Ico, succ_sub_one]; simp ... = (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val) : by simp ... = (∏ x in Ico 1 (p / 2).succ, (if (a * x : zmod p).val ≤ p / 2 then 1 else -1) * (a * x : zmod p).val_min_abs.nat_abs) : prod_congr rfl $ λ _ _, begin simp only [nat_cast_nat_abs_val_min_abs], split_ifs; simp end ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : have (∏ x in Ico 1 (p / 2).succ, if (a * x : zmod p).val ≤ p / 2 then (1 : zmod p) else -1) = (∏ x in (Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2), -1), from prod_bij_ne_one (λ x _ _, x) (λ x, by split_ifs; simp * at * {contextual := tt}) (λ _ _ _ _ _ _, id) (λ b h _, ⟨b, by simp [-not_le, *] at *⟩) (by intros; split_ifs at *; simp * at *), by rw [prod_mul_distrib, this]; simp ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! : by rw [← prod_nat_cast, finset.prod_eq_multiset_prod, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.prod_eq_multiset_prod, prod_Ico_id_eq_factorial] private lemma gauss_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := (mul_left_inj' (show ((p / 2)! : zmod p) ≠ 0, by rw [ne.def, char_p.cast_eq_zero_iff (zmod p) p, hp.1.dvd_factorial, not_le]; exact nat.div_lt_self hp.1.pos dec_trivial)).1 $ by simpa using gauss_lemma_aux₁ p hap private lemma eisenstein_lemma_aux₁ (p : ℕ) [fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card + ∑ x in Ico 1 (p / 2).succ, x + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) := have hp2 : (p : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 hp2.1, calc ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((∑ x in Ico 1 (p / 2).succ, ((a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) : by simp only [mod_add_div] ... = (∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) : by simp only [val_nat_cast]; simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, nat.cast_sum, hp2] ... = _ : congr_arg2 (+) (calc ((∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) : zmod 2) = ∑ x in Ico 1 (p / 2).succ, ((((a * x : zmod p).val_min_abs + (if (a * x : zmod p).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2) : by simp only [(val_eq_ite_val_min_abs _).symm]; simp [nat.cast_sum] ... = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card + ((∑ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : ℕ) : by { simp [ite_cast, add_comm, sum_add_distrib, finset.sum_ite, hp2, nat.cast_sum], } ... = _ : by rw [finset.sum_eq_multiset_sum, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.sum_eq_multiset_sum]; simp [nat.cast_sum]) rfl private lemma eisenstein_lemma_aux₂ (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmod p) ≠ 0) : ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card ≡ ∑ x in Ico 1 (p / 2).succ, (x * a) / p [MOD 2] := have ha2 : (a : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 ha2, (eq_iff_modeq_nat 2).1 $ sub_eq_zero.1 $ by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, nat.cast_sum, add_neg_eq_iff_eq_add.symm, neg_eq_self_mod_two, add_assoc] using eq.symm (eisenstein_lemma_aux₁ p hap) lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card := calc a / b = (Ico 1 (a / b).succ).card : by simp ... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card : congr_arg _ $ finset.ext $ λ x, have x * b ≤ a → x ≤ c, from λ h, le_trans (by rwa [le_div_iff_mul_le _ _ hb0]) hc, by simp [lt_succ_iff, le_div_iff_mul_le _ _ hb0]; tauto /-- The given sum is the number of integer points in the triangle formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)` -/ private lemma sum_Ico_eq_card_lt {p q : ℕ} : ∑ a in Ico 1 (p / 2).succ, (a * q) / p = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)).card := if hp0 : p = 0 then by simp [hp0, finset.ext_iff] else calc ∑ a in Ico 1 (p / 2).succ, (a * q) / p = ∑ a in Ico 1 (p / 2).succ, ((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card : finset.sum_congr rfl $ λ x hx, div_eq_filter_card (nat.pos_of_ne_zero hp0) (calc x * q / p ≤ (p / 2) * q / p : nat.div_le_div_right (mul_le_mul_of_nonneg_right (le_of_lt_succ $ by finish) (nat.zero_le _)) ... ≤ _ : nat.div_mul_div_le_div _ _ _) ... = _ : by rw [← card_sigma]; exact card_congr (λ a _, ⟨a.1, a.2⟩) (by simp only [mem_filter, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, heq_iff_eq, forall_true_iff] {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp only [mem_filter, eq_self_iff_true, exists_prop_of_true, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}⟩) /-- Each of the sums in this lemma is the cardinality of the set integer points in each of the two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them gives the number of points in the rectangle. -/ private lemma sum_mul_div_add_sum_mul_div_eq_mul (p q : ℕ) [hp : fact p.prime] (hq0 : (q : zmod p) ≠ 0) : ∑ a in Ico 1 (p / 2).succ, (a * q) / p + ∑ a in Ico 1 (q / 2).succ, (a * p) / q = (p / 2) * (q / 2) := begin have hswap : (((Ico 1 (q / 2).succ).product (Ico 1 (p / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card := card_congr (λ x _, prod.swap x) (λ ⟨_, _⟩, by simp only [mem_filter, and_self, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, prod.swap_prod_mk, forall_true_iff] {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp only [mem_filter, eq_self_iff_true, and_self, exists_prop_of_true, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}⟩), have hdisj : disjoint (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)) (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)), { apply disjoint_filter.2 (λ x hx hpq hqp, _), have hxp : x.1 < p, from lt_of_le_of_lt (show x.1 ≤ p / 2, by simp only [*, lt_succ_iff, mem_Ico, mem_product] at *; tauto) (nat.div_lt_self hp.1.pos dec_trivial), have : (x.1 : zmod p) = 0, { simpa [hq0] using congr_arg (coe : ℕ → zmod p) (le_antisymm hpq hqp) }, apply_fun zmod.val at this, rw [val_cast_of_lt hxp, val_zero] at this, simpa only [this, nonpos_iff_eq_zero, mem_Ico, one_ne_zero, false_and, mem_product] using hx }, have hunion : ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪ ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) = ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)), from finset.ext (λ x, by have := le_total (x.2 * p) (x.1 * q); simp only [mem_union, mem_filter, mem_Ico, mem_product]; tauto), rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product], simp only [card_Ico, tsub_zero, succ_sub_succ_eq_sub] end variables (p q : ℕ) [fact p.prime] [fact q.prime] namespace zmod /-- The Legendre symbol of `a` and `p` is an integer defined as * `0` if `a` is `0` modulo `p`; * `1` if `a ^ (p / 2)` is `1` modulo `p` (by `euler_criterion` this is equivalent to “`a` is a square modulo `p`”); * `-1` otherwise. -/ def legendre_sym (a p : ℕ) : ℤ := if (a : zmod p) = 0 then 0 else if (a : zmod p) ^ (p / 2) = 1 then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) [hp : fact p.prime] : (legendre_sym a p : zmod p) = (a ^ (p / 2)) := begin rw legendre_sym, by_cases ha : (a : zmod p) = 0, { simp only [if_pos, ha, zero_pow (nat.div_pos (hp.1.two_le) (succ_pos 1)), int.cast_zero] }, cases hp.1.eq_two_or_odd with hp2 hp_odd, { substI p, generalize : (a : (zmod 2)) = b, revert b, dec_trivial, }, { haveI := fact.mk hp_odd, rw if_neg ha, have : (-1 : zmod p) ≠ 1, from (ne_neg_self p one_ne_zero).symm, cases pow_div_two_eq_neg_one_or_one p ha with h h, { rw [if_pos h, h, int.cast_one], }, { rw [h, if_neg this, int.cast_neg, int.cast_one], } } end lemma legendre_sym_eq_one_or_neg_one (a p : ℕ) (ha : (a : zmod p) ≠ 0) : legendre_sym a p = -1 ∨ legendre_sym a p = 1 := by unfold legendre_sym; split_ifs; simp only [*, eq_self_iff_true, or_true, true_or] at * lemma legendre_sym_eq_zero_iff (a p : ℕ) : legendre_sym a p = 0 ↔ (a : zmod p) = 0 := begin split, { classical, contrapose, assume ha, cases legendre_sym_eq_one_or_neg_one a p ha with h h, all_goals { rw h, norm_num } }, { assume ha, rw [legendre_sym, if_pos ha] } end /-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less than `p/2` such that `(a * x) % p > p / 2` -/ lemma gauss_lemma {a : ℕ} [fact (p % 2 = 1)] (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := have (legendre_sym a p : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p), by rw [legendre_sym_eq_pow, gauss_lemma_aux₂ p ha0]; simp, begin cases legendre_sym_eq_one_or_neg_one a p ha0; cases neg_one_pow_eq_or ℤ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card; simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at * end lemma legendre_sym_eq_one_iff {a : ℕ} (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = 1 ↔ (∃ b : zmod p, b ^ 2 = a) := begin rw [euler_criterion p ha0, legendre_sym, if_neg ha0], split_ifs, { simp only [h, eq_self_iff_true] }, finish -- this is quite slow. I'm actually surprised that it can close the goal at all! end lemma eisenstein_lemma [fact (p % 2 = 1)] {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1)^∑ x in Ico 1 (p / 2).succ, (x * a) / p := by rw [neg_one_pow_eq_pow_mod_two, gauss_lemma p ha0, neg_one_pow_eq_pow_mod_two, show _ = _, from eisenstein_lemma_aux₂ p ha1 ha0] /-- **Quadratic reciprocity theorem** -/ theorem quadratic_reciprocity [hp1 : fact (p % 2 = 1)] [hq1 : fact (q % 2 = 1)] (hpq : p ≠ q) : legendre_sym p q * legendre_sym q p = (-1) ^ ((p / 2) * (q / 2)) := have hpq0 : (p : zmod q) ≠ 0, from prime_ne_zero q p hpq.symm, have hqp0 : (q : zmod p) ≠ 0, from prime_ne_zero p q hpq, by rw [eisenstein_lemma q hp1.1 hpq0, eisenstein_lemma p hq1.1 hqp0, ← pow_add, sum_mul_div_add_sum_mul_div_eq_mul q p hpq0, mul_comm] -- move this local attribute [instance] lemma fact_prime_two : fact (nat.prime 2) := ⟨nat.prime_two⟩ lemma legendre_sym_two [hp1 : fact (p % 2 = 1)] : legendre_sym 2 p = (-1) ^ (p / 4 + p / 2) := have hp2 : p ≠ 2, from mt (congr_arg (% 2)) (by simpa using hp1.1), have hp22 : p / 2 / 2 = _ := div_eq_filter_card (show 0 < 2, from dec_trivial) (nat.div_le_self (p / 2) 2), have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp, have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmod p).val = 2 * x, from λ x hx, have h2xp : 2 * x < p, from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left (le_of_lt_succ $ by finish) dec_trivial ... < _ : by conv_rhs {rw [← div_add_mod p 2, hp1.1]}; exact lt_succ_self _, by rw [← nat.cast_two, ← nat.cast_mul, val_cast_of_lt h2xp], have hdisj : disjoint ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)), from disjoint_filter.2 (λ x hx, by simp [hx2 _ hx, mul_comm]), have hunion : ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ∪ ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) = Ico 1 (p / 2).succ, begin rw [filter_union_right], conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]}, exact filter_congr (λ x hx, by simp [hx2 _ hx, lt_or_le, mul_comm]) end, begin rw [gauss_lemma p (prime_ne_zero p 2 hp2), neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)], refine congr_arg2 _ rfl ((eq_iff_modeq_nat 2).1 _), rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add, ← sub_eq_iff_eq_add', sub_eq_add_neg, neg_eq_self_mod_two, ← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard] end lemma exists_sq_eq_two_iff [hp1 : fact (p % 2 = 1)] : (∃ a : zmod p, a ^ 2 = 2) ↔ p % 8 = 1 ∨ p % 8 = 7 := have hp2 : ((2 : ℕ) : zmod p) ≠ 0, from prime_ne_zero p 2 (λ h, by simpa [h] using hp1.1), have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm, have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm, begin rw [show (2 : zmod p) = (2 : ℕ), by simp, ← legendre_sym_eq_one_iff p hp2, legendre_sym_two p, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial), even_add, even_div, even_div], have := nat.mod_lt p (show 0 < 8, from dec_trivial), resetI, rw fact_iff at hp1, revert this hp1, erw [hpm4, hpm2], generalize hm : p % 8 = m, unfreezingI {clear_dependent p}, dec_trivial!, end lemma exists_sq_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) [hq1 : fact (q % 2 = 1)] : (∃ a : zmod p, a ^ 2 = q) ↔ ∃ b : zmod q, b ^ 2 = p := if hpq : p = q then by substI hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin haveI hp_odd : fact (p % 2 = 1) := ⟨odd_of_mod_four_eq_one hp1⟩, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg hqp0, if_neg hpq0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction, end lemma exists_sq_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmod p, a ^ 2 = q) ↔ ¬∃ b : zmod q, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin haveI hp_odd : fact (p % 2 = 1) := ⟨odd_of_mod_four_eq_three hp3⟩, haveI hq_odd : fact (q % 2 = 1) := ⟨odd_of_mod_four_eq_three hq3⟩, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg hpq0, if_neg hqp0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction end end zmod
182e022ff7ac8c107d92e0e68e4190a4c7fbd3ef
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/enat_auto.lean
5126fca1be03125d515388ec25f5d6f4e0748bc4
[]
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
16,527
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.pfun import Mathlib.tactic.norm_num import Mathlib.data.equiv.mul_add import Mathlib.PostPort namespace Mathlib /-! # Natural numbers with infinity The natural numbers and an extra `top` element `⊤`. ## Main definitions The following instances are defined: * `ordered_add_comm_monoid enat` * `canonically_ordered_add_monoid enat` There is no additive analogue of `monoid_with_zero`; if there were then `enat` could be an `add_monoid_with_top`. * `to_with_top` : the map from `enat` to `with_top ℕ`, with theorems that it plays well with `+` and `≤`. * `with_top_add_equiv : enat ≃+ with_top ℕ` * `with_top_order_iso : enat ≃o with_top ℕ` ## Implementation details `enat` is defined to be `roption ℕ`. `+` and `≤` are defined on `enat`, but there is an issue with `*` because it's not clear what `0 * ⊤` should be. `mul` is hence left undefined. Similarly `⊤ - ⊤` is ambiguous so there is no `-` defined on `enat`. Before the `open_locale classical` line, various proofs are made with decidability assumptions. This can cause issues -- see for example the non-simp lemma `to_with_top_zero` proved by `rfl`, followed by `@[simp] lemma to_with_top_zero'` whose proof uses `convert`. ## Tags enat, with_top ℕ -/ /-- Type of natural numbers with infinity (`⊤`) -/ def enat := roption ℕ namespace enat protected instance has_zero : HasZero enat := { zero := roption.some 0 } protected instance inhabited : Inhabited enat := { default := 0 } protected instance has_one : HasOne enat := { one := roption.some 1 } protected instance has_add : Add enat := { add := fun (x y : enat) => roption.mk (roption.dom x ∧ roption.dom y) fun (h : roption.dom x ∧ roption.dom y) => roption.get x sorry + roption.get y sorry } protected instance has_coe : has_coe ℕ enat := has_coe.mk roption.some protected instance dom.decidable (n : ℕ) : Decidable (roption.dom ↑n) := is_true trivial @[simp] theorem coe_inj {x : ℕ} {y : ℕ} : ↑x = ↑y ↔ x = y := roption.some_inj @[simp] theorem dom_coe (x : ℕ) : roption.dom ↑x := trivial protected instance add_comm_monoid : add_comm_monoid enat := add_comm_monoid.mk Add.add sorry 0 sorry sorry sorry protected instance has_le : HasLessEq enat := { LessEq := fun (x y : enat) => ∃ (h : roption.dom y → roption.dom x), ∀ (hy : roption.dom y), roption.get x (h hy) ≤ roption.get y hy } protected instance has_top : has_top enat := has_top.mk roption.none protected instance has_bot : has_bot enat := has_bot.mk 0 protected instance has_sup : has_sup enat := has_sup.mk fun (x y : enat) => roption.mk (roption.dom x ∧ roption.dom y) fun (h : roption.dom x ∧ roption.dom y) => roption.get x sorry ⊔ roption.get y sorry theorem le_def (x : enat) (y : enat) : x ≤ y ↔ ∃ (h : roption.dom y → roption.dom x), ∀ (hy : roption.dom y), roption.get x (h hy) ≤ roption.get y hy := iff.rfl protected theorem cases_on {P : enat → Prop} (a : enat) : P ⊤ → (∀ (n : ℕ), P ↑n) → P a := roption.induction_on @[simp] theorem top_add (x : enat) : ⊤ + x = ⊤ := roption.ext' (false_and (roption.dom x)) fun (h : roption.dom (⊤ + x)) => false.elim (and.left h) @[simp] theorem add_top (x : enat) : x + ⊤ = ⊤ := eq.mpr (id (Eq._oldrec (Eq.refl (x + ⊤ = ⊤)) (add_comm x ⊤))) (eq.mpr (id (Eq._oldrec (Eq.refl (⊤ + x = ⊤)) (top_add x))) (Eq.refl ⊤)) @[simp] theorem coe_zero : ↑0 = 0 := rfl @[simp] theorem coe_one : ↑1 = 1 := rfl @[simp] theorem coe_add (x : ℕ) (y : ℕ) : ↑(x + y) = ↑x + ↑y := roption.ext' (iff.symm (and_true (roption.dom ↑(x + y)))) fun (_x : roption.dom ↑(x + y)) (_x_1 : roption.dom (↑x + ↑y)) => rfl theorem get_coe {x : ℕ} : roption.get (↑x) True.intro = x := rfl @[simp] theorem get_coe' (x : ℕ) (h : roption.dom ↑x) : roption.get (↑x) h = x := rfl theorem coe_add_get {x : ℕ} {y : enat} (h : roption.dom (↑x + y)) : roption.get (↑x + y) h = x + roption.get y (and.right h) := rfl @[simp] theorem get_add {x : enat} {y : enat} (h : roption.dom (x + y)) : roption.get (x + y) h = roption.get x (and.left h) + roption.get y (and.right h) := rfl @[simp] theorem coe_get {x : enat} (h : roption.dom x) : ↑(roption.get x h) = x := roption.ext' (iff_of_true trivial h) fun (_x : roption.dom ↑(roption.get x h)) (_x_1 : roption.dom x) => rfl @[simp] theorem get_zero (h : roption.dom 0) : roption.get 0 h = 0 := rfl @[simp] theorem get_one (h : roption.dom 1) : roption.get 1 h = 1 := rfl theorem dom_of_le_of_dom {x : enat} {y : enat} : x ≤ y → roption.dom y → roption.dom x := sorry theorem dom_of_le_some {x : enat} {y : ℕ} (h : x ≤ ↑y) : roption.dom x := dom_of_le_of_dom h trivial protected instance decidable_le (x : enat) (y : enat) [Decidable (roption.dom x)] [Decidable (roption.dom y)] : Decidable (x ≤ y) := dite (roption.dom x) (fun (hx : roption.dom x) => decidable_of_decidable_of_iff ((fun (this : Decidable (∀ (hy : roption.dom y), roption.get x hx ≤ roption.get y hy)) => this) (Mathlib.forall_prop_decidable fun (hy : roption.dom y) => roption.get x hx ≤ roption.get y hy)) sorry) fun (hx : ¬roption.dom x) => dite (roption.dom y) (fun (hy : roption.dom y) => isFalse sorry) fun (hy : ¬roption.dom y) => is_true sorry /-- The coercion `ℕ → enat` preserves `0` and addition. -/ def coe_hom : ℕ →+ enat := add_monoid_hom.mk coe coe_zero coe_add protected instance partial_order : partial_order enat := partial_order.mk LessEq (preorder.lt._default LessEq) sorry sorry sorry theorem lt_def (x : enat) (y : enat) : x < y ↔ ∃ (hx : roption.dom x), ∀ (hy : roption.dom y), roption.get x hx < roption.get y hy := sorry @[simp] theorem coe_le_coe {x : ℕ} {y : ℕ} : ↑x ≤ ↑y ↔ x ≤ y := sorry @[simp] theorem coe_lt_coe {x : ℕ} {y : ℕ} : ↑x < ↑y ↔ x < y := sorry @[simp] theorem get_le_get {x : enat} {y : enat} {hx : roption.dom x} {hy : roption.dom y} : roption.get x hx ≤ roption.get y hy ↔ x ≤ y := sorry theorem le_coe_iff (x : enat) (n : ℕ) : x ≤ ↑n ↔ ∃ (h : roption.dom x), roption.get x h ≤ n := sorry theorem lt_coe_iff (x : enat) (n : ℕ) : x < ↑n ↔ ∃ (h : roption.dom x), roption.get x h < n := sorry theorem coe_le_iff (n : ℕ) (x : enat) : ↑n ≤ x ↔ ∀ (h : roption.dom x), n ≤ roption.get x h := sorry theorem coe_lt_iff (n : ℕ) (x : enat) : ↑n < x ↔ ∀ (h : roption.dom x), n < roption.get x h := sorry protected theorem zero_lt_one : 0 < 1 := sorry protected instance semilattice_sup_bot : semilattice_sup_bot enat := semilattice_sup_bot.mk ⊥ partial_order.le partial_order.lt partial_order.le_refl partial_order.le_trans partial_order.le_antisymm sorry has_sup.sup sorry sorry sorry protected instance order_top : order_top enat := order_top.mk ⊤ semilattice_sup_bot.le semilattice_sup_bot.lt semilattice_sup_bot.le_refl semilattice_sup_bot.le_trans semilattice_sup_bot.le_antisymm sorry theorem dom_of_lt {x : enat} {y : enat} : x < y → roption.dom x := enat.cases_on x not_top_lt fun (_x : ℕ) (_x : ↑_x < y) => trivial theorem top_eq_none : ⊤ = roption.none := rfl @[simp] theorem coe_lt_top (x : ℕ) : ↑x < ⊤ := lt_of_le_of_ne le_top fun (h : ↑x = ⊤) => absurd (congr_arg roption.dom h) true_ne_false @[simp] theorem coe_ne_top (x : ℕ) : ↑x ≠ ⊤ := ne_of_lt (coe_lt_top x) theorem ne_top_iff {x : enat} : x ≠ ⊤ ↔ ∃ (n : ℕ), x = ↑n := roption.ne_none_iff theorem ne_top_iff_dom {x : enat} : x ≠ ⊤ ↔ roption.dom x := iff.mp not_iff_comm (iff.symm roption.eq_none_iff') theorem ne_top_of_lt {x : enat} {y : enat} (h : x < y) : x ≠ ⊤ := ne_of_lt (lt_of_lt_of_le h le_top) theorem eq_top_iff_forall_lt (x : enat) : x = ⊤ ↔ ∀ (n : ℕ), ↑n < x := sorry theorem eq_top_iff_forall_le (x : enat) : x = ⊤ ↔ ∀ (n : ℕ), ↑n ≤ x := iff.trans (eq_top_iff_forall_lt x) { mp := fun (h : ∀ (n : ℕ), ↑n < x) (n : ℕ) => has_lt.lt.le (h n), mpr := fun (h : ∀ (n : ℕ), ↑n ≤ x) (n : ℕ) => lt_of_lt_of_le (iff.mpr coe_lt_coe (nat.lt_succ_self n)) (h (n + 1)) } theorem pos_iff_one_le {x : enat} : 0 < x ↔ 1 ≤ x := sorry protected instance linear_order : linear_order enat := linear_order.mk partial_order.le partial_order.lt partial_order.le_refl partial_order.le_trans partial_order.le_antisymm sorry (classical.dec_rel LessEq) Mathlib.decidable_eq_of_decidable_le Mathlib.decidable_lt_of_decidable_le protected instance bounded_lattice : bounded_lattice enat := bounded_lattice.mk semilattice_sup_bot.sup order_top.le order_top.lt order_top.le_refl order_top.le_trans order_top.le_antisymm semilattice_sup_bot.le_sup_left semilattice_sup_bot.le_sup_right semilattice_sup_bot.sup_le min min_le_left min_le_right sorry order_top.top order_top.le_top semilattice_sup_bot.bot semilattice_sup_bot.bot_le theorem sup_eq_max {a : enat} {b : enat} : a ⊔ b = max a b := le_antisymm (sup_le (le_max_left a b) (le_max_right a b)) (max_le le_sup_left le_sup_right) theorem inf_eq_min {a : enat} {b : enat} : a ⊓ b = min a b := rfl protected instance ordered_add_comm_monoid : ordered_add_comm_monoid enat := ordered_add_comm_monoid.mk add_comm_monoid.add add_comm_monoid.add_assoc add_comm_monoid.zero add_comm_monoid.zero_add add_comm_monoid.add_zero add_comm_monoid.add_comm linear_order.le linear_order.lt linear_order.le_refl linear_order.le_trans linear_order.le_antisymm sorry sorry protected instance canonically_ordered_add_monoid : canonically_ordered_add_monoid enat := canonically_ordered_add_monoid.mk ordered_add_comm_monoid.add ordered_add_comm_monoid.add_assoc ordered_add_comm_monoid.zero ordered_add_comm_monoid.zero_add ordered_add_comm_monoid.add_zero ordered_add_comm_monoid.add_comm semilattice_sup_bot.le semilattice_sup_bot.lt semilattice_sup_bot.le_refl semilattice_sup_bot.le_trans semilattice_sup_bot.le_antisymm ordered_add_comm_monoid.add_le_add_left ordered_add_comm_monoid.lt_of_add_lt_add_left semilattice_sup_bot.bot semilattice_sup_bot.bot_le sorry protected theorem add_lt_add_right {x : enat} {y : enat} {z : enat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z := sorry protected theorem add_lt_add_iff_right {x : enat} {y : enat} {z : enat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y := { mp := lt_of_add_lt_add_right, mpr := fun (h : x < y) => enat.add_lt_add_right h hz } protected theorem add_lt_add_iff_left {x : enat} {y : enat} {z : enat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y := sorry protected theorem lt_add_iff_pos_right {x : enat} {y : enat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y := sorry theorem lt_add_one {x : enat} (hx : x ≠ ⊤) : x < x + 1 := sorry theorem le_of_lt_add_one {x : enat} {y : enat} (h : x < y + 1) : x ≤ y := sorry theorem add_one_le_of_lt {x : enat} {y : enat} (h : x < y) : x + 1 ≤ y := sorry theorem add_one_le_iff_lt {x : enat} {y : enat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y := sorry theorem lt_add_one_iff_lt {x : enat} {y : enat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y := sorry theorem add_eq_top_iff {a : enat} {b : enat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := sorry protected theorem add_right_cancel_iff {a : enat} {b : enat} {c : enat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b := sorry protected theorem add_left_cancel_iff {a : enat} {b : enat} {c : enat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c := sorry /-- Computably converts an `enat` to a `with_top ℕ`. -/ def to_with_top (x : enat) [Decidable (roption.dom x)] : with_top ℕ := roption.to_option x theorem to_with_top_top : to_with_top ⊤ = ⊤ := rfl @[simp] theorem to_with_top_top' {h : Decidable (roption.dom ⊤)} : to_with_top ⊤ = ⊤ := sorry theorem to_with_top_zero : to_with_top 0 = 0 := rfl @[simp] theorem to_with_top_zero' {h : Decidable (roption.dom 0)} : to_with_top 0 = 0 := sorry theorem to_with_top_coe (n : ℕ) : to_with_top ↑n = ↑n := rfl @[simp] theorem to_with_top_coe' (n : ℕ) {h : Decidable (roption.dom ↑n)} : to_with_top ↑n = ↑n := sorry @[simp] theorem to_with_top_le {x : enat} {y : enat} [Decidable (roption.dom x)] [Decidable (roption.dom y)] : to_with_top x ≤ to_with_top y ↔ x ≤ y := sorry @[simp] theorem to_with_top_lt {x : enat} {y : enat} [Decidable (roption.dom x)] [Decidable (roption.dom y)] : to_with_top x < to_with_top y ↔ x < y := lt_iff_lt_of_le_iff_le to_with_top_le @[simp] theorem to_with_top_add {x : enat} {y : enat} : to_with_top (x + y) = to_with_top x + to_with_top y := sorry /-- `equiv` between `enat` and `with_top ℕ` (for the order isomorphism see `with_top_order_iso`). -/ def with_top_equiv : enat ≃ with_top ℕ := equiv.mk (fun (x : enat) => to_with_top x) (fun (x : with_top ℕ) => sorry) sorry sorry @[simp] theorem with_top_equiv_top : coe_fn with_top_equiv ⊤ = ⊤ := to_with_top_top' @[simp] theorem with_top_equiv_coe (n : ℕ) : coe_fn with_top_equiv ↑n = ↑n := to_with_top_coe' n @[simp] theorem with_top_equiv_zero : coe_fn with_top_equiv 0 = 0 := with_top_equiv_coe 0 @[simp] theorem with_top_equiv_le {x : enat} {y : enat} : coe_fn with_top_equiv x ≤ coe_fn with_top_equiv y ↔ x ≤ y := to_with_top_le @[simp] theorem with_top_equiv_lt {x : enat} {y : enat} : coe_fn with_top_equiv x < coe_fn with_top_equiv y ↔ x < y := to_with_top_lt /-- `to_with_top` induces an order isomorphism between `enat` and `with_top ℕ`. -/ def with_top_order_iso : enat ≃o with_top ℕ := rel_iso.mk (equiv.mk (equiv.to_fun with_top_equiv) (equiv.inv_fun with_top_equiv) sorry sorry) sorry @[simp] theorem with_top_equiv_symm_top : coe_fn (equiv.symm with_top_equiv) ⊤ = ⊤ := rfl @[simp] theorem with_top_equiv_symm_coe (n : ℕ) : coe_fn (equiv.symm with_top_equiv) ↑n = ↑n := rfl @[simp] theorem with_top_equiv_symm_zero : coe_fn (equiv.symm with_top_equiv) 0 = 0 := rfl @[simp] theorem with_top_equiv_symm_le {x : with_top ℕ} {y : with_top ℕ} : coe_fn (equiv.symm with_top_equiv) x ≤ coe_fn (equiv.symm with_top_equiv) y ↔ x ≤ y := sorry @[simp] theorem with_top_equiv_symm_lt {x : with_top ℕ} {y : with_top ℕ} : coe_fn (equiv.symm with_top_equiv) x < coe_fn (equiv.symm with_top_equiv) y ↔ x < y := sorry /-- `to_with_top` induces an additive monoid isomorphism between `enat` and `with_top ℕ`. -/ def with_top_add_equiv : enat ≃+ with_top ℕ := add_equiv.mk (equiv.to_fun with_top_equiv) (equiv.inv_fun with_top_equiv) sorry sorry sorry theorem lt_wf : well_founded Less := sorry protected instance has_well_founded : has_well_founded enat := has_well_founded.mk Less lt_wf /-- The smallest `enat` satisfying a (decidable) predicate `P : ℕ → Prop` -/ def find (P : ℕ → Prop) [decidable_pred P] : enat := roption.mk (∃ (n : ℕ), P n) nat.find @[simp] theorem find_get (P : ℕ → Prop) [decidable_pred P] (h : roption.dom (find P)) : roption.get (find P) h = nat.find h := rfl theorem find_dom (P : ℕ → Prop) [decidable_pred P] (h : ∃ (n : ℕ), P n) : roption.dom (find P) := h theorem lt_find (P : ℕ → Prop) [decidable_pred P] (n : ℕ) (h : ∀ (m : ℕ), m ≤ n → ¬P m) : ↑n < find P := sorry theorem lt_find_iff (P : ℕ → Prop) [decidable_pred P] (n : ℕ) : ↑n < find P ↔ ∀ (m : ℕ), m ≤ n → ¬P m := sorry theorem find_le (P : ℕ → Prop) [decidable_pred P] (n : ℕ) (h : P n) : find P ≤ ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (find P ≤ ↑n)) (propext (le_coe_iff (find P) n)))) (Exists.intro (Exists.intro n h) (nat.find_min' (Exists.intro n h) h)) theorem find_eq_top_iff (P : ℕ → Prop) [decidable_pred P] : find P = ⊤ ↔ ∀ (n : ℕ), ¬P n := iff.trans (eq_top_iff_forall_lt (find P)) { mp := fun (h : ∀ (n : ℕ), ↑n < find P) (n : ℕ) => iff.mp (lt_find_iff P n) (h n) n le_rfl, mpr := fun (h : ∀ (n : ℕ), ¬P n) (n : ℕ) => lt_find P n fun (_x : ℕ) (_x_1 : _x ≤ n) => h _x } end Mathlib
a0c1b4b5804a350b88ba198f6f335d534f6aeef7
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/number_theory/zsqrtd/to_real.lean
aeb45b6ec98a8404f313f4a393d4e26cc898e99a
[ "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
855
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import data.real.sqrt import number_theory.zsqrtd.basic /-! # Image of `zsqrtd` in `ℝ` This file defines `zsqrtd.to_real` and related lemmas. It is in a separate file to avoid pulling in all of `data.real` into `data.zsqrtd`. -/ namespace zsqrtd /-- The image of `zsqrtd` in `ℝ`, using `real.sqrt` which takes the positive root of `d`. If the negative root is desired, use `to_real h a.conj`. -/ @[simps] noncomputable def to_real {d : ℤ} (h : 0 ≤ d) : ℤ√d →+* ℝ := lift ⟨real.sqrt d, real.mul_self_sqrt (int.cast_nonneg.mpr h)⟩ lemma to_real_injective {d : ℤ} (h0d : 0 ≤ d) (hd : ∀ n : ℤ, d ≠ n*n) : function.injective (to_real h0d) := lift_injective _ hd end zsqrtd
f1755a21ab3e557c84a95991f8e24054f0f861d3
159fed64bfae88f3b6a6166836d6278f953bcbf9
/Structure/Generic/Axioms/GeneralizedProperties.lean
bea514a43d41026cc6177240c6003b8ce798e919
[ "MIT" ]
permissive
SReichelt/lean4-experiments
3e56830c8b2fbe3814eda071c48e3c8810d254a8
ff55357a01a34a91bf670d712637480089085ee4
refs/heads/main
1,683,977,454,907
1,622,991,121,000
1,622,991,121,000
340,765,677
2
0
null
null
null
null
UTF-8
Lean
false
false
5,642
lean
import Structure.Generic.Axioms.Universes import Structure.Generic.Axioms.AbstractFunctors import Structure.Generic.Axioms.AbstractEquivalences import Structure.Generic.Lemmas.DerivedFunctors import Structure.Generic.Notation set_option autoBoundImplicitLocal false --set_option pp.universes true universes u v def GeneralizedProperty (α : Sort u) (V : Universe.{v}) := α → V namespace GeneralizedProperty variable {α : Sort u} {V : Universe.{v}} instance hasInstances : HasInstances (GeneralizedProperty α V) := ⟨λ P => ∀ a, P a⟩ section Properties variable (P : GeneralizedProperty α V) class HasInst where (inst (a : α) : P a) end Properties end GeneralizedProperty open GeneralizedProperty -- TODO: Update comments -- We want to formalize a very general "structure with equivalences", so we start with a very basic -- abstraction for something that looks like an equivalence relation except that the codomain is -- generalized to `Sort u` instead of `Prop`. Therefore, `⟨Equiv.refl, Equiv.symm, Equiv.trans⟩`, where -- `Equiv` is the Lean 4 version of the `equiv` type in Lean 3 mathlib, is also an instance of this type -- (with the restriction that both arguments must live in the same universe). -- -- We actually need to generalize slightly further to a codomain that is not necessarily a sort but can be -- coerced to a sort. This way, the codomain can be any Lean structure that bundles a sort, in particular -- it can be our `Structure` type. def GeneralizedRelation (α : Sort u) (V : Universe.{v}) := α → α → V namespace GeneralizedRelation variable {α : Sort u} {V : Universe.{v}} instance hasInstances : HasInstances (GeneralizedRelation α V) := ⟨λ R => ∀ a b, R a b⟩ section Properties variable (R : GeneralizedRelation α V) class HasRefl where (refl (a : α) : R a a) variable [HasInternalFunctors V] class HasTrans where (trans {a b c : α} : R a b ⟶ R b c ⟶ R a c) class IsPreorder extends HasRefl R, HasTrans R variable [HasInternalEquivalences V] class HasSymm where (symm {a b : α} : R a b ⟷ R b a) class IsEquivalence extends IsPreorder R, HasSymm R end Properties def HasTrans.revTrans {R : GeneralizedRelation α V} [HasInternalFunctors V] [HasLinearFunOp V] [h : HasTrans R] {a b c : α} : R b c ⟶ R a b ⟶ R a c := HasLinearFunOp.swapFunFun h.trans @[simp] theorem HasTrans.revTrans.eff {R : GeneralizedRelation α V} [HasInternalFunctors V] [HasLinearFunOp V] [h : HasTrans R] {a b c : α} (g : R b c) (f : R a b) : h.revTrans g f = h.trans f g := by apply HasLinearFunOp.swapFunFun.effEff def HasTrans.trans' {R : GeneralizedRelation α V} [HasInternalFunctors V] [h : HasTrans R] {a b c : α} (f : R a b) (g : R b c) : R a c := h.trans f g def HasSymm.symm' {R : GeneralizedRelation α V} [HasInternalFunctors V] [HasInternalEquivalences V] [h : HasSymm R] {a b : α} (f : R a b) : R b a := HasInternalEquivalences.to h.symm f -- When reasoning about instances of `R a b`, we would like to write `trans` as composition, `refl` as -- identity, and `symm` as inverse. -- Note that `R` can be inferred from `f : R a b` by elaboration. section Notation @[reducible] def revComp {R : GeneralizedRelation α V} [HasInternalFunctors V] [h : HasTrans R] {a b c : α} (g : R b c) (f : R a b) : R a c := h.trans' f g infixr:90 " • " => revComp @[reducible] def ident (R : GeneralizedRelation α V) [h : HasRefl R] (a : α) : R a a := h.refl a @[reducible] def inv {R : GeneralizedRelation α V} [HasInternalFunctors V] [HasInternalEquivalences V] [h : HasSymm R] {a b : α} (f : R a b) : R b a := h.symm' f postfix:max "⁻¹" => inv end Notation end GeneralizedRelation open GeneralizedRelation -- We can attach products, arrows, and/or equivalences to a given sort, in the form of generalized -- relations satisfying appropriate properties. section AttachedRelations variable (α : Sort u) (V : Universe.{v}) [HasInternalFunctors V] class HasArrows where (Arrow : GeneralizedRelation α V) [isPreorder : IsPreorder Arrow] namespace HasArrows variable [h : HasArrows α V] instance arrowPreorder : IsPreorder h.Arrow := h.isPreorder instance hasArrow : HasArrow α α := ⟨h.Arrow⟩ instance : HasInstances (HasArrow.γ α α) := Universe.instInst V instance : IsPreorder (@HasArrow.Arrow α α (hasArrow α V)) := h.isPreorder end HasArrows variable [HasInternalEquivalences V] class HasEquivalences where (Equiv : GeneralizedRelation α V) [isEquiv : IsEquivalence Equiv] namespace HasEquivalences variable [h : HasEquivalences α V] instance equivEquivalence : IsEquivalence h.Equiv := h.isEquiv instance hasEquivalence : HasEquivalence α α := ⟨h.Equiv⟩ instance : HasInstances (HasEquivalence.γ α α) := Universe.instInst V instance : IsEquivalence (@HasEquivalence.Equiv α α (hasEquivalence α V)) := h.isEquiv end HasEquivalences class HasProducts where (Product : GeneralizedRelation α V) [hasSymm : HasSymm Product] namespace HasProducts variable [h : HasProducts α V] instance productSymm : HasSymm h.Product := h.hasSymm instance hasProduct : HasProduct α α := ⟨h.Product⟩ instance : HasInstances (HasProduct.γ α α) := Universe.instInst V instance : HasSymm (@HasProduct.Product α α (hasProduct α V)) := h.hasSymm end HasProducts end AttachedRelations
5ec0261854c2a47175c3b1378d85e9db6695f881
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/linear_independent_auto.lean
be673e708a4232c63d6cd8791cda66400c2ae688
[]
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
32,927
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp, Anne Baanen -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.linear_algebra.finsupp import Mathlib.order.zorn import Mathlib.data.finset.order import Mathlib.data.equiv.fin import Mathlib.PostPort universes u_1 u_3 u_5 u_2 u_6 u u_4 namespace Mathlib /-! # Linear independence This file defines linear independence in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. We define `linear_independent R v` as `ker (finsupp.total ι M R v) = ⊥`. Here `finsupp.total` is the linear map sending a function `f : ι →₀ R` with finite support to the linear combination of vectors from `v` with these coefficients. Then we prove that several other statements are equivalent to this one, including injectivity of `finsupp.total ι M R v` and some versions with explicitly written linear combinations. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. ## Main statements We prove several specialized tests for linear independence of families of vectors and of sets of vectors. * `fintype.linear_independent_iff`: if `ι` is a finite type, then any function `f : ι → R` has finite support, so we can reformulate the statement using `∑ i : ι, f i • v i` instead of a sum over an auxiliary `s : finset ι`; * `linear_independent_empty_type`: a family indexed by an empty type is linearly independent; * `linear_independent_unique_iff`: if `ι` is a singleton, then `linear_independent K v` is equivalent to `v (default ι) ≠ 0`; * linear_independent_option`, `linear_independent_sum`, `linear_independent_fin_cons`, `linear_independent_fin_succ`: type-specific tests for linear independence of families of vector fields; * `linear_independent_insert`, `linear_independent_union`, `linear_independent_pair`, `linear_independent_singleton`: linear independence tests for set operations. In many cases we additionally provide dot-style operations (e.g., `linear_independent.union`) to make the linear independence tests usable as `hv.insert ha` etc. We also prove that any family of vectors includes a linear independent subfamily spanning the same submodule. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence -/ /-- `linear_independent R v` states the family of vectors `v` is linearly independent over `R`. -/ def linear_independent {ι : Type u_1} (R : Type u_3) {M : Type u_5} (v : ι → M) [ring R] [add_comm_group M] [module R M] := linear_map.ker (finsupp.total ι M R v) = ⊥ theorem linear_independent_iff {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] : linear_independent R v ↔ ∀ (l : ι →₀ R), coe_fn (finsupp.total ι M R v) l = 0 → l = 0 := sorry theorem linear_independent_iff_injective_total {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] : linear_independent R v ↔ function.injective ⇑(finsupp.total ι M R v) := iff.trans linear_independent_iff (iff.symm (add_monoid_hom.injective_iff (linear_map.to_add_monoid_hom (finsupp.total ι M R v)))) theorem linear_independent.injective_total {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] : linear_independent R v → function.injective ⇑(finsupp.total ι M R v) := iff.mp linear_independent_iff_injective_total theorem linear_independent_iff' {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] : linear_independent R v ↔ ∀ (s : finset ι) (g : ι → R), (finset.sum s fun (i : ι) => g i • v i) = 0 → ∀ (i : ι), i ∈ s → g i = 0 := sorry theorem linear_independent_iff'' {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] : linear_independent R v ↔ ∀ (s : finset ι) (g : ι → R), (∀ (i : ι), ¬i ∈ s → g i = 0) → (finset.sum s fun (i : ι) => g i • v i) = 0 → ∀ (i : ι), g i = 0 := sorry theorem linear_dependent_iff {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] : ¬linear_independent R v ↔ ∃ (s : finset ι), ∃ (g : ι → R), (finset.sum s fun (i : ι) => g i • v i) = 0 ∧ ∃ (i : ι), ∃ (H : i ∈ s), g i ≠ 0 := sorry theorem fintype.linear_independent_iff {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] [fintype ι] : linear_independent R v ↔ ∀ (g : ι → R), (finset.sum finset.univ fun (i : ι) => g i • v i) = 0 → ∀ (i : ι), g i = 0 := sorry theorem linear_independent_empty_type {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (h : ¬Nonempty ι) : linear_independent R v := eq.mpr (id (Eq._oldrec (Eq.refl (linear_independent R v)) (propext linear_independent_iff))) fun (l : ι →₀ R) (ᾰ : coe_fn (finsupp.total ι M R v) l = 0) => finsupp.ext fun (i : ι) => false.elim (h (Nonempty.intro i)) theorem linear_independent.ne_zero {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] [nontrivial R] (i : ι) (hv : linear_independent R v) : v i ≠ 0 := sorry /-- A subfamily of a linearly independent family (i.e., a composition with an injective map) is a linearly independent family. -/ theorem linear_independent.comp {ι : Type u_1} {ι' : Type u_2} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (h : linear_independent R v) (f : ι' → ι) (hf : function.injective f) : linear_independent R (v ∘ f) := sorry /-- If `v` is a linearly independent family of vectors and the kernel of a linear map `f` is disjoint with the sumodule spaned by the vectors of `v`, then `f ∘ v` is a linearly independent family of vectors. See also `linear_independent.map'` for a special case assuming `ker f = ⊥`. -/ theorem linear_independent.map {ι : Type u_1} {R : Type u_3} {M : Type u_5} {M' : Type u_6} {v : ι → M} [ring R] [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] (hv : linear_independent R v) {f : linear_map R M M'} (hf_inj : disjoint (submodule.span R (set.range v)) (linear_map.ker f)) : linear_independent R (⇑f ∘ v) := sorry /-- An injective linear map sends linearly independent families of vectors to linearly independent families of vectors. See also `linear_independent.map` for a more general statement. -/ theorem linear_independent.map' {ι : Type u_1} {R : Type u_3} {M : Type u_5} {M' : Type u_6} {v : ι → M} [ring R] [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] (hv : linear_independent R v) (f : linear_map R M M') (hf_inj : linear_map.ker f = ⊥) : linear_independent R (⇑f ∘ v) := sorry /-- If the image of a family of vectors under a linear map is linearly independent, then so is the original family. -/ theorem linear_independent.of_comp {ι : Type u_1} {R : Type u_3} {M : Type u_5} {M' : Type u_6} {v : ι → M} [ring R] [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] (f : linear_map R M M') (hfv : linear_independent R (⇑f ∘ v)) : linear_independent R v := sorry /-- If `f` is an injective linear map, then the family `f ∘ v` is linearly independent if and only if the family `v` is linearly independent. -/ protected theorem linear_map.linear_independent_iff {ι : Type u_1} {R : Type u_3} {M : Type u_5} {M' : Type u_6} {v : ι → M} [ring R] [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] (f : linear_map R M M') (hf_inj : linear_map.ker f = ⊥) : linear_independent R (⇑f ∘ v) ↔ linear_independent R v := sorry theorem linear_independent_of_subsingleton {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] [subsingleton R] : linear_independent R v := iff.mpr linear_independent_iff fun (l : ι →₀ R) (hl : coe_fn (finsupp.total ι M R v) l = 0) => subsingleton.elim l 0 theorem linear_independent.injective {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] [nontrivial R] (hv : linear_independent R v) : function.injective v := sorry theorem linear_independent_equiv {ι : Type u_1} {ι' : Type u_2} {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] (e : ι ≃ ι') {f : ι' → M} : linear_independent R (f ∘ ⇑e) ↔ linear_independent R f := sorry theorem linear_independent_equiv' {ι : Type u_1} {ι' : Type u_2} {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] (e : ι ≃ ι') {f : ι' → M} {g : ι → M} (h : f ∘ ⇑e = g) : linear_independent R g ↔ linear_independent R f := h ▸ linear_independent_equiv e theorem linear_independent_subtype_range {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {ι : Type u_1} {f : ι → M} (hf : function.injective f) : linear_independent R coe ↔ linear_independent R f := iff.symm (linear_independent_equiv' (equiv.set.range f hf) rfl) theorem linear_independent.of_subtype_range {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {ι : Type u_1} {f : ι → M} (hf : function.injective f) : linear_independent R coe → linear_independent R f := iff.mp (linear_independent_subtype_range hf) theorem linear_independent.to_subtype_range {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {ι : Type u_1} {f : ι → M} (hf : linear_independent R f) : linear_independent R coe := or.dcases_on (subsingleton_or_nontrivial R) (fun (_inst : subsingleton R) => eq.mpr (id (propext (iff_true_intro linear_independent_of_subsingleton))) trivial) fun (_inst : nontrivial R) => iff.mpr (linear_independent_subtype_range (linear_independent.injective hf)) hf theorem linear_independent.to_subtype_range' {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {ι : Type u_1} {f : ι → M} (hf : linear_independent R f) {t : set M} (ht : set.range f = t) : linear_independent R coe := ht ▸ linear_independent.to_subtype_range hf theorem linear_independent_image {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {ι : Type u_1} {s : set ι} {f : ι → M} (hf : set.inj_on f s) : (linear_independent R fun (x : ↥s) => f ↑x) ↔ linear_independent R fun (x : ↥(f '' s)) => ↑x := linear_independent_equiv' (equiv.set.image_of_inj_on f s hf) rfl theorem linear_independent.image {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {ι : Type u_1} {s : set ι} {f : ι → M} (hs : linear_independent R fun (x : ↥s) => f ↑x) : linear_independent R fun (x : ↥(f '' s)) => ↑x := sorry theorem linear_independent_span {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (hs : linear_independent R v) : linear_independent R fun (i : ι) => { val := v i, property := submodule.subset_span (set.mem_range_self i) } := linear_independent.of_comp (submodule.subtype (submodule.span R (set.range v))) hs /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] {s : set ι} : linear_independent R (v ∘ coe) ↔ ∀ (l : ι →₀ R), l ∈ finsupp.supported R R s → coe_fn (finsupp.total ι M R v) l = 0 → l = 0 := sorry theorem linear_independent_subtype {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {s : set M} : (linear_independent R fun (x : ↥s) => ↑x) ↔ ∀ (l : M →₀ R), l ∈ finsupp.supported R R s → coe_fn (finsupp.total M M R id) l = 0 → l = 0 := linear_independent_comp_subtype theorem linear_independent_comp_subtype_disjoint {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] {s : set ι} : linear_independent R (v ∘ coe) ↔ disjoint (finsupp.supported R R s) (linear_map.ker (finsupp.total ι M R v)) := sorry theorem linear_independent_subtype_disjoint {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {s : set M} : (linear_independent R fun (x : ↥s) => ↑x) ↔ disjoint (finsupp.supported R R s) (linear_map.ker (finsupp.total M M R id)) := linear_independent_comp_subtype_disjoint theorem linear_independent_iff_total_on {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {s : set M} : (linear_independent R fun (x : ↥s) => ↑x) ↔ linear_map.ker (finsupp.total_on M M R id s) = ⊥ := sorry theorem linear_independent.restrict_of_comp_subtype {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] {s : set ι} (hs : linear_independent R (v ∘ coe)) : linear_independent R (set.restrict v s) := hs theorem linear_independent_empty (R : Type u_3) (M : Type u_5) [ring R] [add_comm_group M] [module R M] : linear_independent R fun (x : ↥∅) => ↑x := sorry theorem linear_independent.mono {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {t : set M} {s : set M} (h : t ⊆ s) : (linear_independent R fun (x : ↥s) => ↑x) → linear_independent R fun (x : ↥t) => ↑x := eq.mpr (id (imp_congr_eq (propext linear_independent_subtype_disjoint) (propext linear_independent_subtype_disjoint))) (disjoint.mono_left (finsupp.supported_mono h)) theorem linear_independent.disjoint_span_image {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (hv : linear_independent R v) {s : set ι} {t : set ι} (hs : disjoint s t) : disjoint (submodule.span R (v '' s)) (submodule.span R (v '' t)) := sorry theorem linear_independent_sum {ι : Type u_1} {ι' : Type u_2} {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {v : ι ⊕ ι' → M} : linear_independent R v ↔ linear_independent R (v ∘ sum.inl) ∧ linear_independent R (v ∘ sum.inr) ∧ disjoint (submodule.span R (set.range (v ∘ sum.inl))) (submodule.span R (set.range (v ∘ sum.inr))) := sorry theorem linear_independent.sum_type {ι : Type u_1} {ι' : Type u_2} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] {v' : ι' → M} (hv : linear_independent R v) (hv' : linear_independent R v') (h : disjoint (submodule.span R (set.range v)) (submodule.span R (set.range v'))) : linear_independent R (sum.elim v v') := iff.mpr linear_independent_sum { left := hv, right := { left := hv', right := h } } theorem linear_independent.union {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {s : set M} {t : set M} (hs : linear_independent R fun (x : ↥s) => ↑x) (ht : linear_independent R fun (x : ↥t) => ↑x) (hst : disjoint (submodule.span R s) (submodule.span R t)) : linear_independent R fun (x : ↥(s ∪ t)) => ↑x := sorry theorem linear_independent_of_finite {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] (s : set M) (H : ∀ (t : set M), t ⊆ s → set.finite t → linear_independent R fun (x : ↥t) => ↑x) : linear_independent R fun (x : ↥s) => ↑x := sorry theorem linear_independent_Union_of_directed {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {η : Type u_1} {s : η → set M} (hs : directed has_subset.subset s) (h : ∀ (i : η), linear_independent R fun (x : ↥(s i)) => ↑x) : linear_independent R fun (x : ↥(set.Union fun (i : η) => s i)) => ↑x := sorry theorem linear_independent_sUnion_of_directed {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {s : set (set M)} (hs : directed_on has_subset.subset s) (h : ∀ (a : set M), a ∈ s → linear_independent R fun (x : ↥a) => ↑x) : linear_independent R fun (x : ↥(⋃₀s)) => ↑x := eq.mpr (id (Eq._oldrec (Eq.refl (linear_independent R fun (x : ↥(⋃₀s)) => ↑x)) set.sUnion_eq_Union)) (linear_independent_Union_of_directed (directed_on.directed_coe hs) (eq.mpr (id (propext set_coe.forall)) (eq.mp (Eq.refl (∀ (a : set M), a ∈ s → linear_independent R coe)) h))) theorem linear_independent_bUnion_of_directed {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {η : Type u_1} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o has_subset.subset) s) (h : ∀ (a : η), a ∈ s → linear_independent R fun (x : ↥(t a)) => ↑x) : linear_independent R fun (x : ↥(set.Union fun (a : η) => set.Union fun (H : a ∈ s) => t a)) => ↑x := sorry theorem linear_independent_Union_finite_subtype {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {ι : Type u_1} {f : ι → set M} (hl : ∀ (i : ι), linear_independent R fun (x : ↥(f i)) => ↑x) (hd : ∀ (i : ι) (t : set ι), set.finite t → ¬i ∈ t → disjoint (submodule.span R (f i)) (supr fun (i : ι) => supr fun (H : i ∈ t) => submodule.span R (f i))) : linear_independent R fun (x : ↥(set.Union fun (i : ι) => f i)) => ↑x := sorry theorem linear_independent_Union_finite {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] {η : Type u_1} {ιs : η → Type u_2} {f : (j : η) → ιs j → M} (hindep : ∀ (j : η), linear_independent R (f j)) (hd : ∀ (i : η) (t : set η), set.finite t → ¬i ∈ t → disjoint (submodule.span R (set.range (f i))) (supr fun (i : η) => supr fun (H : i ∈ t) => submodule.span R (set.range (f i)))) : linear_independent R fun (ji : sigma fun (j : η) => ιs j) => f (sigma.fst ji) (sigma.snd ji) := sorry /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (hv : linear_independent R v) : linear_equiv R (ι →₀ R) ↥(submodule.span R (set.range v)) := linear_equiv.of_bijective (linear_map.cod_restrict (submodule.span R (set.range v)) (finsupp.total ι M R v) sorry) sorry sorry /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (hv : linear_independent R v) : linear_map R (↥(submodule.span R (set.range v))) (ι →₀ R) := ↑(linear_equiv.symm (linear_independent.total_equiv hv)) theorem linear_independent.total_repr {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (hv : linear_independent R v) (x : ↥(submodule.span R (set.range v))) : coe_fn (finsupp.total ι M R v) (coe_fn (linear_independent.repr hv) x) = ↑x := iff.mp subtype.ext_iff (linear_equiv.apply_symm_apply (linear_independent.total_equiv hv) x) theorem linear_independent.total_comp_repr {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (hv : linear_independent R v) : linear_map.comp (finsupp.total ι M R v) (linear_independent.repr hv) = submodule.subtype (submodule.span R (set.range v)) := linear_map.ext (linear_independent.total_repr hv) theorem linear_independent.repr_ker {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (hv : linear_independent R v) : linear_map.ker (linear_independent.repr hv) = ⊥ := sorry theorem linear_independent.repr_range {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (hv : linear_independent R v) : linear_map.range (linear_independent.repr hv) = ⊤ := sorry theorem linear_independent.repr_eq {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (hv : linear_independent R v) {l : ι →₀ R} {x : ↥(submodule.span R (set.range v))} (eq : coe_fn (finsupp.total ι M R v) l = ↑x) : coe_fn (linear_independent.repr hv) x = l := sorry theorem linear_independent.repr_eq_single {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] (hv : linear_independent R v) (i : ι) (x : ↥(submodule.span R (set.range v))) (hx : ↑x = v i) : coe_fn (linear_independent.repr hv) x = finsupp.single i 1 := sorry -- TODO: why is this so slow? theorem linear_independent_iff_not_smul_mem_span {ι : Type u_1} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] : linear_independent R v ↔ ∀ (i : ι) (a : R), a • v i ∈ submodule.span R (v '' (set.univ \ singleton i)) → a = 0 := sorry theorem surjective_of_linear_independent_of_span {ι : Type u_1} {ι' : Type u_2} {R : Type u_3} {M : Type u_5} {v : ι → M} [ring R] [add_comm_group M] [module R M] [nontrivial R] (hv : linear_independent R v) (f : ι' ↪ ι) (hss : set.range v ⊆ ↑(submodule.span R (set.range (v ∘ ⇑f)))) : function.surjective ⇑f := sorry theorem eq_of_linear_independent_of_span_subtype {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] [nontrivial R] {s : set M} {t : set M} (hs : linear_independent R fun (x : ↥s) => ↑x) (h : t ⊆ s) (hst : s ⊆ ↑(submodule.span R t)) : s = t := sorry theorem linear_independent.image_subtype {R : Type u_3} {M : Type u_5} {M' : Type u_6} [ring R] [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] {s : set M} {f : linear_map R M M'} (hs : linear_independent R fun (x : ↥s) => ↑x) (hf_inj : disjoint (submodule.span R s) (linear_map.ker f)) : linear_independent R fun (x : ↥(⇑f '' s)) => ↑x := sorry theorem linear_independent.inl_union_inr {R : Type u_3} {M : Type u_5} {M' : Type u_6} [ring R] [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] {s : set M} {t : set M'} (hs : linear_independent R fun (x : ↥s) => ↑x) (ht : linear_independent R fun (x : ↥t) => ↑x) : linear_independent R fun (x : ↥(⇑(linear_map.inl R M M') '' s ∪ ⇑(linear_map.inr R M M') '' t)) => ↑x := sorry theorem linear_independent_inl_union_inr' {ι : Type u_1} {ι' : Type u_2} {R : Type u_3} {M : Type u_5} {M' : Type u_6} [ring R] [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (⇑(linear_map.inl R M M') ∘ v) (⇑(linear_map.inr R M M') ∘ v')) := sorry /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type u_1) [monoid G] (L : Type u_2) [comm_ring L] [no_zero_divisors L] : linear_independent L fun (f : G →* L) => ⇑f := sorry -- We prove linear independence by showing that only the trivial linear combination vanishes. -- To do this, we use `finset` induction, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. -- From these two facts we deduce that `g` actually vanishes on `s`, -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. theorem le_of_span_le_span {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] [nontrivial R] {s : set M} {t : set M} {u : set M} (hl : linear_independent R coe) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : submodule.span R s ≤ submodule.span R t) : s ⊆ t := sorry theorem span_le_span_iff {R : Type u_3} {M : Type u_5} [ring R] [add_comm_group M] [module R M] [nontrivial R] {s : set M} {t : set M} {u : set M} (hl : linear_independent R coe) (hsu : s ⊆ u) (htu : t ⊆ u) : submodule.span R s ≤ submodule.span R t ↔ s ⊆ t := { mp := le_of_span_le_span hl hsu htu, mpr := submodule.span_mono } /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ theorem mem_span_insert_exchange {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {s : set V} {x : V} {y : V} : x ∈ submodule.span K (insert y s) → ¬x ∈ submodule.span K s → y ∈ submodule.span K (insert x s) := sorry theorem linear_independent_iff_not_mem_span {ι : Type u_1} {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} : linear_independent K v ↔ ∀ (i : ι), ¬v i ∈ submodule.span K (v '' (set.univ \ singleton i)) := sorry theorem linear_independent_unique_iff {ι : Type u_1} {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} [unique ι] : linear_independent K v ↔ v Inhabited.default ≠ 0 := sorry theorem linear_independent_unique {ι : Type u_1} {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} [unique ι] : v Inhabited.default ≠ 0 → linear_independent K v := iff.mpr linear_independent_unique_iff theorem linear_independent_singleton {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {x : V} (hx : x ≠ 0) : linear_independent K fun (x_1 : ↥(singleton x)) => ↑x_1 := linear_independent_unique hx theorem linear_independent_option' {ι : Type u_1} {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} {x : V} : (linear_independent K fun (o : Option ι) => option.cases_on' o x v) ↔ linear_independent K v ∧ ¬x ∈ submodule.span K (set.range v) := sorry theorem linear_independent.option {ι : Type u_1} {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} {x : V} (hv : linear_independent K v) (hx : ¬x ∈ submodule.span K (set.range v)) : linear_independent K fun (o : Option ι) => option.cases_on' o x v := iff.mpr linear_independent_option' { left := hv, right := hx } theorem linear_independent_option {ι : Type u_1} {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {v : Option ι → V} : linear_independent K v ↔ linear_independent K (v ∘ coe) ∧ ¬v none ∈ submodule.span K (set.range (v ∘ coe)) := sorry theorem linear_independent.insert {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {s : set V} {x : V} (hs : linear_independent K fun (b : ↥s) => ↑b) (hx : ¬x ∈ submodule.span K s) : linear_independent K fun (b : ↥(insert x s)) => ↑b := sorry theorem linear_independent_insert' {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {ι : Type u_1} {s : set ι} {a : ι} {f : ι → V} (has : ¬a ∈ s) : (linear_independent K fun (x : ↥(insert a s)) => f ↑x) ↔ (linear_independent K fun (x : ↥s) => f ↑x) ∧ ¬f a ∈ submodule.span K (f '' s) := sorry theorem linear_independent_insert {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {s : set V} {x : V} (hxs : ¬x ∈ s) : (linear_independent K fun (b : ↥(insert x s)) => ↑b) ↔ (linear_independent K fun (b : ↥s) => ↑b) ∧ ¬x ∈ submodule.span K s := sorry theorem linear_independent_pair {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {x : V} {y : V} (hx : x ≠ 0) (hy : ∀ (a : K), a • x ≠ y) : linear_independent K coe := Eq.subst (set.pair_comm y x) (linear_independent.insert (linear_independent_singleton hx)) (mt (iff.mp submodule.mem_span_singleton) (iff.mpr not_exists hy)) theorem linear_independent_fin_cons {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {x : V} {n : ℕ} {v : fin n → V} : linear_independent K (fin.cons x v) ↔ linear_independent K v ∧ ¬x ∈ submodule.span K (set.range v) := sorry theorem linear_independent.fin_cons {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {x : V} {n : ℕ} {v : fin n → V} (hv : linear_independent K v) (hx : ¬x ∈ submodule.span K (set.range v)) : linear_independent K (fin.cons x v) := iff.mpr linear_independent_fin_cons { left := hv, right := hx } theorem linear_independent_fin_succ {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {n : ℕ} {v : fin (n + 1) → V} : linear_independent K v ↔ linear_independent K (fin.tail v) ∧ ¬v 0 ∈ submodule.span K (set.range (fin.tail v)) := sorry theorem linear_independent_fin2 {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {f : fin (bit0 1) → V} : linear_independent K f ↔ f 1 ≠ 0 ∧ ∀ (a : K), a • f 1 ≠ f 0 := sorry theorem exists_linear_independent {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {s : set V} {t : set V} (hs : linear_independent K fun (x : ↥s) => ↑x) (hst : s ⊆ t) : ∃ (b : set V), ∃ (H : b ⊆ t), s ⊆ b ∧ t ⊆ ↑(submodule.span K b) ∧ linear_independent K fun (x : ↥b) => ↑x := sorry -- TODO(Mario): rewrite? theorem exists_of_linear_independent_of_finite_span {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {s : set V} {t : finset V} (hs : linear_independent K fun (x : ↥s) => ↑x) (hst : s ⊆ ↑(submodule.span K ↑t)) : ∃ (t' : finset V), ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ finset.card t' = finset.card t := sorry theorem exists_finite_card_le_of_finite_of_linear_independent_of_span {K : Type u_4} {V : Type u} [field K] [add_comm_group V] [vector_space K V] {s : set V} {t : set V} (ht : set.finite t) (hs : linear_independent K fun (x : ↥s) => ↑x) (hst : s ⊆ ↑(submodule.span K t)) : ∃ (h : set.finite s), finset.card (set.finite.to_finset h) ≤ finset.card (set.finite.to_finset ht) := sorry end Mathlib
2a6d4fd7792fe29c6b92a42e9d2d6dd49b9d0f8b
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/specific_limits/basic.lean
db98954d6e8a048e079a4a2e3b6073bc4d0dd645
[ "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
24,564
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Johannes Hölzl, Yury G. Kudryashov, Patrick Massot -/ import algebra.geom_sum import order.filter.archimedean import order.iterate import topology.instances.ennreal /-! # A collection of specific limit computations This file, by design, is independent of `normed_space` in the import hierarchy. It contains important specific limit computations in metric spaces, in ordered rings/fields, and in specific instances of these such as `ℝ`, `ℝ≥0` and `ℝ≥0∞`. -/ noncomputable theory open classical set function filter finset metric open_locale classical topological_space nat big_operators uniformity nnreal ennreal variables {α : Type*} {β : Type*} {ι : Type*} lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) := tendsto_inv_at_top_zero.comp tendsto_coe_nat_at_top_at_top lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ≥0)⁻¹) at_top (𝓝 0) := by { rw ← nnreal.tendsto_coe, exact tendsto_inverse_at_top_nhds_0_nat } lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : ℝ≥0) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat lemma tendsto_one_div_add_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) := suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa, (tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1) /-! ### Powers -/ lemma tendsto_add_one_pow_at_top_at_top_of_pos [linear_ordered_semiring α] [archimedean α] {r : α} (h : 0 < r) : tendsto (λ n:ℕ, (r + 1)^n) at_top at_top := tendsto_at_top_at_top_of_monotone' (λ n m, pow_le_pow (le_add_of_nonneg_left (le_of_lt h))) $ not_bdd_above_iff.2 $ λ x, set.exists_range_iff.2 $ add_one_pow_unbounded_of_pos _ h lemma tendsto_pow_at_top_at_top_of_one_lt [linear_ordered_ring α] [archimedean α] {r : α} (h : 1 < r) : tendsto (λn:ℕ, r ^ n) at_top at_top := sub_add_cancel r 1 ▸ tendsto_add_one_pow_at_top_at_top_of_pos (sub_pos.2 h) lemma nat.tendsto_pow_at_top_at_top_of_one_lt {m : ℕ} (h : 1 < m) : tendsto (λn:ℕ, m ^ n) at_top at_top := tsub_add_cancel_of_le (le_of_lt h) ▸ tendsto_add_one_pow_at_top_at_top_of_pos (tsub_pos_of_lt h) lemma tendsto_pow_at_top_nhds_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜] [topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 ≤ r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := h₁.eq_or_lt.elim (assume : 0 = r, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, ← this, tendsto_const_nhds]) (assume : 0 < r, have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0), from tendsto_inv_at_top_zero.comp (tendsto_pow_at_top_at_top_of_one_lt $ one_lt_inv this h₂), this.congr (λ n, by simp)) lemma tendsto_pow_at_top_nhds_within_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜] [topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 < r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝[>] 0) := tendsto_inf.2 ⟨tendsto_pow_at_top_nhds_0_of_lt_1 h₁.le h₂, tendsto_principal.2 $ eventually_of_forall $ λ n, pow_pos h₁ _⟩ lemma uniformity_basis_dist_pow_of_lt_1 {α : Type*} [pseudo_metric_space α] {r : ℝ} (h₀ : 0 < r) (h₁ : r < 1) : (𝓤 α).has_basis (λ k : ℕ, true) (λ k, {p : α × α | dist p.1 p.2 < r ^ k}) := metric.mk_uniformity_basis (λ i _, pow_pos h₀ _) $ λ ε ε0, (exists_pow_lt_of_lt_one ε0 h₁).imp $ λ k hk, ⟨trivial, hk.le⟩ lemma geom_lt {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n) (h : ∀ k < n, c * u k < u (k + 1)) : c ^ n * u 0 < u n := begin refine (monotone_mul_left_of_nonneg hc).seq_pos_lt_seq_of_le_of_lt hn _ _ h, { simp }, { simp [pow_succ, mul_assoc, le_refl] } end lemma geom_le {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) (n : ℕ) (h : ∀ k < n, c * u k ≤ u (k + 1)) : c ^ n * u 0 ≤ u n := by refine (monotone_mul_left_of_nonneg hc).seq_le_seq n _ _ h; simp [pow_succ, mul_assoc, le_refl] lemma lt_geom {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n) (h : ∀ k < n, u (k + 1) < c * u k) : u n < c ^ n * u 0 := begin refine (monotone_mul_left_of_nonneg hc).seq_pos_lt_seq_of_lt_of_le hn _ h _, { simp }, { simp [pow_succ, mul_assoc, le_refl] } end lemma le_geom {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) (n : ℕ) (h : ∀ k < n, u (k + 1) ≤ c * u k) : u n ≤ (c ^ n) * u 0 := by refine (monotone_mul_left_of_nonneg hc).seq_le_seq n _ h _; simp [pow_succ, mul_assoc, le_refl] /-- If a sequence `v` of real numbers satisfies `k * v n ≤ v (n+1)` with `1 < k`, then it goes to +∞. -/ lemma tendsto_at_top_of_geom_le {v : ℕ → ℝ} {c : ℝ} (h₀ : 0 < v 0) (hc : 1 < c) (hu : ∀ n, c * v n ≤ v (n + 1)) : tendsto v at_top at_top := tendsto_at_top_mono (λ n, geom_le (zero_le_one.trans hc.le) n (λ k hk, hu k)) $ (tendsto_pow_at_top_at_top_of_one_lt hc).at_top_mul_const h₀ lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero, tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr] lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0∞} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := begin rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, rw [← ennreal.coe_zero], norm_cast at *, apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr end /-! ### Geometric series-/ section geometric lemma has_sum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := have r ≠ 1, from ne_of_lt h₂, have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds, (has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $ by simp [neg_inv, geom_sum_eq, div_eq_mul_inv, *] at * lemma summable_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, has_sum_geometric_of_lt_1 h₁ h₂⟩ lemma tsum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := (has_sum_geometric_of_lt_1 h₁ h₂).tsum_eq lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 := by convert has_sum_geometric_of_lt_1 _ _; norm_num lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) := ⟨_, has_sum_geometric_two⟩ lemma summable_geometric_two_encode {ι : Type*} [encodable ι] : summable (λ (i : ι), (1/2 : ℝ)^(encodable.encode i)) := summable_geometric_two.comp_injective encodable.encode_injective lemma tsum_geometric_two : ∑'n:ℕ, ((1:ℝ)/2) ^ n = 2 := has_sum_geometric_two.tsum_eq lemma sum_geometric_two_le (n : ℕ) : ∑ (i : ℕ) in range n, (1 / (2 : ℝ)) ^ i ≤ 2 := begin have : ∀ i, 0 ≤ (1 / (2 : ℝ)) ^ i, { intro i, apply pow_nonneg, norm_num }, convert sum_le_tsum (range n) (λ i _, this i) summable_geometric_two, exact tsum_geometric_two.symm end lemma tsum_geometric_inv_two : ∑' n : ℕ, (2 : ℝ)⁻¹ ^ n = 2 := (inv_eq_one_div (2 : ℝ)).symm ▸ tsum_geometric_two /-- The sum of `2⁻¹ ^ i` for `n ≤ i` equals `2 * 2⁻¹ ^ n`. -/ lemma tsum_geometric_inv_two_ge (n : ℕ) : ∑' i, ite (n ≤ i) ((2 : ℝ)⁻¹ ^ i) 0 = 2 * 2⁻¹ ^ n := begin have A : summable (λ (i : ℕ), ite (n ≤ i) ((2⁻¹ : ℝ) ^ i) 0), { apply summable_of_nonneg_of_le _ _ summable_geometric_two; { intro i, by_cases hi : n ≤ i; simp [hi] } }, have B : (finset.range n).sum (λ (i : ℕ), ite (n ≤ i) ((2⁻¹ : ℝ)^i) 0) = 0 := finset.sum_eq_zero (λ i hi, ite_eq_right_iff.2 $ λ h, (lt_irrefl _ ((finset.mem_range.1 hi).trans_le h)).elim), simp only [← sum_add_tsum_nat_add n A, B, if_true, zero_add, zero_le', le_add_iff_nonneg_left, pow_add, tsum_mul_right, tsum_geometric_inv_two], end lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a := begin convert has_sum.mul_left (a / 2) (has_sum_geometric_of_lt_1 (le_of_lt one_half_pos) one_half_lt_one), { funext n, simp, refl, }, { norm_num } end lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) := ⟨a, has_sum_geometric_two' a⟩ lemma tsum_geometric_two' (a : ℝ) : ∑' n:ℕ, (a / 2) / 2^n = a := (has_sum_geometric_two' a).tsum_eq /-- **Sum of a Geometric Series** -/ lemma nnreal.has_sum_geometric {r : ℝ≥0} (hr : r < 1) : has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ := begin apply nnreal.has_sum_coe.1, push_cast, rw [nnreal.coe_sub (le_of_lt hr)], exact has_sum_geometric_of_lt_1 r.coe_nonneg hr end lemma nnreal.summable_geometric {r : ℝ≥0} (hr : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, nnreal.has_sum_geometric hr⟩ lemma tsum_geometric_nnreal {r : ℝ≥0} (hr : r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := (nnreal.has_sum_geometric hr).tsum_eq /-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number, and for `1 ≤ r` the RHS equals `∞`. -/ @[simp] lemma ennreal.tsum_geometric (r : ℝ≥0∞) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := begin cases lt_or_le r 1 with hr hr, { rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, norm_cast at *, convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr), rw [ennreal.coe_inv $ ne_of_gt $ tsub_pos_iff_lt.2 hr] }, { rw [tsub_eq_zero_iff_le.mpr hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top], refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp (λ n hn, lt_of_lt_of_le hn _), calc (n:ℝ≥0∞) = ∑ i in range n, 1 : by rw [sum_const, nsmul_one, card_range] ... ≤ ∑ i in range n, r ^ i : sum_le_sum (λ k _, one_le_pow_of_one_le' hr k) } end end geometric /-! ### Sequences with geometrically decaying distance in metric spaces In this paragraph, we discuss sequences in metric spaces or emetric spaces for which the distance between two consecutive terms decays geometrically. We show that such sequences are Cauchy sequences, and bound their distances to the limit. We also discuss series with geometrically decaying terms. -/ section edist_le_geometric variables [pseudo_emetric_space α] (r C : ℝ≥0∞) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n) include hr hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f := begin refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _, rw [ennreal.tsum_mul_left, ennreal.tsum_geometric], refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _), exact (tsub_pos_iff_lt.2 hr).ne' end omit hr hC /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ (C * r^n) / (1 - r) := begin convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _, simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, div_eq_mul_inv, mul_assoc] end /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ C / (1 - r) := by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0 end edist_le_geometric section edist_le_geometric_two variables [pseudo_emetric_space α] (C : ℝ≥0∞) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a)) include hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f := begin simp only [div_eq_mul_inv, ennreal.inv_pow] at hu, refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu, simp [ennreal.one_lt_two] end omit hC include ha /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) : edist (f n) a ≤ 2 * C / 2^n := begin simp only [div_eq_mul_inv, ennreal.inv_pow] at *, rw [mul_assoc, mul_comm], convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n, rw [ennreal.one_sub_inv_two, inv_inv] end /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f 0` to the limit of `f` is bounded above by `2 * C`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C := by simpa only [pow_zero, div_eq_mul_inv, ennreal.inv_one, mul_one] using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0 end edist_le_geometric_two section le_geometric variables [pseudo_metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α} (hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n) include hr hu lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) := begin rcases sign_cases_of_C_mul_pow_nonneg (λ n, dist_nonneg.trans (hu n)) with rfl | ⟨C₀, r₀⟩, { simp [has_sum_zero] }, { refine has_sum.mul_left C _, simpa using has_sum_geometric_of_lt_1 r₀ hr } end variables (r C) /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence. Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/ lemma cauchy_seq_of_le_geometric : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C / (1 - r) := (aux_has_sum_of_le_geometric hr hu).tsum_eq ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ (C * r^n) / (1 - r) := begin have := aux_has_sum_of_le_geometric hr hu, convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n, simp only [pow_add, mul_left_comm C, mul_div_right_comm], rw [mul_comm], exact (this.mul_left _).tsum_eq.symm end omit hr hu variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n) /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_geometric_two : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C`. -/ lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C := (tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha include hu₂ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f n` to the limit of `f` is bounded above by `C / 2^n`. -/ lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ C / 2^n := begin convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n, simp only [add_comm n, pow_add, ← div_div], symmetry, exact ((has_sum_geometric_two' C).div_const _).tsum_eq end end le_geometric /-! ### Summability tests based on comparison with geometric series -/ /-- A series whose terms are bounded by the terms of a converging geometric series converges. -/ lemma summable_one_div_pow_of_le {m : ℝ} {f : ℕ → ℕ} (hm : 1 < m) (fi : ∀ i, i ≤ f i) : summable (λ i, 1 / m ^ f i) := begin refine summable_of_nonneg_of_le (λ a, one_div_nonneg.mpr (pow_nonneg (zero_le_one.trans hm.le) _)) (λ a, _) (summable_geometric_of_lt_1 (one_div_nonneg.mpr (zero_le_one.trans hm.le)) ((one_div_lt (zero_lt_one.trans hm) zero_lt_one).mpr (one_div_one.le.trans_lt hm))), rw [div_pow, one_pow], refine (one_div_le_one_div _ _).mpr (pow_le_pow hm.le (fi a)); exact pow_pos (zero_lt_one.trans hm) _ end /-! ### Positive sequences with small sums on encodable types -/ /-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/ def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε) (ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} := begin let f := λ n, (ε / 2) / 2 ^ n, have hf : has_sum f ε := has_sum_geometric_two' _, have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos zero_lt_two _), refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩, rcases hf.summable.comp_injective (@encodable.encode_injective ι _) with ⟨c, hg⟩, refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩, { assume i _, exact le_of_lt (f0 _) }, { assume n, exact le_rfl } end lemma set.countable.exists_pos_has_sum_le {ι : Type*} {s : set ι} (hs : s.countable) {ε : ℝ} (hε : 0 < ε) : ∃ ε' : ι → ℝ, (∀ i, 0 < ε' i) ∧ ∃ c, has_sum (λ i : s, ε' i) c ∧ c ≤ ε := begin haveI := hs.to_encodable, rcases pos_sum_of_encodable hε s with ⟨f, hf0, ⟨c, hfc, hcε⟩⟩, refine ⟨λ i, if h : i ∈ s then f ⟨i, h⟩ else 1, λ i, _, ⟨c, _, hcε⟩⟩, { split_ifs, exacts [hf0 _, zero_lt_one] }, { simpa only [subtype.coe_prop, dif_pos, subtype.coe_eta] } end lemma set.countable.exists_pos_forall_sum_le {ι : Type*} {s : set ι} (hs : s.countable) {ε : ℝ} (hε : 0 < ε) : ∃ ε' : ι → ℝ, (∀ i, 0 < ε' i) ∧ ∀ t : finset ι, ↑t ⊆ s → ∑ i in t, ε' i ≤ ε := begin rcases hs.exists_pos_has_sum_le hε with ⟨ε', hpos, c, hε'c, hcε⟩, refine ⟨ε', hpos, λ t ht, _⟩, rw [← sum_subtype_of_mem _ ht], refine (sum_le_has_sum _ _ hε'c).trans hcε, exact λ _ _, (hpos _).le end namespace nnreal theorem exists_pos_sum_of_encodable {ε : ℝ≥0} (hε : ε ≠ 0) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε := let ⟨a, a0, aε⟩ := exists_between (pos_iff_ne_zero.2 hε) in let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in ⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.1 $ hε' i, ⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc, lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩ end nnreal namespace ennreal theorem exists_pos_sum_of_encodable {ε : ℝ≥0∞} (hε : ε ≠ 0) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∑' i, (ε' i : ℝ≥0∞) < ε := begin rcases exists_between (pos_iff_ne_zero.2 hε) with ⟨r, h0r, hrε⟩, rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩, rcases nnreal.exists_pos_sum_of_encodable (coe_pos.1 h0r).ne' ι with ⟨ε', hp, c, hc, hcr⟩, exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩ end theorem exists_pos_sum_of_encodable' {ε : ℝ≥0∞} (hε : ε ≠ 0) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0∞, (∀ i, 0 < ε' i) ∧ (∑' i, ε' i) < ε := let ⟨δ, δpos, hδ⟩ := exists_pos_sum_of_encodable hε ι in ⟨λ i, δ i, λ i, ennreal.coe_pos.2 (δpos i), hδ⟩ theorem exists_pos_tsum_mul_lt_of_encodable {ε : ℝ≥0∞} (hε : ε ≠ 0) {ι} [encodable ι] (w : ι → ℝ≥0∞) (hw : ∀ i, w i ≠ ∞) : ∃ δ : ι → ℝ≥0, (∀ i, 0 < δ i) ∧ ∑' i, (w i * δ i : ℝ≥0∞) < ε := begin lift w to ι → ℝ≥0 using hw, rcases exists_pos_sum_of_encodable hε ι with ⟨δ', Hpos, Hsum⟩, have : ∀ i, 0 < max 1 (w i), from λ i, zero_lt_one.trans_le (le_max_left _ _), refine ⟨λ i, δ' i / max 1 (w i), λ i, nnreal.div_pos (Hpos _) (this i), _⟩, refine lt_of_le_of_lt (ennreal.tsum_le_tsum $ λ i, _) Hsum, rw [coe_div (this i).ne'], refine mul_le_of_le_div' (ennreal.mul_le_mul le_rfl $ ennreal.inv_le_inv.2 _), exact coe_le_coe.2 (le_max_right _ _) end end ennreal /-! ### Factorial -/ lemma factorial_tendsto_at_top : tendsto nat.factorial at_top at_top := tendsto_at_top_at_top_of_monotone nat.monotone_factorial (λ n, ⟨n, n.self_le_factorial⟩) lemma tendsto_factorial_div_pow_self_at_top : tendsto (λ n, n! / n^n : ℕ → ℝ) at_top (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds (tendsto_const_div_at_top_nhds_0_nat 1) (eventually_of_forall $ λ n, div_nonneg (by exact_mod_cast n.factorial_pos.le) (pow_nonneg (by exact_mod_cast n.zero_le) _)) begin refine (eventually_gt_at_top 0).mono (λ n hn, _), rcases nat.exists_eq_succ_of_ne_zero hn.ne.symm with ⟨k, rfl⟩, rw [← prod_range_add_one_eq_factorial, pow_eq_prod_const, div_eq_mul_inv, ← inv_eq_one_div, prod_nat_cast, nat.cast_succ, ← prod_inv_distrib, ← prod_mul_distrib, finset.prod_range_succ'], simp only [prod_range_succ', one_mul, nat.cast_add, zero_add, nat.cast_one], refine mul_le_of_le_one_left (inv_nonneg.mpr $ by exact_mod_cast hn.le) (prod_le_one _ _); intros x hx; rw finset.mem_range at hx, { refine mul_nonneg _ (inv_nonneg.mpr _); norm_cast; linarith }, { refine (div_le_one $ by exact_mod_cast hn).mpr _, norm_cast, linarith } end /-! ### Ceil and floor -/ section lemma tendsto_nat_floor_at_top {α : Type*} [linear_ordered_semiring α] [floor_semiring α] : tendsto (λ (x : α), ⌊x⌋₊) at_top at_top := nat.floor_mono.tendsto_at_top_at_top (λ x, ⟨max 0 (x + 1), by simp [nat.le_floor_iff]⟩) variables {R : Type*} [topological_space R] [linear_ordered_field R] [order_topology R] [floor_ring R] lemma tendsto_nat_floor_mul_div_at_top {a : R} (ha : 0 ≤ a) : tendsto (λ x, (⌊a * x⌋₊ : R) / x) at_top (𝓝 a) := begin have A : tendsto (λ (x : R), a - x⁻¹) at_top (𝓝 (a - 0)) := tendsto_const_nhds.sub tendsto_inv_at_top_zero, rw sub_zero at A, apply tendsto_of_tendsto_of_tendsto_of_le_of_le' A tendsto_const_nhds, { refine eventually_at_top.2 ⟨1, λ x hx, _⟩, simp only [le_div_iff (zero_lt_one.trans_le hx), sub_mul, inv_mul_cancel (zero_lt_one.trans_le hx).ne'], have := nat.lt_floor_add_one (a * x), linarith }, { refine eventually_at_top.2 ⟨1, λ x hx, _⟩, rw div_le_iff (zero_lt_one.trans_le hx), simp [nat.floor_le (mul_nonneg ha (zero_le_one.trans hx))] } end lemma tendsto_nat_floor_div_at_top : tendsto (λ x, (⌊x⌋₊ : R) / x) at_top (𝓝 1) := by simpa using tendsto_nat_floor_mul_div_at_top (zero_le_one' R) lemma tendsto_nat_ceil_mul_div_at_top {a : R} (ha : 0 ≤ a) : tendsto (λ x, (⌈a * x⌉₊ : R) / x) at_top (𝓝 a) := begin have A : tendsto (λ (x : R), a + x⁻¹) at_top (𝓝 (a + 0)) := tendsto_const_nhds.add tendsto_inv_at_top_zero, rw add_zero at A, apply tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds A, { refine eventually_at_top.2 ⟨1, λ x hx, _⟩, rw le_div_iff (zero_lt_one.trans_le hx), exact nat.le_ceil _ }, { refine eventually_at_top.2 ⟨1, λ x hx, _⟩, simp [div_le_iff (zero_lt_one.trans_le hx), inv_mul_cancel (zero_lt_one.trans_le hx).ne', (nat.ceil_lt_add_one ((mul_nonneg ha (zero_le_one.trans hx)))).le, add_mul] } end lemma tendsto_nat_ceil_div_at_top : tendsto (λ x, (⌈x⌉₊ : R) / x) at_top (𝓝 1) := by simpa using tendsto_nat_ceil_mul_div_at_top (zero_le_one' R) end
239d4741442a14f0868b3a623270f81c2d2daeae
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/nat/prime.lean
f075322bf4dcfb8de1cea4e787a24b1c69247895
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
24,311
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 algebra.group_power import tactic.wlog /-! # 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.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, (decidable.lt_or_eq_of_le $ le_of_dvd (le_of_succ_le p2) d).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 ▸ 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⟩ /-- This instance is slower than the instance `decidable_prime` defined below, but has the advantage that it works 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. -/ def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' local attribute [instance] decidable_prime_1 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 := dec_trivial theorem not_prime_one : ¬ prime 1 := dec_trivial theorem prime_two : prime 2 := dec_trivial theorem prime_three : prime 3 := dec_trivial 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 _ _) 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 := rfl | 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 := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (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 (dvd_trans d 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 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) : pow_two (min_fac n) ... ≤ (n/min_fac n) * (min_fac n) : 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. There exist infinitely many prime numbers. 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 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) lemma mem_factors : ∀ {n p}, p ∈ factors n → prime p | 0 := λ p, false.elim | 1 := λ p, false.elim | 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 h, or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial) mem_factors lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n | 0 := (lt_irrefl _).elim | 1 := λ h, rfl | n@(k+2) := λ h, let m := min_fac n in have n / m < n := factors_lemma, show list.prod (m :: factors (n / m)) = 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 [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 /-- `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)))) := rfl 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, (dvd.trans (min_fac_dvd (gcd m n)) (gcd_dvd_left m n)), (dvd.trans (min_fac_dvd (gcd m n)) (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, exact (pp.dvd_mul.1 h).elim id IH] lemma prime.pow_not_prime {x n : ℕ} (hn : 2 ≤ n) : ¬ (x ^ n).prime := λ hp, (hp.2 x $ dvd_trans ⟨x, pow_two _⟩ (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_pow_two_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 [pow_two], begin wlog := hp.dvd_mul.1 pdvdxy using x y, cases case with a ha, have hap : a ∣ p, from ⟨y, by rwa [ha, pow_two, 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 [*, pow_two, nat.mul_right_inj hp.pos] at * {contextual := tt}) (λ _, by clear_aux_decl; simp [*, pow_two, 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 ▸ (pow_two _).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]; 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 (@mem_factors n) ((prod_factors hn).symm ▸ h)⟩ 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 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₂ (@mem_factors _) 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 := ⟨⟨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
abf5f87d58bd4ef02d67d46480baa5cd293df9ce
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/preadditive/schur.lean
97eba89df7dadafd3d619341d8a4a35cfae30774
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
6,979
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import algebra.group.ext import category_theory.simple import category_theory.linear import category_theory.endomorphism import algebra.algebra.spectrum /-! # Schur's lemma We first prove the part of Schur's Lemma that holds in any preadditive category with kernels, that any nonzero morphism between simple objects is an isomorphism. Second, we prove Schur's lemma for `𝕜`-linear categories with finite dimensional hom spaces, over an algebraically closed field `𝕜`: the hom space `X ⟶ Y` between simple objects `X` and `Y` is at most one dimensional, and is 1-dimensional iff `X` and `Y` are isomorphic. ## Future work It might be nice to provide a `division_ring` instance on `End X` when `X` is simple. This is an easy consequence of the results here, but may take some care setting up usable instances. -/ namespace category_theory open category_theory.limits universes v u variables {C : Type u} [category.{v} C] variables [preadditive C] /-- The part of **Schur's lemma** that holds in any preadditive category with kernels: that a nonzero morphism between simple objects is an isomorphism. -/ lemma is_iso_of_hom_simple [has_kernels C] {X Y : C} [simple X] [simple Y] {f : X ⟶ Y} (w : f ≠ 0) : is_iso f := begin haveI : mono f := preadditive.mono_of_kernel_zero (kernel_zero_of_nonzero_from_simple w), exact is_iso_of_mono_of_nonzero w end /-- As a corollary of Schur's lemma for preadditive categories, any morphism between simple objects is (exclusively) either an isomorphism or zero. -/ lemma is_iso_iff_nonzero [has_kernels C] {X Y : C} [simple.{v} X] [simple.{v} Y] (f : X ⟶ Y) : is_iso.{v} f ↔ f ≠ 0 := ⟨λ I, begin introI h, apply id_nonzero X, simp only [←is_iso.hom_inv_id f, h, zero_comp], end, λ w, is_iso_of_hom_simple w⟩ open finite_dimensional variables (𝕜 : Type*) [field 𝕜] /-- Part of **Schur's lemma** for `𝕜`-linear categories: the hom space between two non-isomorphic simple objects is 0-dimensional. -/ lemma finrank_hom_simple_simple_eq_zero_of_not_iso [has_kernels C] [linear 𝕜 C] {X Y : C} [simple.{v} X] [simple.{v} Y] (h : (X ≅ Y) → false): finrank 𝕜 (X ⟶ Y) = 0 := begin haveI := subsingleton_of_forall_eq (0 : X ⟶ Y) (λ f, begin have p := not_congr (is_iso_iff_nonzero f), simp only [not_not, ne.def] at p, refine p.mp (λ _, by exactI h (as_iso f)), end), exact finrank_zero_of_subsingleton, end variables [is_alg_closed 𝕜] [linear 𝕜 C] -- In the proof below we have some difficulty using `I : finite_dimensional 𝕜 (X ⟶ X)` -- where we need a `finite_dimensional 𝕜 (End X)`. -- These are definitionally equal, but without eta reduction Lean can't see this. -- To get around this, we use `convert I`, -- then check the various instances agree field-by-field, -- using `ext` equipped with the following extra lemmas: local attribute [ext] module distrib_mul_action mul_action has_scalar /-- An auxiliary lemma for Schur's lemma. If `X ⟶ X` is finite dimensional, and every nonzero endomorphism is invertible, then `X ⟶ X` is 1-dimensional. -/ -- We prove this with the explicit `is_iso_iff_nonzero` assumption, -- rather than just `[simple X]`, as this form is useful for -- Müger's formulation of semisimplicity. lemma finrank_endomorphism_eq_one {X : C} (is_iso_iff_nonzero : ∀ f : X ⟶ X, is_iso f ↔ f ≠ 0) [I : finite_dimensional 𝕜 (X ⟶ X)] : finrank 𝕜 (X ⟶ X) = 1 := begin have id_nonzero := (is_iso_iff_nonzero (𝟙 X)).mp (by apply_instance), apply finrank_eq_one (𝟙 X), { exact id_nonzero, }, { intro f, haveI : nontrivial (End X) := nontrivial_of_ne _ _ id_nonzero, obtain ⟨c, nu⟩ := @spectrum.nonempty_of_is_alg_closed_of_finite_dimensional 𝕜 (End X) _ _ _ _ _ (by { convert I, ext, refl, ext, refl, }) (End.of f), use c, rw [spectrum.mem_iff, is_unit.sub_iff, is_unit_iff_is_iso, is_iso_iff_nonzero, ne.def, not_not, sub_eq_zero, algebra.algebra_map_eq_smul_one] at nu, exact nu.symm, }, end variables [has_kernels C] /-- **Schur's lemma** for endomorphisms in `𝕜`-linear categories. -/ lemma finrank_endomorphism_simple_eq_one (X : C) [simple.{v} X] [I : finite_dimensional 𝕜 (X ⟶ X)] : finrank 𝕜 (X ⟶ X) = 1 := finrank_endomorphism_eq_one 𝕜 is_iso_iff_nonzero lemma endomorphism_simple_eq_smul_id {X : C} [simple.{v} X] [I : finite_dimensional 𝕜 (X ⟶ X)] (f : X ⟶ X) : ∃ c : 𝕜, c • 𝟙 X = f := (finrank_eq_one_iff_of_nonzero' (𝟙 X) (id_nonzero X)).mp (finrank_endomorphism_simple_eq_one 𝕜 X) f /-- **Schur's lemma** for `𝕜`-linear categories: if hom spaces are finite dimensional, then the hom space between simples is at most 1-dimensional. See `finrank_hom_simple_simple_eq_one_iff` and `finrank_hom_simple_simple_eq_zero_iff` below for the refinements when we know whether or not the simples are isomorphic. -/ -- We don't really need `[∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)]` here, -- just at least one of `[finite_dimensional 𝕜 (X ⟶ X)]` or `[finite_dimensional 𝕜 (Y ⟶ Y)]`. lemma finrank_hom_simple_simple_le_one (X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] : finrank 𝕜 (X ⟶ Y) ≤ 1 := begin cases subsingleton_or_nontrivial (X ⟶ Y) with h, { resetI, convert zero_le_one, exact finrank_zero_of_subsingleton, }, { obtain ⟨f, nz⟩ := (nontrivial_iff_exists_ne 0).mp h, haveI fi := (is_iso_iff_nonzero f).mpr nz, apply finrank_le_one f, intro g, obtain ⟨c, w⟩ := endomorphism_simple_eq_smul_id 𝕜 (g ≫ inv f), exact ⟨c, by simpa using w =≫ f⟩, }, end lemma finrank_hom_simple_simple_eq_one_iff (X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] : finrank 𝕜 (X ⟶ Y) = 1 ↔ nonempty (X ≅ Y) := begin fsplit, { intro h, rw finrank_eq_one_iff' at h, obtain ⟨f, nz, -⟩ := h, rw ←is_iso_iff_nonzero at nz, exactI ⟨as_iso f⟩, }, { rintro ⟨f⟩, have le_one := finrank_hom_simple_simple_le_one 𝕜 X Y, have zero_lt : 0 < finrank 𝕜 (X ⟶ Y) := finrank_pos_iff_exists_ne_zero.mpr ⟨f.hom, (is_iso_iff_nonzero f.hom).mp infer_instance⟩, linarith, } end lemma finrank_hom_simple_simple_eq_zero_iff (X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] : finrank 𝕜 (X ⟶ Y) = 0 ↔ is_empty (X ≅ Y) := begin rw [← not_nonempty_iff, ← not_congr (finrank_hom_simple_simple_eq_one_iff 𝕜 X Y)], refine ⟨λ h, by { rw h, simp, }, λ h, _⟩, have := finrank_hom_simple_simple_le_one 𝕜 X Y, interval_cases finrank 𝕜 (X ⟶ Y) with h', { exact h', }, { exact false.elim (h h'), }, end end category_theory
fa6bf1d66a1528bd63ea5497c32f340294d10acd
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/inlineIssue.lean
eb5067532b895e2fc232d2982f29d6dac8bfa21d
[ "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
376
lean
import Lean def f (x : Nat) := let g (y z : Nat) := match y with | 0 => x * z * x * y * y | .succ y => y + z let h (x : Nat) := g x x h (x+1) + h (x+2) + h (x+3) + h (x+4) + h (x+5) + h (x+6) + h (x+7) + h (x+8) + h (x+9) #eval Lean.Compiler.compile #[``f] -- set_option trace.Compiler.simp true -- TODO: uncomment #eval Lean.Compiler.compile #[``f]
59b5be58f48d3478a8775255a03c055233a4b5f9
b73bd2854495d87ad5ce4f247cfcd6faa7e71c7e
/src/game/intro.lean
c4d3991d81dd002c1be5a9540869afaf6f5e9999
[]
no_license
agusakov/category-theory-game
20db0b26270e0c95a3d5605498570273d72f731d
652dd7e90ae706643b2a597e2c938403653e167d
refs/heads/master
1,669,201,216,310
1,595,740,057,000
1,595,740,057,000
280,895,295
12
0
null
null
null
null
UTF-8
Lean
false
false
1,745
lean
/- # The Category Theory Game, version 0.1 ## By Alena Gusakov # What is this game? Welcome to the category theory game -- a game to help undergraduates learn category theory through Lean, a formal proof verification system. Starting from the definition of categories, we develop the theory of functors, natural transformations, equivalence of categories, representable functors and the Yoneda lemma. We develop the theory through problem-solving, getting students to formalise proofs in the theory. This game is a sequel to <a href="http://wwwf.imperial.ac.uk/~buzzard/xena/natural_number_game/" target="blank">the natural number game</a>. The levels in the Category Theory Game need to be solved using tactics. To learn how to use these tactics, I would recommend that you first play the Natural Number Game up to at least "Advanced Proposition world". I will not go through a careful explanation of the tactics taught by the natural number game here. Blue nodes on the graph are ones that you are ready to enter. Grey nodes you should stay away from -- try blue ones higher up the chain first. Green nodes are completed. # Thanks Many thanks to Mohammad Pedramfar, without whom this game would not exist. # Questions? You can ask questions on the <a href="https://leanprover.zulipchat.com/" target="blank">Lean Zulip chat</a>, where I am often to be found. The Category Theory Game is brought to you by the Xena project, a project based at Imperial College London whose aim is to get mathematics undergraduates using computer theorem provers. Lean is a computer theorem prover being developed at Microsoft Research. Prove a theorem. Write a function. <a href="https://twitter.com/XenaProject" target="blank">@XenaProject</a>. -/
da74cace5fd30608a64b8ac8d26b8d47d785aafb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/simpAtDefIssue.lean
e82f81f901b91473d9e85e6990bc4e5ab404b12d
[ "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
194
lean
@[simp] def g (x y : Nat) : Nat := match x, y with | 0, 0 => 1 | 0, y => y | x+1, 5 => 2 * g x 0 | x+1, y => 2 * g x y #check g._eq_1 #check g._eq_2 #check g._eq_3 #check g._eq_4
4279d0f2351cff704d549edd614e3e5c1dbfe13d
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/ring_theory/jacobson.lean
3a03bc503546cc4170de3fffee5628be7d1729cc
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
10,818
lean
/- Copyright (c) 2020 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Devon Tuma -/ import data.mv_polynomial import ring_theory.ideal.basic import ring_theory.ideal.operations import ring_theory.jacobson_ideal import ring_theory.localization /-! # Jacobson Rings The following conditions are equivalent for a ring `R`: 1. Every radical ideal `I` is equal to its jacobson radical 2. Every radical ideal `I` can be written as an intersection of maximal ideals 3. Every prime ideal `I` is equal to its jacobson radical Any ring satisfying any of these equivalent conditions is said to be Jacobson. Some particular examples of Jacobson rings are also proven. `is_jacobson_quotient` says that the quotient of a Jacobson ring is Jacobson. `is_jacobson_localization` says the localization of a Jacobson ring to a single element is Jacobson. ## Main definitions Let `R` be a commutative ring. Jacobson Rings are defined using the first of the above conditions * `is_jacobson R` is the proposition that `R` is a Jacobson ring. It is a class, implemented as the predicate that for any ideal, `I.radical = I` implies `I.jacobson = I`. ## Main statements * `is_jacobson_iff_prime_eq` is the equivalence between conditions 1 and 3 above. * `is_jacobson_iff_Inf_maximal` is the equivalence between conditions 1 and 2 above. * `is_jacobson_of_surjective` says that if `R` is a Jacobson ring and `f : R →+* S` is surjective, then `S` is also a Jacobson ring ## Tags Jacobson, Jacobson Ring -/ universes u v namespace ideal variables {R : Type u} [comm_ring R] {I : ideal R} variables {S : Type v} [comm_ring S] section is_jacobson /-- A ring is a Jacobson ring if for every radical ideal `I`, the Jacobson radical of `I` is equal to `I`. See `is_jacobson_iff_prime_eq` and `is_jacobson_iff_Inf_maximal` for equivalent definitions. -/ @[class] def is_jacobson (R : Type u) [comm_ring R] := ∀ (I : ideal R), I.radical = I → I.jacobson = I /-- A ring is a Jacobson ring if and only if for all prime ideals `P`, the Jacobson radical of `P` is equal to `P`. -/ lemma is_jacobson_iff_prime_eq : is_jacobson R ↔ ∀ P : ideal R, is_prime P → P.jacobson = P := begin split, { exact λ h I hI, h I (is_prime.radical hI) }, { refine λ h I hI, le_antisymm (λ x hx, _) (λ x hx, mem_Inf.mpr (λ _ hJ, hJ.left hx)), erw mem_Inf at hx, rw [← hI, radical_eq_Inf I, mem_Inf], intros P hP, rw set.mem_set_of_eq at hP, erw [← h P hP.right, mem_Inf], exact λ J hJ, hx ⟨le_trans hP.left hJ.left, hJ.right⟩ } end /-- A ring `R` is Jacobson if and only if for every prime ideal `I`, `I` can be written as the infimum of some collection of maximal ideals. Allowing ⊤ in the set `M` of maximal ideals is equivalent, but makes some proofs cleaner. -/ lemma is_jacobson_iff_Inf_maximal : is_jacobson R ↔ ∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R), (∀ J ∈ M, is_maximal J ∨ J = ⊤) ∧ I = Inf M := ⟨λ H I h, eq_jacobson_iff_Inf_maximal.1 (H _ (is_prime.radical h)), λ H , is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal.2 (H hP))⟩ lemma is_jacobson_iff_Inf_maximal' : is_jacobson R ↔ ∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R), (∀ (J ∈ M) (K : ideal R), J < K → K = ⊤) ∧ I = Inf M := ⟨λ H I h, eq_jacobson_iff_Inf_maximal'.1 (H _ (is_prime.radical h)), λ H , is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal'.2 (H hP))⟩ lemma radical_eq_jacobson (H : is_jacobson R) (I : ideal R) : I.radical = I.jacobson := le_antisymm (le_Inf (λ J ⟨hJ, hJ_max⟩, (is_prime.radical_le_iff hJ_max.is_prime).mpr hJ)) ((H I.radical (radical_idem I)) ▸ (jacobson_mono le_radical)) /-- Fields have only two ideals, and the condition holds for both of them -/ @[priority 100] instance is_jacobson_field {K : Type u} [field K] : is_jacobson K := λ I hI, or.rec_on (eq_bot_or_top I) (λ h, le_antisymm (Inf_le ⟨le_of_eq rfl, (eq.symm h) ▸ bot_is_maximal⟩) ((eq.symm h) ▸ bot_le)) (λ h, by rw [h, jacobson_eq_top_iff]) theorem is_jacobson_of_surjective [H : is_jacobson R] : (∃ (f : R →+* S), function.surjective f) → is_jacobson S := begin rintros ⟨f, hf⟩, rw is_jacobson_iff_Inf_maximal, intros p hp, use map f '' {J : ideal R | comap f p ≤ J ∧ J.is_maximal }, use λ j ⟨J, hJ, hmap⟩, hmap ▸ or.symm (map_eq_top_or_is_maximal_of_surjective f hf hJ.right), have : p = map f ((comap f p).jacobson), from (H (comap f p) (by rw [← comap_radical, is_prime.radical hp])).symm ▸ (map_comap_of_surjective f hf p).symm, exact eq.trans this (map_Inf hf (λ J ⟨hJ, _⟩, le_trans (ideal.ker_le_comap f) hJ)), end @[priority 100] instance is_jacobson_quotient [is_jacobson R] : is_jacobson (quotient I) := is_jacobson_of_surjective ⟨quotient.mk I, (by rintro ⟨x⟩; use x; refl)⟩ lemma is_jacobson_iso (e : R ≃+* S) : is_jacobson R ↔ is_jacobson S := ⟨λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e : R →+* S), e.surjective⟩, λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e.symm : S →+* R), e.symm.surjective⟩⟩ end is_jacobson section localization open localization_map variables {y : R} (f : away_map y S) lemma disjoint_powers_iff_not_mem {I : ideal R} (hI : I.radical = I) : disjoint ((submonoid.powers y) : set R) ↑I ↔ y ∉ I.1 := begin refine ⟨λ h, set.disjoint_left.1 h (submonoid.mem_powers _), λ h, _⟩, rw [disjoint_iff, eq_bot_iff], rintros x ⟨hx, hx'⟩, obtain ⟨n, hn⟩ := hx, rw [← hn, ← hI] at hx', exact absurd (hI ▸ mem_radical_of_pow_mem hx' : y ∈ I.carrier) h end /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y`. This lemma gives the correspondence in the particular case of an ideal and its comap. See `le_rel_iso_of_maximal` for the more general relation isomorphism -/ lemma is_maximal_iff_is_maximal_disjoint [H : is_jacobson R] (J : ideal S) : J.is_maximal ↔ (comap f.to_map J).is_maximal ∧ y ∉ ideal.comap f.to_map J := begin split, { refine λ h, ⟨_, λ hy, h.1 (ideal.eq_top_of_is_unit_mem _ hy (map_units f ⟨y, submonoid.mem_powers _⟩))⟩, have hJ : J.is_prime := is_maximal.is_prime h, rw is_prime_iff_is_prime_disjoint f at hJ, have : y ∉ (comap f.to_map J).1 := set.disjoint_left.1 hJ.right (submonoid.mem_powers _), erw [← H (comap f.to_map J) (is_prime.radical hJ.left), mem_Inf] at this, push_neg at this, rcases this with ⟨I, hI, hI'⟩, convert hI.right, by_cases hJ : J = map f.to_map I, { rw [hJ, comap_map_of_is_prime_disjoint f I (is_maximal.is_prime hI.right)], rwa disjoint_powers_iff_not_mem (is_maximal.is_prime hI.right).radical}, { have hI_p : (map f.to_map I).is_prime, { refine is_prime_of_is_prime_disjoint f I hI.right.is_prime _, rwa disjoint_powers_iff_not_mem (is_maximal.is_prime hI.right).radical }, have : J ≤ map f.to_map I := (map_comap f J) ▸ (map_mono hI.left), exact absurd (h.right _ (lt_of_le_of_ne this hJ)) hI_p.left } }, { refine λ h, ⟨λ hJ, h.left.left (eq_top_iff.2 _), λ I hI, _⟩, { rwa [eq_top_iff, (order_embedding f).map_rel_iff] at hJ }, { have := congr_arg (map f.to_map) (h.left.right _ ⟨comap_mono (le_of_lt hI), _⟩), rwa [map_comap f I, map_top f.to_map] at this, refine λ hI', hI.right _, rw [← map_comap f I, ← map_comap f J], exact map_mono hI' } } end /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y`. This lemma gives the correspondence in the particular case of an ideal and its map. See `le_rel_iso_of_maximal` for the more general statement, and the reverse of this implication -/ lemma is_maximal_of_is_maximal_disjoint [is_jacobson R] (I : ideal R) (hI : I.is_maximal) (hy : y ∉ I) : (map f.to_map I).is_maximal := begin rw [is_maximal_iff_is_maximal_disjoint f, comap_map_of_is_prime_disjoint f I (is_maximal.is_prime hI) ((disjoint_powers_iff_not_mem (is_maximal.is_prime hI).radical).2 hy)], exact ⟨hI, hy⟩ end /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y` -/ def order_iso_of_maximal [is_jacobson R] : {p : ideal S // p.is_maximal} ≃o {p : ideal R // p.is_maximal ∧ y ∉ p} := { to_fun := λ p, ⟨ideal.comap f.to_map p.1, (is_maximal_iff_is_maximal_disjoint f p.1).1 p.2⟩, inv_fun := λ p, ⟨ideal.map f.to_map p.1, is_maximal_of_is_maximal_disjoint f p.1 p.2.1 p.2.2⟩, left_inv := λ J, subtype.eq (map_comap f J), right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint f I.1 (is_maximal.is_prime I.2.1) ((disjoint_powers_iff_not_mem I.2.1.is_prime.radical).2 I.2.2)), map_rel_iff' := λ I I', ⟨λ h x hx, h hx, λ h, (show I.val ≤ I'.val, from (map_comap f I.val) ▸ (map_comap f I'.val) ▸ (ideal.map_mono h))⟩ } /-- If `S` is the localization of the Jacobson ring `R` at the submonoid generated by `y : R`, then `S` is Jacobson. -/ lemma is_jacobson_localization [H : is_jacobson R] (f : away_map y S) : is_jacobson S := begin rw is_jacobson_iff_prime_eq, refine λ P' hP', le_antisymm _ le_jacobson, obtain ⟨hP', hPM⟩ := (localization_map.is_prime_iff_is_prime_disjoint f P').mp hP', have hP := H (comap f.to_map P') (is_prime.radical hP'), refine le_trans (le_trans (le_of_eq (localization_map.map_comap f P'.jacobson).symm) (map_mono _)) (le_of_eq (localization_map.map_comap f P')), have : Inf { I : ideal R | comap f.to_map P' ≤ I ∧ I.is_maximal ∧ y ∉ I } ≤ comap f.to_map P', { intros x hx, have hxy : x * y ∈ (comap f.to_map P').jacobson, { rw [ideal.jacobson, mem_Inf], intros J hJ, by_cases y ∈ J, { exact J.smul_mem x h }, { exact (mul_comm y x) ▸ J.smul_mem y ((mem_Inf.1 hx) ⟨hJ.left, ⟨hJ.right, h⟩⟩) } }, rw hP at hxy, cases hP'.right hxy with hxy hxy, { exact hxy }, { exfalso, refine hPM ⟨submonoid.mem_powers _, hxy⟩ } }, refine le_trans _ this, rw [ideal.jacobson, comap_Inf', Inf_eq_infi], refine infi_le_infi_of_subset (λ I hI, ⟨map f.to_map I, ⟨_, _⟩⟩), { exact ⟨le_trans (le_of_eq ((localization_map.map_comap f P').symm)) (map_mono hI.1), is_maximal_of_is_maximal_disjoint f _ hI.2.1 hI.2.2⟩ }, { exact localization_map.comap_map_of_is_prime_disjoint f I (is_maximal.is_prime hI.2.1) ((disjoint_powers_iff_not_mem hI.2.1.is_prime.radical).2 hI.2.2) } end end localization end ideal
1e739ef46b651c44f696fe9230fbb8d8f1e0e993
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/category_theory/isomorphism.lean
554338d66b68690121a462b0c197ac98460ec27b
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
9,379
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open category structure iso {C : Type u} [category.{v} C] (X Y : C) := (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id' : hom ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ hom = 𝟙 Y . obviously) restate_axiom iso.hom_inv_id' restate_axiom iso.inv_hom_id' attribute [simp] iso.hom_inv_id iso.inv_hom_id infixr ` ≅ `:10 := iso -- type as \cong or \iso variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 variables {X Y Z : C} namespace iso @[simp] lemma hom_inv_id_assoc (α : X ≅ Y) (f : X ⟶ Z) : α.hom ≫ α.inv ≫ f = f := by rw [←category.assoc, α.hom_inv_id, category.id_comp] @[simp] lemma inv_hom_id_assoc (α : X ≅ Y) (f : Y ⟶ Z) : α.inv ≫ α.hom ≫ f = f := by rw [←category.assoc, α.inv_hom_id, category.id_comp] @[extensionality] lemma ext (α β : X ≅ Y) (w : α.hom = β.hom) : α = β := suffices α.inv = β.inv, by cases α; cases β; cc, calc α.inv = α.inv ≫ (β.hom ≫ β.inv) : by rw [iso.hom_inv_id, category.comp_id] ... = (α.inv ≫ α.hom) ≫ β.inv : by rw [category.assoc, ←w] ... = β.inv : by rw [iso.inv_hom_id, category.id_comp] @[symm] def symm (I : X ≅ Y) : Y ≅ X := { hom := I.inv, inv := I.hom, hom_inv_id' := I.inv_hom_id', inv_hom_id' := I.hom_inv_id' } @[simp] lemma symm_hom (α : X ≅ Y) : α.symm.hom = α.inv := rfl @[simp] lemma symm_inv (α : X ≅ Y) : α.symm.inv = α.hom := rfl @[simp] lemma symm_mk {X Y : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) : iso.symm {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} = {hom := inv, inv := hom, hom_inv_id' := inv_hom_id, inv_hom_id' := hom_inv_id} := rfl @[refl] def refl (X : C) : X ≅ X := { hom := 𝟙 X, inv := 𝟙 X } @[simp] lemma refl_hom (X : C) : (iso.refl X).hom = 𝟙 X := rfl @[simp] lemma refl_inv (X : C) : (iso.refl X).inv = 𝟙 X := rfl @[trans] def trans (α : X ≅ Y) (β : Y ≅ Z) : X ≅ Z := { hom := α.hom ≫ β.hom, inv := β.inv ≫ α.inv } infixr ` ≪≫ `:80 := iso.trans -- type as `\ll \gg`. @[simp] lemma trans_hom (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).hom = α.hom ≫ β.hom := rfl @[simp] lemma trans_inv (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).inv = β.inv ≫ α.inv := rfl @[simp] lemma trans_mk {X Y Z : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) (hom' : Y ⟶ Z) (inv' : Z ⟶ Y) (hom_inv_id') (inv_hom_id') (hom_inv_id'') (inv_hom_id'') : iso.trans {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} {hom := hom', inv := inv', hom_inv_id' := hom_inv_id', inv_hom_id' := inv_hom_id'} = {hom := hom ≫ hom', inv := inv' ≫ inv, hom_inv_id' := hom_inv_id'', inv_hom_id' := inv_hom_id''} := rfl @[simp] lemma refl_symm (X : C) : (iso.refl X).hom = 𝟙 X := rfl @[simp] lemma trans_symm (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).inv = β.inv ≫ α.inv := rfl lemma inv_comp_eq (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : α.inv ≫ f = g ↔ f = α.hom ≫ g := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_inv_comp (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : g = α.inv ≫ f ↔ α.hom ≫ g = f := (inv_comp_eq α.symm).symm lemma comp_inv_eq (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ α.inv = g ↔ f = g ≫ α.hom := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_comp_inv (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ α.inv ↔ g ≫ α.hom = f := (comp_inv_eq α.symm).symm lemma inv_eq_inv (f g : X ≅ Y) : f.inv = g.inv ↔ f.hom = g.hom := have ∀{X Y : C} (f g : X ≅ Y), f.hom = g.hom → f.inv = g.inv, from λ X Y f g h, by rw [ext _ _ h], ⟨this f.symm g.symm, this f g⟩ lemma hom_comp_eq_id (α : X ≅ Y) {f : Y ⟶ X} : α.hom ≫ f = 𝟙 X ↔ f = α.inv := by rw [←eq_inv_comp, comp_id] lemma comp_hom_eq_id (α : X ≅ Y) {f : Y ⟶ X} : f ≫ α.hom = 𝟙 Y ↔ f = α.inv := by rw [←eq_comp_inv, id_comp] lemma hom_eq_inv (α : X ≅ Y) (β : Y ≅ X) : α.hom = β.inv ↔ β.hom = α.inv := by { erw [inv_eq_inv α.symm β, eq_comm], refl } end iso /-- `is_iso` typeclass expressing that a morphism is invertible. This contains the data of the inverse, but is a subsingleton type. -/ class is_iso (f : X ⟶ Y) := (inv : Y ⟶ X) (hom_inv_id' : f ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ f = 𝟙 Y . obviously) def inv (f : X ⟶ Y) [is_iso f] := is_iso.inv f namespace is_iso @[simp] lemma hom_inv_id (f : X ⟶ Y) [is_iso f] : f ≫ category_theory.inv f = 𝟙 X := is_iso.hom_inv_id' f @[simp] lemma inv_hom_id (f : X ⟶ Y) [is_iso f] : category_theory.inv f ≫ f = 𝟙 Y := is_iso.inv_hom_id' f @[simp] lemma hom_inv_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : X ⟶ Z) : f ≫ category_theory.inv f ≫ g = g := by rw [←category.assoc, hom_inv_id, category.id_comp] @[simp] lemma inv_hom_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : Y ⟶ Z) : category_theory.inv f ≫ f ≫ g = g := by rw [←category.assoc, inv_hom_id, category.id_comp] instance (X : C) : is_iso (𝟙 X) := { inv := 𝟙 X } instance of_iso (f : X ≅ Y) : is_iso f.hom := { inv := f.inv } instance of_iso_inverse (f : X ≅ Y) : is_iso f.inv := { inv := f.hom } variables {f g : X ⟶ Y} {h : Y ⟶ Z} instance inv_is_iso [is_iso f] : is_iso (category_theory.inv f) := { inv := f, hom_inv_id' := inv_hom_id f, inv_hom_id' := hom_inv_id f } instance comp_is_iso [is_iso f] [is_iso h] : is_iso (f ≫ h) := { inv := category_theory.inv h ≫ category_theory.inv f, hom_inv_id' := begin erw [category.assoc, hom_inv_id_assoc], exact hom_inv_id f, end, inv_hom_id' := begin erw [category.assoc, inv_hom_id_assoc], exact inv_hom_id h, end } @[simp] lemma inv_id : category_theory.inv (𝟙 X) = 𝟙 X := rfl @[simp] lemma inv_comp [is_iso f] [is_iso h] : category_theory.inv (f ≫ h) = category_theory.inv h ≫ category_theory.inv f := rfl @[simp] lemma is_iso.inv_inv [is_iso f] : category_theory.inv (category_theory.inv f) = f := rfl @[simp] lemma iso.inv_inv (f : X ≅ Y) : category_theory.inv (f.inv) = f.hom := rfl @[simp] lemma iso.inv_hom (f : X ≅ Y) : category_theory.inv (f.hom) = f.inv := rfl instance epi_of_iso (f : X ⟶ Y) [is_iso f] : epi f := { left_cancellation := λ Z g h w, -- This is an interesting test case for better rewrite automation. by rw [←category.id_comp C g, ←category.id_comp C h, ←is_iso.inv_hom_id f, category.assoc, w, category.assoc] } instance mono_of_iso (f : X ⟶ Y) [is_iso f] : mono f := { right_cancellation := λ Z g h w, by rw [←category.comp_id C g, ←category.comp_id C h, ←is_iso.hom_inv_id f, ←category.assoc, w, ←category.assoc] } end is_iso open is_iso lemma eq_of_inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] (p : inv f = inv g) : f = g := begin apply (cancel_epi (inv f)).1, erw [inv_hom_id, p, inv_hom_id], end def as_iso (f : X ⟶ Y) [is_iso f] : X ≅ Y := { hom := f, inv := inv f } @[simp] lemma as_iso_hom (f : X ⟶ Y) [is_iso f] : (as_iso f).hom = f := rfl @[simp] lemma as_iso_inv (f : X ⟶ Y) [is_iso f] : (as_iso f).inv = inv f := rfl instance (f : X ⟶ Y) : subsingleton (is_iso f) := ⟨λ a b, suffices a.inv = b.inv, by cases a; cases b; congr; exact this, show (@as_iso C _ _ _ f a).inv = (@as_iso C _ _ _ f b).inv, by congr' 1; ext; refl⟩ lemma is_iso.inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] : inv f = inv g ↔ f = g := iso.inv_eq_inv (as_iso f) (as_iso g) instance is_iso_comp (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso f] [is_iso g] : is_iso (f ≫ g) := { inv := inv g ≫ inv f } instance is_iso_id : is_iso (𝟙 X) := { inv := 𝟙 X } namespace functor universes u₁ v₁ u₂ v₂ variables {D : Type u₂} variables [𝒟 : category.{v₂} D] include 𝒟 def map_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.obj X ≅ F.obj Y := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id], inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] } @[simp] lemma map_iso_hom (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.map_iso i).hom = F.map i.hom := rfl @[simp] lemma map_iso_inv (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.map_iso i).inv = F.map i.inv := rfl @[simp] lemma map_iso_trans (F : C ⥤ D) {X Y Z : C} (i : X ≅ Y) (j : Y ≅ Z) : F.map_iso (i ≪≫ j) = (F.map_iso i) ≪≫ (F.map_iso j) := by ext; apply functor.map_comp instance (F : C ⥤ D) (f : X ⟶ Y) [is_iso f] : is_iso (F.map f) := { ..(F.map_iso (as_iso f)) } @[simp] lemma map_hom_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map f ≫ F.map (inv f) = 𝟙 (F.obj X) := by rw [←map_comp, is_iso.hom_inv_id, map_id] @[simp] lemma map_inv_hom (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) ≫ F.map f = 𝟙 (F.obj Y) := by rw [←map_comp, is_iso.inv_hom_id, map_id] @[simp] lemma map_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) = inv (F.map f) := rfl end functor end category_theory
93210858973c19d2f5702ad312f67c6ea696d3a5
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/dense_embedding.lean
22f27d6a90f94576fc98a849fe4346b7d13d12c4
[ "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,407
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.separation /-! # Dense embeddings This file defines three properties of functions: * `dense_range f` means `f` has dense image; * `dense_inducing i` means `i` is also `inducing`; * `dense_embedding e` means `e` is also an `embedding`. The main theorem `continuous_extend` gives a criterion for a function `f : X → Z` to a regular (T₃) space Z to extend along a dense embedding `i : X → Y` to a continuous function `g : Y → Z`. Actually `i` only has to be `dense_inducing` (not necessarily injective). -/ noncomputable theory open set filter open_locale classical topological_space filter variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section dense_range variables [topological_space β] [topological_space γ] (f : α → β) (g : β → γ) /-- `f : α → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := ∀ x, x ∈ closure (range f) variables {f} lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := eq_univ_iff_forall.symm lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := eq_univ_iff_forall.mpr h lemma dense_range.nhds_within_ne_bot (h : dense_range f) (x : β) : ne_bot (nhds_within x (range f)) := mem_closure_iff_cluster_pt.1 (h x) lemma dense_range.comp (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := begin have : g '' (closure $ range f) ⊆ closure (g '' range f), from image_closure_subset_closure_image cg, have : closure (g '' closure (range f)) ⊆ closure (g '' range f), by simpa [closure_closure] using (closure_mono this), intro c, rw range_comp, apply this, rw [hf.closure_range, image_univ], exact hg c end /-- If `f : α → β` has dense range and `β` contains some element, then `α` must too. -/ def dense_range.inhabited (df : dense_range f) (b : β) : inhabited α := ⟨classical.choice $ by simpa only [univ_inter, range_nonempty_iff_nonempty] using mem_closure_iff.1 (df b) _ is_open_univ trivial⟩ lemma dense_range.nonempty (hf : dense_range f) : nonempty α ↔ nonempty β := ⟨nonempty.map f, λ ⟨b⟩, @nonempty_of_inhabited _ (hf.inhabited b)⟩ lemma dense_range.prod {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (λ p : ι × κ, (f p.1, g p.2)) := have closure (range $ λ p : ι×κ, (f p.1, g p.2)) = set.prod (closure $ range f) (closure $ range g), by rw [←closure_prod_eq, prod_range_range_eq], assume ⟨b, d⟩, this.symm ▸ mem_prod.2 ⟨hf _, hg _⟩ end dense_range /-- `i : α → β` is "dense inducing" if it has dense range and the topology on `α` is the one induced by `i` from the topology on `β`. -/ structure dense_inducing [topological_space α] [topological_space β] (i : α → β) extends inducing i : Prop := (dense : dense_range i) namespace dense_inducing variables [topological_space α] [topological_space β] variables {i : α → β} (di : dense_inducing i) lemma nhds_eq_comap (di : dense_inducing i) : ∀ a : α, 𝓝 a = comap i (𝓝 $ i a) := di.to_inducing.nhds_eq_comap protected lemma continuous (di : dense_inducing i) : continuous i := di.to_inducing.continuous lemma closure_range : closure (range i) = univ := di.dense.closure_range lemma self_sub_closure_image_preimage_of_open {s : set β} (di : dense_inducing i) : is_open s → s ⊆ closure (i '' (i ⁻¹' s)) := begin intros s_op b b_in_s, rw [image_preimage_eq_inter_range, mem_closure_iff], intros U U_op b_in, rw ←inter_assoc, exact (dense_iff_inter_open.1 di.closure_range) _ (is_open_inter U_op s_op) ⟨b, b_in, b_in_s⟩ end lemma closure_image_nhds_of_nhds {s : set α} {a : α} (di : dense_inducing i) : s ∈ 𝓝 a → closure (i '' s) ∈ 𝓝 (i a) := begin rw [di.nhds_eq_comap a, mem_comap_sets], intro h, rcases h with ⟨t, t_nhd, sub⟩, rw mem_nhds_sets_iff at t_nhd, rcases t_nhd with ⟨U, U_sub, ⟨U_op, e_a_in_U⟩⟩, have := calc i ⁻¹' U ⊆ i⁻¹' t : preimage_mono U_sub ... ⊆ s : sub, have := calc U ⊆ closure (i '' (i ⁻¹' U)) : self_sub_closure_image_preimage_of_open di U_op ... ⊆ closure (i '' s) : closure_mono (image_subset i this), have U_nhd : U ∈ 𝓝 (i a) := mem_nhds_sets U_op e_a_in_U, exact (𝓝 (i a)).sets_of_superset U_nhd this end /-- The product of two dense inducings is a dense inducing -/ protected lemma prod [topological_space γ] [topological_space δ] {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_inducing e₁) (de₂ : dense_inducing e₂) : dense_inducing (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { induced := (de₁.to_inducing.prod_mk de₂.to_inducing).induced, dense := de₁.dense.prod de₂.dense } variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β} /-- γ -f→ α g↓ ↓e δ -h→ β -/ lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (di : dense_inducing i) (H : tendsto h (𝓝 d) (𝓝 (i a))) (comm : h ∘ g = i ∘ f) : tendsto f (comap g (𝓝 d)) (𝓝 a) := begin have lim1 : map g (comap g (𝓝 d)) ≤ 𝓝 d := map_comap_le, replace lim1 : map h (map g (comap g (𝓝 d))) ≤ map h (𝓝 d) := map_mono lim1, rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1, have lim2 : comap i (map h (𝓝 d)) ≤ comap i (𝓝 (i a)) := comap_mono H, rw ← di.nhds_eq_comap at lim2, exact le_trans lim1 lim2, end protected lemma nhds_within_ne_bot (di : dense_inducing i) (b : β) : ne_bot (nhds_within b (range i)) := di.dense.nhds_within_ne_bot b lemma comap_nhds_ne_bot (di : dense_inducing i) (b : β) : ne_bot (comap i (𝓝 b)) := comap_ne_bot $ λ s hs, let ⟨_, ⟨ha, a, rfl⟩⟩ := mem_closure_iff_nhds.1 (di.dense b) s hs in ⟨a, ha⟩ variables [topological_space γ] /-- If `i : α → β` is a dense inducing, then any function `f : α → γ` "extends" to a function `g = extend di f : β → γ`. If `γ` is Hausdorff and `f` has a continuous extension, then `g` is the unique such extension. In general, `g` might not be continuous or even extend `f`. -/ def extend (di : dense_inducing i) (f : α → γ) (b : β) : γ := @@lim _ ⟨f (di.dense.inhabited b).default⟩ (comap i (𝓝 b)) f lemma extend_eq_of_tendsto [t2_space γ] {b : β} {c : γ} {f : α → γ} (hf : tendsto f (comap i (𝓝 b)) (𝓝 c)) : di.extend f b = c := by haveI := di.comap_nhds_ne_bot; exact hf.lim_eq lemma extend_eq_at [t2_space γ] {f : α → γ} (a : α) (hf : continuous_at f a) : di.extend f (i a) = f a := extend_eq_of_tendsto _ $ di.nhds_eq_comap a ▸ hf lemma extend_eq [t2_space γ] {f : α → γ} (hf : continuous f) (a : α) : di.extend f (i a) = f a := di.extend_eq_at a hf.continuous_at lemma extend_unique_at [t2_space γ] {b : β} {f : α → γ} {g : β → γ} (di : dense_inducing i) (hf : ∀ᶠ x in comap i (𝓝 b), g (i x) = f x) (hg : continuous_at g b) : di.extend f b = g b := begin refine di.extend_eq_of_tendsto (λ s hs, mem_map.2 _), suffices : ∀ᶠ (x : α) in comap i (𝓝 b), g (i x) ∈ s, from hf.mp (this.mono $ λ x hgx hfx, hfx ▸ hgx), clear hf f, refine eventually_comap.2 ((hg.eventually hs).mono _), rintros _ hxs x rfl, exact hxs end lemma extend_unique [t2_space γ] {f : α → γ} {g : β → γ} (di : dense_inducing i) (hf : ∀ x, g (i x) = f x) (hg : continuous g) : di.extend f = g := funext $ λ b, extend_unique_at di (eventually_of_forall hf) hg.continuous_at lemma continuous_at_extend [regular_space γ] {b : β} {f : α → γ} (di : dense_inducing i) (hf : ∀ᶠ x in 𝓝 b, ∃c, tendsto f (comap i $ 𝓝 x) (𝓝 c)) : continuous_at (di.extend f) b := begin set φ := di.extend f, haveI := di.comap_nhds_ne_bot, suffices : ∀ V' ∈ 𝓝 (φ b), is_closed V' → φ ⁻¹' V' ∈ 𝓝 b, by simpa [continuous_at, (closed_nhds_basis _).tendsto_right_iff], intros V' V'_in V'_closed, set V₁ := {x | tendsto f (comap i $ 𝓝 x) (𝓝 $ φ x)}, have V₁_in : V₁ ∈ 𝓝 b, { filter_upwards [hf], rintros x ⟨c, hc⟩, dsimp [V₁, φ], rwa di.extend_eq_of_tendsto hc }, obtain ⟨V₂, V₂_in, V₂_op, hV₂⟩ : ∃ V₂ ∈ 𝓝 b, is_open V₂ ∧ ∀ x ∈ i ⁻¹' V₂, f x ∈ V', { simpa [and_assoc] using ((nhds_basis_opens' b).comap i).tendsto_left_iff.mp (mem_of_nhds V₁_in : b ∈ V₁) V' V'_in }, suffices : ∀ x ∈ V₁ ∩ V₂, φ x ∈ V', { filter_upwards [inter_mem_sets V₁_in V₂_in], exact this }, rintros x ⟨x_in₁, x_in₂⟩, have hV₂x : V₂ ∈ 𝓝 x := mem_nhds_sets V₂_op x_in₂, apply mem_of_closed_of_tendsto x_in₁ V'_closed, use V₂, tauto, end lemma continuous_extend [regular_space γ] {f : α → γ} (di : dense_inducing i) (hf : ∀b, ∃c, tendsto f (comap i (𝓝 b)) (𝓝 c)) : continuous (di.extend f) := continuous_iff_continuous_at.mpr $ assume b, di.continuous_at_extend $ univ_mem_sets' hf lemma mk' (i : α → β) (c : continuous i) (dense : ∀x, x ∈ closure (range i)) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (i a), ∀ b, i b ∈ t → b ∈ s) : dense_inducing i := { induced := (induced_iff_nhds_eq i).2 $ λ a, le_antisymm (tendsto_iff_comap.1 $ c.tendsto _) (by simpa [le_def] using H a), dense := dense } end dense_inducing /-- A dense embedding is an embedding with dense image. -/ structure dense_embedding [topological_space α] [topological_space β] (e : α → β) extends dense_inducing e : Prop := (inj : function.injective e) theorem dense_embedding.mk' [topological_space α] [topological_space β] (e : α → β) (c : continuous e) (dense : ∀x, x ∈ closure (range e)) (inj : function.injective e) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (e a), ∀ b, e b ∈ t → b ∈ s) : dense_embedding e := { inj := inj, ..dense_inducing.mk' e c dense H} namespace dense_embedding variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] variables {e : α → β} (de : dense_embedding e) lemma inj_iff {x y} : e x = e y ↔ x = y := de.inj.eq_iff lemma to_embedding : embedding e := { induced := de.induced, inj := de.inj } /-- The product of two dense embeddings is a dense embedding -/ protected lemma prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) : dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩, ..dense_inducing.prod de₁.to_dense_inducing de₂.to_dense_inducing } /-- The dense embedding of a subtype inside its closure. -/ def subtype_emb {α : Type*} (p : α → Prop) (e : α → β) (x : {x // p x}) : {x // x ∈ closure (e '' {x | p x})} := ⟨e x, subset_closure $ mem_image_of_mem e x.prop⟩ protected lemma subtype (p : α → Prop) : dense_embedding (subtype_emb p e) := { dense_embedding . dense := assume ⟨x, hx⟩, closure_subtype.mpr $ have (λ (x : {x // p x}), e x) = e ∘ coe, from rfl, begin rw ← image_univ, simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ], rw [this, image_comp, subtype.coe_image], simp, assumption end, inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h, induced := (induced_iff_nhds_eq _).2 (assume ⟨x, hx⟩, by simp [subtype_emb, nhds_subtype_eq_comap, de.to_inducing.nhds_eq_comap, comap_comap, (∘)]) } end dense_embedding lemma is_closed_property [topological_space β] {e : α → β} {p : β → Prop} (he : dense_range e) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) : ∀b, p b := have univ ⊆ {b | p b}, from calc univ = closure (range e) : he.closure_range.symm ... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h ... = _ : hp.closure_eq, assume b, this trivial lemma is_closed_property2 [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) : ∀b₁ b₂, p b₁ b₂ := have ∀q:β×β, p q.1 q.2, from is_closed_property (he.prod he) hp $ λ _, h _ _, assume b₁ b₂, this ⟨b₁, b₂⟩ lemma is_closed_property3 [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) : ∀b₁ b₂ b₃, p b₁ b₂ b₃ := have ∀q:β×β×β, p q.1 q.2.1 q.2.2, from is_closed_property (he.prod $ he.prod he) hp $ λ _, h _ _ _, assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩ @[elab_as_eliminator] lemma dense_range.induction_on [topological_space β] {e : α → β} (he : dense_range e) {p : β → Prop} (b₀ : β) (hp : is_closed {b | p b}) (ih : ∀a:α, p $ e a) : p b₀ := is_closed_property he hp ih b₀ @[elab_as_eliminator] lemma dense_range.induction_on₂ [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) (b₁ b₂ : β) : p b₁ b₂ := is_closed_property2 he hp h _ _ @[elab_as_eliminator] lemma dense_range.induction_on₃ [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) (b₁ b₂ b₃ : β) : p b₁ b₂ b₃ := is_closed_property3 he hp h _ _ _ section variables [topological_space β] [topological_space γ] [t2_space γ] variables {f : α → β} /-- Two continuous functions to a t2-space that agree on the dense range of a function are equal. -/ lemma dense_range.equalizer (hfd : dense_range f) {g h : β → γ} (hg : continuous g) (hh : continuous h) (H : g ∘ f = h ∘ f) : g = h := funext $ λ y, hfd.induction_on y (is_closed_eq hg hh) $ congr_fun H end
9816dc3ae6ac044155d81127198b43c4d5f6c9ca
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/set_theory/game/short.lean
b346fb5ad07e847139623b81a8617539608b77f7
[]
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
11,948
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.set_theory.game import Mathlib.data.fintype.basic import Mathlib.PostPort universes u l u_1 namespace Mathlib /-! # Short games A combinatorial game is `short` [Conway, ch.9][conway2001] if it has only finitely many positions. In particular, this means there is a finite set of moves at every point. We prove that the order relations `≤` and `<`, and the equivalence relation `≈`, are decidable on short games, although unfortunately in practice `dec_trivial` doesn't seem to be able to prove anything using these instances. -/ namespace pgame /-- A short game is a game with a finite set of moves at every turn. -/ class inductive short : pgame → Type (u + 1) where | mk : {α β : Type u} → {L : α → pgame} → {R : β → pgame} → ((i : α) → short (L i)) → ((j : β) → short (R j)) → [_inst_1 : fintype α] → [_inst_2 : fintype β] → short (mk α β L R) protected instance subsingleton_short (x : pgame) : subsingleton (short x) := sorry /-- A synonym for `short.mk` that specifies the pgame in an implicit argument. -/ def short.mk' {x : pgame} [fintype (left_moves x)] [fintype (right_moves x)] (sL : (i : left_moves x) → short (move_left x i)) (sR : (j : right_moves x) → short (move_right x j)) : short x := pgame.cases_on x (fun (x_α x_β : Type u_1) (x_ᾰ : x_α → pgame) (x_ᾰ_1 : x_β → pgame) [_inst_1 : fintype (left_moves (mk x_α x_β x_ᾰ x_ᾰ_1))] [_inst_2 : fintype (right_moves (mk x_α x_β x_ᾰ x_ᾰ_1))] (sL : (i : left_moves (mk x_α x_β x_ᾰ x_ᾰ_1)) → short (move_left (mk x_α x_β x_ᾰ x_ᾰ_1) i)) (sR : (j : right_moves (mk x_α x_β x_ᾰ x_ᾰ_1)) → short (move_right (mk x_α x_β x_ᾰ x_ᾰ_1) j)) => id (fun (x_α x_β : Type u_1) (x_ᾰ : x_α → pgame) (x_ᾰ_1 : x_β → pgame) (sL : (i : x_α) → short (x_ᾰ i)) (sR : (j : x_β) → short (x_ᾰ_1 j)) => short.mk sL sR) x_α x_β x_ᾰ x_ᾰ_1 _inst_1 _inst_2 sL sR) _inst_1 _inst_2 sL sR /-- Extracting the `fintype` instance for the indexing type for Left's moves in a short game. This is an unindexed typeclass, so it can't be made a global instance. -/ def fintype_left {α : Type u} {β : Type u} {L : α → pgame} {R : β → pgame} [S : short (mk α β L R)] : fintype α := short.cases_on S (fun {S_α S_β : Type u} {S_L : S_α → pgame} {S_R : S_β → pgame} (S_sL : (i : S_α) → short (S_L i)) (S_sR : (j : S_β) → short (S_R j)) [F : fintype S_α] [S__inst_2 : fintype S_β] (H_1 : mk α β L R = mk S_α S_β S_L S_R) => pgame.no_confusion H_1 fun (α_eq : α = S_α) => Eq._oldrec (fun {S_L : α → pgame} (S_sL : (i : α) → short (S_L i)) [F : fintype α] (β_eq : β = S_β) => Eq._oldrec (fun {S_R : β → pgame} (S_sR : (j : β) → short (S_R j)) (ᾰ_eq : L == S_L) => Eq._oldrec (fun (S_sL : (i : α) → short (L i)) (ᾰ_eq : R == S_R) => Eq._oldrec (fun (S_sR : (j : β) → short (R j)) (H_2 : S == short.mk S_sL S_sR) => Eq._oldrec F sorry) sorry S_sR) sorry S_sL) β_eq S_R S_sR S__inst_2) α_eq S_L S_sL F) sorry sorry protected instance fintype_left_moves (x : pgame) [S : short x] : fintype (left_moves x) := pgame.cases_on x (fun (x_α x_β : Type u_1) (x_ᾰ : x_α → pgame) (x_ᾰ_1 : x_β → pgame) => id fintype_left) S /-- Extracting the `fintype` instance for the indexing type for Right's moves in a short game. This is an unindexed typeclass, so it can't be made a global instance. -/ def fintype_right {α : Type u} {β : Type u} {L : α → pgame} {R : β → pgame} [S : short (mk α β L R)] : fintype β := short.cases_on S (fun {S_α S_β : Type u} {S_L : S_α → pgame} {S_R : S_β → pgame} (S_sL : (i : S_α) → short (S_L i)) (S_sR : (j : S_β) → short (S_R j)) [S__inst_1 : fintype S_α] [F : fintype S_β] (H_1 : mk α β L R = mk S_α S_β S_L S_R) => pgame.no_confusion H_1 fun (α_eq : α = S_α) => Eq._oldrec (fun {S_L : α → pgame} (S_sL : (i : α) → short (S_L i)) (β_eq : β = S_β) => Eq._oldrec (fun {S_R : β → pgame} (S_sR : (j : β) → short (S_R j)) [F : fintype β] (ᾰ_eq : L == S_L) => Eq._oldrec (fun (S_sL : (i : α) → short (L i)) (ᾰ_eq : R == S_R) => Eq._oldrec (fun (S_sR : (j : β) → short (R j)) (H_2 : S == short.mk S_sL S_sR) => Eq._oldrec F sorry) sorry S_sR) sorry S_sL) β_eq S_R S_sR F) α_eq S_L S_sL S__inst_1) sorry sorry protected instance fintype_right_moves (x : pgame) [S : short x] : fintype (right_moves x) := pgame.cases_on x (fun (x_α x_β : Type u_1) (x_ᾰ : x_α → pgame) (x_ᾰ_1 : x_β → pgame) => id fintype_right) S protected instance move_left_short (x : pgame) [S : short x] (i : left_moves x) : short (move_left x i) := short.cases_on S (fun {S_α S_β : Type u_1} {S_L : S_α → pgame} {S_R : S_β → pgame} (L : (i : S_α) → short (S_L i)) (S_sR : (j : S_β) → short (S_R j)) (H_1 : x = mk S_α S_β S_L S_R) => Eq._oldrec (fun [S : short (mk S_α S_β S_L S_R)] (i : left_moves (mk S_α S_β S_L S_R)) (H_2 : S == short.mk L S_sR) => Eq._oldrec (L i) sorry) sorry S i) (Eq.refl x) sorry /-- Extracting the `short` instance for a move by Left. This would be a dangerous instance potentially introducing new metavariables in typeclass search, so we only make it an instance locally. -/ def move_left_short' {xl : Type u_1} {xr : Type u_1} (xL : xl → pgame) (xR : xr → pgame) [S : short (mk xl xr xL xR)] (i : xl) : short (xL i) := short.cases_on S (fun {S_α S_β : Type u_1} {S_L : S_α → pgame} {S_R : S_β → pgame} (L : (i : S_α) → short (S_L i)) (S_sR : (j : S_β) → short (S_R j)) [S__inst_1 : fintype S_α] [S__inst_2 : fintype S_β] (H_1 : mk xl xr xL xR = mk S_α S_β S_L S_R) => pgame.no_confusion H_1 fun (α_eq : xl = S_α) => Eq._oldrec (fun {S_L : xl → pgame} (L : (i : xl) → short (S_L i)) (β_eq : xr = S_β) => Eq._oldrec (fun {S_R : xr → pgame} (S_sR : (j : xr) → short (S_R j)) (ᾰ_eq : xL == S_L) => Eq._oldrec (fun (L : (i : xl) → short (xL i)) (ᾰ_eq : xR == S_R) => Eq._oldrec (fun (S_sR : (j : xr) → short (xR j)) (H_2 : S == short.mk L S_sR) => Eq._oldrec (L i) sorry) sorry S_sR) sorry L) β_eq S_R S_sR S__inst_2) α_eq S_L L S__inst_1) sorry sorry protected instance move_right_short (x : pgame) [S : short x] (j : right_moves x) : short (move_right x j) := short.cases_on S (fun {S_α S_β : Type u_1} {S_L : S_α → pgame} {S_R : S_β → pgame} (S_sL : (i : S_α) → short (S_L i)) (R : (j : S_β) → short (S_R j)) (H_1 : x = mk S_α S_β S_L S_R) => Eq._oldrec (fun [S : short (mk S_α S_β S_L S_R)] (j : right_moves (mk S_α S_β S_L S_R)) (H_2 : S == short.mk S_sL R) => Eq._oldrec (R j) sorry) sorry S j) (Eq.refl x) sorry /-- Extracting the `short` instance for a move by Right. This would be a dangerous instance potentially introducing new metavariables in typeclass search, so we only make it an instance locally. -/ def move_right_short' {xl : Type u_1} {xr : Type u_1} (xL : xl → pgame) (xR : xr → pgame) [S : short (mk xl xr xL xR)] (j : xr) : short (xR j) := short.cases_on S (fun {S_α S_β : Type u_1} {S_L : S_α → pgame} {S_R : S_β → pgame} (S_sL : (i : S_α) → short (S_L i)) (R : (j : S_β) → short (S_R j)) [S__inst_1 : fintype S_α] [S__inst_2 : fintype S_β] (H_1 : mk xl xr xL xR = mk S_α S_β S_L S_R) => pgame.no_confusion H_1 fun (α_eq : xl = S_α) => Eq._oldrec (fun {S_L : xl → pgame} (S_sL : (i : xl) → short (S_L i)) (β_eq : xr = S_β) => Eq._oldrec (fun {S_R : xr → pgame} (R : (j : xr) → short (S_R j)) (ᾰ_eq : xL == S_L) => Eq._oldrec (fun (S_sL : (i : xl) → short (xL i)) (ᾰ_eq : xR == S_R) => Eq._oldrec (fun (R : (j : xr) → short (xR j)) (H_2 : S == short.mk S_sL R) => Eq._oldrec (R j) sorry) sorry R) sorry S_sL) β_eq S_R R S__inst_2) α_eq S_L S_sL S__inst_1) sorry sorry protected instance short.of_pempty {xL : pempty → pgame} {xR : pempty → pgame} : short (mk pempty pempty xL xR) := short.mk (fun (i : pempty) => pempty.elim i) fun (j : pempty) => pempty.elim j protected instance short_0 : short 0 := short.mk (fun (i : pempty) => pempty.cases_on (fun (i : pempty) => short (pempty.elim i)) i) fun (i : pempty) => pempty.cases_on (fun (i : pempty) => short (pempty.elim i)) i protected instance short_1 : short 1 := short.mk (fun (i : PUnit) => punit.cases_on i pgame.short_0) fun (j : pempty) => pempty.cases_on (fun (j : pempty) => short (pempty.elim j)) j /-- Evidence that every `pgame` in a list is `short`. -/ class inductive list_short : List pgame → Type (u + 1) where | nil : list_short [] | cons : (hd : pgame) → [_inst_1 : short hd] → (tl : List pgame) → [_inst_2 : list_short tl] → list_short (hd :: tl) protected instance list_short_nth_le (L : List pgame) [list_short L] (i : fin (list.length L)) : short (list.nth_le L (↑i) (list_short_nth_le._proof_1 L i)) := sorry protected instance short_of_lists (L : List pgame) (R : List pgame) [list_short L] [list_short R] : short (of_lists L R) := sorry /-- If `x` is a short game, and `y` is a relabelling of `x`, then `y` is also short. -/ def short_of_relabelling {x : pgame} {y : pgame} (R : relabelling x y) (S : short x) : short y := sorry /-- If `x` has no left move or right moves, it is (very!) short. -/ def short_of_equiv_empty {x : pgame} (el : left_moves x ≃ pempty) (er : right_moves x ≃ pempty) : short x := short_of_relabelling (relabelling.symm (relabel_relabelling el er)) short.of_pempty protected instance short_neg (x : pgame) [short x] : short (-x) := sorry protected instance short_add (x : pgame) (y : pgame) [short x] [short y] : short (x + y) := sorry protected instance short_nat (n : ℕ) : short ↑n := sorry protected instance short_bit0 (x : pgame) [short x] : short (bit0 x) := id (pgame.short_add x x) protected instance short_bit1 (x : pgame) [short x] : short (bit1 x) := id (pgame.short_add (bit0 x) 1) /-- Auxiliary construction of decidability instances. We build `decidable (x ≤ y)` and `decidable (x < y)` in a simultaneous induction. Instances for the two projections separately are provided below. -/ def le_lt_decidable (x : pgame) (y : pgame) [short x] [short y] : Decidable (x ≤ y) × Decidable (x < y) := sorry protected instance le_decidable (x : pgame) (y : pgame) [short x] [short y] : Decidable (x ≤ y) := prod.fst (le_lt_decidable x y _inst_1 _inst_2) protected instance lt_decidable (x : pgame) (y : pgame) [short x] [short y] : Decidable (x < y) := prod.snd (le_lt_decidable x y _inst_1 _inst_2) protected instance equiv_decidable (x : pgame) (y : pgame) [short x] [short y] : Decidable (x ≈ y) := and.decidable
e4e7a8b24def5283928bdf8fc7fec915abcacc23
9028d228ac200bbefe3a711342514dd4e4458bff
/src/category_theory/limits/shapes/equalizers.lean
fced6ad619e51f66e781e205de9a1b15e26f9ebd
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,338
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.epi_mono import category_theory.limits.limits /-! # Equalizers and coequalizers This file defines (co)equalizers as special cases of (co)limits. An equalizer is the categorical generalization of the subobject {a ∈ A | f(a) = g(a)} known from abelian groups or modules. It is a limit cone over the diagram formed by `f` and `g`. A coequalizer is the dual concept. ## Main definitions * `walking_parallel_pair` is the indexing category used for (co)equalizer_diagrams * `parallel_pair` is a functor from `walking_parallel_pair` to our category `C`. * a `fork` is a cone over a parallel pair. * there is really only one interesting morphism in a fork: the arrow from the vertex of the fork to the domain of f and g. It is called `fork.ι`. * an `equalizer` is now just a `limit (parallel_pair f g)` Each of these has a dual. ## Main statements * `equalizer.ι_mono` states that every equalizer map is a monomorphism * `is_iso_limit_cone_parallel_pair_of_self` states that the identity on the domain of `f` is an equalizer of `f` and `f`. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1] -/ noncomputable theory open category_theory namespace category_theory.limits local attribute [tidy] tactic.case_bash universes v u /-- The type of objects for the diagram indexing a (co)equalizer. -/ @[derive decidable_eq, derive inhabited] inductive walking_parallel_pair : Type v | zero | one open walking_parallel_pair /-- The type family of morphisms for the diagram indexing a (co)equalizer. -/ @[derive decidable_eq] inductive walking_parallel_pair_hom : walking_parallel_pair → walking_parallel_pair → Type v | left : walking_parallel_pair_hom zero one | right : walking_parallel_pair_hom zero one | id : Π X : walking_parallel_pair.{v}, walking_parallel_pair_hom X X /-- Satisfying the inhabited linter -/ instance : inhabited (walking_parallel_pair_hom zero one) := { default := walking_parallel_pair_hom.left } open walking_parallel_pair_hom /-- Composition of morphisms in the indexing diagram for (co)equalizers. -/ def walking_parallel_pair_hom.comp : Π (X Y Z : walking_parallel_pair) (f : walking_parallel_pair_hom X Y) (g : walking_parallel_pair_hom Y Z), walking_parallel_pair_hom X Z | _ _ _ (id _) h := h | _ _ _ left (id one) := left | _ _ _ right (id one) := right . instance walking_parallel_pair_hom_category : small_category walking_parallel_pair := { hom := walking_parallel_pair_hom, id := walking_parallel_pair_hom.id, comp := walking_parallel_pair_hom.comp } @[simp] lemma walking_parallel_pair_hom_id (X : walking_parallel_pair) : walking_parallel_pair_hom.id X = 𝟙 X := rfl variables {C : Type u} [category.{v} C] variables {X Y : C} /-- `parallel_pair f g` is the diagram in `C` consisting of the two morphisms `f` and `g` with common domain and codomain. -/ def parallel_pair (f g : X ⟶ Y) : walking_parallel_pair.{v} ⥤ C := { obj := λ x, match x with | zero := X | one := Y end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, left := f | _, _, right := g end, -- `tidy` can cope with this, but it's too slow: map_comp' := begin rintros (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) ⟨⟩⟨⟩; { unfold_aux, simp; refl }, end, }. @[simp] lemma parallel_pair_obj_zero (f g : X ⟶ Y) : (parallel_pair f g).obj zero = X := rfl @[simp] lemma parallel_pair_obj_one (f g : X ⟶ Y) : (parallel_pair f g).obj one = Y := rfl @[simp] lemma parallel_pair_map_left (f g : X ⟶ Y) : (parallel_pair f g).map left = f := rfl @[simp] lemma parallel_pair_map_right (f g : X ⟶ Y) : (parallel_pair f g).map right = g := rfl @[simp] lemma parallel_pair_functor_obj {F : walking_parallel_pair ⥤ C} (j : walking_parallel_pair) : (parallel_pair (F.map left) (F.map right)).obj j = F.obj j := begin cases j; refl end /-- Every functor indexing a (co)equalizer is naturally isomorphic (actually, equal) to a `parallel_pair` -/ @[simps {rhs_md := semireducible}] def diagram_iso_parallel_pair (F : walking_parallel_pair ⥤ C) : F ≅ parallel_pair (F.map left) (F.map right) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy /-- A fork on `f` and `g` is just a `cone (parallel_pair f g)`. -/ abbreviation fork (f g : X ⟶ Y) := cone (parallel_pair f g) /-- A cofork on `f` and `g` is just a `cocone (parallel_pair f g)`. -/ abbreviation cofork (f g : X ⟶ Y) := cocone (parallel_pair f g) variables {f g : X ⟶ Y} @[simp, reassoc] lemma fork.app_zero_left (s : fork f g) : s.π.app zero ≫ f = s.π.app one := by rw [←s.w left, parallel_pair_map_left] @[simp, reassoc] lemma fork.app_zero_right (s : fork f g) : s.π.app zero ≫ g = s.π.app one := by rw [←s.w right, parallel_pair_map_right] @[simp, reassoc] lemma cofork.left_app_one (s : cofork f g) : f ≫ s.ι.app one = s.ι.app zero := by rw [←s.w left, parallel_pair_map_left] @[simp, reassoc] lemma cofork.right_app_one (s : cofork f g) : g ≫ s.ι.app one = s.ι.app zero := by rw [←s.w right, parallel_pair_map_right] /-- A fork on `f g : X ⟶ Y` is determined by the morphism `ι : P ⟶ X` satisfying `ι ≫ f = ι ≫ g`. -/ def fork.of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork f g := { X := P, π := { app := λ X, begin cases X, exact ι, exact ι ≫ f, end, naturality' := λ X Y f, begin cases X; cases Y; cases f; dsimp; simp, { dsimp, simp, }, -- See note [dsimp, simp]. { exact w }, { dsimp, simp, }, end } } /-- A cofork on `f g : X ⟶ Y` is determined by the morphism `π : Y ⟶ P` satisfying `f ≫ π = g ≫ π`. -/ def cofork.of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork f g := { X := P, ι := { app := λ X, begin cases X, exact f ≫ π, exact π, end, naturality' := λ X Y f, begin cases X; cases Y; cases f; dsimp; simp, { dsimp, simp, }, { exact w.symm }, { dsimp, simp, }, end } } @[simp] lemma fork.of_ι_app_zero {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (fork.of_ι ι w).π.app zero = ι := rfl @[simp] lemma fork.of_ι_app_one {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (fork.of_ι ι w).π.app one = ι ≫ f := rfl @[simp] lemma cofork.of_π_app_zero {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : (cofork.of_π π w).ι.app zero = f ≫ π := rfl @[simp] lemma cofork.of_π_app_one {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : (cofork.of_π π w).ι.app one = π := rfl /-- A fork `t` on the parallel pair `f g : X ⟶ Y` consists of two morphisms `t.π.app zero : t.X ⟶ X` and `t.π.app one : t.X ⟶ Y`. Of these, only the first one is interesting, and we give it the shorter name `fork.ι t`. -/ abbreviation fork.ι (t : fork f g) := t.π.app zero /-- A cofork `t` on the parallel_pair `f g : X ⟶ Y` consists of two morphisms `t.ι.app zero : X ⟶ t.X` and `t.ι.app one : Y ⟶ t.X`. Of these, only the second one is interesting, and we give it the shorter name `cofork.π t`. -/ abbreviation cofork.π (t : cofork f g) := t.ι.app one @[simp] lemma fork.ι_of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork.ι (fork.of_ι ι w) = ι := rfl @[simp] lemma cofork.π_of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork.π (cofork.of_π π w) = π := rfl lemma fork.ι_eq_app_zero (t : fork f g) : fork.ι t = t.π.app zero := rfl lemma cofork.π_eq_app_one (t : cofork f g) : cofork.π t = t.ι.app one := rfl @[reassoc] lemma fork.condition (t : fork f g) : fork.ι t ≫ f = fork.ι t ≫ g := by rw [t.app_zero_left, t.app_zero_right] @[reassoc] lemma cofork.condition (t : cofork f g) : f ≫ cofork.π t = g ≫ cofork.π t := by rw [t.left_app_one, t.right_app_one] /-- To check whether two maps are equalized by both maps of a fork, it suffices to check it for the first map -/ lemma fork.equalizer_ext (s : fork f g) {W : C} {k l : W ⟶ s.X} (h : k ≫ fork.ι s = l ≫ fork.ι s) : ∀ (j : walking_parallel_pair), k ≫ s.π.app j = l ≫ s.π.app j | zero := h | one := by rw [←fork.app_zero_left, reassoc_of h] /-- To check whether two maps are coequalized by both maps of a cofork, it suffices to check it for the second map -/ lemma cofork.coequalizer_ext (s : cofork f g) {W : C} {k l : s.X ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) : ∀ (j : walking_parallel_pair), s.ι.app j ≫ k = s.ι.app j ≫ l | zero := by simp only [←cofork.left_app_one, category.assoc, h] | one := h lemma fork.is_limit.hom_ext {s : fork f g} (hs : is_limit s) {W : C} {k l : W ⟶ s.X} (h : k ≫ fork.ι s = l ≫ fork.ι s) : k = l := hs.hom_ext $ fork.equalizer_ext _ h lemma cofork.is_colimit.hom_ext {s : cofork f g} (hs : is_colimit s) {W : C} {k l : s.X ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) : k = l := hs.hom_ext $ cofork.coequalizer_ext _ h /-- If `s` is a limit fork over `f` and `g`, then a morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/ def fork.is_limit.lift' {s : fork f g} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : {l : W ⟶ s.X // l ≫ fork.ι s = k} := ⟨hs.lift $ fork.of_ι _ h, hs.fac _ _⟩ /-- If `s` is a colimit cofork over `f` and `g`, then a morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/ def cofork.is_colimit.desc' {s : cofork f g} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : {l : s.X ⟶ W // cofork.π s ≫ l = k} := ⟨hs.desc $ cofork.of_π _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def fork.is_limit.mk (t : fork f g) (lift : Π (s : fork f g), s.X ⟶ t.X) (fac : ∀ (s : fork f g), lift s ≫ fork.ι t = fork.ι s) (uniq : ∀ (s : fork f g) (m : s.X ⟶ t.X) (w : ∀ j : walking_parallel_pair, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, walking_parallel_pair.cases_on j (fac s) $ by erw [←s.w left, ←t.w left, ←category.assoc, fac]; refl, uniq' := uniq } /-- This is another convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def fork.is_limit.mk' {X Y : C} {f g : X ⟶ Y} (t : fork f g) (create : Π (s : fork f g), {l // l ≫ t.ι = s.ι ∧ ∀ {m}, m ≫ t.ι = s.ι → m = l}) : is_limit t := fork.is_limit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s m w, (create s).2.2 (w zero)) /-- This is a slightly more convenient method to verify that a cofork is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def cofork.is_colimit.mk (t : cofork f g) (desc : Π (s : cofork f g), t.X ⟶ s.X) (fac : ∀ (s : cofork f g), cofork.π t ≫ desc s = cofork.π s) (uniq : ∀ (s : cofork f g) (m : t.X ⟶ s.X) (w : ∀ j : walking_parallel_pair, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, walking_parallel_pair.cases_on j (by erw [←s.w left, ←t.w left, category.assoc, fac]; refl) (fac s), uniq' := uniq } /-- This is another convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def cofork.is_colimit.mk' {X Y : C} {f g : X ⟶ Y} (t : cofork f g) (create : Π (s : cofork f g), {l : t.X ⟶ s.X // t.π ≫ l = s.π ∧ ∀ {m}, t.π ≫ m = s.π → m = l}) : is_colimit t := cofork.is_colimit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s m w, (create s).2.2 (w one)) /-- This is a helper construction that can be useful when verifying that a category has all equalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a fork on `F.map left` and `F.map right`, we get a cone on `F`. If you're thinking about using this, have a look at `has_equalizers_of_has_limit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cone.of_fork {F : walking_parallel_pair ⥤ C} (t : fork (F.map left) (F.map right)) : cone F := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy), naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } /-- This is a helper construction that can be useful when verifying that a category has all coequalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a cofork on `F.map left` and `F.map right`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_coequalizers_of_has_colimit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cocone.of_cofork {F : walking_parallel_pair ⥤ C} (t : cofork (F.map left) (F.map right)) : cocone F := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } @[simp] lemma cone.of_fork_π {F : walking_parallel_pair ⥤ C} (t : fork (F.map left) (F.map right)) (j) : (cone.of_fork t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cocone.of_cofork_ι {F : walking_parallel_pair ⥤ C} (t : cofork (F.map left) (F.map right)) (j) : (cocone.of_cofork t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cone on `F`, we get a fork on `F.map left` and `F.map right`. -/ def fork.of_cone {F : walking_parallel_pair ⥤ C} (t : cone F) : fork (F.map left) (F.map right) := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy) } } /-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cocone on `F`, we get a cofork on `F.map left` and `F.map right`. -/ def cofork.of_cocone {F : walking_parallel_pair ⥤ C} (t : cocone F) : cofork (F.map left) (F.map right) := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X } } @[simp] lemma fork.of_cone_π {F : walking_parallel_pair ⥤ C} (t : cone F) (j) : (fork.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cofork.of_cocone_ι {F : walking_parallel_pair ⥤ C} (t : cocone F) (j) : (cofork.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- Helper function for constructing morphisms between equalizer forks. -/ @[simps] def fork.mk_hom {s t : fork f g} (k : s.X ⟶ t.X) (w : k ≫ t.ι = s.ι) : s ⟶ t := { hom := k, w' := begin rintro ⟨_|_⟩, exact w, simpa using w =≫ f, end } /-- To construct an isomorphism between forks, it suffices to give an isomorphism between the cone points and check that it commutes with the `ι` morphisms. -/ @[simps] def fork.ext {s t : fork f g} (i : s.X ≅ t.X) (w : i.hom ≫ t.ι = s.ι) : s ≅ t := { hom := fork.mk_hom i.hom w, inv := fork.mk_hom i.inv (by rw [← w, iso.inv_hom_id_assoc]) } /-- Helper function for constructing morphisms between coequalizer coforks. -/ @[simps] def cofork.mk_hom {s t : cofork f g} (k : s.X ⟶ t.X) (w : s.π ≫ k = t.π) : s ⟶ t := { hom := k, w' := begin rintro ⟨_|_⟩, simpa using f ≫= w, exact w, end } /-- To construct an isomorphism between coforks, it suffices to give an isomorphism between the cocone points and check that it commutes with the `π` morphisms. -/ def cofork.ext {s t : cofork f g} (i : s.X ≅ t.X) (w : s.π ≫ i.hom = t.π) : s ≅ t := { hom := cofork.mk_hom i.hom w, inv := cofork.mk_hom i.inv (by rw [iso.comp_inv_eq, w]) } variables (f g) section /-- `has_equalizer f g` represents a particular choice of limiting cone for the parallel pair of morphisms `f` and `g`. -/ abbreviation has_equalizer := has_limit (parallel_pair f g) variables [has_equalizer f g] /-- If an equalizer of `f` and `g` exists, we can access an arbitrary choice of such by saying `equalizer f g`. -/ abbreviation equalizer : C := limit (parallel_pair f g) /-- If an equalizer of `f` and `g` exists, we can access the inclusion `equalizer f g ⟶ X` by saying `equalizer.ι f g`. -/ abbreviation equalizer.ι : equalizer f g ⟶ X := limit.π (parallel_pair f g) zero /-- An equalizer cone for a parallel pair `f` and `g`. -/ abbreviation equalizer.fork : fork f g := limit.cone (parallel_pair f g) @[simp] lemma equalizer.fork_ι : (equalizer.fork f g).ι = equalizer.ι f g := rfl @[simp] lemma equalizer.fork_π_app_zero : (equalizer.fork f g).π.app zero = equalizer.ι f g := rfl @[reassoc] lemma equalizer.condition : equalizer.ι f g ≫ f = equalizer.ι f g ≫ g := fork.condition $ limit.cone $ parallel_pair f g /-- The equalizer built from `equalizer.ι f g` is limiting. -/ def equalizer_is_equalizer : is_limit (fork.of_ι (equalizer.ι f g) (equalizer.condition f g)) := is_limit.of_iso_limit (limit.is_limit _) (fork.ext (iso.refl _) (by tidy)) variables {f g} /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` factors through the equalizer of `f` and `g` via `equalizer.lift : W ⟶ equalizer f g`. -/ abbreviation equalizer.lift {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : W ⟶ equalizer f g := limit.lift (parallel_pair f g) (fork.of_ι k h) @[simp, reassoc] lemma equalizer.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : equalizer.lift k h ≫ equalizer.ι f g = k := limit.lift_π _ _ /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ equalizer f g` satisfying `l ≫ equalizer.ι f g = k`. -/ def equalizer.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : {l : W ⟶ equalizer f g // l ≫ equalizer.ι f g = k} := ⟨equalizer.lift k h, equalizer.lift_ι _ _⟩ /-- Two maps into an equalizer are equal if they are are equal when composed with the equalizer map. -/ @[ext] lemma equalizer.hom_ext {W : C} {k l : W ⟶ equalizer f g} (h : k ≫ equalizer.ι f g = l ≫ equalizer.ι f g) : k = l := fork.is_limit.hom_ext (limit.is_limit _) h /-- An equalizer morphism is a monomorphism -/ instance equalizer.ι_mono : mono (equalizer.ι f g) := { right_cancellation := λ Z h k w, equalizer.hom_ext w } end section variables {f g} /-- The equalizer morphism in any limit cone is a monomorphism. -/ lemma mono_of_is_limit_parallel_pair {c : cone (parallel_pair f g)} (i : is_limit c) : mono (fork.ι c) := { right_cancellation := λ Z h k w, fork.is_limit.hom_ext i w } end section variables {f g} /-- The identity determines a cone on the equalizer diagram of `f` and `g` if `f = g`. -/ def id_fork (h : f = g) : fork f g := fork.of_ι (𝟙 X) $ h ▸ rfl /-- The identity on `X` is an equalizer of `(f, g)`, if `f = g`. -/ def is_limit_id_fork (h : f = g) : is_limit (id_fork h) := fork.is_limit.mk _ (λ s, fork.ι s) (λ s, category.comp_id _) (λ s m h, by { convert h zero, exact (category.comp_id _).symm }) /-- Every equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_eq (h₀ : f = g) {c : cone (parallel_pair f g)} (h : is_limit c) : is_iso (c.π.app zero) := is_iso.of_iso $ is_limit.cone_point_unique_up_to_iso h $ is_limit_id_fork h₀ /-- The equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def equalizer.ι_of_eq [has_equalizer f g] (h : f = g) : is_iso (equalizer.ι f g) := is_iso_limit_cone_parallel_pair_of_eq h $ limit.is_limit _ /-- Every equalizer of `(f, f)` is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_self {c : cone (parallel_pair f f)} (h : is_limit c) : is_iso (c.π.app zero) := is_iso_limit_cone_parallel_pair_of_eq rfl h /-- An equalizer that is an epimorphism is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_epi {c : cone (parallel_pair f g)} (h : is_limit c) [epi (c.π.app zero)] : is_iso (c.π.app zero) := is_iso_limit_cone_parallel_pair_of_eq ((cancel_epi _).1 (fork.condition c)) h end instance : has_equalizer f f := has_limit.mk { cone := id_fork rfl, is_limit := is_limit_id_fork rfl } /-- The equalizer inclusion for `(f, f)` is an isomorphism. -/ instance equalizer.ι_of_self : is_iso (equalizer.ι f f) := equalizer.ι_of_eq rfl /-- The equalizer of a morphism with itself is isomorphic to the source. -/ def equalizer.iso_source_of_self : equalizer f f ≅ X := as_iso (equalizer.ι f f) @[simp] lemma equalizer.iso_source_of_self_hom : (equalizer.iso_source_of_self f).hom = equalizer.ι f f := rfl @[simp] lemma equalizer.iso_source_of_self_inv : (equalizer.iso_source_of_self f).inv = equalizer.lift (𝟙 X) (by simp) := rfl section /-- `has_coequalizer f g` represents a particular choice of colimiting cocone for the parallel pair of morphisms `f` and `g`. -/ abbreviation has_coequalizer := has_colimit (parallel_pair f g) variables [has_coequalizer f g] /-- If a coequalizer of `f` and `g` exists, we can access an arbitrary choice of such by saying `coequalizer f g`. -/ abbreviation coequalizer : C := colimit (parallel_pair f g) /-- If a coequalizer of `f` and `g` exists, we can access the corresponding projection by saying `coequalizer.π f g`. -/ abbreviation coequalizer.π : Y ⟶ coequalizer f g := colimit.ι (parallel_pair f g) one /-- An arbitrary choice of coequalizer cocone for a parallel pair `f` and `g`. -/ abbreviation coequalizer.cofork : cofork f g := colimit.cocone (parallel_pair f g) @[simp] lemma coequalizer.cofork_π : (coequalizer.cofork f g).π = coequalizer.π f g := rfl @[simp] lemma coequalizer.cofork_ι_app_one : (coequalizer.cofork f g).ι.app one = coequalizer.π f g := rfl @[reassoc] lemma coequalizer.condition : f ≫ coequalizer.π f g = g ≫ coequalizer.π f g := cofork.condition $ colimit.cocone $ parallel_pair f g /-- The cofork built from `coequalizer.π f g` is colimiting. -/ def coequalizer_is_coequalizer : is_colimit (cofork.of_π (coequalizer.π f g) (coequalizer.condition f g)) := is_colimit.of_iso_colimit (colimit.is_colimit _) (cofork.ext (iso.refl _) (by tidy)) variables {f g} /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` factors through the coequalizer of `f` and `g` via `coequalizer.desc : coequalizer f g ⟶ W`. -/ abbreviation coequalizer.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer f g ⟶ W := colimit.desc (parallel_pair f g) (cofork.of_π k h) @[simp, reassoc] lemma coequalizer.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer.π f g ≫ coequalizer.desc k h = k := colimit.ι_desc _ _ /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : coequalizer f g ⟶ W` satisfying `coequalizer.π ≫ g = l`. -/ def coequalizer.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : {l : coequalizer f g ⟶ W // coequalizer.π f g ≫ l = k} := ⟨coequalizer.desc k h, coequalizer.π_desc _ _⟩ /-- Two maps from a coequalizer are equal if they are equal when composed with the coequalizer map -/ @[ext] lemma coequalizer.hom_ext {W : C} {k l : coequalizer f g ⟶ W} (h : coequalizer.π f g ≫ k = coequalizer.π f g ≫ l) : k = l := cofork.is_colimit.hom_ext (colimit.is_colimit _) h /-- A coequalizer morphism is an epimorphism -/ instance coequalizer.π_epi : epi (coequalizer.π f g) := { left_cancellation := λ Z h k w, coequalizer.hom_ext w } end section variables {f g} /-- The coequalizer morphism in any colimit cocone is an epimorphism. -/ lemma epi_of_is_colimit_parallel_pair {c : cocone (parallel_pair f g)} (i : is_colimit c) : epi (c.ι.app one) := { left_cancellation := λ Z h k w, cofork.is_colimit.hom_ext i w } end section variables {f g} /-- The identity determines a cocone on the coequalizer diagram of `f` and `g`, if `f = g`. -/ def id_cofork (h : f = g) : cofork f g := cofork.of_π (𝟙 Y) $ h ▸ rfl /-- The identity on `Y` is a coequalizer of `(f, g)`, where `f = g`. -/ def is_colimit_id_cofork (h : f = g) : is_colimit (id_cofork h) := cofork.is_colimit.mk _ (λ s, cofork.π s) (λ s, category.id_comp _) (λ s m h, by { convert h one, exact (category.id_comp _).symm }) /-- Every coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def is_iso_colimit_cocone_parallel_pair_of_eq (h₀ : f = g) {c : cocone (parallel_pair f g)} (h : is_colimit c) : is_iso (c.ι.app one) := is_iso.of_iso $ is_colimit.cocone_point_unique_up_to_iso (is_colimit_id_cofork h₀) h /-- The coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def coequalizer.π_of_eq [has_coequalizer f g] (h : f = g) : is_iso (coequalizer.π f g) := is_iso_colimit_cocone_parallel_pair_of_eq h $ colimit.is_colimit _ /-- Every coequalizer of `(f, f)` is an isomorphism. -/ def is_iso_colimit_cocone_parallel_pair_of_self {c : cocone (parallel_pair f f)} (h : is_colimit c) : is_iso (c.ι.app one) := is_iso_colimit_cocone_parallel_pair_of_eq rfl h /-- A coequalizer that is a monomorphism is an isomorphism. -/ def is_iso_limit_cocone_parallel_pair_of_epi {c : cocone (parallel_pair f g)} (h : is_colimit c) [mono (c.ι.app one)] : is_iso (c.ι.app one) := is_iso_colimit_cocone_parallel_pair_of_eq ((cancel_mono _).1 (cofork.condition c)) h end instance : has_coequalizer f f := has_colimit.mk { cocone := id_cofork rfl, is_colimit := is_colimit_id_cofork rfl } /-- The coequalizer projection for `(f, f)` is an isomorphism. -/ instance coequalizer.π_of_self : is_iso (coequalizer.π f f) := coequalizer.π_of_eq rfl /-- The coequalizer of a morphism with itself is isomorphic to the target. -/ def coequalizer.iso_target_of_self : coequalizer f f ≅ Y := (as_iso (coequalizer.π f f)).symm @[simp] lemma coequalizer.iso_target_of_self_hom : (coequalizer.iso_target_of_self f).hom = coequalizer.desc (𝟙 Y) (by simp) := rfl @[simp] lemma coequalizer.iso_target_of_self_inv : (coequalizer.iso_target_of_self f).inv = coequalizer.π f f := rfl variables (C) /-- `has_equalizers` represents a choice of equalizer for every pair of morphisms -/ abbreviation has_equalizers := has_limits_of_shape walking_parallel_pair C /-- `has_coequalizers` represents a choice of coequalizer for every pair of morphisms -/ abbreviation has_coequalizers := has_colimits_of_shape walking_parallel_pair C /-- If `C` has all limits of diagrams `parallel_pair f g`, then it has all equalizers -/ lemma has_equalizers_of_has_limit_parallel_pair [Π {X Y : C} {f g : X ⟶ Y}, has_limit (parallel_pair f g)] : has_equalizers C := { has_limit := λ F, has_limit_of_iso (diagram_iso_parallel_pair F).symm } /-- If `C` has all colimits of diagrams `parallel_pair f g`, then it has all coequalizers -/ lemma has_coequalizers_of_has_colimit_parallel_pair [Π {X Y : C} {f g : X ⟶ Y}, has_colimit (parallel_pair f g)] : has_coequalizers C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_parallel_pair F) } section -- In this section we show that a split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. variables {C} [split_mono f] /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. Here we build the cone, and show in `split_mono_equalizes` that it is a limit cone. -/ def cone_of_split_mono : cone (parallel_pair (𝟙 Y) (retraction f ≫ f)) := fork.of_ι f (by tidy) @[simp] lemma cone_of_split_mono_π_app_zero : (cone_of_split_mono f).π.app zero = f := rfl @[simp] lemma cone_of_split_mono_π_app_one : (cone_of_split_mono f).π.app one = f ≫ 𝟙 Y := rfl /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. -/ def split_mono_equalizes {X Y : C} (f : X ⟶ Y) [split_mono f] : is_limit (cone_of_split_mono f) := { lift := λ s, s.π.app zero ≫ retraction f, fac' := λ s, begin rintros (⟨⟩|⟨⟩), { rw [cone_of_split_mono_π_app_zero], erw [category.assoc, ← s.π.naturality right, s.π.naturality left, category.comp_id], }, { erw [cone_of_split_mono_π_app_one, category.comp_id, category.assoc, ← s.π.naturality right, category.id_comp], } end, uniq' := λ s m w, begin rw ←(w zero), simp, end, } end section -- In this section we show that a split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. variables {C} [split_epi f] /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. Here we build the cocone, and show in `split_epi_coequalizes` that it is a colimit cocone. -/ def cocone_of_split_epi : cocone (parallel_pair (𝟙 X) (f ≫ section_ f)) := cofork.of_π f (by tidy) @[simp] lemma cocone_of_split_epi_ι_app_one : (cocone_of_split_epi f).ι.app one = f := rfl @[simp] lemma cocone_of_split_epi_ι_app_zero : (cocone_of_split_epi f).ι.app zero = 𝟙 X ≫ f := rfl /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. -/ def split_epi_coequalizes {X Y : C} (f : X ⟶ Y) [split_epi f] : is_colimit (cocone_of_split_epi f) := { desc := λ s, section_ f ≫ s.ι.app one, fac' := λ s, begin rintros (⟨⟩|⟨⟩), { erw [cocone_of_split_epi_ι_app_zero, category.assoc, category.id_comp, ←category.assoc, s.ι.naturality right, functor.const.obj_map, category.comp_id], }, { erw [cocone_of_split_epi_ι_app_one, ←category.assoc, s.ι.naturality right, ←s.ι.naturality left, category.id_comp] } end, uniq' := λ s m w, begin rw ←(w one), simp, end, } end end category_theory.limits
3df592c08acf86880a0456351e3dab56287163cc
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/group_theory/submonoid/basic.lean
d4ba45e82042a1dcec90bac3612e94eeb4431e5c
[ "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
15,958
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import data.set.lattice /-! # Submonoids: definition and `complete_lattice` structure This file defines bundled multiplicative and additive submonoids. We also define a `complete_lattice` structure on `submonoid`s, define the closure of a set as the minimal submonoid that includes this set, and prove a few results about extending properties from a dense set (i.e. a set with `closure s = ⊤`) to the whole monoid, see `submonoid.dense_induction` and `monoid_hom.of_mdense`. ## Main definitions * `submonoid M`: the type of bundled submonoids of a monoid `M`; the underlying set is given in the `carrier` field of the structure, and should be accessed through coercion as in `(S : set M)`. * `add_submonoid M` : the type of bundled submonoids of an additive monoid `M`. For each of the following definitions in the `submonoid` namespace, there is a corresponding definition in the `add_submonoid` namespace. * `submonoid.copy` : copy of a submonoid with `carrier` replaced by a set that is equal but possibly not definitionally equal to the carrier of the original `submonoid`. * `submonoid.closure` : monoid closure of a set, i.e., the least submonoid that includes the set. * `submonoid.gi` : `closure : set M → submonoid M` and coercion `coe : submonoid M → set M` form a `galois_insertion`; * `monoid_hom.eq_mlocus`: the submonoid of elements `x : M` such that `f x = g x`; * `monoid_hom.of_mdense`: if a map `f : M → N` between two monoids satisfies `f 1 = 1` and `f (x * y) = f x * f y` for `y` from some dense set `s`, then `f` is a monoid homomorphism. E.g., if `f : ℕ → M` satisfies `f 0 = 0` and `f (x + 1) = f x + f 1`, then `f` is an additive monoid homomorphism. ## Implementation notes Submonoid inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a submonoid's underlying set. This file is designed to have very few dependencies. In particular, it should not use natural numbers. ## Tags submonoid, submonoids -/ variables {M : Type*} [monoid M] {s : set M} variables {A : Type*} [add_monoid A] {t : set A} /-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/ structure submonoid (M : Type*) [monoid M] := (carrier : set M) (one_mem' : (1 : M) ∈ carrier) (mul_mem' {a b} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) /-- An additive submonoid of an additive monoid `M` is a subset containing 0 and closed under addition. -/ structure add_submonoid (M : Type*) [add_monoid M] := (carrier : set M) (zero_mem' : (0 : M) ∈ carrier) (add_mem' {a b} : a ∈ carrier → b ∈ carrier → a + b ∈ carrier) attribute [to_additive add_submonoid] submonoid namespace submonoid @[to_additive] instance : has_coe (submonoid M) (set M) := ⟨submonoid.carrier⟩ @[to_additive] instance : has_coe_to_sort (submonoid M) := ⟨Type*, λ S, S.carrier⟩ @[to_additive] instance : has_mem M (submonoid M) := ⟨λ m S, m ∈ (S:set M)⟩ @[simp, to_additive] lemma mem_carrier {s : submonoid M} {x : M} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp, norm_cast, to_additive] lemma mem_coe {S : submonoid M} {m : M} : m ∈ (S : set M) ↔ m ∈ S := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (s : submonoid M) : ↥(s : set M) = s := rfl attribute [norm_cast] add_submonoid.mem_coe add_submonoid.coe_coe @[to_additive] protected lemma «exists» {s : submonoid M} {p : s → Prop} : (∃ x : s, p x) ↔ ∃ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.exists @[to_additive] protected lemma «forall» {s : submonoid M} {p : s → Prop} : (∀ x : s, p x) ↔ ∀ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.forall /-- Two submonoids are equal if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if the underlying subsets are equal."] theorem ext' ⦃S T : submonoid M⦄ (h : (S : set M) = T) : S = T := by cases S; cases T; congr' /-- Two submonoids are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {S T : submonoid M} : S = T ↔ (S : set M) = T := ⟨λ h, h ▸ rfl, λ h, ext' h⟩ /-- Two submonoids are equal if they have the same elements. -/ @[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."] theorem ext {S T : submonoid M} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h attribute [ext] add_submonoid.ext /-- Copy a submonoid replacing `carrier` with a set that is equal to it. -/ @[to_additive "Copy an additive submonoid replacing `carrier` with a set that is equal to it."] def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M := { carrier := s, one_mem' := hs.symm ▸ S.one_mem', mul_mem' := hs.symm ▸ S.mul_mem' } variable {S : submonoid M} @[simp, to_additive] lemma coe_copy {s : set M} (hs : s = S) : (S.copy s hs : set M) = s := rfl @[to_additive] lemma copy_eq {s : set M} (hs : s = S) : S.copy s hs = S := ext' hs variable (S) /-- A submonoid contains the monoid's 1. -/ @[to_additive "An `add_submonoid` contains the monoid's 0."] theorem one_mem : (1 : M) ∈ S := S.one_mem' /-- A submonoid is closed under multiplication. -/ @[to_additive "An `add_submonoid` is closed under addition."] theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := submonoid.mul_mem' S @[to_additive] lemma coe_injective : function.injective (coe : S → M) := subtype.val_injective @[simp, to_additive] lemma coe_eq_coe (x y : S) : (x : M) = y ↔ x = y := set_coe.ext_iff attribute [norm_cast] coe_eq_coe add_submonoid.coe_eq_coe @[to_additive] instance : has_le (submonoid M) := ⟨λ S T, ∀ ⦃x⦄, x ∈ S → x ∈ T⟩ @[to_additive] lemma le_def {S T : submonoid M} : S ≤ T ↔ ∀ ⦃x : M⦄, x ∈ S → x ∈ T := iff.rfl @[simp, norm_cast, to_additive] lemma coe_subset_coe {S T : submonoid M} : (S : set M) ⊆ T ↔ S ≤ T := iff.rfl @[to_additive] instance : partial_order (submonoid M) := { le := λ S T, ∀ ⦃x⦄, x ∈ S → x ∈ T, .. partial_order.lift (coe : submonoid M → set M) ext' } @[simp, norm_cast, to_additive] lemma coe_ssubset_coe {S T : submonoid M} : (S : set M) ⊂ T ↔ S < T := iff.rfl attribute [norm_cast] add_submonoid.coe_subset_coe add_submonoid.coe_ssubset_coe /-- The submonoid `M` of the monoid `M`. -/ @[to_additive "The additive submonoid `M` of the `add_monoid M`."] instance : has_top (submonoid M) := ⟨{ carrier := set.univ, one_mem' := set.mem_univ 1, mul_mem' := λ _ _ _ _, set.mem_univ _ }⟩ /-- The trivial submonoid `{1}` of an monoid `M`. -/ @[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."] instance : has_bot (submonoid M) := ⟨{ carrier := {1}, one_mem' := set.mem_singleton 1, mul_mem' := λ a b ha hb, by { simp only [set.mem_singleton_iff] at *, rw [ha, hb, mul_one] }}⟩ @[to_additive] instance : inhabited (submonoid M) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : M} : x ∈ (⊥ : submonoid M) ↔ x = 1 := set.mem_singleton_iff @[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊤ : submonoid M) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : submonoid M) : set M) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : submonoid M) : set M) = {1} := rfl /-- The inf of two submonoids is their intersection. -/ @[to_additive "The inf of two `add_submonoid`s is their intersection."] instance : has_inf (submonoid M) := ⟨λ S₁ S₂, { carrier := S₁ ∩ S₂, one_mem' := ⟨S₁.one_mem, S₂.one_mem⟩, mul_mem' := λ _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩, ⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ }⟩ @[simp, to_additive] lemma coe_inf (p p' : submonoid M) : ((p ⊓ p' : submonoid M) : set M) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : submonoid M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (submonoid M) := ⟨λ s, { carrier := ⋂ t ∈ s, ↑t, one_mem' := set.mem_bInter $ λ i h, i.one_mem, mul_mem' := λ x y hx hy, set.mem_bInter $ λ i h, i.mul_mem (by apply set.mem_bInter_iff.1 hx i h) (by apply set.mem_bInter_iff.1 hy i h) }⟩ @[simp, to_additive] lemma coe_Inf (S : set (submonoid M)) : ((Inf S : submonoid M) : set M) = ⋂ s ∈ S, ↑s := rfl @[to_additive] lemma mem_Inf {S : set (submonoid M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → submonoid M} {x : M} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ι : Sort*} {S : ι → submonoid M} : (↑(⨅ i, S i) : set M) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_Inf coe_infi /-- Submonoids of a monoid form a complete lattice. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."] instance : complete_lattice (submonoid M) := { le := (≤), lt := (<), bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), Inf := has_Inf.Inf, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (submonoid M) $ λ s, is_glb.of_image (λ S T, show (S : set M) ≤ T ↔ S ≤ T, from coe_subset_coe) is_glb_binfi } /-- The `submonoid` generated by a set. -/ @[to_additive "The `add_submonoid` generated by a set"] def closure (s : set M) : submonoid M := Inf {S | s ⊆ S} @[to_additive] lemma mem_closure {x : M} : x ∈ closure s ↔ ∀ S : submonoid M, s ⊆ S → x ∈ S := mem_Inf /-- The submonoid generated by a set includes the set. -/ @[simp, to_additive "The `add_submonoid` generated by a set includes the set."] lemma subset_closure : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx variable {S} open set /-- A submonoid `S` includes `closure s` if and only if it includes `s`. -/ @[simp, to_additive "An additive submonoid `S` includes `closure s` if and only if it includes `s`"] lemma closure_le : closure s ≤ S ↔ s ⊆ S := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ /-- Submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ @[to_additive "Additive submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`"] lemma closure_mono ⦃s t : set M⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ subset.trans h subset_closure @[to_additive] lemma closure_eq_of_le (h₁ : s ⊆ S) (h₂ : S ≤ closure s) : closure s = S := le_antisymm (closure_le.2 h₁) h₂ variable (S) /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `s`, and is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `s`, and is preserved under addition, then `p` holds for all elements of the additive closure of `s`."] lemma closure_induction {p : M → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul⟩).2 Hs h attribute [elab_as_eliminator] submonoid.closure_induction add_submonoid.closure_induction /-- If `s` is a dense set in a monoid `M`, `submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 1`, and verify that `p x` and `p y` imply `p (x * y)`. -/ @[to_additive] lemma dense_induction {p : M → Prop} (x : M) {s : set M} (hs : closure s = ⊤) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := have ∀ x ∈ closure s, p x, from λ x hx, closure_induction hx Hs H1 Hmul, by simpa [hs] using this x /-- If `s` is a dense set in an additive monoid `M`, `add_submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 0`, and verify that `p x` and `p y` imply `p (x + y)`. -/ add_decl_doc add_submonoid.dense_induction attribute [elab_as_eliminator] dense_induction add_submonoid.dense_induction variable (M) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure M _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {M} /-- Closure of a submonoid `S` equals `S`. -/ @[simp, to_additive "Additive closure of an additive submonoid `S` equals `S`"] lemma closure_eq : closure (S : set M) = S := (submonoid.gi M).l_u_eq S @[simp, to_additive] lemma closure_empty : closure (∅ : set M) = ⊥ := (submonoid.gi M).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set M) = ⊤ := @coe_top M _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set M) : closure (s ∪ t) = closure s ⊔ closure t := (submonoid.gi M).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set M) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (submonoid.gi M).gc.l_supr end submonoid namespace monoid_hom variables {N : Type*} {P : Type*} [monoid N] [monoid P] (S : submonoid M) open submonoid /-- The submonoid of elements `x : M` such that `f x = g x` -/ @[to_additive "The additive submonoid of elements `x : M` such that `f x = g x`"] def eq_mlocus (f g : M →* N) : submonoid M := { carrier := {x | f x = g x}, one_mem' := by rw [set.mem_set_of_eq, f.map_one, g.map_one], mul_mem' := λ x y (hx : _ = _) (hy : _ = _), by simp [*] } /-- If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure. -/ @[to_additive] lemma eq_on_mclosure {f g : M →* N} {s : set M} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_mlocus g, from closure_le.2 h @[to_additive] lemma eq_of_eq_on_mtop {f g : M →* N} (h : set.eq_on f g (⊤ : submonoid M)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_mdense {s : set M} (hs : closure s = ⊤) {f g : M →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_mtop $ hs ▸ eq_on_mclosure h /-- Let `s` be a subset of a monoid `M` such that the closure of `s` is the whole monoid. Then `monoid_hom.of_mdense` defines a monoid homomorphism from `M` asking for a proof of `f (x * y) = f x * f y` only for `y ∈ s`. -/ @[to_additive] def of_mdense (f : M → N) (hs : closure s = ⊤) (h1 : f 1 = 1) (hmul : ∀ x (y ∈ s), f (x * y) = f x * f y) : M →* N := { to_fun := f, map_one' := h1, map_mul' := λ x y, dense_induction y hs (λ y hy x, hmul x y hy) (by simp [h1]) (λ y₁ y₂ h₁ h₂ x, by simp only [← mul_assoc, h₁, h₂]) x } /-- Let `s` be a subset of an additive monoid `M` such that the closure of `s` is the whole monoid. Then `add_monoid_hom.of_mdense` defines an additive monoid homomorphism from `M` asking for a proof of `f (x + y) = f x + f y` only for `y ∈ s`. -/ add_decl_doc add_monoid_hom.of_mdense @[simp, to_additive] lemma coe_of_mdense (f : M → N) (hs : closure s = ⊤) (h1 hmul) : ⇑(of_mdense f hs h1 hmul) = f := rfl attribute [norm_cast] coe_of_mdense add_monoid_hom.coe_of_mdense end monoid_hom
7a7854097e7dcc248babe0496db0396bce7d1025
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/tests/lean/run/meta7.lean
728877e644ff85ac4bd853bef01fa1b947448b94
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,724
lean
import Lean.Meta open Lean open Lean.Meta partial def fact : Nat → Nat | 0 => 1 | n+1 => (n+1)*fact n set_option trace.Meta.debug true set_option trace.Meta.check false def print (msg : MessageData) : MetaM Unit := trace! `Meta.debug msg def checkM (x : MetaM Bool) : MetaM Unit := unless (← x) do throwError "check failed" def ex (x_1 x_2 x_3 : Nat) : Nat × Nat := let x := fact (10 + x_1 + x_2 + x_3); let ty := Nat → Nat; let f : ty := fun x => x; let n := 20; let z := f 10; (let y : { v : Nat // v = n } := ⟨20, rfl⟩; y.1 + n + f x, z + 10) def tst1 : MetaM Unit := do print "----- tst1 -----"; let c ← getConstInfo `ex; lambdaTelescope c.value?.get! fun xs body => withTrackingZeta do check body; let ys ← getZetaFVarIds; let ys := ys.toList.map mkFVar; print ys; checkM $ pure $ ys.length == 2; let c ← mkAuxDefinitionFor `foo body; print c; check c; pure () #eval tst1 #print foo def tst2 : MetaM Unit := do print "----- tst2 -----"; let nat := mkConst `Nat; let t0 := mkApp (mkConst `IO) nat; let t := mkForall `_ BinderInfo.default nat t0; print t; check t; forallBoundedTelescope t (some 1) fun xs b => do print b; checkM $ pure $ xs.size == 1; checkM $ pure $ b == t0; pure () #eval tst2 def tst3 : MetaM Unit := do print "----- tst2 -----"; let nat := mkConst `Nat; let t0 := mkApp (mkConst `IO) nat; let t := t0; print t; check t; forallBoundedTelescope t (some 0) fun xs b => do print b; checkM $ pure $ xs.size == 0; checkM $ pure $ b == t0; pure () #eval tst3 def tst4 : MetaM Unit := do print "----- tst4 -----"; let nat := mkConst `Nat; withLocalDeclD `x nat fun x => withLocalDeclD `y nat fun y => do let m ← mkFreshExprMVar nat; print (← ppGoal m.mvarId!); let val ← mkAppM `Add.add #[mkNatLit 10, y]; let ⟨zId, nId, subst⟩ ← assertAfter m.mvarId! x.fvarId! `z nat val; print m; print (← ppGoal nId); withMVarContext nId do { print (subst.apply x ++ " " ++ subst.apply y ++ " " ++ mkFVar zId); assignExprMVar nId (← mkAppM `Add.add #[subst.apply x, mkFVar zId]); print (mkMVar nId) }; print m; let expected ← mkAppM `Add.add #[x, val]; checkM (isDefEq m expected); pure () #eval tst4 def tst5 : MetaM Unit := do print "----- tst5 -----"; let prop := mkSort levelZero; withLocalDeclD `p prop fun p => withLocalDeclD `q prop fun q => do withLocalDeclD `h₁ p fun h₁ => do let eq ← mkEq p q; withLocalDeclD `h₂ eq fun h₂ => do let m ← mkFreshExprMVar q; let r ← replaceLocalDecl m.mvarId! h₁.fvarId! q h₂; print (← ppGoal r.mvarId); assignExprMVar r.mvarId (mkFVar r.fvarId); print m; check m; pure () #eval tst5 def tst6 : MetaM Unit := do print "----- tst6 -----"; let nat := mkConst `Nat; withLocalDeclD `x nat fun x => withLocalDeclD `y nat fun y => do let m ← mkFreshExprMVar nat; print (← ppGoal m.mvarId!); let val ← mkAppM `Add.add #[mkNatLit 10, y]; let ⟨zId, nId, subst⟩ ← assertAfter m.mvarId! y.fvarId! `z nat val; print m; print (← ppGoal nId); withMVarContext nId do { print (subst.apply x ++ " " ++ subst.apply y ++ " " ++ mkFVar zId); assignExprMVar nId (← mkAppM `Add.add #[subst.apply x, mkFVar zId]); print (mkMVar nId) }; print m; let expected ← mkAppM `Add.add #[x, val]; checkM (isDefEq m expected); pure () #eval tst6 def tst7 : MetaM Unit := do print "----- tst7 -----"; let nat := mkConst `Nat; withLocalDeclD `x nat fun x => withLocalDeclD `y nat fun y => do let val ← mkAppM `Add.add #[x, y]; print val; let val := val.replaceFVars #[x, y] #[mkNatLit 0, mkNatLit 1]; print val; let expected ← mkAppM `Add.add #[mkNatLit 0, mkNatLit 1]; print expected; checkM (pure $ val == expected); pure () #eval tst7
54b3ff2928c24b4085cb342f966de59288c0510d
4727251e0cd73359b15b664c3170e5d754078599
/src/order/cover.lean
bcb6c46c22f2aa769df47c0c9d2e1cb9bb3f94f2
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
9,271
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Violeta Hernández Palacios, Grayson Burton, Floris van Doorn -/ import data.set.intervals.ord_connected /-! # The covering relation This file defines the covering relation in an order. `b` is said to cover `a` if `a < b` and there is no element in between. We say that `b` weakly covers `a` if `a ≤ b` and there is no element between `a` and `b`. In a partial order this is equivalent to `a ⋖ b ∨ a = b`, in a preorder this is equivalent to `a ⋖ b ∨ (a ≤ b ∧ b ≤ a)` ## Notation * `a ⋖ b` means that `b` covers `a`. * `a ⩿ b` means that `b` weakly covers `a`. -/ open set order_dual variables {α β : Type*} section weakly_covers section preorder variables [preorder α] [preorder β] {a b c: α} /-- `wcovby a b` means that `a = b` or `b` covers `a`. This means that `a ≤ b` and there is no element in between. -/ def wcovby (a b : α) : Prop := a ≤ b ∧ ∀ ⦃c⦄, a < c → ¬ c < b infix ` ⩿ `:50 := wcovby lemma wcovby.le (h : a ⩿ b) : a ≤ b := h.1 lemma wcovby.refl (a : α) : a ⩿ a := ⟨le_rfl, λ c hc, hc.not_lt⟩ lemma wcovby.rfl : a ⩿ a := wcovby.refl a protected lemma eq.wcovby (h : a = b) : a ⩿ b := h ▸ wcovby.rfl lemma wcovby_of_le_of_le (h1 : a ≤ b) (h2 : b ≤ a) : a ⩿ b := ⟨h1, λ c hac hcb, (hac.trans hcb).not_le h2⟩ alias wcovby_of_le_of_le ← has_le.le.wcovby_of_le lemma wcovby.wcovby_iff_le (hab : a ⩿ b) : b ⩿ a ↔ b ≤ a := ⟨λ h, h.le, λ h, h.wcovby_of_le hab.le⟩ lemma wcovby_of_eq_or_eq (hab : a ≤ b) (h : ∀ c, a ≤ c → c ≤ b → c = a ∨ c = b) : a ⩿ b := ⟨hab, λ c ha hb, (h c ha.le hb.le).elim ha.ne' hb.ne⟩ /-- If `a ≤ b`, then `b` does not cover `a` iff there's an element in between. -/ lemma not_wcovby_iff (h : a ≤ b) : ¬ a ⩿ b ↔ ∃ c, a < c ∧ c < b := by simp_rw [wcovby, h, true_and, not_forall, exists_prop, not_not] instance wcovby.is_refl : is_refl α (⩿) := ⟨wcovby.refl⟩ lemma wcovby.Ioo_eq (h : a ⩿ b) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x hx, h.2 hx.1 hx.2 lemma wcovby.of_image (f : α ↪o β) (h : f a ⩿ f b) : a ⩿ b := ⟨f.le_iff_le.mp h.le, λ c hac hcb, h.2 (f.lt_iff_lt.mpr hac) (f.lt_iff_lt.mpr hcb)⟩ lemma wcovby.image (f : α ↪o β) (hab : a ⩿ b) (h : (range f).ord_connected) : f a ⩿ f b := begin refine ⟨f.monotone hab.le, λ c ha hb, _⟩, obtain ⟨c, rfl⟩ := h.out (mem_range_self _) (mem_range_self _) ⟨ha.le, hb.le⟩, rw f.lt_iff_lt at ha hb, exact hab.2 ha hb, end lemma set.ord_connected.apply_wcovby_apply_iff (f : α ↪o β) (h : (range f).ord_connected) : f a ⩿ f b ↔ a ⩿ b := ⟨λ h2, h2.of_image f, λ hab, hab.image f h⟩ @[simp] lemma apply_wcovby_apply_iff {E : Type*} [order_iso_class E α β] (e : E) : e a ⩿ e b ↔ a ⩿ b := (ord_connected_range (e : α ≃o β)).apply_wcovby_apply_iff ((e : α ≃o β) : α ↪o β) @[simp] lemma to_dual_wcovby_to_dual_iff : to_dual b ⩿ to_dual a ↔ a ⩿ b := and_congr_right' $ forall_congr $ λ c, forall_swap @[simp] lemma of_dual_wcovby_of_dual_iff {a b : αᵒᵈ} : of_dual a ⩿ of_dual b ↔ b ⩿ a := and_congr_right' $ forall_congr $ λ c, forall_swap alias to_dual_wcovby_to_dual_iff ↔ _ wcovby.to_dual alias of_dual_wcovby_of_dual_iff ↔ _ wcovby.of_dual end preorder section partial_order variables [partial_order α] {a b c : α} lemma wcovby.eq_or_eq (h : a ⩿ b) (h2 : a ≤ c) (h3 : c ≤ b) : c = a ∨ c = b := begin rcases h2.eq_or_lt with h2|h2, { exact or.inl h2.symm }, rcases h3.eq_or_lt with h3|h3, { exact or.inr h3 }, exact (h.2 h2 h3).elim end lemma wcovby.le_and_le_iff (h : a ⩿ b) : a ≤ c ∧ c ≤ b ↔ c = a ∨ c = b := begin refine ⟨λ h2, h.eq_or_eq h2.1 h2.2, _⟩, rintro (rfl|rfl), exacts [⟨le_rfl, h.le⟩, ⟨h.le, le_rfl⟩] end lemma wcovby.Icc_eq (h : a ⩿ b) : Icc a b = {a, b} := by { ext c, exact h.le_and_le_iff } lemma wcovby.Ico_subset (h : a ⩿ b) : Ico a b ⊆ {a} := by rw [← Icc_diff_right, h.Icc_eq, diff_singleton_subset_iff, pair_comm] lemma wcovby.Ioc_subset (h : a ⩿ b) : Ioc a b ⊆ {b} := by rw [← Icc_diff_left, h.Icc_eq, diff_singleton_subset_iff] end partial_order end weakly_covers section has_lt variables [has_lt α] {a b : α} /-- `covby a b` means that `b` covers `a`: `a < b` and there is no element in between. -/ def covby (a b : α) : Prop := a < b ∧ ∀ ⦃c⦄, a < c → ¬ c < b infix ` ⋖ `:50 := covby lemma covby.lt (h : a ⋖ b) : a < b := h.1 /-- If `a < b`, then `b` does not cover `a` iff there's an element in between. -/ lemma not_covby_iff (h : a < b) : ¬a ⋖ b ↔ ∃ c, a < c ∧ c < b := by simp_rw [covby, h, true_and, not_forall, exists_prop, not_not] alias not_covby_iff ↔ exists_lt_lt_of_not_covby _ alias exists_lt_lt_of_not_covby ← has_lt.lt.exists_lt_lt /-- In a dense order, nothing covers anything. -/ lemma not_covby [densely_ordered α] : ¬ a ⋖ b := λ h, let ⟨c, hc⟩ := exists_between h.1 in h.2 hc.1 hc.2 lemma densely_ordered_iff_forall_not_covby : densely_ordered α ↔ ∀ a b : α, ¬ a ⋖ b := ⟨λ h a b, @not_covby _ _ _ _ h, λ h, ⟨λ a b hab, exists_lt_lt_of_not_covby hab $ h _ _⟩⟩ @[simp] lemma to_dual_covby_to_dual_iff : to_dual b ⋖ to_dual a ↔ a ⋖ b := and_congr_right' $ forall_congr $ λ c, forall_swap @[simp] lemma of_dual_covby_of_dual_iff {a b : αᵒᵈ} : of_dual a ⋖ of_dual b ↔ b ⋖ a := and_congr_right' $ forall_congr $ λ c, forall_swap alias to_dual_covby_to_dual_iff ↔ _ covby.to_dual alias of_dual_covby_of_dual_iff ↔ _ covby.of_dual end has_lt section preorder variables [preorder α] [preorder β] {a b : α} lemma covby.le (h : a ⋖ b) : a ≤ b := h.1.le protected lemma covby.ne (h : a ⋖ b) : a ≠ b := h.lt.ne lemma covby.ne' (h : a ⋖ b) : b ≠ a := h.lt.ne' protected lemma covby.wcovby (h : a ⋖ b) : a ⩿ b := ⟨h.le, h.2⟩ lemma wcovby.covby_of_not_le (h : a ⩿ b) (h2 : ¬ b ≤ a) : a ⋖ b := ⟨h.le.lt_of_not_le h2, h.2⟩ lemma wcovby.covby_of_lt (h : a ⩿ b) (h2 : a < b) : a ⋖ b := ⟨h2, h.2⟩ lemma covby_iff_wcovby_and_lt : a ⋖ b ↔ a ⩿ b ∧ a < b := ⟨λ h, ⟨h.wcovby, h.lt⟩, λ h, h.1.covby_of_lt h.2⟩ lemma covby_iff_wcovby_and_not_le : a ⋖ b ↔ a ⩿ b ∧ ¬ b ≤ a := ⟨λ h, ⟨h.wcovby, h.lt.not_le⟩, λ h, h.1.covby_of_not_le h.2⟩ lemma wcovby_iff_covby_or_le_and_le : a ⩿ b ↔ a ⋖ b ∨ (a ≤ b ∧ b ≤ a) := ⟨λ h, or_iff_not_imp_right.mpr $ λ h', h.covby_of_not_le $ λ hba, h' ⟨h.le, hba⟩, λ h', h'.elim (λ h, h.wcovby) (λ h, h.1.wcovby_of_le h.2)⟩ instance : is_nonstrict_strict_order α (⩿) (⋖) := ⟨λ a b, covby_iff_wcovby_and_not_le.trans $ and_congr_right $ λ h, h.wcovby_iff_le.not.symm⟩ instance covby.is_irrefl : is_irrefl α (⋖) := ⟨λ a ha, ha.ne rfl⟩ lemma covby.Ioo_eq (h : a ⋖ b) : Ioo a b = ∅ := h.wcovby.Ioo_eq lemma covby.of_image (f : α ↪o β) (h : f a ⋖ f b) : a ⋖ b := ⟨f.lt_iff_lt.mp h.lt, λ c hac hcb, h.2 (f.lt_iff_lt.mpr hac) (f.lt_iff_lt.mpr hcb)⟩ lemma covby.image (f : α ↪o β) (hab : a ⋖ b) (h : (range f).ord_connected) : f a ⋖ f b := (hab.wcovby.image f h).covby_of_lt $ f.strict_mono hab.lt lemma set.ord_connected.apply_covby_apply_iff (f : α ↪o β) (h : (range f).ord_connected) : f a ⋖ f b ↔ a ⋖ b := ⟨covby.of_image f, λ hab, hab.image f h⟩ @[simp] lemma apply_covby_apply_iff {E : Type*} [order_iso_class E α β] (e : E) : e a ⋖ e b ↔ a ⋖ b := (ord_connected_range (e : α ≃o β)).apply_covby_apply_iff ((e : α ≃o β) : α ↪o β) end preorder section partial_order variables [partial_order α] {a b : α} lemma wcovby.covby_of_ne (h : a ⩿ b) (h2 : a ≠ b) : a ⋖ b := ⟨h.le.lt_of_ne h2, h.2⟩ lemma covby_iff_wcovby_and_ne : a ⋖ b ↔ a ⩿ b ∧ a ≠ b := ⟨λ h, ⟨h.wcovby, h.ne⟩, λ h, h.1.covby_of_ne h.2⟩ lemma wcovby_iff_covby_or_eq : a ⩿ b ↔ a ⋖ b ∨ a = b := by rw [le_antisymm_iff, wcovby_iff_covby_or_le_and_le] lemma covby.Ico_eq (h : a ⋖ b) : Ico a b = {a} := by rw [←Ioo_union_left h.lt, h.Ioo_eq, empty_union] lemma covby.Ioc_eq (h : a ⋖ b) : Ioc a b = {b} := by rw [←Ioo_union_right h.lt, h.Ioo_eq, empty_union] lemma covby.Icc_eq (h : a ⋖ b) : Icc a b = {a, b} := h.wcovby.Icc_eq end partial_order section linear_order variables [linear_order α] {a b : α} lemma covby.Ioi_eq (h : a ⋖ b) : Ioi a = Ici b := by rw [← Ioo_union_Ici_eq_Ioi h.lt, h.Ioo_eq, empty_union] lemma covby.Iio_eq (h : a ⋖ b) : Iio b = Iic a := by rw [← Iic_union_Ioo_eq_Iio h.lt, h.Ioo_eq, union_empty] end linear_order namespace set lemma wcovby_insert (x : α) (s : set α) : s ⩿ insert x s := begin refine wcovby_of_eq_or_eq (subset_insert x s) (λ t hst h2t, _), by_cases h : x ∈ t, { exact or.inr (subset_antisymm h2t $ insert_subset.mpr ⟨h, hst⟩) }, { refine or.inl (subset_antisymm _ hst), rwa [← diff_singleton_eq_self h, diff_singleton_subset_iff] } end lemma covby_insert {x : α} {s : set α} (hx : x ∉ s) : s ⋖ insert x s := (wcovby_insert x s).covby_of_lt $ ssubset_insert hx end set