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
f57624dad0e1b1e9068f383c5c26da0a361330e8
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/tools/super/clause.lean
a44deac0cbd4fb23371a749b69b001d11fcf1e0c
[ "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
8,704
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import init.meta.tactic .utils .trim open expr list tactic monad decidable namespace super meta def is_local_not (local_false : expr) (e : expr) : option expr := match e with | (pi _ _ a b) := if b = local_false then some a else none | _ := if local_false = false_ then is_not e else none end meta structure clause := (num_quants : ℕ) (num_lits : ℕ) (proof : expr) (type : expr) (local_false : expr) namespace clause meta def num_binders (c : clause) : ℕ := num_quants c + num_lits c meta def inst (c : clause) (e : expr) : clause := (if num_quants c > 0 then mk (num_quants c - 1) (num_lits c) else mk 0 (num_lits c - 1)) (app (proof c) e) (instantiate_var (binding_body (type c)) e) c^.local_false meta def instn (c : clause) (es : list expr) : clause := foldr (λe c', inst c' e) c es meta def open_const (c : clause) : tactic (clause × expr) := do n ← mk_fresh_name, b ← return $ local_const n (binding_name (type c)) (binding_info (type c)) (binding_domain (type c)), return (inst c b, b) meta def open_meta (c : clause) : tactic (clause × expr) := do b ← mk_meta_var (binding_domain (type c)), return (inst c b, b) meta def close_const (c : clause) (e : expr) : clause := match e with | local_const uniq pp info t := let abst_type' := abstract_local (type c) (local_uniq_name e) in let type' := pi pp binder_info.default t (abstract_local (type c) uniq) in let abs_prf := abstract_local (proof c) uniq in let proof' := lambdas [e] c^.proof in if num_quants c > 0 ∨ has_var abst_type' then { c with num_quants := c^.num_quants + 1, proof := proof', type := type' } else { c with num_lits := c^.num_lits + 1, proof := proof', type := type' } | _ := ⟨0, 0, default expr, default expr, default expr⟩ end meta def open_constn : clause → ℕ → tactic (clause × list expr) | c 0 := return (c, nil) | c (n+1) := do (c', b) ← open_const c, (c'', bs) ← open_constn c' n, return (c'', b::bs) meta def open_metan : clause → ℕ → tactic (clause × list expr) | c 0 := return (c, nil) | c (n+1) := do (c', b) ← open_meta c, (c'', bs) ← open_metan c' n, return (c'', b::bs) meta def close_constn : clause → list expr → clause | c [] := c | c (b::bs') := close_const (close_constn c bs') b private meta def parse_clause (local_false : expr) : expr → expr → tactic clause | proof (pi n bi d b) := do lc_n ← mk_fresh_name, lc ← return $ local_const lc_n n bi d, c ← parse_clause (app proof lc) (instantiate_var b lc), return $ c^.close_const $ local_const lc_n n binder_info.default d | proof (app (const ``not []) formula) := parse_clause proof (formula^.imp false_) | proof type := if type = local_false then do return { num_quants := 0, num_lits := 0, proof := proof, type := type, local_false := local_false } else do univ ← infer_univ type, not_type ← return $ imp type local_false, parse_clause (lam `H binder_info.default not_type $ app (mk_var 0) proof) (imp not_type local_false) meta def of_proof_and_type (local_false proof type : expr) : tactic clause := parse_clause local_false proof type meta def of_proof (local_false proof : expr) : tactic clause := do type ← infer_type proof, of_proof_and_type local_false proof type meta def of_classical_proof (proof : expr) : tactic clause := of_proof false_ proof meta def inst_mvars (c : clause) : tactic clause := do proof' ← instantiate_mvars (proof c), type' ← instantiate_mvars (type c), return { c with proof := proof', type := type' } meta inductive literal | left : expr → literal | right : expr → literal namespace literal meta instance : decidable_eq literal := by mk_dec_eq_instance meta def formula : literal → expr | (left f) := f | (right f) := f meta def is_neg : literal → bool | (left _) := tt | (right _) := ff meta def is_pos (l : literal) : bool := bnot l^.is_neg meta def to_formula (l : literal) : expr := if l^.is_neg then app (const ``not []) l^.formula else formula l meta def type_str : literal → string | (literal.left _) := "left" | (literal.right _) := "right" meta instance : has_to_tactic_format literal := ⟨λl, do pp_f ← pp l^.formula, return $ to_fmt l^.type_str ++ " (" ++ pp_f ++ ")"⟩ end literal private meta def get_binding_body : expr → ℕ → expr | e 0 := e | e (i+1) := get_binding_body e^.binding_body i meta def get_binder (e : expr) (i : nat) := binding_domain (get_binding_body e i) meta def validate (c : clause) : tactic unit := do concl ← return $ get_binding_body c^.type c^.num_binders, unify concl c^.local_false <|> (do pp_concl ← pp concl, pp_lf ← pp c^.local_false, fail $ to_fmt "wrong local false: " ++ pp_concl ++ " =!= " ++ pp_lf), type' ← infer_type c^.proof, unify c^.type type' <|> (do pp_ty ← pp c^.type, pp_ty' ← pp type', fail (to_fmt "wrong type: " ++ pp_ty ++ " =!= " ++ pp_ty')) meta def get_lit (c : clause) (i : nat) : literal := let bind := get_binder (type c) (num_quants c + i) in match is_local_not c^.local_false bind with | some formula := literal.right formula | none := literal.left bind end meta def lits_where (c : clause) (p : literal → bool) : list nat := list.filter (λl, p (get_lit c l)) (range (num_lits c)) meta def get_lits (c : clause) : list literal := list.map (get_lit c) (range c^.num_lits) private meta def tactic_format (c : clause) : tactic format := do c ← c^.open_metan c^.num_quants, pp (do l ← c.1^.get_lits, [l^.to_formula]) meta instance : has_to_tactic_format clause := ⟨tactic_format⟩ meta def is_maximal (gt : expr → expr → bool) (c : clause) (i : nat) : bool := list.empty (list.filter (λj, gt (get_lit c j)^.formula (get_lit c i)^.formula) (range c^.num_lits)) meta def normalize (c : clause) : tactic clause := do opened ← open_constn c (num_binders c), lconsts_in_types ← return $ contained_lconsts_list (list.map local_type opened.2), quants' ← return $ list.filter (λlc, rb_map.contains lconsts_in_types (local_uniq_name lc)) opened.2, lits' ← return $ list.filter (λlc, ¬rb_map.contains lconsts_in_types (local_uniq_name lc)) opened.2, return $ close_constn opened.1 (quants' ++ lits') meta def whnf_head_lit (c : clause) : tactic clause := do atom' ← whnf $ literal.formula $ get_lit c 0, return $ if literal.is_neg (get_lit c 0) then { c with type := imp atom' (binding_body c^.type) } else { c with type := imp (app (const ``not []) atom') c^.type^.binding_body } end clause meta def unify_lit (l1 l2 : clause.literal) : tactic unit := if clause.literal.is_pos l1 = clause.literal.is_pos l2 then unify (clause.literal.formula l1) (clause.literal.formula l2) transparency.none else fail "cannot unify literals" -- FIXME: this is most definitely broken with meta-variables that were already in the goal meta def sort_and_constify_metas : list expr → tactic (list expr) | exprs_with_metas := do inst_exprs ← mapm instantiate_mvars exprs_with_metas, metas ← return $ inst_exprs >>= get_metas, match list.filter (λm, ¬has_meta_var (get_meta_type m)) metas with | [] := if metas^.empty then return [] else do for' metas (λm, do trace (expr.to_string m), t ← infer_type m, trace (expr.to_string t)), fail "could not sort metas" | ((mvar n t) :: _) := do c ← infer_type (mvar n t) >>= mk_local_def `x, unify c (mvar n t), rest ← sort_and_constify_metas metas, c ← instantiate_mvars c, return ([c] ++ rest) | _ := failed end namespace clause meta def meta_closure (metas : list expr) (qf : clause) : tactic clause := do bs ← sort_and_constify_metas metas, qf' ← clause.inst_mvars qf, clause.inst_mvars $ clause.close_constn qf' bs private meta def distinct' (local_false : expr) : list expr → expr → clause | [] proof := ⟨ 0, 0, proof, local_false, local_false ⟩ | (h::hs) proof := let (dups, rest) := partition (λh' : expr, h^.local_type = h'^.local_type) hs, proof_wo_dups := foldl (λproof (h' : expr), instantiate_var (abstract_local proof h'^.local_uniq_name) h) proof dups in (distinct' rest proof_wo_dups)^.close_const h meta def distinct (c : clause) : tactic clause := do (qf, vs) ← c^.open_constn c^.num_quants, (fls, hs) ← qf^.open_constn qf^.num_lits, return $ (distinct' c^.local_false hs fls^.proof)^.close_constn vs end clause end super
d42db64dca8e7edc7fa3edfec34da0fe4f895d82
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/algebra/group_power/lemmas.lean
b347f752e529c8c94f1eeb0d5d6027d9ae792a1c
[ "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
28,509
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.group_power.basic import algebra.opposites import data.list.basic import data.int.cast import data.equiv.basic import data.equiv.mul_add import deprecated.group /-! # Lemmas about power operations on monoids and groups This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `gsmul` which require additional imports besides those available in `.basic`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n •ℕ (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n •ℕ (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩ (one_nsmul _) @[simp, priority 500] theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n := begin induction n with n ih, { refl }, { rw [list.repeat_succ, list.prod_cons, ih], refl, } end @[simp, priority 500] theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n •ℕ a := @list.prod_repeat (multiplicative A) _ @[simp, norm_cast] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n := (units.coe_hom M).map_pow u n lemma is_unit_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : is_unit x := begin cases n, { exact (nat.not_lt_zero _ hn).elim }, refine ⟨⟨x, x ^ n, _, _⟩, rfl⟩, { rwa [pow_succ] at hx }, { rwa [pow_succ'] at hx } end end monoid theorem nat.nsmul_eq_mul (m n : ℕ) : m •ℕ n = m * n := by induction m with m ih; [rw [zero_nsmul, zero_mul], rw [succ_nsmul', ih, nat.succ_mul]] section group variables [group G] [group H] [add_group A] [add_group B] open int local attribute [ematch] le_of_lt open nat theorem gsmul_one [has_one A] (n : ℤ) : n •ℤ (1 : A) = n := by cases n; simp lemma gpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a | (of_nat n) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+0] := by simp [int.neg_succ_of_nat_eq] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg, ← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev, inv_mul_cancel_right] theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) •ℤ a = i •ℤ a + a := @gpow_add_one (multiplicative A) _ lemma gpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm ... = a^n * a⁻¹ : by rw [← gpow_add_one, sub_add_cancel] lemma gpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, gpow_add_one, ihn, mul_assoc] }, { rw [gpow_sub_one, ← mul_assoc, ← ihn, ← gpow_sub_one, add_sub_assoc] } end lemma mul_self_gpow (b : G) (m : ℤ) : b*b^m = b^(m+1) := by { conv_lhs {congr, rw ← gpow_one b }, rw [← gpow_add, add_comm] } lemma mul_gpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) := by { conv_lhs {congr, skip, rw ← gpow_one b }, rw [← gpow_add, add_comm] } theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) •ℤ a = i •ℤ a + j •ℤ a := @gpow_add (multiplicative A) _ lemma gpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by rw [sub_eq_add_neg, gpow_add, gpow_neg] lemma sub_gsmul (m n : ℤ) (a : A) : (m - n) •ℤ a = m •ℤ a - n •ℤ a := by simpa only [sub_eq_add_neg] using @gpow_sub (multiplicative A) _ _ _ _ theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) •ℤ a = a + i •ℤ a := @gpow_one_add (multiplicative A) _ theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : A) (i j), i •ℤ a + j •ℤ a = j •ℤ a + i •ℤ a := @gpow_mul_comm (multiplicative A) _ theorem gpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n := int.induction_on n (by simp) (λ n ihn, by simp [mul_add, gpow_add, ihn]) (λ n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one]) theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n •ℤ a = n •ℤ (m •ℤ a) := @gpow_mul (multiplicative A) _ theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : A) (m n : ℤ) : m * n •ℤ a = m •ℤ (n •ℤ a) := by rw [mul_comm, gsmul_mul'] theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n •ℤ a = n •ℤ a + n •ℤ a := gpow_add _ _ _ theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add, gpow_bit0, gpow_one] theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n •ℤ a = n •ℤ a + n •ℤ a + a := @gpow_bit1 (multiplicative A) _ @[simp] theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)] @[simp] theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n •ℤ a) = n •ℤ f a := f.to_multiplicative.map_gpow a n @[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n := (units.coe_hom G).map_gpow u n end group section ordered_add_comm_group variables [ordered_add_comm_group A] /-! Lemmas about `gsmul` under ordering, placed here (rather than in `algebra.group_power.basic` with their friends) because they require facts from `data.int.basic`-/ open int lemma gsmul_pos {a : A} (ha : 0 < a) {k : ℤ} (hk : (0:ℤ) < k) : 0 < k •ℤ a := begin lift k to ℕ using int.le_of_lt hk, apply nsmul_pos ha, exact coe_nat_pos.mp hk, end theorem gsmul_le_gsmul {a : A} {n m : ℤ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℤ a ≤ m •ℤ a := calc n •ℤ a = n •ℤ a + 0 : (add_zero _).symm ... ≤ n •ℤ a + (m - n) •ℤ a : add_le_add_left (gsmul_nonneg ha (sub_nonneg.mpr h)) _ ... = m •ℤ a : by { rw [← add_gsmul], simp } theorem gsmul_lt_gsmul {a : A} {n m : ℤ} (ha : 0 < a) (h : n < m) : n •ℤ a < m •ℤ a := calc n •ℤ a = n •ℤ a + 0 : (add_zero _).symm ... < n •ℤ a + (m - n) •ℤ a : add_lt_add_left (gsmul_pos ha (sub_pos.mpr h)) _ ... = m •ℤ a : by { rw [← add_gsmul], simp } end ordered_add_comm_group section linear_ordered_add_comm_group variable [linear_ordered_add_comm_group A] theorem gsmul_le_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n •ℤ a ≤ m •ℤ a ↔ n ≤ m := begin refine ⟨λ h, _, gsmul_le_gsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (gsmul_lt_gsmul ha (not_le.mp H)) h) end theorem gsmul_lt_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n •ℤ a < m •ℤ a ↔ n < m := begin refine ⟨λ h, _, gsmul_lt_gsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (gsmul_le_gsmul (le_of_lt ha) $ not_lt.mp H) h) end theorem nsmul_le_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n •ℕ a ≤ m •ℕ a ↔ n ≤ m := begin refine ⟨λ h, _, nsmul_le_nsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (nsmul_lt_nsmul ha (not_le.mp H)) h) end theorem nsmul_lt_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n •ℕ a < m •ℕ a ↔ n < m := begin refine ⟨λ h, _, nsmul_lt_nsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (nsmul_le_nsmul (le_of_lt ha) $ not_lt.mp H) h) end end linear_ordered_add_comm_group @[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) : ((nsmul n a : A) : with_bot A) = nsmul n a := add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n •ℕ a = a * n := by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero], rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]] @[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n •ℕ a = n * a := by rw [nsmul_eq_mul', (n.cast_commute a).eq] theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = a * (n •ℕ b) := by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc] theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = n •ℕ a * b := by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc] @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [pow_succ', pow_succ', nat.cast_mul, ih]] @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [pow_succ', pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, pow_succ', ih]] -- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. lemma bit0_mul [ring R] {n r : R} : bit0 n * r = gsmul 2 (n * r) := by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], } lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = gsmul 2 (r * n) := by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], } lemma bit1_mul [ring R] {n r : R} : bit1 n * r = gsmul 2 (n * r) + r := by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], } lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = gsmul 2 (r * n) + r := by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], } @[simp] theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a | (n : ℕ) := nsmul_eq_mul _ _ | -[1+ n] := show -(_ •ℕ _)=-_*_, by rw [neg_mul_eq_neg_mul_symm, nsmul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, (n.cast_commute a).eq] theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp] lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul] lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] section ordered_semiring variable [ordered_semiring R] /-- Bernoulli's inequality. This version works for semirings but requires additional hypotheses `0 ≤ a * a` and `0 ≤ (1 + a) * (1 + a)`. -/ theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (Hsqr' : 0 ≤ (1 + a) * (1 + a)) (H : 0 ≤ 2 + a) : ∀ (n : ℕ), 1 + (n : R) * a ≤ (1 + a) ^ n | 0 := by simp | 1 := by simp | (n+2) := have 0 ≤ (n : R) * (a * a * (2 + a)) + a * a, from add_nonneg (mul_nonneg n.cast_nonneg (mul_nonneg Hsqr H)) Hsqr, calc 1 + (↑(n + 2) : R) * a ≤ 1 + ↑(n + 2) * a + (n * (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n * a) : by { simp [add_mul, mul_add, bit0, mul_assoc, (n.cast_commute (_ : R)).left_comm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) Hsqr' ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp only [add_zero], rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_lt_pow_iff_of_lt_one {a : R} {n m : ℕ} (hpos : 0 < a) (h : a < 1) : a ^ m < a ^ n ↔ n < m := begin have : strict_mono (λ (n : order_dual ℕ), a ^ (id n : ℕ)) := λ m n, pow_lt_pow_of_lt_one hpos h, exact this.lt_iff_lt end lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : R) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end ordered_semiring section linear_ordered_semiring variables [linear_ordered_semiring R] lemma sign_cases_of_C_mul_pow_nonneg {C r : R} (h : ∀ n : ℕ, 0 ≤ C * r ^ n) : C = 0 ∨ (0 < C ∧ 0 ≤ r) := begin have : 0 ≤ C, by simpa only [pow_zero, mul_one] using h 0, refine this.eq_or_lt.elim (λ h, or.inl h.symm) (λ hC, or.inr ⟨hC, _⟩), refine nonneg_of_mul_nonneg_left _ hC, simpa only [pow_one] using h 1 end end linear_ordered_semiring section linear_ordered_ring variables [linear_ordered_ring R] @[simp] lemma abs_pow (a : R) (n : ℕ) : abs (a ^ n) = abs a ^ n := abs_hom.to_monoid_hom.map_pow a n @[simp] theorem pow_bit1_neg_iff {a : R} {n : ℕ} : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ pow_nonneg h' _, λ h, mul_neg_of_neg_of_pos h (pow_bit0_pos h.ne _)⟩ @[simp] theorem pow_bit1_nonneg_iff {a : R} {n : ℕ} : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 pow_bit1_neg_iff @[simp] theorem pow_bit1_nonpos_iff {a : R} {n : ℕ} : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := by simp only [le_iff_lt_or_eq, pow_bit1_neg_iff, pow_eq_zero_iff (bit1_pos (zero_le n))] @[simp] theorem pow_bit1_pos_iff {a : R} {n : ℕ} : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le pow_bit1_nonpos_iff lemma strict_mono_pow_bit1 (n : ℕ) : strict_mono (λ a : R, a ^ bit1 n) := begin intros a b hab, cases le_total a 0 with ha ha, { cases le_or_lt b 0 with hb hb, { rw [← neg_lt_neg_iff, ← neg_pow_bit1, ← neg_pow_bit1], exact pow_lt_pow_of_lt_left (neg_lt_neg hab) (neg_nonneg.2 hb) (bit1_pos (zero_le n)) }, { exact (pow_bit1_nonpos_iff.2 ha).trans_lt (pow_bit1_pos_iff.2 hb) } }, { exact pow_lt_pow_of_lt_left hab ha (bit1_pos (zero_le n)) } end /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow {a : R} (H : -2 ≤ a) (n : ℕ) : 1 + (n : R) * a ≤ (1 + a) ^ n := one_add_mul_le_pow' (mul_self_nonneg _) (mul_self_nonneg _) (neg_le_iff_add_nonneg'.1 H) _ /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_mul_sub_le_pow {a : R} (H : -1 ≤ a) (n : ℕ) : 1 + (n : R) * (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by rwa [bit0, neg_add, ← sub_eq_add_neg, sub_le_sub_iff_right], by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n end linear_ordered_ring /-- Bernoulli's inequality reformulated to estimate `(n : K)`. -/ theorem nat.cast_le_pow_sub_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ (a ^ n - 1) / (a - 1) := (le_div_iff (sub_pos.2 H)).2 $ le_sub_left_of_add_le $ one_add_mul_sub_le_pow ((neg_le_self $ @zero_le_one K _).trans H.le) _ /-- For any `a > 1` and a natural `n` we have `n ≤ a ^ n / (a - 1)`. See also `nat.cast_le_pow_sub_div_sub` for a stronger inequality with `a ^ n - 1` in the numerator. -/ theorem nat.cast_le_pow_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ a ^ n / (a - 1) := (n.cast_le_pow_sub_div_sub H).trans $ div_le_div_of_le (sub_nonneg.2 H.le) (sub_le_self _ zero_le_one) namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (pow_two u).symm ▸ units_mul_self u lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] @[simp] lemma nat_abs_pow_two (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 := by rw [pow_two, int.nat_abs_mul_self', pow_two] lemma abs_le_self_pow_two (a : ℤ) : (int.nat_abs a : ℤ) ≤ a ^ 2 := by { rw [← int.nat_abs_pow_two a, pow_two], norm_cast, apply nat.le_mul_self } lemma le_self_pow_two (b : ℤ) : b ≤ b ^ 2 := le_trans (le_nat_abs) (abs_le_self_pow_two _) end int variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, pow_zero x, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := gpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← of_add_gsmul ] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n •ℕ x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_nsmul, right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n •ℤ x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_gsmul, right_inv := λ f, add_monoid_hom.ext_int $ one_gsmul (f 1) } variables {M G A} @[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) : powers_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) : (powers_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma gpowers_hom_apply [group G] (x : G) (n : multiplicative ℤ) : gpowers_hom G x n = x ^ n.to_add := rfl @[simp] lemma gpowers_hom_symm_apply [group G] (f : multiplicative ℤ →* G) : (gpowers_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_hom_apply [add_monoid A] (x : A) (n : ℕ) : multiples_hom A x n = n •ℕ x := rfl @[simp] lemma multiples_hom_symm_apply [add_monoid A] (f : ℕ →+ A) : (multiples_hom A).symm f = f 1 := rfl @[simp] lemma gmultiples_hom_apply [add_group A] (x : A) (n : ℤ) : gmultiples_hom A x n = n •ℤ x := rfl @[simp] lemma gmultiples_hom_symm_apply [add_group A] (f : ℤ →+ A) : (gmultiples_hom A).symm f = f 1 := rfl lemma monoid_hom.apply_mnat [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply] @[ext] lemma monoid_hom.ext_mnat [monoid M] ⦃f g : multiplicative ℕ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [f.apply_mnat, g.apply_mnat, h] lemma monoid_hom.apply_mint [group M] (f : multiplicative ℤ →* M) (n : multiplicative ℤ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← gpowers_hom_symm_apply, ← gpowers_hom_apply, equiv.apply_symm_apply] @[ext] lemma monoid_hom.ext_mint [group M] ⦃f g : multiplicative ℤ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [f.apply_mint, g.apply_mint, h] lemma add_monoid_hom.apply_nat [add_monoid M] (f : ℕ →+ M) (n : ℕ) : f n = n •ℕ (f 1) := by rw [← multiples_hom_symm_apply, ← multiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_nat` is defined in `data.nat.cast` -/ lemma add_monoid_hom.apply_int [add_group M] (f : ℤ →+ M) (n : ℤ) : f n = n •ℤ (f 1) := by rw [← gmultiples_hom_symm_apply, ← gmultiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_int` is defined in `data.int.cast` -/ variables (M G A) /-- If `M` is commutative, `powers_hom` is a multiplicative equivalence. -/ def powers_mul_hom [comm_monoid M] : M ≃* (multiplicative ℕ →* M) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_pow], ..powers_hom M} /-- If `M` is commutative, `gpowers_hom` is a multiplicative equivalence. -/ def gpowers_mul_hom [comm_group G] : G ≃* (multiplicative ℤ →* G) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_gpow], ..gpowers_hom G} /-- If `M` is commutative, `multiples_hom` is an additive equivalence. -/ def multiples_add_hom [add_comm_monoid A] : A ≃+ (ℕ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [nsmul_add], ..multiples_hom A} /-- If `M` is commutative, `gmultiples_hom` is an additive equivalence. -/ def gmultiples_add_hom [add_comm_group A] : A ≃+ (ℤ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [gsmul_add], ..gmultiples_hom A} variables {M G A} @[simp] lemma powers_mul_hom_apply [comm_monoid M] (x : M) (n : multiplicative ℕ) : powers_mul_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_mul_hom_symm_apply [comm_monoid M] (f : multiplicative ℕ →* M) : (powers_mul_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma gpowers_mul_hom_apply [comm_group G] (x : G) (n : multiplicative ℤ) : gpowers_mul_hom G x n = x ^ n.to_add := rfl @[simp] lemma gpowers_mul_hom_symm_apply [comm_group G] (f : multiplicative ℤ →* G) : (gpowers_mul_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_add_hom_apply [add_comm_monoid A] (x : A) (n : ℕ) : multiples_add_hom A x n = n •ℕ x := rfl @[simp] lemma multiples_add_hom_symm_apply [add_comm_monoid A] (f : ℕ →+ A) : (multiples_add_hom A).symm f = f 1 := rfl @[simp] lemma gmultiples_add_hom_apply [add_comm_group A] (x : A) (n : ℤ) : gmultiples_add_hom A x n = n •ℤ x := rfl @[simp] lemma gmultiples_add_hom_symm_apply [add_comm_group A] (f : ℤ →+ A) : (gmultiples_add_hom A).symm f = f 1 := rfl /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by section variables [semiring R] {a x y : R} @[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) := semiconj_by.mul_right (nat.commute_cast _ _) h @[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y := semiconj_by.mul_left (nat.cast_commute _ _) h @[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_nat_mul_left m).cast_nat_mul_right n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m)) | (n : ℕ) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right] | -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right] variables {a b x y x' y' : R} @[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) : semiconj_by a ((m : ℤ) * x) (m * y) := semiconj_by.mul_right (int.commute_cast _ _) h @[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y := semiconj_by.mul_left (int.cast_commute _ _) h @[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_int_mul_left m).cast_int_mul_right n end semiconj_by namespace commute section variables [semiring R] {a b : R} @[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) := h.cast_nat_mul_right n @[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b := h.cast_nat_mul_left n @[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) : commute ((m : R) * a) (n * b) := h.cast_nat_mul_cast_nat_mul m n @[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) := (commute.refl a).cast_nat_mul_right n @[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a := (commute.refl a).cast_nat_mul_left n @[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) := (commute.refl a).cast_nat_mul_cast_nat_mul m n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) : commute a (↑(u^m)) := h.units_gpow_right m @[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) : commute (↑(u^m)) a := (h.symm.units_gpow_right m).symm variables {a b : R} @[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) := h.cast_int_mul_right m @[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b := h.cast_int_mul_left m lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) := h.cast_int_mul_cast_int_mul m n variables (a) (m n : ℤ) @[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n @[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) := (commute.refl a).cast_int_mul_cast_int_mul m n end commute section multiplicative open multiplicative @[simp] lemma nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : to_add (a ^ b) = to_add a * b := begin induction b with b ih, { erw [pow_zero, to_add_one, mul_zero] }, { simp [*, pow_succ, add_comm, nat.mul_succ] } end @[simp] lemma nat.of_add_mul (a b : ℕ) : of_add (a * b) = of_add a ^ b := (nat.to_add_pow _ _).symm @[simp] lemma int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : to_add (a ^ b) = to_add a * b := by induction b; simp [*, mul_add, pow_succ, add_comm] @[simp] lemma int.to_add_gpow (a : multiplicative ℤ) (b : ℤ) : to_add (a ^ b) = to_add a * b := int.induction_on b (by simp) (by simp [gpow_add, mul_add] {contextual := tt}) (by simp [gpow_add, mul_add, sub_eq_add_neg] {contextual := tt}) @[simp] lemma int.of_add_mul (a b : ℤ) : of_add (a * b) = of_add a ^ b := (int.to_add_gpow _ _).symm end multiplicative namespace units variables [monoid M] lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) := (divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:= (u⁻¹).conj_pow x n open opposite /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] lemma op_pow (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', op_mul, h, pow_succ] } end @[simp] lemma unop_pow (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', unop_mul, h, pow_succ] } end end units
5b6937476fe9583619158260bf171a799d4be487
367134ba5a65885e863bdc4507601606690974c1
/src/data/num/bitwise.lean
a564ec8a15b69f24d4cfdd191953a0e4c9d3215d
[ "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
10,964
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.num.basic import data.bitvec.core /-! # Bitwise operations using binary representation of integers ## Definitions * bitwise operations for `pos_num` and `num`, * `snum`, a type that represents integers as a bit string with a sign bit at the end, * arithmetic operations for `snum`. -/ namespace pos_num /-- Bitwise "or" for `pos_num`. -/ def lor : pos_num → pos_num → pos_num | 1 (bit0 q) := bit1 q | 1 q := q | (bit0 p) 1 := bit1 p | p 1 := p | (bit0 p) (bit0 q) := bit0 (lor p q) | (bit0 p) (bit1 q) := bit1 (lor p q) | (bit1 p) (bit0 q) := bit1 (lor p q) | (bit1 p) (bit1 q) := bit1 (lor p q) /-- Bitwise "and" for `pos_num`. -/ def land : pos_num → pos_num → num | 1 (bit0 q) := 0 | 1 _ := 1 | (bit0 p) 1 := 0 | _ 1 := 1 | (bit0 p) (bit0 q) := num.bit0 (land p q) | (bit0 p) (bit1 q) := num.bit0 (land p q) | (bit1 p) (bit0 q) := num.bit0 (land p q) | (bit1 p) (bit1 q) := num.bit1 (land p q) /-- Bitwise `λ a b, a && !b` for `pos_num`. For example, `ldiff 5 9 = 4`: 101 1001 ---- 100 -/ def ldiff : pos_num → pos_num → num | 1 (bit0 q) := 1 | 1 _ := 0 | (bit0 p) 1 := num.pos (bit0 p) | (bit1 p) 1 := num.pos (bit0 p) | (bit0 p) (bit0 q) := num.bit0 (ldiff p q) | (bit0 p) (bit1 q) := num.bit0 (ldiff p q) | (bit1 p) (bit0 q) := num.bit1 (ldiff p q) | (bit1 p) (bit1 q) := num.bit0 (ldiff p q) /-- Bitwise "xor" for `pos_num`. -/ def lxor : pos_num → pos_num → num | 1 1 := 0 | 1 (bit0 q) := num.pos (bit1 q) | 1 (bit1 q) := num.pos (bit0 q) | (bit0 p) 1 := num.pos (bit1 p) | (bit1 p) 1 := num.pos (bit0 p) | (bit0 p) (bit0 q) := num.bit0 (lxor p q) | (bit0 p) (bit1 q) := num.bit1 (lxor p q) | (bit1 p) (bit0 q) := num.bit1 (lxor p q) | (bit1 p) (bit1 q) := num.bit0 (lxor p q) /-- `a.test_bit n` is `tt` iff the `n`-th bit (starting from the LSB) in the binary representation of `a` is active. If the size of `a` is less than `n`, this evaluates to `ff`. -/ def test_bit : pos_num → nat → bool | 1 0 := tt | 1 (n+1) := ff | (bit0 p) 0 := ff | (bit0 p) (n+1) := test_bit p n | (bit1 p) 0 := tt | (bit1 p) (n+1) := test_bit p n /-- `n.one_bits 0` is the list of indices of active bits in the binary representation of `n`. -/ def one_bits : pos_num → nat → list nat | 1 d := [d] | (bit0 p) d := one_bits p (d+1) | (bit1 p) d := d :: one_bits p (d+1) /-- Left-shift the binary representation of a `pos_num`. -/ def shiftl (p : pos_num) : nat → pos_num | 0 := p | (n+1) := bit0 (shiftl n) /-- Right-shift the binary representation of a `pos_num`. -/ def shiftr : pos_num → nat → num | p 0 := num.pos p | 1 (n+1) := 0 | (bit0 p) (n+1) := shiftr p n | (bit1 p) (n+1) := shiftr p n end pos_num namespace num /-- Bitwise "or" for `num`. -/ def lor : num → num → num | 0 q := q | p 0 := p | (pos p) (pos q) := pos (p.lor q) /-- Bitwise "and" for `num`. -/ def land : num → num → num | 0 q := 0 | p 0 := 0 | (pos p) (pos q) := p.land q /-- Bitwise `λ a b, a && !b` for `num`. For example, `ldiff 5 9 = 4`: 101 1001 ---- 100 -/ def ldiff : num → num → num | 0 q := 0 | p 0 := p | (pos p) (pos q) := p.ldiff q /-- Bitwise "xor" for `num`. -/ def lxor : num → num → num | 0 q := q | p 0 := p | (pos p) (pos q) := p.lxor q /-- Left-shift the binary representation of a `num`. -/ def shiftl : num → nat → num | 0 n := 0 | (pos p) n := pos (p.shiftl n) /-- Right-shift the binary representation of a `pos_num`. -/ def shiftr : num → nat → num | 0 n := 0 | (pos p) n := p.shiftr n /-- `a.test_bit n` is `tt` iff the `n`-th bit (starting from the LSB) in the binary representation of `a` is active. If the size of `a` is less than `n`, this evaluates to `ff`. -/ def test_bit : num → nat → bool | 0 n := ff | (pos p) n := p.test_bit n /-- `n.one_bits` is the list of indices of active bits in the binary representation of `n`. -/ def one_bits : num → list nat | 0 := [] | (pos p) := p.one_bits 0 end num /-- This is a nonzero (and "non minus one") version of `snum`. See the documentation of `snum` for more details. -/ @[derive has_reflect, derive decidable_eq] inductive nzsnum : Type | msb : bool → nzsnum | bit : bool → nzsnum → nzsnum /-- Alternative representation of integers using a sign bit at the end. The convention on sign here is to have the argument to `msb` denote the sign of the MSB itself, with all higher bits set to the negation of this sign. The result is interpreted in two's complement. 13 = ..0001101(base 2) = nz (bit1 (bit0 (bit1 (msb tt)))) -13 = ..1110011(base 2) = nz (bit1 (bit1 (bit0 (msb ff)))) As with `num`, a special case must be added for zero, which has no msb, but by two's complement symmetry there is a second special case for -1. Here the `bool` field indicates the sign of the number. 0 = ..0000000(base 2) = zero ff -1 = ..1111111(base 2) = zero tt -/ @[derive has_reflect, derive decidable_eq] inductive snum : Type | zero : bool → snum | nz : nzsnum → snum instance : has_coe nzsnum snum := ⟨snum.nz⟩ instance : has_zero snum := ⟨snum.zero ff⟩ instance : has_one nzsnum := ⟨nzsnum.msb tt⟩ instance : has_one snum := ⟨snum.nz 1⟩ instance : inhabited nzsnum := ⟨1⟩ instance : inhabited snum := ⟨0⟩ /-! The `snum` representation uses a bit string, essentially a list of 0 (`ff`) and 1 (`tt`) bits, and the negation of the MSB is sign-extended to all higher bits. -/ namespace nzsnum notation a :: b := bit a b /-- Sign of a `nzsnum`. -/ def sign : nzsnum → bool | (msb b) := bnot b | (b :: p) := sign p /-- Bitwise `not` for `nzsnum`. -/ @[pattern] def not : nzsnum → nzsnum | (msb b) := msb (bnot b) | (b :: p) := bnot b :: not p prefix ~ := not /-- Add an inactive bit at the end of a `nzsnum`. This mimics `pos_num.bit0`. -/ def bit0 : nzsnum → nzsnum := bit ff /-- Add an active bit at the end of a `nzsnum`. This mimics `pos_num.bit1`. -/ def bit1 : nzsnum → nzsnum := bit tt /-- The `head` of a `nzsnum` is the boolean value of its LSB. -/ def head : nzsnum → bool | (msb b) := b | (b :: p) := b /-- The `tail` of a `nzsnum` is the `snum` obtained by removing the LSB. Edge cases: `tail 1 = 0` and `tail (-2) = -1`. -/ def tail : nzsnum → snum | (msb b) := snum.zero (bnot b) | (b :: p) := p end nzsnum namespace snum open nzsnum /-- Sign of a `snum`. -/ def sign : snum → bool | (zero z) := z | (nz p) := p.sign /-- Bitwise `not` for `snum`. -/ @[pattern] def not : snum → snum | (zero z) := zero (bnot z) | (nz p) := ~p prefix ~ := not /-- Add a bit at the end of a `snum`. This mimics `nzsnum.bit`. -/ @[pattern] def bit : bool → snum → snum | b (zero z) := if b = z then zero b else msb b | b (nz p) := p.bit b notation a :: b := bit a b /-- Add an inactive bit at the end of a `snum`. This mimics `znum.bit0`. -/ def bit0 : snum → snum := bit ff /-- Add an active bit at the end of a `snum`. This mimics `znum.bit1`. -/ def bit1 : snum → snum := bit tt theorem bit_zero (b) : b :: zero b = zero b := by cases b; refl theorem bit_one (b) : b :: zero (bnot b) = msb b := by cases b; refl end snum namespace nzsnum open snum /-- A dependent induction principle for `nzsnum`, with base cases `0 : snum` and `(-1) : snum`. -/ def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b)) (s : Π b p, C p → C (b :: p)) : Π p : nzsnum, C p | (msb b) := by rw ←bit_one; exact s b (snum.zero (bnot b)) (z (bnot b)) | (bit b p) := s b p (drec' p) end nzsnum namespace snum open nzsnum /-- The `head` of a `snum` is the boolean value of its LSB. -/ def head : snum → bool | (zero z) := z | (nz p) := p.head /-- The `tail` of a `snum` is obtained by removing the LSB. Edge cases: `tail 1 = 0`, `tail (-2) = -1`, `tail 0 = 0` and `tail (-1) = -1`. -/ def tail : snum → snum | (zero z) := zero z | (nz p) := p.tail /-- A dependent induction principle for `snum` which avoids relying on `nzsnum`. -/ def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b)) (s : Π b p, C p → C (b :: p)) : Π p, C p | (zero b) := z b | (nz p) := p.drec' z s /-- An induction principle for `snum` which avoids relying on `nzsnum`. -/ def rec' {α} (z : bool → α) (s : bool → snum → α → α) : snum → α := drec' z s /-- `snum.test_bit n a` is `tt` iff the `n`-th bit (starting from the LSB) of `a` is active. If the size of `a` is less than `n`, this evaluates to `ff`. -/ def test_bit : nat → snum → bool | 0 p := head p | (n+1) p := test_bit n (tail p) /-- The successor of a `snum` (i.e. the operation adding one). -/ def succ : snum → snum := rec' (λ b, cond b 0 1) (λb p succp, cond b (ff :: succp) (tt :: p)) /-- The predecessor of a `snum` (i.e. the operation of removing one). -/ def pred : snum → snum := rec' (λ b, cond b (~1) ~0) (λb p predp, cond b (ff :: p) (tt :: predp)) /-- The opposite of a `snum`. -/ protected def neg (n : snum) : snum := succ ~n instance : has_neg snum := ⟨snum.neg⟩ /-- `snum.czadd a b n` is `n + a - b` (where `a` and `b` should be read as either 0 or 1). This is useful to implement the carry system in `cadd`. -/ def czadd : bool → bool → snum → snum | ff ff p := p | ff tt p := pred p | tt ff p := succ p | tt tt p := p end snum namespace snum /-- `a.bits n` is the vector of the `n` first bits of `a` (starting from the LSB). -/ def bits : snum → Π n, vector bool n | p 0 := vector.nil | p (n+1) := head p ::ᵥ bits (tail p) n def cadd : snum → snum → bool → snum := rec' (λ a p c, czadd c a p) $ λa p IH, rec' (λb c, czadd c b (a :: p)) $ λb q _ c, bitvec.xor3 a b c :: IH q (bitvec.carry a b c) /-- Add two `snum`s. -/ protected def add (a b : snum) : snum := cadd a b ff instance : has_add snum := ⟨snum.add⟩ /-- Substract two `snum`s. -/ protected def sub (a b : snum) : snum := a + -b instance : has_sub snum := ⟨snum.sub⟩ /-- Multiply two `snum`s. -/ protected def mul (a : snum) : snum → snum := rec' (λ b, cond b (-a) 0) $ λb q IH, cond b (bit0 IH + a) (bit0 IH) instance : has_mul snum := ⟨snum.mul⟩ end snum
3e06e8abfe2fbefc520649d5d74e1ffd0b716d2a
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world08/level11.lean
f0e63041314925edcd7044d023b10a54e87c0f7c
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
177
lean
lemma add_right_eq_zero {a b : mynat} : a + b = 0 → a = 0 := begin cases a with d, intro h, refl, intro h, rw succ_add at h, exfalso, apply succ_ne_zero (d + b), exact h, end
40701f0425bd629993aca295755231ab52e04389
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/group/conj.lean
84f7df1204648cbc8832b9cb5c20598860374fc1
[ "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
2,007
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Chris Hughes, Michael Howes -/ import algebra.group.hom /-! # Conjugacy of group elements -/ universes u v variables {α : Type u} {β : Type v} variables [group α] [group β] /-- We say that `a` is conjugate to `b` if for some `c` we have `c * a * c⁻¹ = b`. -/ def is_conj (a b : α) := ∃ c : α, c * a * c⁻¹ = b @[refl] lemma is_conj_refl (a : α) : is_conj a a := ⟨1, by rw [one_mul, one_inv, mul_one]⟩ @[symm] lemma is_conj_symm {a b : α} : is_conj a b → is_conj b a | ⟨c, hc⟩ := ⟨c⁻¹, by rw [← hc, mul_assoc, mul_inv_cancel_right, inv_mul_cancel_left]⟩ @[trans] lemma is_conj_trans {a b c : α} : is_conj a b → is_conj b c → is_conj a c | ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := ⟨c₂ * c₁, by rw [← hc₂, ← hc₁, mul_inv_rev]; simp only [mul_assoc]⟩ @[simp] lemma is_conj_one_right {a : α} : is_conj 1 a ↔ a = 1 := ⟨by simp [is_conj, is_conj_refl] {contextual := tt}, by simp [is_conj_refl] {contextual := tt}⟩ @[simp] lemma is_conj_one_left {a : α} : is_conj a 1 ↔ a = 1 := calc is_conj a 1 ↔ is_conj 1 a : ⟨is_conj_symm, is_conj_symm⟩ ... ↔ a = 1 : is_conj_one_right @[simp] lemma conj_inv {a b : α} : (b * a * b⁻¹)⁻¹ = b * a⁻¹ * b⁻¹ := begin rw [mul_inv_rev _ b⁻¹, mul_inv_rev b _, inv_inv, mul_assoc], end @[simp] lemma conj_mul {a b c : α} : (b * a * b⁻¹) * (b * c * b⁻¹) = b * (a * c) * b⁻¹ := begin assoc_rw inv_mul_cancel_right, repeat {rw mul_assoc}, end @[simp] lemma is_conj_iff_eq {α : Type*} [comm_group α] {a b : α} : is_conj a b ↔ a = b := ⟨λ ⟨c, hc⟩, by rw [← hc, mul_right_comm, mul_inv_self, one_mul], λ h, by rw h⟩ protected lemma monoid_hom.map_is_conj (f : α →* β) {a b : α} : is_conj a b → is_conj (f a) (f b) | ⟨c, hc⟩ := ⟨f c, by rw [← f.map_mul, ← f.map_inv, ← f.map_mul, hc]⟩
ebaf29e0875f4c54b09dc32b6d1ae07ee47001d2
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/ordered_ring.lean
654041d206035ff4aa380f9e53270c3fdc0e17f5
[ "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
50,276
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 -/ import algebra.ordered_group import data.set.intervals.basic set_option old_structure_cmd true universe u variable {α : Type u} /-- An `ordered_semiring α` is a semiring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_semiring (α : Type u) extends semiring α, ordered_cancel_add_comm_monoid α := (zero_le_one : 0 ≤ (1 : α)) (mul_lt_mul_of_pos_left : ∀ a b c : α, a < b → 0 < c → c * a < c * b) (mul_lt_mul_of_pos_right : ∀ a b c : α, a < b → 0 < c → a * c < b * c) section ordered_semiring variables [ordered_semiring α] {a b c d : α} lemma zero_le_one : 0 ≤ (1:α) := ordered_semiring.zero_le_one lemma zero_le_two : 0 ≤ (2:α) := add_nonneg zero_le_one zero_le_one lemma one_le_two : 1 ≤ (2:α) := calc (1:α) = 0 + 1 : (zero_add _).symm ... ≤ 1 + 1 : add_le_add_right zero_le_one _ section nontrivial variables [nontrivial α] lemma zero_lt_one : 0 < (1 : α) := lt_of_le_of_ne zero_le_one zero_ne_one lemma zero_lt_two : 0 < (2:α) := add_pos zero_lt_one zero_lt_one @[field_simps] lemma two_ne_zero : (2:α) ≠ 0 := ne.symm (ne_of_lt zero_lt_two) lemma one_lt_two : 1 < (2:α) := calc (2:α) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma zero_lt_three : 0 < (3:α) := add_pos zero_lt_two zero_lt_one lemma zero_lt_four : 0 < (4:α) := add_pos zero_lt_two zero_lt_two end nontrivial lemma mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ h₂ lemma mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ h₂ lemma mul_le_mul_of_nonneg_left (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin cases classical.em (b ≤ a), { simp [h.antisymm h₁] }, cases classical.em (c ≤ 0), { simp [h_1.antisymm h₂] }, exact (mul_lt_mul_of_pos_left (h₁.lt_of_not_le h) (h₂.lt_of_not_le h_1)).le, end lemma mul_le_mul_of_nonneg_right (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin cases classical.em (b ≤ a), { simp [h.antisymm h₁] }, cases classical.em (c ≤ 0), { simp [h_1.antisymm h₂] }, exact (mul_lt_mul_of_pos_right (h₁.lt_of_not_le h) (h₂.lt_of_not_le h_1)).le, end -- TODO: there are four variations, depending on which variables we assume to be nonneg lemma mul_le_mul (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := have h : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h lemma mul_nonpos_of_nonneg_of_nonpos (ha : 0 ≤ a) (hb : b ≤ 0) : a * b ≤ 0 := have h : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : 0 ≤ b) : a * b ≤ 0 := have h : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_lt_mul (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul' (h1 : a ≤ c) (h2 : b < d) (h3 : 0 ≤ b) (h4 : 0 < c) : a * b < c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right h1 h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_pos (ha : 0 < a) (hb : 0 < b) : 0 < a * b := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_self_lt_mul_self (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 lemma strict_mono_incr_on_mul_self : strict_mono_incr_on (λ x : α, x * x) (set.Ici 0) := λ x hx y hy hxy, mul_self_lt_mul_self hx hxy lemma mul_self_le_mul_self (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := mul_le_mul h2 h2 h1 $ h1.trans h2 lemma mul_lt_mul'' (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) : a * b < c * d := (lt_or_eq_of_le h4).elim (λ b0, mul_lt_mul h1 h2.le b0 $ h3.trans h1.le) (λ b0, by rw [← b0, mul_zero]; exact mul_pos (h3.trans_lt h1) (h4.trans_lt h2)) lemma le_mul_of_one_le_right (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, mul_le_mul_of_nonneg_left h hb lemma le_mul_of_one_le_left (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ a * b := suffices 1 * b ≤ a * b, by rwa one_mul at this, mul_le_mul_of_nonneg_right h hb lemma add_le_mul_two_add {a b : α} (a2 : 2 ≤ a) (b0 : 0 ≤ b) : a + (2 + b) ≤ a * (2 + b) := calc a + (2 + b) ≤ a + (a + a * b) : add_le_add_left (add_le_add a2 (le_mul_of_one_le_left b0 (one_le_two.trans a2))) a ... ≤ a * (2 + b) : by rw [mul_add, mul_two, add_assoc] lemma one_le_mul_of_one_le_of_one_le {a b : α} (a1 : 1 ≤ a) (b1 : 1 ≤ b) : (1 : α) ≤ a * b := (mul_one (1 : α)).symm.le.trans (mul_le_mul a1 b1 zero_le_one (zero_le_one.trans a1)) /-- Pullback an `ordered_semiring` under an injective map. -/ def function.injective.ordered_semiring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (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) : ordered_semiring β := { zero_le_one := show f 0 ≤ f 1, by simp only [zero, one, zero_le_one], mul_lt_mul_of_pos_left := λ a b c ab c0, show f (c * a) < f (c * b), begin rw [mul, mul], refine mul_lt_mul_of_pos_left ab _, rwa ← zero, end, mul_lt_mul_of_pos_right := λ a b c ab c0, show f (a * c) < f (b * c), begin rw [mul, mul], refine mul_lt_mul_of_pos_right ab _, rwa ← zero, end, ..hf.ordered_cancel_add_comm_monoid f zero add, ..hf.semiring f zero one add mul } section variable [nontrivial α] lemma bit1_pos (h : 0 ≤ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma lt_add_one (a : α) : a < a + 1 := lt_add_of_le_of_pos le_rfl zero_lt_one lemma lt_one_add (a : α) : a < 1 + a := by { rw [add_comm], apply lt_add_one } end lemma bit1_pos' (h : 0 < a) : 0 < bit1 a := begin nontriviality, exact bit1_pos h.le, end lemma one_lt_mul (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, exact (one_mul (1 : α)) ▸ mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma mul_le_one (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 := begin rw ← one_mul (1 : α), apply mul_le_mul; {assumption <|> apply zero_le_one} end lemma one_lt_mul_of_le_of_lt (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul_of_lt_of_le (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul ha hb zero_lt_one $ zero_le_one.trans ha.le end lemma mul_le_of_le_one_right (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a := calc a * b ≤ a * 1 : mul_le_mul_of_nonneg_left hb1 ha ... = a : mul_one a lemma mul_le_of_le_one_left (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b := calc a * b ≤ 1 * b : mul_le_mul ha1 le_rfl hb zero_le_one ... = b : one_mul b lemma mul_lt_one_of_nonneg_of_lt_one_left (ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := calc a * b ≤ a : mul_le_of_le_one_right ha0 hb ... < 1 : ha lemma mul_lt_one_of_nonneg_of_lt_one_right (ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 := calc a * b ≤ b : mul_le_of_le_one_left hb0 ha ... < 1 : hb end ordered_semiring section ordered_comm_semiring /-- An `ordered_comm_semiring α` is a commutative semiring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_comm_semiring (α : Type u) extends ordered_semiring α, comm_semiring α /-- Pullback an `ordered_comm_semiring` under an injective map. -/ def function.injective.ordered_comm_semiring [ordered_comm_semiring α] {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (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) : ordered_comm_semiring β := { ..hf.comm_semiring f zero one add mul, ..hf.ordered_semiring f zero one add mul } end ordered_comm_semiring /-- A `linear_ordered_semiring α` is a nontrivial semiring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ -- It's not entirely clear we should assume `nontrivial` at this point; -- it would be reasonable to explore changing this, -- but be warned that the instances involving `domain` may cause -- typeclass search loops. @[protect_proj] class linear_ordered_semiring (α : Type u) extends ordered_semiring α, linear_order α, nontrivial α section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c d : α} -- `norm_num` expects the lemma stating `0 < 1` to have a single typeclass argument -- (see `norm_num.prove_pos_nat`). -- Rather than working out how to relax that assumption, -- we provide a synonym for `zero_lt_one` (which needs both `ordered_semiring α` and `nontrivial α`) -- with only a `linear_ordered_semiring` typeclass argument. lemma zero_lt_one' : 0 < (1 : α) := zero_lt_one lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : 0 ≤ c) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left h1 hc, h2.not_lt h) lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : 0 ≤ c) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right h1 hc, h2.not_lt h) lemma le_of_mul_le_mul_left (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, h2.not_le h) lemma le_of_mul_le_mul_right (h : a * c ≤ b * c) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, h2.not_le h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : 0 < a * b) : (0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) := begin rcases lt_trichotomy 0 a with (ha|rfl|ha), { refine or.inl ⟨ha, _⟩, contrapose! hab, exact mul_nonpos_of_nonneg_of_nonpos ha.le hab }, { rw [zero_mul] at hab, exact hab.false.elim }, { refine or.inr ⟨ha, _⟩, contrapose! hab, exact mul_nonpos_of_nonpos_of_nonneg ha.le hab } end lemma nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg (hab : 0 ≤ a * b) : (0 ≤ a ∧ 0 ≤ b) ∨ (a ≤ 0 ∧ b ≤ 0) := begin contrapose! hab, rcases lt_trichotomy 0 a with (ha|rfl|ha), exacts [mul_neg_of_pos_of_neg ha (hab.1 ha.le), ((hab.1 le_rfl).asymm (hab.2 le_rfl)).elim, mul_neg_of_neg_of_pos ha (hab.2 ha.le)] end lemma pos_of_mul_pos_left (h : 0 < a * b) (ha : 0 ≤ a) : 0 < b := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.1.not_le ha).2 lemma pos_of_mul_pos_right (h : 0 < a * b) (hb : 0 ≤ b) : 0 < a := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.2.not_le hb).1 lemma nonneg_of_mul_nonneg_left (h : 0 ≤ a * b) (h1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume h2 : b < 0, (mul_neg_of_pos_of_neg h1 h2).not_le h) lemma nonneg_of_mul_nonneg_right (h : 0 ≤ a * b) (h1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume h2 : a < 0, (mul_neg_of_neg_of_pos h2 h1).not_le h) lemma neg_of_mul_neg_left (h : a * b < 0) (h1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume h2 : b ≥ 0, (mul_nonneg h1 h2).not_lt h) lemma neg_of_mul_neg_right (h : a * b < 0) (h1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume h2 : a ≥ 0, (mul_nonneg h2 h1).not_lt h) lemma nonpos_of_mul_nonpos_left (h : a * b ≤ 0) (h1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume h2 : b > 0, (mul_pos h1 h2).not_le h) lemma nonpos_of_mul_nonpos_right (h : a * b ≤ 0) (h1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume h2 : a > 0, (mul_pos h2 h1).not_le h) @[simp] lemma mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_left h' h, λ h', mul_le_mul_of_nonneg_left h' h.le⟩ @[simp] lemma mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_right h' h, λ h', mul_le_mul_of_nonneg_right h' h.le⟩ @[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_left h' h.le, λ h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_right h' h.le, λ h', mul_lt_mul_of_pos_right h' h⟩ @[simp] lemma zero_le_mul_left (h : 0 < c) : 0 ≤ c * b ↔ 0 ≤ b := by { convert mul_le_mul_left h, simp } @[simp] lemma zero_le_mul_right (h : 0 < c) : 0 ≤ b * c ↔ 0 ≤ b := by { convert mul_le_mul_right h, simp } @[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b ↔ 0 < b := by { convert mul_lt_mul_left h, simp } @[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c ↔ 0 < b := by { convert mul_lt_mul_right h, simp } lemma add_le_mul_of_left_le_right (a2 : 2 ≤ a) (ab : a ≤ b) : a + b ≤ a * b := have 0 < b, from calc 0 < 2 : zero_lt_two ... ≤ a : a2 ... ≤ b : ab, calc a + b ≤ b + b : add_le_add_right ab b ... = 2 * b : (two_mul b).symm ... ≤ a * b : (mul_le_mul_right this).mpr a2 lemma add_le_mul_of_right_le_left (b2 : 2 ≤ b) (ba : b ≤ a) : a + b ≤ a * b := have 0 < a, from calc 0 < 2 : zero_lt_two ... ≤ b : b2 ... ≤ a : ba, calc a + b ≤ a + a : add_le_add_left ba a ... = a * 2 : (mul_two a).symm ... ≤ a * b : (mul_le_mul_left this).mpr b2 lemma add_le_mul (a2 : 2 ≤ a) (b2 : 2 ≤ b) : a + b ≤ a * b := if hab : a ≤ b then add_le_mul_of_left_le_right a2 hab else add_le_mul_of_right_le_left b2 (le_of_not_le hab) lemma add_le_mul' (a2 : 2 ≤ a) (b2 : 2 ≤ b) : a + b ≤ b * a := (le_of_eq (add_comm _ _)).trans (add_le_mul b2 a2) section variables [nontrivial α] @[simp] lemma bit0_le_bit0 : bit0 a ≤ bit0 b ↔ a ≤ b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit1_le_bit1 : bit1 a ≤ bit1 b ↔ a ≤ b := (add_le_add_iff_right 1).trans bit0_le_bit0 @[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b := (add_lt_add_iff_right 1).trans bit0_lt_bit0 @[simp] lemma one_le_bit1 : (1 : α) ≤ bit1 a ↔ 0 ≤ a := by rw [bit1, le_add_iff_nonneg_left, bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma one_lt_bit1 : (1 : α) < bit1 a ↔ 0 < a := by rw [bit1, lt_add_iff_pos_left, bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_le_bit0 : (0 : α) ≤ bit0 a ↔ 0 ≤ a := by rw [bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_lt_bit0 : (0 : α) < bit0 a ↔ 0 < a := by rw [bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] end lemma le_mul_iff_one_le_left (hb : 0 < b) : b ≤ a * b ↔ 1 ≤ a := suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right (hb : 0 < b) : b ≤ b * a ↔ 1 ≤ a := suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right (hb : 0 < b) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb lemma lt_mul_of_one_lt_right (hb : 0 < b) : 1 < a → b < b * a := (lt_mul_iff_one_lt_right hb).2 theorem mul_nonneg_iff_right_nonneg_of_pos (h : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b := ⟨assume : 0 ≤ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≤ b, mul_nonneg this h.le⟩ lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 h.not_le), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 h.not_le) ⟩ lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 h.not_le), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 h.not_le) ⟩ lemma nonpos_of_mul_nonneg_left (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 := le_of_not_gt (λ ha, absurd h (mul_neg_of_pos_of_neg ha hb).not_le) lemma nonpos_of_mul_nonneg_right (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 := le_of_not_gt (λ hb, absurd h (mul_neg_of_neg_of_pos ha hb).not_le) lemma neg_of_mul_pos_left (h : 0 < a * b) (hb : b ≤ 0) : a < 0 := lt_of_not_ge (λ ha, absurd h (mul_nonpos_of_nonneg_of_nonpos ha hb).not_lt) lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a ≤ 0) : b < 0 := lt_of_not_ge (λ hb, absurd h (mul_nonpos_of_nonpos_of_nonneg ha hb).not_lt) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] : no_top_order α := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ /-- Pullback a `linear_ordered_semiring` under an injective map. -/ def function.injective.linear_ordered_semiring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [nontrivial β] (f : β → α) (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) : linear_ordered_semiring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_semiring f zero one add mul } end linear_ordered_semiring section mono variables {β : Type*} [linear_ordered_semiring α] [preorder β] {f g : β → α} {a : α} lemma monotone_mul_left_of_nonneg (ha : 0 ≤ a) : monotone (λ x, a*x) := assume b c b_le_c, mul_le_mul_of_nonneg_left b_le_c ha lemma monotone_mul_right_of_nonneg (ha : 0 ≤ a) : monotone (λ x, x*a) := assume b c b_le_c, mul_le_mul_of_nonneg_right b_le_c ha lemma monotone.mul_const (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, (f x) * a) := (monotone_mul_right_of_nonneg ha).comp hf lemma monotone.const_mul (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, a * (f x)) := (monotone_mul_left_of_nonneg ha).comp hf lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y) lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (λ x, a * x) := assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (λ x, x * a) := assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, (f x) * a) := (strict_mono_mul_right_of_pos ha).comp hf lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, a * (f x)) := (strict_mono_mul_left_of_pos ha).comp hf lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 < g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul (hf h) (hg h.le) (hg0 x) (hf0 y) lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : ∀ x, 0 < f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul' (hf h.le) (hg h) (hg0 x) (hf0 y) lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x) end mono section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c : α} @[simp] lemma decidable.mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_left h @[simp] lemma decidable.mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_right h lemma mul_max_of_nonneg (b c : α) (ha : 0 ≤ a) : a * max b c = max (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_max lemma mul_min_of_nonneg (b c : α) (ha : 0 ≤ a) : a * min b c = min (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_min lemma max_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : max a b * c = max (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_max lemma min_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : min a b * c = min (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_min end linear_ordered_semiring /-- An `ordered_ring α` is a ring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_ring (α : Type u) extends ring α, ordered_add_comm_group α := (zero_le_one : 0 ≤ (1 : α)) (mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b) section ordered_ring variables [ordered_ring α] {a b c : α} lemma ordered_ring.mul_nonneg (a b : α) (h₁ : 0 ≤ a) (h₂ : 0 ≤ b) : 0 ≤ a * b := begin cases classical.em (a ≤ 0), { simp [le_antisymm h h₁] }, cases classical.em (b ≤ 0), { simp [le_antisymm h_1 h₂] }, exact (le_not_le_of_lt (ordered_ring.mul_pos a b (h₁.lt_of_not_le h) (h₂.lt_of_not_le h_1))).left, end lemma ordered_ring.mul_le_mul_of_nonneg_left (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin rw [← sub_nonneg, ← mul_sub], exact ordered_ring.mul_nonneg c (b - a) h₂ (sub_nonneg.2 h₁), end lemma ordered_ring.mul_le_mul_of_nonneg_right (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin rw [← sub_nonneg, ← sub_mul], exact ordered_ring.mul_nonneg _ _ (sub_nonneg.2 h₁) h₂, end lemma ordered_ring.mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := begin rw [← sub_pos, ← mul_sub], exact ordered_ring.mul_pos _ _ h₂ (sub_pos.2 h₁), end lemma ordered_ring.mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := begin rw [← sub_pos, ← sub_mul], exact ordered_ring.mul_pos _ _ (sub_pos.2 h₁) h₂, end @[priority 100] -- see Note [lower instance priority] instance ordered_ring.to_ordered_semiring : ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right α _, ..‹ordered_ring α› } lemma mul_le_mul_of_nonpos_left {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : c * a ≤ c * b := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left h this, have -(c * b) ≤ -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right h this, have -(b * c) ≤ -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, le_of_neg_le_neg this lemma mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := have 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_lt_mul_of_neg_left {a b c : α} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : α} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : α} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this /-- Pullback an `ordered_ring` under an injective map. -/ def function.injective.ordered_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (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) : ordered_ring β := { mul_pos := λ a b a0 b0, show f 0 < f (a * b), by { rw [zero, mul], apply mul_pos; rwa ← zero }, ..hf.ordered_semiring f zero one add mul, ..hf.ring_sub f zero one add mul neg sub } end ordered_ring section ordered_comm_ring /-- An `ordered_comm_ring α` is a commutative ring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_comm_ring (α : Type u) extends ordered_ring α, ordered_comm_semiring α, comm_ring α /-- Pullback an `ordered_comm_ring` under an injective map. -/ def function.injective.ordered_comm_ring [ordered_comm_ring α] {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (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) : ordered_comm_ring β := { ..hf.ordered_comm_semiring f zero one add mul, ..hf.ordered_ring f zero one add mul neg sub, ..hf.comm_ring_sub f zero one add mul neg sub } end ordered_comm_ring /-- A `linear_ordered_ring α` is a ring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_ring (α : Type u) extends ordered_ring α, linear_order α, nontrivial α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_add_comm_group [s : linear_ordered_ring α] : linear_ordered_add_comm_group α := { .. s } section linear_ordered_ring variables [linear_ordered_ring α] {a b c : α} @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right α _, le_total := linear_ordered_ring.le_total, ..‹linear_ordered_ring α› } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_domain : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros a b hab, contrapose! hab, cases (lt_or_gt_of_ne hab.1) with ha ha; cases (lt_or_gt_of_ne hab.2) with hb hb, exacts [(mul_pos_of_neg_of_neg ha hb).ne.symm, (mul_neg_of_neg_of_pos ha hb).ne, (mul_neg_of_pos_of_neg ha hb).ne, (mul_pos ha hb).ne.symm] end, .. ‹linear_ordered_ring α› } @[simp] lemma abs_one : abs (1 : α) = 1 := abs_of_pos zero_lt_one @[simp] lemma abs_two : abs (2 : α) = 2 := abs_of_pos zero_lt_two lemma abs_mul (a b : α) : abs (a * b) = abs a * abs b := begin rw [abs_eq (mul_nonneg (abs_nonneg a) (abs_nonneg b))], cases le_total a 0 with ha ha; cases le_total b 0 with hb hb; simp [abs_of_nonpos, abs_of_nonneg, *] end /-- `abs` as a `monoid_with_zero_hom`. -/ def abs_hom : monoid_with_zero_hom α α := ⟨abs, abs_zero, abs_one, abs_mul⟩ @[simp] lemma abs_mul_abs_self (a : α) : abs a * abs a = a * a := abs_by_cases (λ x, x * x = a * a) rfl (neg_mul_neg a a) @[simp] lemma abs_mul_self (a : α) : abs (a * a) = a * a := by rw [abs_mul, abs_mul_abs_self] lemma mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := ⟨pos_and_pos_or_neg_and_neg_of_mul_pos, λ h, h.elim (and_imp.2 mul_pos) (and_imp.2 mul_pos_of_neg_of_neg)⟩ lemma mul_neg_iff : a * b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by rw [← neg_pos, neg_mul_eq_mul_neg, mul_pos_iff, neg_pos, neg_lt_zero] lemma mul_nonneg_iff : 0 ≤ a * b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := ⟨nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg, λ h, h.elim (and_imp.2 mul_nonneg) (and_imp.2 mul_nonneg_of_nonpos_of_nonpos)⟩ lemma mul_nonpos_iff : a * b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by rw [← neg_nonneg, neg_mul_eq_mul_neg, mul_nonneg_iff, neg_nonneg, neg_nonpos] lemma mul_self_nonneg (a : α) : 0 ≤ a * a := abs_mul_self a ▸ abs_nonneg _ @[simp] lemma neg_le_self_iff : -a ≤ a ↔ 0 ≤ a := by simp [neg_le_iff_add_nonneg, ← two_mul, mul_nonneg_iff, zero_le_one, (@zero_lt_two α _ _).not_le] @[simp] lemma neg_lt_self_iff : -a < a ↔ 0 < a := by simp [neg_lt_iff_pos_add, ← two_mul, mul_pos_iff, zero_lt_one, (@zero_lt_two α _ _).not_lt] @[simp] lemma le_neg_self_iff : a ≤ -a ↔ a ≤ 0 := calc a ≤ -a ↔ -(-a) ≤ -a : by rw neg_neg ... ↔ 0 ≤ -a : neg_le_self_iff ... ↔ a ≤ 0 : neg_nonneg @[simp] lemma lt_neg_self_iff : a < -a ↔ a < 0 := calc a < -a ↔ -(-a) < -a : by rw neg_neg ... ↔ 0 < -a : neg_lt_self_iff ... ↔ a < 0 : neg_pos @[simp] lemma abs_eq_self : abs a = a ↔ 0 ≤ a := by simp [abs] @[simp] lemma abs_eq_neg_self : abs a = -a ↔ a ≤ 0 := by simp [abs] lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c ≤ 0) : b < a := have nhc : 0 ≤ -c, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma neg_one_lt_zero : -1 < (0:α) := neg_lt_zero.2 zero_lt_one lemma le_of_mul_le_of_one_le {a b c : α} (h : a * c ≤ b) (hb : 0 ≤ b) (hc : 1 ≤ c) : a ≤ b := have h' : a * c ≤ b * c, from calc a * c ≤ b : h ... = b * 1 : by rewrite mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (zero_lt_one.trans_le hc) lemma nonneg_le_nonneg_of_squares_le {a b : α} (hb : 0 ≤ b) (h : a * a ≤ b * b) : a ≤ b := le_of_not_gt (λhab, (mul_self_lt_mul_self hb hab).not_le h) lemma mul_self_le_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a ≤ b ↔ a * a ≤ b * b := ⟨mul_self_le_mul_self h1, nonneg_le_nonneg_of_squares_le h2⟩ lemma mul_self_lt_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a < b ↔ a * a < b * b := ((@strict_mono_incr_on_mul_self α _).lt_iff_lt h1 h2).symm lemma mul_self_inj {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a * a = b * b ↔ a = b := (@strict_mono_incr_on_mul_self α _).inj_on.eq_iff h1 h2 @[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h, λ h', mul_le_mul_of_nonpos_left h' h.le⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h, λ h', mul_le_mul_of_nonpos_right h' h.le⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : α) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) lemma mul_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a := by rcases lt_trichotomy a 0 with h|h|h; [exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h] lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y := begin rw [← abs_mul_abs_self x], exact mul_self_le_mul_self (abs_nonneg x) (abs_le.2 ⟨neg_le.2 h₂, h₁⟩) end lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a := le_of_not_gt (λ ha, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b := le_of_not_gt (λ hb, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a := lt_of_not_ge (λ ha, absurd h (mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b := lt_of_not_ge (λ hb, absurd h (mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) /-- The sum of two squares is zero iff both elements are zero. -/ lemma mul_self_add_mul_self_eq_zero {x y : α} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := by rw [add_eq_zero_iff', mul_self_eq_zero, mul_self_eq_zero]; apply mul_self_nonneg lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 := (mul_self_add_mul_self_eq_zero.mp h).left lemma abs_eq_iff_mul_self_eq : abs a = abs b ↔ a * a = b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact (mul_self_inj (abs_nonneg a) (abs_nonneg b)).symm, end lemma abs_lt_iff_mul_self_lt : abs a < abs b ↔ a * a < b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_lt_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_iff_mul_self_le : abs a ≤ abs b ↔ a * a ≤ b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_le_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_one_iff_mul_self_le_one : abs a ≤ 1 ↔ a * a ≤ 1 := by simpa only [abs_one, one_mul] using @abs_le_iff_mul_self_le α _ a 1 /-- Pullback a `linear_ordered_ring` under an injective map. -/ def function.injective.linear_ordered_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [nontrivial β] (f : β → α) (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) : linear_ordered_ring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_ring f zero one add mul neg sub } end linear_ordered_ring /-- A `linear_ordered_comm_ring α` is a commutative ring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_comm_ring (α : Type u) extends linear_ordered_ring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_ordered_comm_ring [d : linear_ordered_comm_ring α] : ordered_comm_ring α := -- One might hope that `{ ..linear_ordered_ring.to_linear_ordered_semiring, ..d }` -- achieved the same result here. -- Unfortunately with that definition we see mismatched instances in `algebra.star.chsh`. let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in { zero_mul := @linear_ordered_semiring.zero_mul α s, mul_zero := @linear_ordered_semiring.mul_zero α s, add_left_cancel := @linear_ordered_semiring.add_left_cancel α s, add_right_cancel := @linear_ordered_semiring.add_right_cancel α s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s, ..d } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_integral_domain [s : linear_ordered_comm_ring α] : integral_domain α := { ..linear_ordered_ring.to_domain, ..s } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_linear_ordered_semiring [d : linear_ordered_comm_ring α] : linear_ordered_semiring α := -- One might hope that `{ ..linear_ordered_ring.to_linear_ordered_semiring, ..d }` -- achieved the same result here. -- Unfortunately with that definition we see mismatched `preorder ℝ` instances in -- `topology.metric_space.basic`. let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in { zero_mul := @linear_ordered_semiring.zero_mul α s, mul_zero := @linear_ordered_semiring.mul_zero α s, add_left_cancel := @linear_ordered_semiring.add_left_cancel α s, add_right_cancel := @linear_ordered_semiring.add_right_cancel α s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s, ..d } section linear_ordered_comm_ring variables [linear_ordered_comm_ring α] {a b c d : α} lemma max_mul_mul_le_max_mul_max (b c : α) (ha : 0 ≤ a) (hd: 0 ≤ d) : max (a * b) (d * c) ≤ max a c * max d b := have ba : b * a ≤ max d b * max c a, from mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)), have cd : c * d ≤ max a c * max b d, from mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)), max_le (by simpa [mul_comm, max_comm] using ba) (by simpa [mul_comm, max_comm] using cd) lemma abs_sub_square (a b : α) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp [left_distrib, right_distrib, add_assoc, add_comm, add_left_comm, mul_comm, sub_eq_add_neg], end /-- Pullback a `linear_ordered_comm_ring` under an injective map. -/ def function.injective.linear_ordered_comm_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [nontrivial β] (f : β → α) (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) : linear_ordered_comm_ring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_comm_ring f zero one add mul neg sub } end linear_ordered_comm_ring /-- Extend `nonneg_add_comm_group` to support ordered rings specified by their nonnegative elements -/ class nonneg_ring (α : Type*) extends ring α, nonneg_add_comm_group α := (one_nonneg : nonneg 1) (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (mul_pos : ∀ {a b}, pos a → pos b → pos (a * b)) /-- Extend `nonneg_add_comm_group` to support linearly ordered rings specified by their nonnegative elements -/ class linear_nonneg_ring (α : Type*) extends domain α, nonneg_add_comm_group α := (one_pos : pos 1) (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (nonneg_total : ∀ a, nonneg a ∨ nonneg (-a)) namespace nonneg_ring open nonneg_add_comm_group variable [nonneg_ring α] /-- `to_linear_nonneg_ring` shows that a `nonneg_ring` with a total order is a `domain`, hence a `linear_nonneg_ring`. -/ def to_linear_nonneg_ring [nontrivial α] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_nonneg_ring α := { one_pos := (pos_iff 1).mpr ⟨one_nonneg, λ h, zero_ne_one (nonneg_antisymm one_nonneg h).symm⟩, nonneg_total := nonneg_total, eq_zero_or_eq_zero_of_mul_eq_zero := suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0, from λ a b, (nonneg_total a).elim (this b) (λ na, by simpa using this b na), suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0, from λ a b na, (nonneg_total b).elim (this na) (λ nb, by simpa using this na nb), λ a b na nb z, classical.by_cases (λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna)) (λ pa, classical.by_cases (λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb)) (λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos ((pos_iff _).2 ⟨na, pa⟩) ((pos_iff _).2 ⟨nb, pb⟩))), ..‹nontrivial α›, ..‹nonneg_ring α› } end nonneg_ring namespace linear_nonneg_ring open nonneg_add_comm_group variable [linear_nonneg_ring α] @[priority 100] -- see Note [lower instance priority] instance to_nonneg_ring : nonneg_ring α := { one_nonneg := ((pos_iff _).mp one_pos).1, mul_pos := λ a b pa pb, let ⟨a1, a2⟩ := (pos_iff a).1 pa, ⟨b1, b2⟩ := (pos_iff b).1 pb in have ab : nonneg (a * b), from mul_nonneg a1 b1, (pos_iff _).2 ⟨ab, λ hn, have a * b = 0, from nonneg_antisymm ab hn, (eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim (ne_of_gt (pos_def.1 pa)) (ne_of_gt (pos_def.1 pb))⟩, ..‹linear_nonneg_ring α› } /-- Construct `linear_order` from `linear_nonneg_ring`. This is not an instance because we don't use it in `mathlib`. -/ local attribute [instance] def to_linear_order [decidable_pred (nonneg : α → Prop)] : linear_order α := { le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α) } /-- Construct `linear_ordered_ring` from `linear_nonneg_ring`. This is not an instance because we don't use it in `mathlib`. -/ local attribute [instance] def to_linear_ordered_ring [decidable_pred (nonneg : α → Prop)] : linear_ordered_ring α := { mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _, zero_le_one := le_of_lt $ lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin rw [zero_sub] at h, have := mul_nonneg h h, simp at this, exact zero_ne_one (nonneg_antisymm this h).symm end, ..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α), ..(infer_instance : linear_order α) } /-- Convert a `linear_nonneg_ring` with a commutative multiplication and decidable non-negativity into a `linear_ordered_comm_ring` -/ def to_linear_ordered_comm_ring [decidable_pred (@nonneg α _)] [comm : @is_commutative α (*)] : linear_ordered_comm_ring α := { mul_comm := is_commutative.comm, ..@linear_nonneg_ring.to_linear_ordered_ring _ _ _ } end linear_nonneg_ring /-- A canonically ordered commutative semiring is an ordered, commutative semiring in which `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_comm_semiring (α : Type*) extends canonically_ordered_add_monoid α, comm_semiring α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) namespace canonically_ordered_semiring variables [canonically_ordered_comm_semiring α] {a b : α} open canonically_ordered_add_monoid (le_iff_exists_add) @[priority 100] -- see Note [lower instance priority] instance canonically_ordered_comm_semiring.to_no_zero_divisors : no_zero_divisors α := ⟨canonically_ordered_comm_semiring.eq_zero_or_eq_zero_of_mul_eq_zero⟩ lemma mul_le_mul {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) : a * c ≤ b * d := begin rcases (le_iff_exists_add _ _).1 hab with ⟨b, rfl⟩, rcases (le_iff_exists_add _ _).1 hcd with ⟨d, rfl⟩, suffices : a * c ≤ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul, add_assoc], exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩ end lemma mul_le_mul_left' {b c : α} (h : b ≤ c) (a : α) : a * b ≤ a * c := mul_le_mul le_rfl h lemma mul_le_mul_right' {b c : α} (h : b ≤ c) (a : α) : b * a ≤ c * a := mul_le_mul h le_rfl /-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/ lemma zero_lt_one [nontrivial α] : (0:α) < 1 := (zero_le 1).lt_of_ne zero_ne_one lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) := by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] end canonically_ordered_semiring namespace with_top instance [nonempty α] : nontrivial (with_top α) := option.nontrivial variable [decidable_eq α] section has_mul variables [has_zero α] [has_mul α] instance : mul_zero_class (with_top α) := { zero := 0, mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } lemma mul_def {a b : with_top α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ := top_mul top_ne_zero end has_mul section mul_zero_class variables [mul_zero_class α] @[norm_cast] lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b)) | none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm @[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := begin cases a; cases b; simp only [none_eq_top, some_eq_coe], { simp [← coe_mul] }, { suffices : ⊤ * (b : with_top α) = ⊤ ↔ b ≠ 0, by simpa, by_cases hb : b = 0; simp [hb] }, { suffices : (a : with_top α) * ⊤ = ⊤ ↔ a ≠ 0, by simpa, by_cases ha : a = 0; simp [ha] }, { simp [← coe_mul] } end end mul_zero_class section no_zero_divisors variables [mul_zero_class α] [no_zero_divisors α] instance : no_zero_divisors (with_top α) := ⟨λ a b, by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, mul_eq_zero] at *⟩ end no_zero_divisors variables [canonically_ordered_comm_semiring α] private lemma comm (a b : with_top α) : a * b = b * a := begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊤ = a * ⊤ + b * ⊤, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end private lemma assoc (a b c : with_top α) : (a * b) * c = a * (b * c) := begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end -- `nontrivial α` is needed here as otherwise -- we have `1 * ⊤ = ⊤` but also `= 0 * ⊤ = 0`. private lemma one_mul' [nontrivial α] : ∀a : with_top α, 1 * a = a | none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_top.coe_one] | (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_top.coe_one] instance [nontrivial α] : canonically_ordered_comm_semiring (with_top α) := { one := (1 : α), right_distrib := distrib', left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl, mul_assoc := assoc, mul_comm := comm, one_mul := one_mul', mul_one := assume a, by rw [comm, one_mul'], .. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_add_monoid, .. with_top.no_zero_divisors, .. with_top.nontrivial } lemma mul_lt_top [nontrivial α] {a b : with_top α} (ha : a < ⊤) (hb : b < ⊤) : a * b < ⊤ := begin lift a to α using ne_top_of_lt ha, lift b to α using ne_top_of_lt hb, simp only [← coe_mul, coe_lt_top] end end with_top
1a41da991b23a4b09020f69cc505ad87371a5e37
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/data/zsqrtd/gaussian_int.lean
d2c88327f3d89a1a194e37b104901076feedd516
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
12,747
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.zsqrtd.basic import data.complex.basic import ring_theory.principal_ideal_domain import number_theory.quadratic_reciprocity /-! # Gaussian integers The Gaussian integers are complex integer, complex numbers whose real and imaginary parts are both integers. ## Main definitions The Euclidean domain structure on `ℤ[i]` is defined in this file. The homomorphism `to_complex` into the complex numbers is also defined in this file. ## Main statements `prime_iff_mod_four_eq_three_of_nat_prime` A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4` ## Notations This file uses the local notation `ℤ[i]` for `gaussian_int` ## Implementation notes Gaussian integers are implemented using the more general definition `zsqrtd`, the type of integers adjoined a square root of `d`, in this case `-1`. The definition is reducible, so that properties and definitions about `zsqrtd` can easily be used. -/ open zsqrtd complex @[reducible] def gaussian_int : Type := zsqrtd (-1) local notation `ℤ[i]` := gaussian_int namespace gaussian_int instance : has_repr ℤ[i] := ⟨λ x, "⟨" ++ repr x.re ++ ", " ++ repr x.im ++ "⟩"⟩ instance : comm_ring ℤ[i] := zsqrtd.comm_ring section local attribute [-instance] complex.field -- Avoid making things noncomputable unnecessarily. /-- The embedding of the Gaussian integers into the complex numbers, as a ring homomorphism. -/ def to_complex : ℤ[i] →+* ℂ := begin refine_struct { to_fun := λ x : ℤ[i], (x.re + x.im * I : ℂ), .. }; intros; apply complex.ext; dsimp; norm_cast; simp; abel end end instance : has_coe (ℤ[i]) ℂ := ⟨to_complex⟩ lemma to_complex_def (x : ℤ[i]) : (x : ℂ) = x.re + x.im * I := rfl lemma to_complex_def' (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ) = x + y * I := by simp [to_complex_def] lemma to_complex_def₂ (x : ℤ[i]) : (x : ℂ) = ⟨x.re, x.im⟩ := by apply complex.ext; simp [to_complex_def] @[simp] lemma to_real_re (x : ℤ[i]) : ((x.re : ℤ) : ℝ) = (x : ℂ).re := by simp [to_complex_def] @[simp] lemma to_real_im (x : ℤ[i]) : ((x.im : ℤ) : ℝ) = (x : ℂ).im := by simp [to_complex_def] @[simp] lemma to_complex_re (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).re = x := by simp [to_complex_def] @[simp] lemma to_complex_im (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).im = y := by simp [to_complex_def] @[simp] lemma to_complex_add (x y : ℤ[i]) : ((x + y : ℤ[i]) : ℂ) = x + y := to_complex.map_add _ _ @[simp] lemma to_complex_mul (x y : ℤ[i]) : ((x * y : ℤ[i]) : ℂ) = x * y := to_complex.map_mul _ _ @[simp] lemma to_complex_one : ((1 : ℤ[i]) : ℂ) = 1 := to_complex.map_one @[simp] lemma to_complex_zero : ((0 : ℤ[i]) : ℂ) = 0 := to_complex.map_zero @[simp] lemma to_complex_neg (x : ℤ[i]) : ((-x : ℤ[i]) : ℂ) = -x := to_complex.map_neg _ @[simp] lemma to_complex_sub (x y : ℤ[i]) : ((x - y : ℤ[i]) : ℂ) = x - y := to_complex.map_sub _ _ @[simp] lemma to_complex_inj {x y : ℤ[i]} : (x : ℂ) = y ↔ x = y := by cases x; cases y; simp [to_complex_def₂] @[simp] lemma to_complex_eq_zero {x : ℤ[i]} : (x : ℂ) = 0 ↔ x = 0 := by rw [← to_complex_zero, to_complex_inj] @[simp] lemma nat_cast_real_norm (x : ℤ[i]) : (x.norm : ℝ) = (x : ℂ).norm_sq := by rw [norm, norm_sq]; simp @[simp] lemma nat_cast_complex_norm (x : ℤ[i]) : (x.norm : ℂ) = (x : ℂ).norm_sq := by cases x; rw [norm, norm_sq]; simp lemma norm_nonneg (x : ℤ[i]) : 0 ≤ norm x := norm_nonneg trivial _ @[simp] lemma norm_eq_zero {x : ℤ[i]} : norm x = 0 ↔ x = 0 := by rw [← @int.cast_inj ℝ _ _ _]; simp lemma norm_pos {x : ℤ[i]} : 0 < norm x ↔ x ≠ 0 := by rw [lt_iff_le_and_ne, ne.def, eq_comm, norm_eq_zero]; simp [norm_nonneg] @[simp] lemma coe_nat_abs_norm (x : ℤ[i]) : (x.norm.nat_abs : ℤ) = x.norm := int.nat_abs_of_nonneg (norm_nonneg _) @[simp] lemma nat_cast_nat_abs_norm {α : Type*} [ring α] (x : ℤ[i]) : (x.norm.nat_abs : α) = x.norm := by rw [← int.cast_coe_nat, coe_nat_abs_norm] lemma nat_abs_norm_eq (x : ℤ[i]) : x.norm.nat_abs = x.re.nat_abs * x.re.nat_abs + x.im.nat_abs * x.im.nat_abs := int.coe_nat_inj $ begin simp, simp [norm] end protected def div (x y : ℤ[i]) : ℤ[i] := let n := (rat.of_int (norm y))⁻¹ in let c := y.conj in ⟨round (rat.of_int (x * c).re * n : ℚ), round (rat.of_int (x * c).im * n : ℚ)⟩ instance : has_div ℤ[i] := ⟨gaussian_int.div⟩ lemma div_def (x y : ℤ[i]) : x / y = ⟨round ((x * conj y).re / norm y : ℚ), round ((x * conj y).im / norm y : ℚ)⟩ := show zsqrtd.mk _ _ = _, by simp [rat.of_int_eq_mk, rat.mk_eq_div, div_eq_mul_inv] lemma to_complex_div_re (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).re = round ((x / y : ℂ).re) := by rw [div_def, ← @rat.cast_round ℝ _ _]; simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul] lemma to_complex_div_im (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).im = round ((x / y : ℂ).im) := by rw [div_def, ← @rat.cast_round ℝ _ _, ← @rat.cast_round ℝ _ _]; simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul] local notation `abs'` := _root_.abs lemma norm_sq_le_norm_sq_of_re_le_of_im_le {x y : ℂ} (hre : abs' x.re ≤ abs' y.re) (him : abs' x.im ≤ abs' y.im) : x.norm_sq ≤ y.norm_sq := by rw [norm_sq, norm_sq, ← _root_.abs_mul_self, _root_.abs_mul, ← _root_.abs_mul_self y.re, _root_.abs_mul y.re, ← _root_.abs_mul_self x.im, _root_.abs_mul x.im, ← _root_.abs_mul_self y.im, _root_.abs_mul y.im]; exact (add_le_add (mul_self_le_mul_self (abs_nonneg _) hre) (mul_self_le_mul_self (abs_nonneg _) him)) lemma norm_sq_div_sub_div_lt_one (x y : ℤ[i]) : ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq < 1 := calc ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq = ((x / y : ℂ).re - ((x / y : ℤ[i]) : ℂ).re + ((x / y : ℂ).im - ((x / y : ℤ[i]) : ℂ).im) * I : ℂ).norm_sq : congr_arg _ $ by apply complex.ext; simp ... ≤ (1 / 2 + 1 / 2 * I).norm_sq : have abs' (2 / (2 * 2) : ℝ) = 1 / 2, by rw _root_.abs_of_nonneg; norm_num, norm_sq_le_norm_sq_of_re_le_of_im_le (by rw [to_complex_div_re]; simp [norm_sq, this]; simpa using abs_sub_round (x / y : ℂ).re) (by rw [to_complex_div_im]; simp [norm_sq, this]; simpa using abs_sub_round (x / y : ℂ).im) ... < 1 : by simp [norm_sq]; norm_num protected def mod (x y : ℤ[i]) : ℤ[i] := x - y * (x / y) instance : has_mod ℤ[i] := ⟨gaussian_int.mod⟩ lemma mod_def (x y : ℤ[i]) : x % y = x - y * (x / y) := rfl lemma norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm < y.norm := have (y : ℂ) ≠ 0, by rwa [ne.def, ← to_complex_zero, to_complex_inj], (@int.cast_lt ℝ _ _ _).1 $ calc ↑(norm (x % y)) = (x - y * (x / y : ℤ[i]) : ℂ).norm_sq : by simp [mod_def] ... = (y : ℂ).norm_sq * (((x / y) - (x / y : ℤ[i])) : ℂ).norm_sq : by rw [← norm_sq_mul, mul_sub, mul_div_cancel' _ this] ... < (y : ℂ).norm_sq * 1 : mul_lt_mul_of_pos_left (norm_sq_div_sub_div_lt_one _ _) (norm_sq_pos.2 this) ... = norm y : by simp lemma nat_abs_norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm.nat_abs < y.norm.nat_abs := int.coe_nat_lt.1 (by simp [-int.coe_nat_lt, norm_mod_lt x hy]) lemma norm_le_norm_mul_left (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (norm x).nat_abs ≤ (norm (x * y)).nat_abs := by rw [norm_mul, int.nat_abs_mul]; exact le_mul_of_one_le_right' (nat.zero_le _) (int.coe_nat_le.1 (by rw [coe_nat_abs_norm]; exact norm_pos.2 hy)) instance : nonzero ℤ[i] := { zero_ne_one := dec_trivial } instance : euclidean_domain ℤ[i] := { quotient := (/), remainder := (%), quotient_zero := λ _, by simp [div_def]; refl, quotient_mul_add_remainder_eq := λ _ _, by simp [mod_def], r := _, r_well_founded := measure_wf (int.nat_abs ∘ norm), remainder_lt := nat_abs_norm_mod_lt, mul_left_not_lt := λ a b hb0, not_lt_of_ge $ norm_le_norm_mul_left a hb0, .. gaussian_int.comm_ring, .. gaussian_int.nonzero } open principal_ideal_ring lemma mod_four_eq_three_of_nat_prime_of_prime (p : ℕ) [hp : fact p.prime] (hpi : prime (p : ℤ[i])) : p % 4 = 3 := hp.eq_two_or_odd.elim (λ hp2, absurd hpi (mt irreducible_iff_prime.2 $ λ ⟨hu, h⟩, begin have := h ⟨1, 1⟩ ⟨1, -1⟩ (hp2.symm ▸ rfl), rw [← norm_eq_one_iff, ← norm_eq_one_iff] at this, exact absurd this dec_trivial end)) (λ hp1, by_contradiction $ λ hp3 : p % 4 ≠ 3, have hp41 : p % 4 = 1, begin rw [← nat.mod_mul_left_mod p 2 2, show 2 * 2 = 4, from rfl] at hp1, have := nat.mod_lt p (show 0 < 4, from dec_trivial), revert this hp3 hp1, generalize hm : p % 4 = m, clear hm, revert m, exact dec_trivial, end, let ⟨k, hk⟩ := (zmod.exists_pow_two_eq_neg_one_iff_mod_four_ne_three p).2 $ by rw hp41; exact dec_trivial in begin obtain ⟨k, k_lt_p, rfl⟩ : ∃ (k' : ℕ) (h : k' < p), (k' : zmod p) = k, { refine ⟨k.val, k.val_lt, zmod.cast_val k⟩ }, have hpk : p ∣ k ^ 2 + 1, by rw [← char_p.cast_eq_zero_iff (zmod p) p]; simp *, have hkmul : (k ^ 2 + 1 : ℤ[i]) = ⟨k, 1⟩ * ⟨k, -1⟩ := by simp [_root_.pow_two, zsqrtd.ext], have hpne1 : p ≠ 1, from (ne_of_lt (hp.one_lt)).symm, have hkltp : 1 + k * k < p * p, from calc 1 + k * k ≤ k + k * k : add_le_add_right (nat.pos_of_ne_zero (λ hk0, by clear_aux_decl; simp [*, nat.pow_succ] at *)) _ ... = k * (k + 1) : by simp [add_comm, mul_add] ... < p * p : mul_lt_mul k_lt_p k_lt_p (nat.succ_pos _) (nat.zero_le _), have hpk₁ : ¬ (p : ℤ[i]) ∣ ⟨k, -1⟩ := λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $ calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k, -1⟩).nat_abs : by rw hx ... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, norm] using hkltp ... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _ (λ hx0, (show (-1 : ℤ) ≠ 0, from dec_trivial) $ by simpa [hx0] using congr_arg zsqrtd.im hx), have hpk₂ : ¬ (p : ℤ[i]) ∣ ⟨k, 1⟩ := λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $ calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k, 1⟩).nat_abs : by rw hx ... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, norm] using hkltp ... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _ (λ hx0, (show (1 : ℤ) ≠ 0, from dec_trivial) $ by simpa [hx0] using congr_arg zsqrtd.im hx), have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2 (by rw [norm_nat_cast, int.nat_abs_mul, nat.mul_eq_one_iff]; exact λ h, (ne_of_lt hp.one_lt).symm h.1), obtain ⟨y, hy⟩ := hpk, have := hpi.2.2 ⟨k, 1⟩ ⟨k, -1⟩ ⟨y, by rw [← hkmul, ← nat.cast_mul p, ← hy]; simp⟩, clear_aux_decl, tauto end) lemma sum_two_squares_of_nat_prime_of_not_irreducible (p : ℕ) [hp : fact p.prime] (hpi : ¬irreducible (p : ℤ[i])) : ∃ a b, a^2 + b^2 = p := have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2 $ by rw [norm_nat_cast, int.nat_abs_mul, nat.mul_eq_one_iff]; exact λ h, (ne_of_lt hp.one_lt).symm h.1, have hab : ∃ a b, (p : ℤ[i]) = a * b ∧ ¬ is_unit a ∧ ¬ is_unit b, by simpa [irreducible, hpu, classical.not_forall, not_or_distrib] using hpi, let ⟨a, b, hpab, hau, hbu⟩ := hab in have hnap : (norm a).nat_abs = p, from ((hp.mul_eq_prime_pow_two_iff (mt norm_eq_one_iff.1 hau) (mt norm_eq_one_iff.1 hbu)).1 $ by rw [← int.coe_nat_inj', int.coe_nat_pow, _root_.pow_two, ← @norm_nat_cast (-1), hpab]; simp).1, ⟨a.re.nat_abs, a.im.nat_abs, by simpa [nat_abs_norm_eq, nat.pow_two] using hnap⟩ lemma prime_of_nat_prime_of_mod_four_eq_three (p : ℕ) [hp : fact p.prime] (hp3 : p % 4 = 3) : prime (p : ℤ[i]) := irreducible_iff_prime.1 $ classical.by_contradiction $ λ hpi, let ⟨a, b, hab⟩ := sum_two_squares_of_nat_prime_of_not_irreducible p hpi in have ∀ a b : zmod 4, a^2 + b^2 ≠ p, by erw [← zmod.cast_mod_nat 4 p, hp3]; exact dec_trivial, this a b (hab ▸ by simp) /-- A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4` -/ lemma prime_iff_mod_four_eq_three_of_nat_prime (p : ℕ) [hp : fact p.prime] : prime (p : ℤ[i]) ↔ p % 4 = 3 := ⟨mod_four_eq_three_of_nat_prime_of_prime p, prime_of_nat_prime_of_mod_four_eq_three p⟩ end gaussian_int
86a31824683224be0701e37a7dd3019735c623bd
d406927ab5617694ec9ea7001f101b7c9e3d9702
/archive/100-theorems-list/45_partition.lean
6c60da78735da5612d3e5f6e61de5179abc29217
[ "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
20,956
lean
/- Copyright (c) 2020 Bhavik Mehta, Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Aaron Anderson -/ import ring_theory.power_series.basic import combinatorics.partition import data.nat.parity import data.finset.nat_antidiagonal import data.fin.tuple.nat_antidiagonal import tactic.interval_cases import tactic.apply_fun import tactic.congrm /-! # Euler's Partition Theorem This file proves Theorem 45 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). The theorem concerns the counting of integer partitions -- ways of writing a positive integer `n` as a sum of positive integer parts. Specifically, Euler proved that the number of integer partitions of `n` into *distinct* parts equals the number of partitions of `n` into *odd* parts. ## Proof outline The proof is based on the generating functions for odd and distinct partitions, which turn out to be equal: $$\prod_{i=0}^\infty \frac {1}{1-X^{2i+1}} = \prod_{i=0}^\infty (1+X^{i+1})$$ In fact, we do not take a limit: it turns out that comparing the `n`'th coefficients of the partial products up to `m := n + 1` is sufficient. In particular, we 1. define the partial product for the generating function for odd partitions `partial_odd_gf m` := $$\prod_{i=0}^m \frac {1}{1-X^{2i+1}}$$; 2. prove `odd_gf_prop`: if `m` is big enough (`m * 2 > n`), the partial product's coefficient counts the number of odd partitions; 3. define the partial product for the generating function for distinct partitions `partial_distinct_gf m` := $$\prod_{i=0}^m (1+X^{i+1})$$; 4. prove `distinct_gf_prop`: if `m` is big enough (`m + 1 > n`), the `n`th coefficient of the partial product counts the number of distinct partitions of `n`; 5. prove `same_coeffs`: if m is big enough (`m ≥ n`), the `n`th coefficient of the partial products are equal; 6. combine the above in `partition_theorem`. ## References https://en.wikipedia.org/wiki/Partition_(number_theory)#Odd_parts_and_distinct_parts -/ open power_series noncomputable theory variables {α : Type*} open finset open_locale big_operators open_locale classical /-- The partial product for the generating function for odd partitions. TODO: As `m` tends to infinity, this converges (in the `X`-adic topology). If `m` is sufficiently large, the `i`th coefficient gives the number of odd partitions of the natural number `i`: proved in `odd_gf_prop`. It is stated for an arbitrary field `α`, though it usually suffices to use `ℚ` or `ℝ`. -/ def partial_odd_gf (m : ℕ) [field α] := ∏ i in range m, (1 - (X : power_series α)^(2*i+1))⁻¹ /-- The partial product for the generating function for distinct partitions. TODO: As `m` tends to infinity, this converges (in the `X`-adic topology). If `m` is sufficiently large, the `i`th coefficient gives the number of distinct partitions of the natural number `i`: proved in `distinct_gf_prop`. It is stated for an arbitrary commutative semiring `α`, though it usually suffices to use `ℕ`, `ℚ` or `ℝ`. -/ def partial_distinct_gf (m : ℕ) [comm_semiring α] := ∏ i in range m, (1 + (X : power_series α)^(i+1)) /-- Functions defined only on `s`, which sum to `n`. In other words, a partition of `n` indexed by `s`. Every function in here is finitely supported, and the support is a subset of `s`. This should be thought of as a generalisation of `finset.nat.antidiagonal_tuple` where `antidiagonal_tuple k n` is the same thing as `cut (s : finset.univ (fin k)) n`. -/ def cut {ι : Type*} (s : finset ι) (n : ℕ) : finset (ι → ℕ) := finset.filter (λ f, s.sum f = n) ((s.pi (λ _, range (n+1))).map ⟨λ f i, if h : i ∈ s then f i h else 0, λ f g h, by { ext i hi, simpa [dif_pos hi] using congr_fun h i }⟩) lemma mem_cut {ι : Type*} (s : finset ι) (n : ℕ) (f : ι → ℕ) : f ∈ cut s n ↔ s.sum f = n ∧ ∀ i ∉ s, f i = 0 := begin rw [cut, mem_filter, and_comm, and_congr_right], intro h, simp only [mem_map, exists_prop, function.embedding.coe_fn_mk, mem_pi], split, { rintro ⟨_, _, rfl⟩ _ _, simp [dif_neg H] }, { intro hf, refine ⟨λ i hi, f i, λ i hi, _, _⟩, { rw [mem_range, nat.lt_succ_iff, ← h], apply single_le_sum _ hi, simp }, { ext, rw [dite_eq_ite, ite_eq_left_iff, eq_comm], exact hf x } } end lemma cut_equiv_antidiag (n : ℕ) : equiv.finset_congr (equiv.bool_arrow_equiv_prod _) (cut univ n) = nat.antidiagonal n := begin ext ⟨x₁, x₂⟩, simp_rw [equiv.finset_congr_apply, mem_map, equiv.to_embedding, function.embedding.coe_fn_mk, ←equiv.eq_symm_apply], simp [mem_cut, add_comm], end lemma cut_univ_fin_eq_antidiagonal_tuple (n : ℕ) (k : ℕ) : cut univ n = nat.antidiagonal_tuple k n := by { ext, simp [nat.mem_antidiagonal_tuple, mem_cut] } /-- There is only one `cut` of 0. -/ @[simp] lemma cut_zero {ι : Type*} (s : finset ι) : cut s 0 = {0} := begin -- In general it's nice to prove things using `mem_cut` but in this case it's easier to just -- use the definition. rw [cut, range_one, pi_const_singleton, map_singleton, function.embedding.coe_fn_mk, filter_singleton, if_pos, singleton_inj], { ext, split_ifs; refl }, rw sum_eq_zero_iff, intros x hx, apply dif_pos hx, end @[simp] lemma cut_empty_succ {ι : Type*} (n : ℕ) : cut (∅ : finset ι) (n+1) = ∅ := begin apply eq_empty_of_forall_not_mem, intros x hx, rw [mem_cut, sum_empty] at hx, cases hx.1, end lemma cut_insert {ι : Type*} (n : ℕ) (a : ι) (s : finset ι) (h : a ∉ s) : cut (insert a s) n = (nat.antidiagonal n).bUnion (λ (p : ℕ × ℕ), (cut s p.snd).map ⟨λ f, f + λ t, if t = a then p.fst else 0, add_left_injective _⟩) := begin ext f, rw [mem_cut, mem_bUnion, sum_insert h], split, { rintro ⟨rfl, h₁⟩, simp only [exists_prop, function.embedding.coe_fn_mk, mem_map, nat.mem_antidiagonal, prod.exists], refine ⟨f a, s.sum f, rfl, λ i, if i = a then 0 else f i, _, _⟩, { rw [mem_cut], refine ⟨_, _⟩, { rw [sum_ite], have : (filter (λ x, x ≠ a) s) = s, { apply filter_true_of_mem, rintro i hi rfl, apply h hi }, simp [this] }, { intros i hi, rw ite_eq_left_iff, intro hne, apply h₁, simp [not_or_distrib, hne, hi] } }, { ext, obtain rfl|h := eq_or_ne x a, { simp }, { simp [if_neg h] } } }, { simp only [mem_insert, function.embedding.coe_fn_mk, mem_map, nat.mem_antidiagonal, prod.exists, exists_prop, mem_cut, not_or_distrib], rintro ⟨p, q, rfl, g, ⟨rfl, hg₂⟩, rfl⟩, refine ⟨_, _⟩, { simp [sum_add_distrib, if_neg h, hg₂ _ h, add_comm] }, { rintro i ⟨h₁, h₂⟩, simp [if_neg h₁, hg₂ _ h₂] } } end lemma coeff_prod_range [comm_semiring α] {ι : Type*} (s : finset ι) (f : ι → power_series α) (n : ℕ) : coeff α n (∏ j in s, f j) = ∑ l in cut s n, ∏ i in s, coeff α (l i) (f i) := begin revert n, apply finset.induction_on s, { rintro ⟨_ | n⟩, { simp }, simp [cut_empty_succ, if_neg (nat.succ_ne_zero _)] }, intros a s hi ih n, rw [cut_insert _ _ _ hi, prod_insert hi, coeff_mul, sum_bUnion], { congrm finset.sum _ (λ i, _), simp only [sum_map, pi.add_apply, function.embedding.coe_fn_mk, prod_insert hi, if_pos rfl, ih, mul_sum], apply sum_congr rfl _, intros x hx, rw mem_cut at hx, rw [hx.2 a hi, zero_add], congrm _ * _, apply prod_congr rfl, intros k hk, rw [if_neg, add_zero], exact ne_of_mem_of_not_mem hk hi }, { simp only [set.pairwise_disjoint, set.pairwise, prod.forall, not_and, ne.def, nat.mem_antidiagonal, disjoint_left, mem_map, exists_prop, function.embedding.coe_fn_mk, exists_imp_distrib, not_exists, finset.mem_coe, function.on_fun, mem_cut, and_imp], rintro p₁ q₁ rfl p₂ q₂ h t x p hp hp2 hp3 q hq hq2 hq3, have z := hp3.trans hq3.symm, have := sum_congr (eq.refl s) (λ x _, function.funext_iff.1 z x), obtain rfl : q₁ = q₂, { simpa [sum_add_distrib, hp, hq, if_neg hi] using this }, obtain rfl : p₂ = p₁, { simpa using h }, exact (t rfl).elim } end /-- A convenience constructor for the power series whose coefficients indicate a subset. -/ def indicator_series (α : Type*) [semiring α] (s : set ℕ) : power_series α := power_series.mk (λ n, if n ∈ s then 1 else 0) lemma coeff_indicator (s : set ℕ) [semiring α] (n : ℕ) : coeff α n (indicator_series _ s) = if n ∈ s then 1 else 0 := coeff_mk _ _ lemma coeff_indicator_pos (s : set ℕ) [semiring α] (n : ℕ) (h : n ∈ s): coeff α n (indicator_series _ s) = 1 := by rw [coeff_indicator, if_pos h] lemma coeff_indicator_neg (s : set ℕ) [semiring α] (n : ℕ) (h : n ∉ s): coeff α n (indicator_series _ s) = 0 := by rw [coeff_indicator, if_neg h] lemma constant_coeff_indicator (s : set ℕ) [semiring α] : constant_coeff α (indicator_series _ s) = if 0 ∈ s then 1 else 0 := rfl lemma two_series (i : ℕ) [semiring α] : (1 + (X : power_series α)^i.succ) = indicator_series α {0, i.succ} := begin ext, simp only [coeff_indicator, coeff_one, coeff_X_pow, set.mem_insert_iff, set.mem_singleton_iff, map_add], cases n with d, { simp [(nat.succ_ne_zero i).symm] }, { simp [nat.succ_ne_zero d], }, end lemma num_series' [field α] (i : ℕ) : (1 - (X : power_series α)^(i+1))⁻¹ = indicator_series α { k | i + 1 ∣ k } := begin rw power_series.inv_eq_iff_mul_eq_one, { ext, cases n, { simp [mul_sub, zero_pow, constant_coeff_indicator] }, { simp only [coeff_one, if_neg n.succ_ne_zero, mul_sub, mul_one, coeff_indicator, linear_map.map_sub], simp_rw [coeff_mul, coeff_X_pow, coeff_indicator, boole_mul, sum_ite, filter_filter, sum_const_zero, add_zero, sum_const, nsmul_eq_mul, mul_one, sub_eq_iff_eq_add, zero_add, filter_congr_decidable], symmetry, split_ifs, { suffices : ((nat.antidiagonal n.succ).filter (λ (a : ℕ × ℕ), i + 1 ∣ a.fst ∧ a.snd = i + 1)).card = 1, { simp only [set.mem_set_of_eq], rw this, norm_cast }, rw card_eq_one, cases h with p hp, refine ⟨((i+1) * (p-1), i+1), _⟩, ext ⟨a₁, a₂⟩, simp only [mem_filter, prod.mk.inj_iff, nat.mem_antidiagonal, mem_singleton], split, { rintro ⟨a_left, ⟨a, rfl⟩, rfl⟩, refine ⟨_, rfl⟩, rw [nat.mul_sub_left_distrib, ← hp, ← a_left, mul_one, nat.add_sub_cancel] }, { rintro ⟨rfl, rfl⟩, cases p, { rw mul_zero at hp, cases hp }, rw hp, simp [nat.succ_eq_add_one, mul_add] } }, { suffices : (filter (λ (a : ℕ × ℕ), i + 1 ∣ a.fst ∧ a.snd = i + 1) (nat.antidiagonal n.succ)).card = 0, { simp only [set.mem_set_of_eq], rw this, norm_cast }, rw card_eq_zero, apply eq_empty_of_forall_not_mem, simp only [prod.forall, mem_filter, not_and, nat.mem_antidiagonal], rintro _ h₁ h₂ ⟨a, rfl⟩ rfl, apply h, simp [← h₂] } } }, { simp [zero_pow] }, end def mk_odd : ℕ ↪ ℕ := ⟨λ i, 2 * i + 1, λ x y h, by linarith⟩ -- The main workhorse of the partition theorem proof. lemma partial_gf_prop (α : Type*) [comm_semiring α] (n : ℕ) (s : finset ℕ) (hs : ∀ i ∈ s, 0 < i) (c : ℕ → set ℕ) (hc : ∀ i ∉ s, 0 ∈ c i) : (finset.card ((univ : finset (nat.partition n)).filter (λ p, (∀ j, p.parts.count j ∈ c j) ∧ ∀ j ∈ p.parts, j ∈ s)) : α) = (coeff α n) (∏ (i : ℕ) in s, indicator_series α ((* i) '' c i)) := begin simp_rw [coeff_prod_range, coeff_indicator, prod_boole, sum_boole], congr' 1, refine finset.card_congr (λ p _ i, multiset.count i p.parts • i) _ _ _, { simp only [mem_filter, mem_cut, mem_univ, true_and, exists_prop, and_assoc, and_imp, smul_eq_zero, function.embedding.coe_fn_mk, exists_imp_distrib], rintro ⟨p, hp₁, hp₂⟩ hp₃ hp₄, dsimp only at *, refine ⟨_, _, _⟩, { rw [←hp₂, ←sum_multiset_count_of_subset p s (λ x hx, hp₄ _ (multiset.mem_to_finset.mp hx))] }, { intros i hi, left, exact multiset.count_eq_zero_of_not_mem (mt (hp₄ i) hi) }, { exact λ i hi, ⟨_, hp₃ i, rfl⟩ } }, { intros p₁ p₂ hp₁ hp₂ h, apply nat.partition.ext, simp only [true_and, mem_univ, mem_filter] at hp₁ hp₂, ext i, rw function.funext_iff at h, specialize h i, cases i, { rw multiset.count_eq_zero_of_not_mem, rw multiset.count_eq_zero_of_not_mem, intro a, exact nat.lt_irrefl 0 (hs 0 (hp₂.2 0 a)), intro a, exact nat.lt_irrefl 0 (hs 0 (hp₁.2 0 a)) }, { rwa [nat.nsmul_eq_mul, nat.nsmul_eq_mul, mul_left_inj' i.succ_ne_zero] at h } }, { simp only [mem_filter, mem_cut, mem_univ, exists_prop, true_and, and_assoc], rintros f ⟨hf₁, hf₂, hf₃⟩, refine ⟨⟨∑ i in s, multiset.repeat i (f i / i), _, _⟩, _, _, _⟩, { intros i hi, simp only [exists_prop, mem_sum, mem_map, function.embedding.coe_fn_mk] at hi, rcases hi with ⟨t, ht, z⟩, apply hs, rwa multiset.eq_of_mem_repeat z }, { simp_rw [multiset.sum_sum, multiset.sum_repeat, nat.nsmul_eq_mul, ←hf₁], refine sum_congr rfl (λ i hi, nat.div_mul_cancel _), rcases hf₃ i hi with ⟨w, hw, hw₂⟩, rw ← hw₂, exact dvd_mul_left _ _ }, { intro i, simp_rw [multiset.count_sum', multiset.count_repeat, sum_ite_eq], split_ifs with h h, { rcases hf₃ i h with ⟨w, hw₁, hw₂⟩, rwa [← hw₂, nat.mul_div_cancel _ (hs i h)] }, { exact hc _ h } }, { intros i hi, rw mem_sum at hi, rcases hi with ⟨j, hj₁, hj₂⟩, rwa multiset.eq_of_mem_repeat hj₂ }, { ext i, simp_rw [multiset.count_sum', multiset.count_repeat, sum_ite_eq], split_ifs, { apply nat.div_mul_cancel, rcases hf₃ i h with ⟨w, hw, hw₂⟩, apply dvd.intro_left _ hw₂ }, { rw [zero_smul, hf₂ i h] } } }, end lemma partial_odd_gf_prop [field α] (n m : ℕ) : (finset.card ((univ : finset (nat.partition n)).filter (λ p, ∀ j ∈ p.parts, j ∈ (range m).map mk_odd)) : α) = coeff α n (partial_odd_gf m) := begin rw partial_odd_gf, convert partial_gf_prop α n ((range m).map mk_odd) _ (λ _, set.univ) (λ _ _, trivial) using 2, { congrm card (filter (λ p, _) _), simp only [true_and, forall_const, set.mem_univ] }, { rw finset.prod_map, simp_rw num_series', congrm finset.prod _ (λ x, indicator_series α _), ext k, split, { rintro ⟨p, rfl⟩, refine ⟨p, ⟨⟩, _⟩, apply mul_comm }, rintro ⟨a_w, -, rfl⟩, apply dvd.intro_left a_w rfl }, { intro i, rw mem_map, rintro ⟨a, -, rfl⟩, exact nat.succ_pos _ }, end /-- If m is big enough, the partial product's coefficient counts the number of odd partitions -/ theorem odd_gf_prop [field α] (n m : ℕ) (h : n < m * 2) : (finset.card (nat.partition.odds n) : α) = coeff α n (partial_odd_gf m) := begin rw [← partial_odd_gf_prop], congrm card (filter (λ p, (_ : Prop)) _), apply ball_congr, intros i hi, have hin : i ≤ n, { simpa [p.parts_sum] using multiset.single_le_sum (λ _ _, nat.zero_le _) _ hi }, simp only [mk_odd, exists_prop, mem_range, function.embedding.coe_fn_mk, mem_map], split, { intro hi₂, have := nat.mod_add_div i 2, rw nat.not_even_iff at hi₂, rw [hi₂, add_comm] at this, refine ⟨i / 2, _, this⟩, rw nat.div_lt_iff_lt_mul zero_lt_two, exact lt_of_le_of_lt hin h }, { rintro ⟨a, -, rfl⟩, rw even_iff_two_dvd, apply nat.two_not_dvd_two_mul_add_one }, end lemma partial_distinct_gf_prop [comm_semiring α] (n m : ℕ) : (finset.card ((univ : finset (nat.partition n)).filter (λ p, p.parts.nodup ∧ ∀ j ∈ p.parts, j ∈ (range m).map ⟨nat.succ, nat.succ_injective⟩)) : α) = coeff α n (partial_distinct_gf m) := begin rw partial_distinct_gf, convert partial_gf_prop α n ((range m).map ⟨nat.succ, nat.succ_injective⟩) _ (λ _, {0, 1}) (λ _ _, or.inl rfl) using 2, { congrm card (filter (λ p, _ ∧ _) _), rw multiset.nodup_iff_count_le_one, congrm ∀ (i : ℕ), (_ : Prop), rcases multiset.count i p.parts with _|_|ms; simp }, { simp_rw [finset.prod_map, two_series], congrm finset.prod _ (λ i, indicator_series _ _), simp [set.image_pair] }, { simp only [mem_map, function.embedding.coe_fn_mk], rintro i ⟨_, _, rfl⟩, apply nat.succ_pos } end /-- If m is big enough, the partial product's coefficient counts the number of distinct partitions -/ theorem distinct_gf_prop [comm_semiring α] (n m : ℕ) (h : n < m + 1) : ((nat.partition.distincts n).card : α) = coeff α n (partial_distinct_gf m) := begin erw [← partial_distinct_gf_prop], congrm card (filter (λ p, _) _), apply (and_iff_left _).symm, intros i hi, have : i ≤ n, { simpa [p.parts_sum] using multiset.single_le_sum (λ _ _, nat.zero_le _) _ hi }, simp only [mk_odd, exists_prop, mem_range, function.embedding.coe_fn_mk, mem_map], refine ⟨i-1, _, nat.succ_pred_eq_of_pos (p.parts_pos hi)⟩, rw tsub_lt_iff_right (nat.one_le_iff_ne_zero.mpr (p.parts_pos hi).ne'), exact lt_of_le_of_lt this h, end /-- The key proof idea for the partition theorem, showing that the generating functions for both sequences are ultimately the same (since the factor converges to 0 as m tends to infinity). It's enough to not take the limit though, and just consider large enough `m`. -/ lemma same_gf [field α] (m : ℕ) : partial_odd_gf m * (range m).prod (λ i, (1 - (X : power_series α)^(m+i+1))) = partial_distinct_gf m := begin rw [partial_odd_gf, partial_distinct_gf], induction m with m ih, { simp }, rw nat.succ_eq_add_one, set π₀ : power_series α := ∏ i in range m, (1 - X ^ (m + 1 + i + 1)) with hπ₀, set π₁ : power_series α := ∏ i in range m, (1 - X ^ (2 * i + 1))⁻¹ with hπ₁, set π₂ : power_series α := ∏ i in range m, (1 - X ^ (m + i + 1)) with hπ₂, set π₃ : power_series α := ∏ i in range m, (1 + X ^ (i + 1)) with hπ₃, rw ←hπ₃ at ih, have h : constant_coeff α (1 - X ^ (2 * m + 1)) ≠ 0, { rw [ring_hom.map_sub, ring_hom.map_pow, constant_coeff_one, constant_coeff_X, zero_pow (2 * m).succ_pos, sub_zero], exact one_ne_zero }, calc (∏ i in range (m + 1), (1 - X ^ (2 * i + 1))⁻¹) * ∏ i in range (m + 1), (1 - X ^ (m + 1 + i + 1)) = π₁ * (1 - X ^ (2 * m + 1))⁻¹ * (π₀ * (1 - X ^ (m + 1 + m + 1))) : by rw [prod_range_succ _ m, ←hπ₁, prod_range_succ _ m, ←hπ₀] ... = π₁ * (1 - X ^ (2 * m + 1))⁻¹ * (π₀ * ((1 + X ^ (m + 1)) * (1 - X ^ (m + 1)))) : by rw [←sq_sub_sq, one_pow, add_assoc _ m 1, ←two_mul (m + 1), pow_mul'] ... = π₀ * (1 - X ^ (m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by ring ... = (∏ i in range (m + 1), (1 - X ^ (m + 1 + i))) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by { rw [prod_range_succ', add_zero, hπ₀], simp_rw ←add_assoc } ... = π₂ * (1 - X ^ (m + 1 + m)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by { rw [add_right_comm, hπ₂, ←prod_range_succ], simp_rw [add_right_comm] } ... = π₂ * (1 - X ^ (2 * m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by rw [two_mul, add_right_comm _ m 1] ... = (1 - X ^ (2 * m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * π₂ * (π₁ * (1 + X ^ (m + 1))) : by ring ... = π₂ * (π₁ * (1 + X ^ (m + 1))) : by rw [power_series.mul_inv_cancel _ h, one_mul] ... = π₁ * π₂ * (1 + X ^ (m + 1)) : by ring ... = π₃ * (1 + X ^ (m + 1)) : by rw ih ... = _ : by rw prod_range_succ, end lemma same_coeffs [field α] (m n : ℕ) (h : n ≤ m) : coeff α n (partial_odd_gf m) = coeff α n (partial_distinct_gf m) := begin rw [← same_gf, coeff_mul_prod_one_sub_of_lt_order], rintros i -, rw order_X_pow, exact_mod_cast nat.lt_succ_of_le (le_add_right h), end theorem partition_theorem (n : ℕ) : (nat.partition.odds n).card = (nat.partition.distincts n).card := begin -- We need the counts to live in some field (which contains ℕ), so let's just use ℚ suffices : ((nat.partition.odds n).card : ℚ) = (nat.partition.distincts n).card, { exact_mod_cast this }, rw distinct_gf_prop n (n+1) (by linarith), rw odd_gf_prop n (n+1) (by linarith), apply same_coeffs (n+1) n n.le_succ, end
49d8ec07dbbe984d55338beae5abe8cdfcc7e8e5
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/data/finset/basic.lean
6d89146ef29ff3a092b3d246ffe7d6792db866a9
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
101,751
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, Minchao Wu, Mario Carneiro -/ import data.multiset.finset_ops import tactic.monotonicity import tactic.apply import tactic.nth_rewrite /-! # Finite sets mathlib has several different models for finite sets, and it can be confusing when you're first getting used to them! This file builds the basic theory of `finset α`, modelled as a `multiset α` without duplicates. It's "constructive" in the since that there is an underlying list of elements, although this is wrapped in a quotient by permutations, so anytime you actually use this list you're obligated to show you didn't depend on the ordering. There's also the typeclass `fintype α` (which asserts that there is some `finset α` containing every term of type `α`) as well as the predicate `finite` on `s : set α` (which asserts `nonempty (fintype s)`). -/ open multiset subtype nat function variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := erase_dup_eq_self.2 s.2 instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /-! ### membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /-! ### set coercion -/ /-- Convert a finset to a set in the natural way. -/ instance : has_coe_t (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩ @[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = s := rfl @[simp] lemma coe_mem {s : finset α} (x : (s : set α)) : ↑x ∈ s := x.2 @[simp] lemma mk_coe {s : finset α} (x : (s : set α)) {h} : (⟨x, h⟩ : (s : set α)) = x := subtype.coe_eta _ _ instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ (s : set α)) := s.decidable_mem _ /-! ### extensionality -/ theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[ext] theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext_iff.2 @[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (s₁ : set α) = s₂ ↔ s₁ = s₂ := set.ext_iff.trans ext_iff.symm lemma coe_injective {α} : injective (coe : finset α → set α) := λ s t, coe_inj.1 /-! ### subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset_of_eq {s t : finset α} (h : s = t) : s ⊆ t := h ▸ subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ := λ h' h, subset.trans h h' -- TODO: these should be global attributes, but this will require fixing other files local attribute [trans] subset.trans superset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} : (s₁ : set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff @[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (s₁ : set α) ⊂ s₂ ↔ s₁ ⊂ s₂ := show (s₁ : set α) ⊂ s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_def, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ := set.ssubset_iff_of_subset h /-! ### Nonempty -/ /-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s @[simp, norm_cast] lemma coe_nonempty {s : finset α} : (s:set α).nonempty ↔ s.nonempty := iff.rfl lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty := set.nonempty.mono hst hs /-! ### empty -/ /-- The empty finset -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem not_nonempty_empty : ¬(∅ : finset α).nonempty := λ ⟨x, hx⟩, not_mem_empty x hx @[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : finset α) = ∅ := rfl theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ := λ e, not_mem_empty a $ e ▸ h theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ := exists.elim h $ λ a, ne_empty_of_mem @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ := ⟨nonempty.ne_empty, nonempty_of_ne_empty⟩ theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h)) @[simp] lemma coe_empty : ((∅ : finset α) : set α) = ∅ := rfl /-- A `finset` for an empty type is empty. -/ lemma eq_empty_of_not_nonempty (h : ¬ nonempty α) (s : finset α) : s = ∅ := finset.eq_empty_of_forall_not_mem $ λ x, false.elim $ not_nonempty_iff_imp_false.1 h x /-! ### singleton -/ /-- `{a} : finset a` is the set `{a}` containing `a` and nothing else. This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`. -/ instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩ @[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = a ::ₘ 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl theorem singleton_inj {a b : α} : ({a} : finset α) = {b} ↔ a = b := ⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩ @[simp] theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩ @[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty @[simp, norm_cast] lemma coe_singleton (a : α) : (({a} : finset α) : set α) = {a} := by { ext, simp } lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := begin split; intro t, rw t, refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩, ext, rw finset.mem_singleton, refine ⟨t.right _, λ r, r.symm ▸ t.left⟩ end lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s := by simp only [eq_singleton_iff_unique_mem, exists_unique] lemma singleton_subset_set_iff {s : set α} {a : α} : ↑({a} : finset α) ⊆ s ↔ a ∈ s := by rw [coe_singleton, set.singleton_subset_iff] @[simp] lemma singleton_subset_iff {s : finset α} {a : α} : {a} ⊆ s ↔ a ∈ s := singleton_subset_set_iff /-! ### cons -/ /-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as `insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`, and the union is guaranteed to be disjoint. -/ def cons {α} (a : α) (s : finset α) (h : a ∉ s) : finset α := ⟨a ::ₘ s.1, multiset.nodup_cons.2 ⟨h, s.2⟩⟩ @[simp] theorem mem_cons {α a s h b} : b ∈ @cons α a s h ↔ b = a ∨ b ∈ s := by rcases s with ⟨⟨s⟩⟩; apply list.mem_cons_iff @[simp] theorem cons_val {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl @[simp] theorem mk_cons {a : α} {s : multiset α} (h : (a ::ₘ s).nodup) : (⟨a ::ₘ s, h⟩ : finset α) = cons a ⟨s, (multiset.nodup_cons.1 h).2⟩ (multiset.nodup_cons.1 h).1 := rfl @[simp] theorem nonempty_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).nonempty := ⟨a, mem_cons.2 (or.inl rfl)⟩ @[simp] lemma nonempty_mk_coe : ∀ {l : list α} {hl}, (⟨↑l, hl⟩ : finset α).nonempty ↔ l ≠ [] | [] hl := by simp | (a::l) hl := by simp [← multiset.cons_coe] /-! ### disjoint union -/ /-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`. It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis ensures that the sets are disjoint. -/ def disj_union {α} (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : finset α := ⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, h⟩⟩ @[simp] theorem mem_disj_union {α s t h a} : a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t := by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append /-! ### insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a ::ₘ s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a ::ₘ s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] theorem cons_eq_insert {α} [decidable_eq α] (a s h) : @cons α a s h = insert a s := ext $ λ a, by simp @[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] lemma mem_insert_coe {s : finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : set α) := by simp instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩ @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = {a} := insert_eq_of_mem $ mem_singleton_self _ theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, by simp only [mem_insert, or.left_comm] theorem insert_singleton_comm (a b : α) : ({a, b} : finset α) = {b, a} := begin ext, simp [or.comm] end @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_nonempty (a : α) (s : finset α) : (insert a s).nonempty := ⟨a, mem_insert_self a s⟩ @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := (insert_nonempty a s).ne_empty lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a ∉ s, insert a s ⊆ t) := by exact_mod_cast @set.ssubset_iff_insert α s t lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[elab_as_eliminator] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a ::ₘ s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [insert_val, ndinsert_of_not_mem m] } end) nd /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s /-- To prove a proposition about `S : finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α ⊆ S`, then it holds for the `finset` obtained by inserting a new element of `S`. -/ @[elab_as_eliminator] theorem induction_on' {α : Type*} {p : finset α → Prop} [decidable_eq α] (S : finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S := @finset.induction_on α (λ T, T ⊆ S → p T) _ S (λ _, h₁) (λ a s has hqs hs, let ⟨hS, sS⟩ := finset.insert_subset.1 hs in h₂ hS sS has (hqs sS)) (finset.subset.refl S) /-- Inserting an element to a finite set is equivalent to the option type. -/ def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) : {i // i ∈ insert x t} ≃ option {i // i ∈ t} := begin refine { to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩, inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩, .. }, { intro y, by_cases h : ↑y = x, simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk], simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, { rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk], have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 }, simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, end /-! ### union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion @[simp] theorem disj_union_eq_union {α} [decidable_eq α] (s t h) : @disj_union α s t h = s ∪ t := ext $ λ a, by simp theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem forall_mem_union {s₁ s₂ : finset α} {p : α → Prop} : (∀ ab ∈ (s₁ ∪ s₂), p ab) ↔ (∀ a ∈ s₁, p a) ∧ (∀ b ∈ s₂, p b) := ⟨λ h, ⟨λ a, h a ∘ mem_union_left _, λ b, h b ∘ mem_union_right _⟩, λ h ab hab, (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩ theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp, norm_cast] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ lemma union_subset_union {s1 t1 s2 t2 : finset α} (h1 : s1 ⊆ t1) (h2 : s2 ⊆ t2) : s1 ∪ s2 ⊆ t1 ∪ t2 := by { intros x hx, rw finset.mem_union at hx ⊢, tauto } theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] @[simp] lemma union_eq_left_iff_subset {s t : finset α} : s ∪ t = s ↔ t ⊆ s := begin split, { assume h, have : t ⊆ s ∪ t := subset_union_right _ _, rwa h at this }, { assume h, exact subset.antisymm (union_subset (subset.refl _) h) (subset_union_left _ _) } end @[simp] lemma left_eq_union_iff_subset {s t : finset α} : s = s ∪ t ↔ t ⊆ s := by rw [← union_eq_left_iff_subset, eq_comm] @[simp] lemma union_eq_right_iff_subset {s t : finset α} : t ∪ s = s ↔ t ⊆ s := by rw [union_comm, union_eq_left_iff_subset] @[simp] lemma right_eq_union_iff_subset {s t : finset α} : s = t ∪ s ↔ t ⊆ s := by rw [← union_eq_right_iff_subset, eq_comm] /-! ### inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp, norm_cast] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left] @[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and_assoc] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and.left_comm] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext $ λ _, mem_inter.trans $ false_and _ @[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s := by rw [inter_comm, union_inter_cancel_right] @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] @[mono] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s := finset.inter_subset_inter h (finset.subset.refl _) lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y := finset.inter_subset_inter (finset.subset.refl _) h /-! ### lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice } instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.semilattice_inf_bot, ..finset.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff /-! ### erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro /-- An element of `s` that is not an element of `erase s a` must be `a`. -/ lemma eq_of_mem_of_not_mem_erase {a b : α} {s : finset α} (hs : b ∈ s) (hsa : b ∉ s.erase a) : b = a := begin rw [mem_erase, not_and] at hsa, exact not_imp_not.mp hsa hs end theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ /-! ### sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩ @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 lemma not_mem_sdiff_of_mem_right {a : α} {s t : finset α} (h : a ∈ t) : a ∉ s \ t := by simp only [mem_sdiff, h, not_true, not_false_iff, and_false] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := ext $ λ a, by simpa only [mem_sdiff, mem_union, or_comm, or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a) theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := (union_comm _ _).trans (sdiff_union_of_subset h) theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := (inter_comm _ _).trans (inter_sdiff_self _ _) @[simp] theorem sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ := by ext; simp theorem sdiff_inter_distrib_right (s₁ s₂ s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = (s₁ \ s₂) ∪ (s₁ \ s₃) := by ext; simp only [and_or_distrib_left, mem_union, not_and_distrib, mem_sdiff, mem_inter] @[simp] theorem sdiff_inter_self_left (s₁ s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ := by simp only [sdiff_inter_distrib_right, sdiff_self, empty_union] @[simp] theorem sdiff_inter_self_right (s₁ s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ := by simp only [sdiff_inter_distrib_right, sdiff_self, union_empty] @[simp] theorem sdiff_empty {s₁ : finset α} : s₁ \ ∅ = s₁ := ext (by simp) @[mono] theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂) theorem sdiff_subset_self {s₁ s₂ : finset α} : s₁ \ s₂ ⊆ s₁ := suffices s₁ \ s₂ ⊆ s₁ \ ∅, by simpa [sdiff_empty] using this, sdiff_subset_sdiff (subset.refl _) (empty_subset _) @[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] theorem union_sdiff_self_eq_union {s t : finset α} : s ∪ (t \ s) = s ∪ t := ext $ λ a, by simp only [mem_union, mem_sdiff, or_iff_not_imp_left, imp_and_distrib, and_iff_left id] @[simp] theorem sdiff_union_self_eq_union {s t : finset α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_sdiff_self_eq_union, union_comm] lemma union_sdiff_symm {s t : finset α} : s ∪ (t \ s) = t ∪ (s \ t) := by rw [union_sdiff_self_eq_union, union_sdiff_self_eq_union, union_comm] lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s := by { simp only [ext_iff, mem_union, mem_sdiff, mem_inter], tauto } @[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t := by { simp only [ext_iff, mem_sdiff], tauto } lemma sdiff_eq_empty_iff_subset {s t : finset α} : s \ t = ∅ ↔ s ⊆ t := by { rw [subset_iff, ext_iff], simp } @[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ := by { rw sdiff_eq_empty_iff_subset, exact empty_subset _ } lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) : (insert x s) \ t = insert x (s \ t) := begin rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_not_mem s h end lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) : (insert x s) \ t = s \ t := begin rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_mem s h end @[simp] lemma insert_sdiff_insert (s t : finset α) (x : α) : (insert x s) \ (insert x t) = s \ insert x t := insert_sdiff_of_mem _ (mem_insert_self _ _) lemma sdiff_insert_of_not_mem {s : finset α} {x : α} (h : x ∉ s) (t : finset α) : s \ (insert x t) = s \ t := begin refine subset.antisymm (sdiff_subset_sdiff (subset.refl _) (subset_insert _ _)) (λ y hy, _), simp only [mem_sdiff, mem_insert, not_or_distrib] at hy ⊢, exact ⟨hy.1, λ hxy, h $ hxy ▸ hy.1, hy.2⟩ end @[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s := by simp [subset_iff, mem_sdiff] {contextual := tt} lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := by { simp only [ext_iff, mem_sdiff, mem_union], tauto } lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) := by { simp only [ext_iff, mem_union, mem_sdiff, mem_inter], tauto } lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t := by rw [union_sdiff_distrib, sdiff_self, union_empty] lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a := by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto } lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t := by { simp only [ext_iff, mem_sdiff, mem_inter], tauto } lemma inter_eq_inter_of_sdiff_eq_sdiff {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ → s ∩ t₁ = s ∩ t₂ := by { simp only [ext_iff, mem_sdiff, mem_inter], intros b c, replace b := b c, split; tauto } end decidable_eq /-! ### attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) : sizeof x < sizeof s := by { cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof], apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx } @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl /-! ### piecewise -/ section piecewise /-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/ def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] : Πi, δ i := λi, if i ∈ s then f i else g i variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) @[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } variable [∀j, decidable (j ∈ s)] @[norm_cast] lemma piecewise_coe [∀j, decidable (j ∈ (s : set α))] : (s : set α).piecewise f g = s.piecewise f g := by { ext, congr } @[simp, priority 980] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 980] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] lemma piecewise_congr {f f' g g' : Π i, δ i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) : s.piecewise f g = s.piecewise f' g' := funext $ λ i, if_ctx_congr iff.rfl (hf i) (hg i) @[simp, priority 990] lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)] (h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = update (s.piecewise f g) j (f j) := begin classical, rw [← piecewise_coe, ← piecewise_coe, ← set.piecewise_insert, ← coe_insert j s], congr end lemma piecewise_cases {i} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) := by by_cases hi : i ∈ s; simpa [hi] lemma piecewise_mem_set_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)} {f g} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : s.piecewise f g ∈ set.pi t t' := by { classical, rw ← piecewise_coe, exact set.piecewise_mem_pi ↑s hf hg } lemma piecewise_singleton [decidable_eq α] (i : α) : piecewise {i} f g = update g i (f i) := by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty] lemma piecewise_piecewise_of_subset_left {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : Π a, δ a) : s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g := s.piecewise_congr (λ i hi, piecewise_eq_of_mem _ _ _ (h hi)) (λ _ _, rfl) @[simp] lemma piecewise_idem_left (f₁ f₂ g : Π a, δ a) : s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g := piecewise_piecewise_of_subset_left (subset.refl _) _ _ _ lemma piecewise_piecewise_of_subset_right {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : Π a, δ a) : s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ := s.piecewise_congr (λ _ _, rfl) (λ i hi, t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi)) @[simp] lemma piecewise_idem_right (f g₁ g₂ : Π a, δ a) : s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ := piecewise_piecewise_of_subset_right (subset.refl _) f g₁ g₂ lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) : update f i v = piecewise (singleton i) (λj, v) f := (piecewise_singleton _ _ _).symm lemma update_piecewise [decidable_eq α] (i : α) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) := begin ext j, rcases em (j = i) with (rfl|hj); by_cases hs : j ∈ s; simp * end lemma update_piecewise_of_mem [decidable_eq α] {i : α} (hi : i ∈ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) g := begin rw update_piecewise, refine s.piecewise_congr (λ _ _, rfl) (λ j hj, update_noteq _ _ _), exact λ h, hj (h.symm ▸ hi) end lemma update_piecewise_of_not_mem [decidable_eq α] {i : α} (hi : i ∉ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise f (update g i v) := begin rw update_piecewise, refine s.piecewise_congr (λ j hj, update_noteq _ _ _) (λ _ _, rfl), exact λ h, hi (h ▸ hj) end lemma piecewise_le_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : f ≤ h) (Hg : g ≤ h) : s.piecewise f g ≤ h := λ x, piecewise_cases s f g (≤ h x) (Hf x) (Hg x) lemma le_piecewise_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : h ≤ f) (Hg : h ≤ g) : h ≤ s.piecewise f g := λ x, piecewise_cases s f g (λ y, h x ≤ y) (Hf x) (Hg x) lemma piecewise_mem_Icc_of_mem_of_mem {δ : α → Type*} [Π i, preorder (δ i)] {f f₁ g g₁ : Π i, δ i} (hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) : s.piecewise f g ∈ set.Icc f₁ g₁ := ⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩ lemma piecewise_mem_Icc {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : f ≤ g) : s.piecewise f g ∈ set.Icc f g := piecewise_mem_Icc_of_mem_of_mem _ (set.left_mem_Icc.2 h) (set.right_mem_Icc.2 h) lemma piecewise_mem_Icc' {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : g ≤ f) : s.piecewise f g ∈ set.Icc g f := piecewise_mem_Icc_of_mem_of_mem _ (set.right_mem_Icc.2 h) (set.left_mem_Icc.2 h) end piecewise section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /-! ### filter -/ section filter variables (p q : α → Prop) [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ _ variable {p} @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x := ⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩, λ ⟨x, hs, hp⟩, ⟨s.filter_subset _, λ h, hp (mem_filter.1 (h hs)).2⟩⟩ variable (p) theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext $ assume a, by simp only [mem_filter, and_false]; refl variables {p q} /-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/ @[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s := ext $ λ x, ⟨λ h, (mem_filter.1 h).1, λ hx, mem_filter.2 ⟨hx, h x hx⟩⟩ /-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/ lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ := eq_empty_of_forall_not_mem (by simpa) lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H variables (p q) lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ @[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] lemma filter_mem_eq_inter {s t : finset α} [Π i, decidable (i ∈ t)] : s.filter (λ i, i ∈ t) = s ∩ t := ext $ λ i, by rw [mem_filter, mem_inter] theorem filter_inter (s t : finset α) : filter p s ∩ t = filter p (s ∩ t) := by { ext, simp only [mem_inter, mem_filter, and.right_comm] } theorem inter_filter (s t : finset α) : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else filter p s := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter] theorem sdiff_eq_self (s₁ s₂ : finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ := by { simp [subset.antisymm_iff,sdiff_subset_self], split; intro h, { transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp }, { calc s₁ \ s₂ ⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)] ... ⊇ s₁ \ ∅ : by mono using [(⊇)] ... ⊇ s₁ : by simp [(⊇)] } } theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset p s)] theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin classical, refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, em] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{ x ∈ s | p x }` for `finset.filter s p`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{ x ∈ s | p x }` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{ x ∈ s | p x }` to `finset.filter s p`. If `p` happens to be decidable, the simp-lemma `filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq'` with the equality the other way. -/ -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter (eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintros m ⟨e⟩, exact h m, } end /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq` with the equality the other way. -/ lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ := trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b) lemma filter_ne [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, b ≠ a) = s.erase b := by { ext, simp only [mem_filter, mem_erase, ne.def], cc, } lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a ≠ b) = s.erase b := trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b) end filter /-! ### range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_coe (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem range_mono : monotone range := λ _ _, range_subset.2 end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset /-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/ def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ := { to_fun := λ i, i.1 - k, inv_fun := λ j, ⟨j + k, by simp⟩, left_inv := begin assume j, rw subtype.ext_iff_val, apply nat.sub_add_cancel, simpa using j.2 end, right_inv := λ j, nat.add_sub_cancel _ _ } @[simp] lemma coe_not_mem_range_equiv (k : ℕ) : (not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl @[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) : ((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl namespace option /-- Construct an empty or singleton finset from an `option` -/ def to_finset (o : option α) : finset α := match o with | none := ∅ | some a := {a} end @[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl @[simp] theorem to_finset_some {a : α} : (some a).to_finset = {a} := rfl @[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o := by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl end option /-! ### erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 (erase_dup_eq_self.2 n).symm @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a ::ₘ s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_nsmul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (n •ℕ s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, one_nsmul] }, { rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_union (s t : multiset α) : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by ext; simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero @[simp] lemma to_finset_subset (m1 m2 : multiset α) : m1.to_finset ⊆ m2.to_finset ↔ m1 ⊆ m2 := by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset] end multiset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] lemma to_finset_surj_on : set.surj_on to_finset {l : list α | l.nodup} set.univ := begin rintro s -, cases s with t hl, induction t using quot.ind with l, refine ⟨l, hl, (to_finset_eq hl).symm⟩ end theorem to_finset_surjective : surjective (to_finset : list α → finset α) := by { intro s, rcases to_finset_surj_on (set.mem_univ s) with ⟨l, -, hls⟩, exact ⟨l, hls⟩ } end list namespace finset /-! ### map -/ section map open function /-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/ def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_injective f.2 theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 @[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : finset α) : (↑(s.map f) : set β) = f '' ↑s := set.ext $ λ x, mem_map.trans set.mem_image_iff_bex.symm theorem coe_map_subset_range (f : α ↪ β) (s : finset α) : (↑(s.map f) : set β) ⊆ set.range f := calc ↑(s.map f) = f '' ↑s : coe_map f s ... ⊆ set.range f : set.image_subset_range f ↑s theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] @[simp] theorem map_refl : s.map (embedding.refl _) = s := ext $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := by simp only [subset.antisymm_iff, map_subset_map] /-- Associate to an embedding `f` from `α` to `β` the embedding that maps a finset to its image under `f`. -/ def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩ @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := ext $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩, by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := ext $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := ext $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact ⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩, by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩ @[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} := ext $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ lemma nonempty.map (h : s.nonempty) (f : α ↪ β) : (s.map f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, (mem_map' f).mpr ha⟩ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ.inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] /-! ### image -/ section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ lemma filter_mem_image_eq_image (f : α → β) (s : finset α) (t : finset β) (h : ∀ x ∈ s, f x ∈ t) : t.filter (λ y, y ∈ s.image f) = s.image f := by { ext, rw [mem_filter, mem_image], simp only [and_imp, exists_prop, and_iff_right_iff_imp, exists_imp_distrib], rintros x xel rfl, exact h _ xel } lemma fiber_nonempty_iff_mem_image (f : α → β) (s : finset α) (y : β) : (s.filter (λ x, f x = y)).nonempty ↔ y ∈ s.image f := by simp [finset.nonempty] @[simp, norm_cast] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans set.mem_image_iff_bex.symm lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩ theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f := multiset.erase_dup_eq_self.2 (nodup_map_on H s.2) @[simp] theorem image_id [decidable_eq α] : s.image id = s := ext $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_subset_iff {s : finset α} {t : finset β} {f : α → β} : s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t := calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t : by norm_cast ... ↔ _ : set.image_subset_iff theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image theorem coe_image_subset_range : ↑(s.image f) ⊆ set.range f := calc ↑(s.image f) = f '' ↑s : coe_image ... ⊆ set.range f : set.image_subset_range f ↑s theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} := ext $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (λ h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (λ h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b := ext $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, h.bex, true_and, mem_singleton, eq_comm] /-- Because `finset.image` requires a `decidable_eq` instances for the target type, we can only construct a `functor finset` when working classically. -/ instance [Π P, decidable P] : functor finset := { map := λ α β f s, s.image f, } instance [Π P, decidable P] : is_lawful_functor finset := { id_map := λ α x, image_id, comp_map := λ α β γ f g s, image_image.symm, } /-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose elements belong to `s`. -/ protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subtype_eq_empty {p : α → Prop} [decidable_pred p] {s : finset α} : s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s := by simp [ext_iff, subtype.forall, subtype.coe_mk]; refl /-- `s.subtype p` converts back to `s.filter p` with `embedding.subtype`. -/ @[simp] lemma subtype_map (p : α → Prop) [decidable_pred p] : (s.subtype p).map (embedding.subtype _) = s.filter p := begin ext x, rw mem_map, change (∃ a : {x // p x}, ∃ H, (a : α) = x) ↔ _, split, { rintros ⟨y, hy, hyval⟩, rw [mem_subtype, hyval] at hy, rw mem_filter, use hy, rw ← hyval, use y.property }, { intro hx, rw mem_filter at hx, use ⟨⟨x, hx.2⟩, mem_subtype.2 hx.1, rfl⟩ } end /-- If all elements of a `finset` satisfy the predicate `p`, `s.subtype p` converts back to `s` with `embedding.subtype`. -/ lemma subtype_map_of_mem {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : (s.subtype p).map (embedding.subtype _) = s := by rw [subtype_map, filter_true_of_mem h] /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, all elements of the result have the property of the subtype. -/ lemma property_of_mem_map_subtype {p : α → Prop} (s : finset {x // p x}) {a : α} (h : a ∈ s.map (embedding.subtype _)) : p a := begin rcases mem_map.1 h with ⟨x, hx, rfl⟩, exact x.2 end /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result does not contain any value that does not satisfy the property of the subtype. -/ lemma not_mem_map_subtype_of_not_property {p : α → Prop} (s : finset {x // p x}) {a : α} (h : ¬ p a) : a ∉ (s.map (embedding.subtype _)) := mt s.property_of_mem_map_subtype h /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result is a subset of the set giving the subtype. -/ lemma map_subtype_subset {t : set α} (s : finset t) : ↑(s.map (embedding.subtype _)) ⊆ t := begin intros a ha, rw mem_coe at ha, convert property_of_mem_map_subtype s ha end lemma subset_image_iff {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin classical, split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, induction s using finset.induction with a s has ih h, { refine ⟨∅, set.empty_subset _, _⟩, convert finset.image_empty _ }, rw [finset.coe_insert, set.insert_subset] at h, rcases ih h.2 with ⟨s', hst, hsi⟩, rcases h.1 with ⟨x, hxt, rfl⟩, refine ⟨insert x s', _, _⟩, { rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ }, rw [finset.image_insert, hsi], congr end end image end finset theorem multiset.to_finset_map [decidable_eq α] [decidable_eq β] (f : α → β) (m : multiset α) : (m.map f).to_finset = m.to_finset.image f := finset.val_inj.1 (multiset.erase_dup_map_erase_dup_eq _ _).symm namespace finset /-! ### card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] lemma card_mk {m nodup} : (⟨m, nodup⟩ : finset α).card = m.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s.nonempty := pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 := (not_congr card_eq_zero).2 (ne_empty_of_mem h) theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = {a} := by cases s; simp only [multiset.card_eq_one, finset.card, ← val_inj, singleton_val] @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by simpa only [card_cons, card, insert_val] using congr_arg multiset.card (ndinsert_of_not_mem h) theorem card_insert_of_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∈ s) : card (insert a s) = card s := by rw insert_eq_of_mem h theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card ({a} : finset α) = 1 := card_singleton _ lemma card_singleton_inter [decidable_eq α] {x : α} {s : finset α} : ({x} ∩ s).card ≤ 1 := begin cases (finset.decidable_mem x s), { simp [finset.singleton_inter_of_not_mem h] }, { simp [finset.singleton_inter_of_mem h] }, end theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} : card (erase s a) ≤ card s := card_erase_le theorem pred_card_le_card_erase [decidable_eq α] {a : α} {s : finset α} : card s - 1 ≤ card (erase s a) := begin by_cases h : a ∈ s, { rw [card_erase_of_mem h], refl }, { rw [erase_eq_of_not_mem h], apply nat.sub_le } end @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach end card end finset theorem multiset.to_finset_card_le [decidable_eq α] (m : multiset α) : m.to_finset.card ≤ m.card := card_le_of_le (erase_dup_le _) theorem list.to_finset_card_le [decidable_eq α] (l : list α) : l.to_finset.card ≤ l.length := multiset.to_finset_card_le ⟦l⟧ namespace finset section card theorem card_image_le [decidable_eq β] {f : α → β} {s : finset α} : card (image f s) ≤ card s := by simpa only [card_map] using (s.1.map f).to_finset_card_le theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h lemma fiber_card_ne_zero_iff_mem_image (s : finset α) (f : α → β) [decidable_eq β] (y : β) : (s.filter (λ x, f x = y)).card ≠ 0 ↔ y ∈ s.image f := by { rw [←zero_lt_iff_ne_zero, card_pos, fiber_nonempty_iff_mem_image] } @[simp] lemma card_map {α β} (f : α ↪ β) {s : finset α} : (s.map f).card = s.card := multiset.card_map _ _ lemma card_eq_of_bijective {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := begin classical, have : ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have : s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext_iff, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n end lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := begin classical, calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end end /-- If there are more pigeons than pigeonholes, then there are two pigeons in the same pigeonhole. -/ lemma exists_ne_map_eq_of_card_lt_of_maps_to {s : finset α} {t : finset β} (hc : t.card < s.card) {f : α → β} (hf : ∀ a ∈ s, f a ∈ t) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin classical, by_contra hz, push_neg at hz, refine hc.not_le (card_le_card_of_inj_on f hf _), intros x hx y hy, contrapose, exact hz x hx y hy, end lemma card_le_of_inj_on {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂) /-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to define an object on `s`. Then one can inductively define an object on all finsets, starting from the empty set and iterating. This can be used either to define data, or to prove properties. -/ @[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s | ⟨s, nd⟩ ih := multiset.strong_induction_on s (λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) $ λ a r har, by by_cases a ∈ s; simp *; cc lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ le_add_right _ _ lemma card_union_eq [decidable_eq α] {s t : finset α} (h : disjoint s t) : (s ∪ t).card = s.card + t.card := begin rw [← card_union_add_card_inter], convert (add_zero _).symm, rw [card_eq_zero], rwa [disjoint_iff] at h end lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f a a.prop) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a a.prop) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end open function lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha) (hst : card s ≤ card t) ⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s) (ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in let g : {x // x ∈ t} → {x // x ∈ s} := @surj_inv _ _ f' (λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in have hg : injective g, from injective_surj_inv _, have hsg : surjective g, from λ x, let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x) (λ x _, show (g x) ∈ s.attach, from mem_attach _ _) (λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in ⟨y, hy.snd.symm⟩, have hif : injective f', from (left_inverse_of_surjective_of_right_inverse hsg (right_inverse_surj_inv _)).injective, subtype.ext_iff_val.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂)) end card /-! ### bind -/ section bind variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bind s t` is the union of `t x` over `x ∈ s` -/ protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bind_val (s : finset α) (t : α → finset β) : (s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl @[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t := ext $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib] @[simp] lemma singleton_bind {a : α} : finset.bind {a} t = t a := begin classical, rw [← insert_emptyc_eq, bind_insert, bind_empty, union_empty] end theorem bind_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bind f ∩ t = s.bind (λ x, f x ∩ t) := begin ext x, simp only [mem_bind, mem_inter], tauto end theorem inter_bind (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bind f = s.bind (λ x, t ∩ f x) := by rw [inter_comm, bind_inter]; simp [inter_comm] theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bind t = s.bind (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bind_insert, ih]) theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bind t).image f = s.bind (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bind_insert, image_union, ih]) theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) := ext $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop] lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop] lemma bind_subset_bind_of_subset_left {α : Type*} {s₁ s₂ : finset α} (t : α → finset β) (h : s₁ ⊆ s₂) : s₁.bind t ⊆ s₂.bind t := begin intro x, simp only [and_imp, mem_bind, exists_prop], exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩) end lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f := ext $ λ x, by simp only [mem_bind, mem_image, mem_singleton, eq_comm] @[simp] lemma bind_singleton_eq_self [decidable_eq α] : s.bind (singleton : α → finset α) = s := by { rw bind_singleton, exact image_id } lemma bind_filter_eq_of_maps_to [decidable_eq α] {s : finset α} {t : finset β} {f : α → β} (h : ∀ x ∈ s, f x ∈ t) : t.bind (λa, s.filter $ (λc, f c = a)) = s := begin ext b, suffices : (∃ a ∈ t, b ∈ s ∧ f b = a) ↔ b ∈ s, by simpa, exact ⟨λ ⟨a, ha, hb, hab⟩, hb, λ hb, ⟨f b, h b hb, hb, rfl⟩⟩ end lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bind (λa, s.filter $ (λc, g c = a)) = s := bind_filter_eq_of_maps_to (λ x, mem_image_of_mem g) end bind /-! ### prod -/ section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} : s ⊆ (s.image prod.fst).product (s.image prod.snd) := λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩ theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bind (λa, t.image $ λb, (a, b)) := ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ theorem filter_product (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : (s.product t).filter (λ (x : α × β), p x.1 ∧ q x.2) = (s.filter p).product (t.filter q) := by { ext ⟨a, b⟩, simp only [mem_filter, mem_product], finish, } lemma filter_product_card (s : finset α) (t : finset β) (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : ((s.product t).filter (λ (x : α × β), p x.1 ↔ q x.2)).card = (s.filter p).card * (t.filter q).card + (s.filter (not ∘ p)).card * (t.filter (not ∘ q)).card := begin classical, rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_eq], { apply congr_arg, ext ⟨a, b⟩, simp only [filter_union_right, mem_filter, mem_product], split; intros; finish, }, { rw disjoint_iff, change _ ∩ _ = ∅, ext ⟨a, b⟩, rw mem_inter, finish, }, end end prod /-! ### sigma -/ section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bind [decidable_eq (Σ a, σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bind (λa, (t a).map $ embedding.sigma_mk a) := by { ext ⟨x, y⟩, simp [and.left_comm] } end sigma /-! ### disjoint -/ section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) := decidable_of_decidable_of_iff (by apply_instance) eq_bot_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans singleton_disjoint @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint lemma sdiff_eq_self_iff_disjoint {s t : finset α} : s \ t = s ↔ disjoint s t := by rw [sdiff_eq_self, subset_empty, disjoint_iff_inter_eq_empty] lemma sdiff_eq_self_of_disjoint {s t : finset α} (h : disjoint s t) : s \ t = s := sdiff_eq_self_iff_disjoint.2 h lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ := disjoint_self lemma disjoint_bind_left {ι : Type*} (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bind f) t ↔ (∀i∈s, disjoint (f i) t) := begin classical, refine s.induction _ _, { simp only [forall_mem_empty_iff, bind_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bind_insert, his, forall_mem_insert, ih] } end lemma disjoint_bind_right {ι : Type*} (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bind f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bind_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) := by split; simp [disjoint_left] {contextual := tt} lemma disjoint_filter_filter {s t : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : (disjoint s t) → disjoint (s.filter p) (t.filter q) := disjoint.mono (filter_subset _ _) (filter_subset _ _) lemma disjoint_iff_disjoint_coe {α : Type*} {a b : finset α} [decidable_eq α] : disjoint a b ↔ disjoint (↑a : set α) (↑b : set α) := by { rw [finset.disjoint_left, set.disjoint_left], refl } lemma filter_card_add_filter_neg_card_eq_card {α : Type*} {s : finset α} (p : α → Prop) [decidable_pred p] : (s.filter p).card + (s.filter (not ∘ p)).card = s.card := by { classical, simp [← card_union_eq, filter_union_filter_neg_eq, disjoint_filter], } end disjoint section self_prod variables (s : finset α) [decidable_eq α] /-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for `a ∈ s`. -/ def diag := (s.product s).filter (λ (a : α × α), a.fst = a.snd) /-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`. -/ def off_diag := (s.product s).filter (λ (a : α × α), a.fst ≠ a.snd) @[simp] lemma mem_diag (x : α × α) : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 := by { simp only [diag, mem_filter, mem_product], split; intros; finish, } @[simp] lemma mem_off_diag (x : α × α) : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := by { simp only [off_diag, mem_filter, mem_product], split; intros; finish, } @[simp] lemma diag_card : (diag s).card = s.card := begin suffices : diag s = s.image (λ a, (a, a)), { rw this, apply card_image_of_inj_on, finish, }, ext ⟨a₁, a₂⟩, rw mem_diag, split; intros; finish, end @[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card := begin suffices : (diag s).card + (off_diag s).card = s.card * s.card, { nth_rewrite 2 ← s.diag_card, finish, }, rw ← card_product, apply filter_card_add_filter_neg_card_eq_card, end end self_prod /-- Given a set A and a set B inside it, we can shrink A to any appropriate size, and keep B inside it. -/ lemma exists_intermediate_set {A B : finset α} (i : ℕ) (h₁ : i + card B ≤ card A) (h₂ : B ⊆ A) : ∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B := begin classical, rcases nat.le.dest h₁ with ⟨k, _⟩, clear h₁, induction k with k ih generalizing A, { exact ⟨A, h₂, subset.refl _, h.symm⟩ }, { have : (A \ B).nonempty, { rw [← card_pos, card_sdiff h₂, ← h, nat.add_right_comm, nat.add_sub_cancel, nat.add_succ], apply nat.succ_pos }, rcases this with ⟨a, ha⟩, have z : i + card B + k = card (erase A a), { rw [card_erase_of_mem, ← h, nat.add_succ, nat.pred_succ], rw mem_sdiff at ha, exact ha.1 }, rcases ih _ z with ⟨B', hB', B'subA', cards⟩, { exact ⟨B', hB', trans B'subA' (erase_subset _ _), cards⟩ }, { rintros t th, apply mem_erase_of_ne_of_mem _ (h₂ th), rintro rfl, exact not_mem_sdiff_of_mem_right th ha } } end /-- We can shrink A to any smaller size. -/ lemma exists_smaller_set (A : finset α) (i : ℕ) (h₁ : i ≤ card A) : ∃ (B : finset α), B ⊆ A ∧ card B = i := let ⟨B, _, x₁, x₂⟩ := exists_intermediate_set i (by simpa) (empty_subset A) in ⟨B, x₁, x₂⟩ /-- `finset.fin_range k` is the finset `{0, 1, ..., k-1}`, as a `finset (fin k)`. -/ def fin_range (k : ℕ) : finset (fin k) := ⟨list.fin_range k, list.nodup_fin_range k⟩ @[simp] lemma fin_range_card {k : ℕ} : (fin_range k).card = k := by simp [fin_range] @[simp] lemma mem_fin_range {k : ℕ} (m : fin k) : m ∈ fin_range k := list.mem_fin_range m /-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n` is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.veq_of_eq) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ (a : ℕ) ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ /-! ### choose -/ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the ambient type. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose theorem lt_wf {α} : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf end finset namespace equiv /-- Given an equivalence `α` to `β`, produce an equivalence between `finset α` and `finset β`. -/ protected def finset_congr (e : α ≃ β) : finset α ≃ finset β := { to_fun := λ s, s.map e.to_embedding, inv_fun := λ s, s.map e.symm.to_embedding, left_inv := λ s, by simp [finset.map_map], right_inv := λ s, by simp [finset.map_map] } @[simp] lemma finset_congr_apply (e : α ≃ β) (s : finset α) : e.finset_congr s = s.map e.to_embedding := rfl @[simp] lemma finset_congr_symm_apply (e : α ≃ β) (s : finset β) : e.finset_congr.symm s = s.map e.symm.to_embedding := rfl end equiv namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h end list namespace multiset variable [decidable_eq α] theorem to_finset_card_of_nodup {l : multiset α} (h : l.nodup) : l.to_finset.card = l.card := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h lemma disjoint_to_finset (m1 m2 : multiset α) : _root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 := begin rw finset.disjoint_iff_ne, split, { intro h, intros a ha1 ha2, rw ← multiset.mem_to_finset at ha1 ha2, exact h _ ha1 _ ha2 rfl }, { rintros h a ha b hb rfl, rw multiset.mem_to_finset at ha hb, exact h ha hb } end end multiset
b3c47a329d5f3cc74fba3b877e58f862fcec10bf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/free_module/rank.lean
8527af1eb787988c06e1621103bb6a3cc993fb1d
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,038
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import linear_algebra.free_module.basic import linear_algebra.finsupp_vector_space /-! # Rank of free modules This is a basic API for the rank of free modules. -/ universes u v w variables (R : Type u) (M : Type v) (N : Type w) open_locale tensor_product direct_sum big_operators cardinal open cardinal namespace module.free section ring variables [ring R] [strong_rank_condition R] variables [add_comm_group M] [module R M] [module.free R M] variables [add_comm_group N] [module R N] [module.free R N] /-- The rank of a free module `M` over `R` is the cardinality of `choose_basis_index R M`. -/ lemma rank_eq_card_choose_basis_index : module.rank R M = #(choose_basis_index R M) := (choose_basis R M).mk_eq_dim''.symm /-- The rank of `(ι →₀ R)` is `(# ι).lift`. -/ @[simp] lemma rank_finsupp {ι : Type v} : module.rank R (ι →₀ R) = (# ι).lift := by simpa [lift_id', lift_umax] using (basis.of_repr (linear_equiv.refl _ (ι →₀ R))).mk_eq_dim.symm /-- If `R` and `ι` lie in the same universe, the rank of `(ι →₀ R)` is `# ι`. -/ lemma rank_finsupp' {ι : Type u} : module.rank R (ι →₀ R) = # ι := by simp /-- The rank of `M × N` is `(module.rank R M).lift + (module.rank R N).lift`. -/ @[simp] lemma rank_prod : module.rank R (M × N) = lift.{w v} (module.rank R M) + lift.{v w} (module.rank R N) := by simpa [rank_eq_card_choose_basis_index R M, rank_eq_card_choose_basis_index R N, lift_umax, lift_umax'] using ((choose_basis R M).prod (choose_basis R N)).mk_eq_dim.symm /-- If `M` and `N` lie in the same universe, the rank of `M × N` is `(module.rank R M) + (module.rank R N)`. -/ lemma rank_prod' (N : Type v) [add_comm_group N] [module R N] [module.free R N] : module.rank R (M × N) = (module.rank R M) + (module.rank R N) := by simp /-- The rank of the direct sum is the sum of the ranks. -/ @[simp] lemma rank_direct_sum {ι : Type v} (M : ι → Type w) [Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.rank R (⨁ i, M i) = cardinal.sum (λ i, module.rank R (M i)) := begin let B := λ i, choose_basis R (M i), let b : basis _ R (⨁ i, M i) := dfinsupp.basis (λ i, B i), simp [← b.mk_eq_dim'', λ i, (B i).mk_eq_dim''], end /-- The rank of a finite product is the sum of the ranks. -/ @[simp] lemma rank_pi_finite {ι : Type v} [finite ι] {M : ι → Type w} [Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.rank R (Π i, M i) = cardinal.sum (λ i, module.rank R (M i)) := by { casesI nonempty_fintype ι, rw [←(direct_sum.linear_equiv_fun_on_fintype _ _ M).dim_eq, rank_direct_sum] } /-- If `m` and `n` are `fintype`, the rank of `m × n` matrices is `(# m).lift * (# n).lift`. -/ @[simp] lemma rank_matrix (m : Type v) (n : Type w) [finite m] [finite n] : module.rank R (matrix m n R) = (lift.{(max v w u) v} (# m)) * (lift.{(max v w u) w} (# n)) := begin casesI nonempty_fintype m, casesI nonempty_fintype n, have h := (matrix.std_basis R m n).mk_eq_dim, rw [← lift_lift.{(max v w u) (max v w)}, lift_inj] at h, simpa using h.symm, end /-- If `m` and `n` are `fintype` that lie in the same universe, the rank of `m × n` matrices is `(# n * # m).lift`. -/ @[simp] lemma rank_matrix' (m n : Type v) [finite m] [finite n] : module.rank R (matrix m n R) = (# m * # n).lift := by rw [rank_matrix, lift_mul, lift_umax] /-- If `m` and `n` are `fintype` that lie in the same universe as `R`, the rank of `m × n` matrices is `# m * # n`. -/ @[simp] lemma rank_matrix'' (m n : Type u) [finite m] [finite n] : module.rank R (matrix m n R) = # m * # n := by simp end ring section comm_ring variables [comm_ring R] [strong_rank_condition R] variables [add_comm_group M] [module R M] [module.free R M] variables [add_comm_group N] [module R N] [module.free R N] /-- The rank of `M ⊗[R] N` is `(module.rank R M).lift * (module.rank R N).lift`. -/ @[simp] lemma rank_tensor_product : module.rank R (M ⊗[R] N) = lift.{w v} (module.rank R M) * lift.{v w} (module.rank R N) := begin let ιM := choose_basis_index R M, let ιN := choose_basis_index R N, have h₁ := linear_equiv.lift_dim_eq (tensor_product.congr (repr R M) (repr R N)), let b : basis (ιM × ιN) R (_ →₀ R) := finsupp.basis_single_one, rw [linear_equiv.dim_eq (finsupp_tensor_finsupp' R ιM ιN), ← b.mk_eq_dim, mk_prod] at h₁, rw [lift_inj.1 h₁, rank_eq_card_choose_basis_index R M, rank_eq_card_choose_basis_index R N], end /-- If `M` and `N` lie in the same universe, the rank of `M ⊗[R] N` is `(module.rank R M) * (module.rank R N)`. -/ lemma rank_tensor_product' (N : Type v) [add_comm_group N] [module R N] [module.free R N] : module.rank R (M ⊗[R] N) = (module.rank R M) * (module.rank R N) := by simp end comm_ring end module.free
5316a127736fdc3a6cb3546b1db31188d12ff293
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/whiskering.lean
7229b7ebf45508c860c57dc1ea0f48323000f5ed
[]
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,089
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.natural_isomorphism import Mathlib.PostPort universes u₁ u₂ u₃ v₁ v₂ v₃ u₄ v₄ u₅ v₅ namespace Mathlib namespace category_theory /-- If `α : G ⟶ H` then `whisker_left F α : (F ⋙ G) ⟶ (F ⋙ H)` has components `α.app (F.obj X)`. -/ @[simp] theorem whisker_left_app {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D) {G : D ⥤ E} {H : D ⥤ E} (α : G ⟶ H) (X : C) : nat_trans.app (whisker_left F α) X = nat_trans.app α (functor.obj F X) := Eq.refl (nat_trans.app (whisker_left F α) X) /-- If `α : G ⟶ H` then `whisker_right α F : (G ⋙ F) ⟶ (G ⋙ F)` has components `F.map (α.app X)`. -/ def whisker_right {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {G : C ⥤ D} {H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) : G ⋙ F ⟶ H ⋙ F := nat_trans.mk fun (X : C) => functor.map F (nat_trans.app α X) /-- Left-composition gives a functor `(C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E))`. `(whiskering_lift.obj F).obj G` is `F ⋙ G`, and `(whiskering_lift.obj F).map α` is `whisker_left F α`. -/ def whiskering_left (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] : (C ⥤ D) ⥤ (D ⥤ E) ⥤ C ⥤ E := functor.mk (fun (F : C ⥤ D) => functor.mk (fun (G : D ⥤ E) => F ⋙ G) fun (G H : D ⥤ E) (α : G ⟶ H) => whisker_left F α) fun (F G : C ⥤ D) (τ : F ⟶ G) => nat_trans.mk fun (H : D ⥤ E) => nat_trans.mk fun (c : C) => functor.map H (nat_trans.app τ c) /-- Right-composition gives a functor `(D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E))`. `(whiskering_right.obj H).obj F` is `F ⋙ H`, and `(whiskering_right.obj H).map α` is `whisker_right α H`. -/ @[simp] theorem whiskering_right_obj_map (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] (H : D ⥤ E) (_x : C ⥤ D) : ∀ (_x_1 : C ⥤ D) (α : _x ⟶ _x_1), functor.map (functor.obj (whiskering_right C D E) H) α = whisker_right α H := fun (_x_1 : C ⥤ D) (α : _x ⟶ _x_1) => Eq.refl (functor.map (functor.obj (whiskering_right C D E) H) α) @[simp] theorem whisker_left_id {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D) {G : D ⥤ E} : whisker_left F (nat_trans.id G) = nat_trans.id (F ⋙ G) := rfl @[simp] theorem whisker_left_id' {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D) {G : D ⥤ E} : whisker_left F 𝟙 = 𝟙 := rfl @[simp] theorem whisker_right_id {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {G : C ⥤ D} (F : D ⥤ E) : whisker_right (nat_trans.id G) F = nat_trans.id (G ⋙ F) := functor.map_id (functor.obj (whiskering_right C D E) F) G @[simp] theorem whisker_right_id' {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {G : C ⥤ D} (F : D ⥤ E) : whisker_right 𝟙 F = 𝟙 := functor.map_id (functor.obj (whiskering_right C D E) F) G @[simp] theorem whisker_left_comp {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D) {G : D ⥤ E} {H : D ⥤ E} {K : D ⥤ E} (α : G ⟶ H) (β : H ⟶ K) : whisker_left F (α ≫ β) = whisker_left F α ≫ whisker_left F β := rfl @[simp] theorem whisker_right_comp {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {G : C ⥤ D} {H : C ⥤ D} {K : C ⥤ D} (α : G ⟶ H) (β : H ⟶ K) (F : D ⥤ E) : whisker_right (α ≫ β) F = whisker_right α F ≫ whisker_right β F := functor.map_comp (functor.obj (whiskering_right C D E) F) α β /-- If `α : G ≅ H` is a natural isomorphism then `iso_whisker_left F α : (F ⋙ G) ≅ (F ⋙ H)` has components `α.app (F.obj X)`. -/ def iso_whisker_left {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D) {G : D ⥤ E} {H : D ⥤ E} (α : G ≅ H) : F ⋙ G ≅ F ⋙ H := functor.map_iso (functor.obj (whiskering_left C D E) F) α @[simp] theorem iso_whisker_left_hom {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D) {G : D ⥤ E} {H : D ⥤ E} (α : G ≅ H) : iso.hom (iso_whisker_left F α) = whisker_left F (iso.hom α) := rfl @[simp] theorem iso_whisker_left_inv {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D) {G : D ⥤ E} {H : D ⥤ E} (α : G ≅ H) : iso.inv (iso_whisker_left F α) = whisker_left F (iso.inv α) := rfl /-- If `α : G ≅ H` then `iso_whisker_right α F : (G ⋙ F) ≅ (G ⋙ F)` has components `F.map_iso (α.app X)`. -/ def iso_whisker_right {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {G : C ⥤ D} {H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : G ⋙ F ≅ H ⋙ F := functor.map_iso (functor.obj (whiskering_right C D E) F) α @[simp] theorem iso_whisker_right_hom {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {G : C ⥤ D} {H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : iso.hom (iso_whisker_right α F) = whisker_right (iso.hom α) F := rfl @[simp] theorem iso_whisker_right_inv {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {G : C ⥤ D} {H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : iso.inv (iso_whisker_right α F) = whisker_right (iso.inv α) F := rfl protected instance is_iso_whisker_left {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D) {G : D ⥤ E} {H : D ⥤ E} (α : G ⟶ H) [is_iso α] : is_iso (whisker_left F α) := is_iso.mk (iso.inv (iso_whisker_left F (as_iso α))) protected instance is_iso_whisker_right {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {G : C ⥤ D} {H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) [is_iso α] : is_iso (whisker_right α F) := is_iso.mk (iso.inv (iso_whisker_right (as_iso α) F)) @[simp] theorem whisker_left_twice {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {B : Type u₄} [category B] (F : B ⥤ C) (G : C ⥤ D) {H : D ⥤ E} {K : D ⥤ E} (α : H ⟶ K) : whisker_left F (whisker_left G α) = whisker_left (F ⋙ G) α := rfl @[simp] theorem whisker_right_twice {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {B : Type u₄} [category B] {H : B ⥤ C} {K : B ⥤ C} (F : C ⥤ D) (G : D ⥤ E) (α : H ⟶ K) : whisker_right (whisker_right α F) G = whisker_right α (F ⋙ G) := rfl theorem whisker_right_left {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {B : Type u₄} [category B] (F : B ⥤ C) {G : C ⥤ D} {H : C ⥤ D} (α : G ⟶ H) (K : D ⥤ E) : whisker_right (whisker_left F α) K = whisker_left F (whisker_right α K) := rfl namespace functor /-- The left unitor, a natural isomorphism `((𝟭 _) ⋙ F) ≅ F`. -/ @[simp] theorem left_unitor_hom_app {A : Type u₁} [category A] {B : Type u₂} [category B] (F : A ⥤ B) (X : A) : nat_trans.app (iso.hom (left_unitor F)) X = 𝟙 := Eq.refl (nat_trans.app (iso.hom (left_unitor F)) X) /-- The right unitor, a natural isomorphism `(F ⋙ (𝟭 B)) ≅ F`. -/ @[simp] theorem right_unitor_hom_app {A : Type u₁} [category A] {B : Type u₂} [category B] (F : A ⥤ B) (X : A) : nat_trans.app (iso.hom (right_unitor F)) X = 𝟙 := Eq.refl (nat_trans.app (iso.hom (right_unitor F)) X) /-- The associator for functors, a natural isomorphism `((F ⋙ G) ⋙ H) ≅ (F ⋙ (G ⋙ H))`. (In fact, `iso.refl _` will work here, but it tends to make Lean slow later, and it's usually best to insert explicit associators.) -/ @[simp] theorem associator_inv_app {A : Type u₁} [category A] {B : Type u₂} [category B] {C : Type u₃} [category C] {D : Type u₄} [category D] (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) (_x : A) : nat_trans.app (iso.inv (associator F G H)) _x = 𝟙 := Eq.refl (nat_trans.app (iso.inv (associator F G H)) _x) theorem triangle {A : Type u₁} [category A] {B : Type u₂} [category B] {C : Type u₃} [category C] (F : A ⥤ B) (G : B ⥤ C) : iso.hom (associator F 𝟭 G) ≫ whisker_left F (iso.hom (left_unitor G)) = whisker_right (iso.hom (right_unitor F)) G := sorry theorem pentagon {A : Type u₁} [category A] {B : Type u₂} [category B] {C : Type u₃} [category C] {D : Type u₄} [category D] {E : Type u₅} [category E] (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) (K : D ⥤ E) : whisker_right (iso.hom (associator F G H)) K ≫ iso.hom (associator F (G ⋙ H) K) ≫ whisker_left F (iso.hom (associator G H K)) = iso.hom (associator (F ⋙ G) H K) ≫ iso.hom (associator F G (H ⋙ K)) := sorry
aebe8805bc4e425584b032fe9f3ce68f5e4eebeb
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/hf.lean
13334fe487549148cb980c41d6d8928f70bbd9f9
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
25,411
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Hereditarily finite sets: finite sets whose elements are all hereditarily finite sets. Remark: all definitions compute, however the performace is quite poor since we implement this module using a bijection from (finset nat) to nat, and this bijection is implemeted using the Ackermann coding. -/ import data.nat data.finset.equiv data.list open nat binary open - [notation] finset definition hf := nat namespace hf local attribute hf [reducible] protected definition prio : num := num.succ std.priority.default protected definition is_inhabited [instance] : inhabited hf := nat.is_inhabited protected definition has_decidable_eq [reducible] [instance] : decidable_eq hf := nat.has_decidable_eq definition of_finset (s : finset hf) : hf := @equiv.to_fun _ _ finset_nat_equiv_nat s definition to_finset (h : hf) : finset hf := @equiv.inv _ _ finset_nat_equiv_nat h definition to_nat (h : hf) : nat := h definition of_nat (n : nat) : hf := n lemma to_finset_of_finset (s : finset hf) : to_finset (of_finset s) = s := @equiv.left_inv _ _ finset_nat_equiv_nat s lemma of_finset_to_finset (s : hf) : of_finset (to_finset s) = s := @equiv.right_inv _ _ finset_nat_equiv_nat s lemma to_finset_inj {s₁ s₂ : hf} : to_finset s₁ = to_finset s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse of_finset_to_finset h lemma of_finset_inj {s₁ s₂ : finset hf} : of_finset s₁ = of_finset s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse to_finset_of_finset h /- empty -/ definition empty : hf := of_finset (finset.empty) notation `∅` := hf.empty /- insert -/ definition insert (a s : hf) : hf := of_finset (finset.insert a (to_finset s)) /- mem -/ definition mem (a : hf) (s : hf) : Prop := finset.mem a (to_finset s) infix ∈ := mem notation [priority finset.prio] a ∉ b := ¬ mem a b lemma insert_lt_of_not_mem {a s : hf} : a ∉ s → s < insert a s := begin unfold [insert, of_finset, equiv.to_fun, finset_nat_equiv_nat, mem, to_finset, equiv.inv], intro h, rewrite [finset.to_nat_insert h], rewrite [to_nat_of_nat, -zero_add s at {1}], apply add_lt_add_right, apply pow_pos_of_pos _ dec_trivial end lemma insert_lt_insert_of_not_mem_of_not_mem_of_lt {a s₁ s₂ : hf} : a ∉ s₁ → a ∉ s₂ → s₁ < s₂ → insert a s₁ < insert a s₂ := begin unfold [insert, of_finset, equiv.to_fun, finset_nat_equiv_nat, mem, to_finset, equiv.inv], intro h₁ h₂ h₃, rewrite [finset.to_nat_insert h₁], rewrite [finset.to_nat_insert h₂, *to_nat_of_nat], apply add_lt_add_left h₃ end open decidable protected definition decidable_mem [instance] : ∀ a s, decidable (a ∈ s) := λ a s, finset.decidable_mem a (to_finset s) lemma insert_le (a s : hf) : s ≤ insert a s := by_cases (suppose a ∈ s, by rewrite [↑insert, insert_eq_of_mem this, of_finset_to_finset]) (suppose a ∉ s, le_of_lt (insert_lt_of_not_mem this)) lemma not_mem_empty (a : hf) : a ∉ ∅ := begin unfold [mem, empty], rewrite to_finset_of_finset, apply finset.not_mem_empty end lemma mem_insert (a s : hf) : a ∈ insert a s := begin unfold [mem, insert], rewrite to_finset_of_finset, apply finset.mem_insert end lemma mem_insert_of_mem {a s : hf} (b : hf) : a ∈ s → a ∈ insert b s := begin unfold [mem, insert], intros, rewrite to_finset_of_finset, apply finset.mem_insert_of_mem, assumption end lemma eq_or_mem_of_mem_insert {a b s : hf} : a ∈ insert b s → a = b ∨ a ∈ s := begin unfold [mem, insert], rewrite to_finset_of_finset, intros, apply eq_or_mem_of_mem_insert, assumption end theorem mem_of_mem_insert_of_ne {x a : hf} {s : hf} : x ∈ insert a s → x ≠ a → x ∈ s := begin unfold [mem, insert], rewrite to_finset_of_finset, intros, apply mem_of_mem_insert_of_ne, repeat assumption end protected theorem ext {s₁ s₂ : hf} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := assume h, assert to_finset s₁ = to_finset s₂, from finset.ext h, assert of_finset (to_finset s₁) = of_finset (to_finset s₂), by rewrite this, by rewrite [*of_finset_to_finset at this]; exact this theorem insert_eq_of_mem {a : hf} {s : hf} : a ∈ s → insert a s = s := begin unfold mem, intro h, unfold [mem, insert], rewrite (finset.insert_eq_of_mem h), rewrite of_finset_to_finset end protected theorem induction [recursor 4] {P : hf → Prop} (h₁ : P empty) (h₂ : ∀ (a s : hf), a ∉ s → P s → P (insert a s)) (s : hf) : P s := assert P (of_finset (to_finset s)), from @finset.induction _ _ _ h₁ (λ a s nain ih, begin unfold [mem, insert] at h₂, rewrite -(to_finset_of_finset s) at nain, have P (insert a (of_finset s)), by exact h₂ a (of_finset s) nain ih, rewrite [↑insert at this, to_finset_of_finset at this], exact this end) (to_finset s), by rewrite of_finset_to_finset at this; exact this lemma insert_le_insert_of_le {a s₁ s₂ : hf} : a ∈ s₁ ∨ a ∉ s₂ → s₁ ≤ s₂ → insert a s₁ ≤ insert a s₂ := suppose a ∈ s₁ ∨ a ∉ s₂, suppose s₁ ≤ s₂, by_cases (suppose s₁ = s₂, by rewrite this) (suppose s₁ ≠ s₂, have s₁ < s₂, from lt_of_le_of_ne `s₁ ≤ s₂` `s₁ ≠ s₂`, by_cases (suppose a ∈ s₁, by_cases (suppose a ∈ s₂, by rewrite [insert_eq_of_mem `a ∈ s₁`, insert_eq_of_mem `a ∈ s₂`]; assumption) (suppose a ∉ s₂, by rewrite [insert_eq_of_mem `a ∈ s₁`]; exact le.trans `s₁ ≤ s₂` !insert_le)) (suppose a ∉ s₁, by_cases (suppose a ∈ s₂, or.elim `a ∈ s₁ ∨ a ∉ s₂` (by contradiction) (by contradiction)) (suppose a ∉ s₂, le_of_lt (insert_lt_insert_of_not_mem_of_not_mem_of_lt `a ∉ s₁` `a ∉ s₂` `s₁ < s₂`)))) /- union -/ definition union (s₁ s₂ : hf) : hf := of_finset (finset.union (to_finset s₁) (to_finset s₂)) infix [priority hf.prio] ∪ := union theorem mem_union_left {a : hf} {s₁ : hf} (s₂ : hf) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := begin unfold mem, intro h, unfold union, rewrite to_finset_of_finset, apply finset.mem_union_left _ h end theorem mem_union_l {a : hf} {s₁ : hf} {s₂ : hf} : a ∈ s₁ → a ∈ s₁ ∪ s₂ := mem_union_left s₂ theorem mem_union_right {a : hf} {s₂ : hf} (s₁ : hf) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := begin unfold mem, intro h, unfold union, rewrite to_finset_of_finset, apply finset.mem_union_right _ h end theorem mem_union_r {a : hf} {s₂ : hf} {s₁ : hf} : a ∈ s₂ → a ∈ s₁ ∪ s₂ := mem_union_right s₁ theorem mem_or_mem_of_mem_union {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∪ s₂ → a ∈ s₁ ∨ a ∈ s₂ := begin unfold [mem, union], rewrite to_finset_of_finset, intro h, apply finset.mem_or_mem_of_mem_union h end theorem mem_union_iff {a : hf} (s₁ s₂ : hf) : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := iff.intro (λ h, mem_or_mem_of_mem_union h) (λ d, or.elim d (λ i, mem_union_left _ i) (λ i, mem_union_right _ i)) theorem mem_union_eq {a : hf} (s₁ s₂ : hf) : (a ∈ s₁ ∪ s₂) = (a ∈ s₁ ∨ a ∈ s₂) := propext !mem_union_iff theorem union_comm (s₁ s₂ : hf) : s₁ ∪ s₂ = s₂ ∪ s₁ := hf.ext (λ a, by rewrite [*mem_union_eq]; exact or.comm) theorem union_assoc (s₁ s₂ s₃ : hf) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := hf.ext (λ a, by rewrite [*mem_union_eq]; exact or.assoc) theorem union_left_comm (s₁ s₂ s₃ : hf) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union_comm union_assoc s₁ s₂ s₃ theorem union_right_comm (s₁ s₂ s₃ : hf) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union_comm union_assoc s₁ s₂ s₃ theorem union_self (s : hf) : s ∪ s = s := hf.ext (λ a, iff.intro (λ ain, or.elim (mem_or_mem_of_mem_union ain) (λ i, i) (λ i, i)) (λ i, mem_union_left _ i)) theorem union_empty (s : hf) : s ∪ ∅ = s := hf.ext (λ a, iff.intro (suppose a ∈ s ∪ ∅, or.elim (mem_or_mem_of_mem_union this) (λ i, i) (λ i, absurd i !not_mem_empty)) (suppose a ∈ s, mem_union_left _ this)) theorem empty_union (s : hf) : ∅ ∪ s = s := calc ∅ ∪ s = s ∪ ∅ : union_comm ... = s : union_empty /- inter -/ definition inter (s₁ s₂ : hf) : hf := of_finset (finset.inter (to_finset s₁) (to_finset s₂)) infix [priority hf.prio] ∩ := inter theorem mem_of_mem_inter_left {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∩ s₂ → a ∈ s₁ := begin unfold mem, unfold inter, rewrite to_finset_of_finset, intro h, apply finset.mem_of_mem_inter_left h end theorem mem_of_mem_inter_right {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∩ s₂ → a ∈ s₂ := begin unfold mem, unfold inter, rewrite to_finset_of_finset, intro h, apply finset.mem_of_mem_inter_right h end theorem mem_inter {a : hf} {s₁ s₂ : hf} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := begin unfold mem, intro h₁ h₂, unfold inter, rewrite to_finset_of_finset, apply finset.mem_inter h₁ h₂ end theorem mem_inter_iff (a : hf) (s₁ s₂ : hf) : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := iff.intro (λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h)) (λ h, mem_inter (and.elim_left h) (and.elim_right h)) theorem mem_inter_eq (a : hf) (s₁ s₂ : hf) : (a ∈ s₁ ∩ s₂) = (a ∈ s₁ ∧ a ∈ s₂) := propext !mem_inter_iff theorem inter_comm (s₁ s₂ : hf) : s₁ ∩ s₂ = s₂ ∩ s₁ := hf.ext (λ a, by rewrite [*mem_inter_eq]; exact and.comm) theorem inter_assoc (s₁ s₂ s₃ : hf) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := hf.ext (λ a, by rewrite [*mem_inter_eq]; exact and.assoc) theorem inter_left_comm (s₁ s₂ s₃ : hf) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_right_comm (s₁ s₂ s₃ : hf) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_self (s : hf) : s ∩ s = s := hf.ext (λ a, iff.intro (λ h, mem_of_mem_inter_right h) (λ h, mem_inter h h)) theorem inter_empty (s : hf) : s ∩ ∅ = ∅ := hf.ext (λ a, iff.intro (suppose a ∈ s ∩ ∅, absurd (mem_of_mem_inter_right this) !not_mem_empty) (suppose a ∈ ∅, absurd this !not_mem_empty)) theorem empty_inter (s : hf) : ∅ ∩ s = ∅ := calc ∅ ∩ s = s ∩ ∅ : inter_comm ... = ∅ : inter_empty /- card -/ definition card (s : hf) : nat := finset.card (to_finset s) theorem card_empty : card ∅ = 0 := rfl lemma ne_empty_of_card_eq_succ {s : hf} {n : nat} : card s = succ n → s ≠ ∅ := by intros; substvars; contradiction /- erase -/ definition erase (a : hf) (s : hf) : hf := of_finset (erase a (to_finset s)) theorem not_mem_erase (a : hf) (s : hf) : a ∉ erase a s := begin unfold [mem, erase], rewrite to_finset_of_finset, apply finset.not_mem_erase end theorem card_erase_of_mem {a : hf} {s : hf} : a ∈ s → card (erase a s) = pred (card s) := begin unfold mem, intro h, unfold [erase, card], rewrite to_finset_of_finset, apply finset.card_erase_of_mem h end theorem card_erase_of_not_mem {a : hf} {s : hf} : a ∉ s → card (erase a s) = card s := begin unfold [mem], intro h, unfold [erase, card], rewrite to_finset_of_finset, apply finset.card_erase_of_not_mem h end theorem erase_empty (a : hf) : erase a ∅ = ∅ := rfl theorem ne_of_mem_erase {a b : hf} {s : hf} : b ∈ erase a s → b ≠ a := by intro h beqa; subst b; exact absurd h !not_mem_erase theorem mem_of_mem_erase {a b : hf} {s : hf} : b ∈ erase a s → b ∈ s := begin unfold [erase, mem], rewrite to_finset_of_finset, intro h, apply mem_of_mem_erase h end theorem mem_erase_of_ne_of_mem {a b : hf} {s : hf} : a ≠ b → a ∈ s → a ∈ erase b s := begin intro h₁, unfold mem, intro h₂, unfold erase, rewrite to_finset_of_finset, apply mem_erase_of_ne_of_mem h₁ h₂ end theorem mem_erase_iff (a b : hf) (s : hf) : a ∈ erase b s ↔ a ∈ s ∧ a ≠ b := iff.intro (assume H, and.intro (mem_of_mem_erase H) (ne_of_mem_erase H)) (assume H, mem_erase_of_ne_of_mem (and.right H) (and.left H)) theorem mem_erase_eq (a b : hf) (s : hf) : a ∈ erase b s = (a ∈ s ∧ a ≠ b) := propext !mem_erase_iff theorem erase_insert {a : hf} {s : hf} : a ∉ s → erase a (insert a s) = s := begin unfold [mem, erase, insert], intro h, rewrite [to_finset_of_finset, finset.erase_insert h, of_finset_to_finset] end theorem insert_erase {a : hf} {s : hf} : a ∈ s → insert a (erase a s) = s := begin unfold mem, intro h, unfold [insert, erase], rewrite [to_finset_of_finset, finset.insert_erase h, of_finset_to_finset] end /- subset -/ definition subset (s₁ s₂ : hf) : Prop := finset.subset (to_finset s₁) (to_finset s₂) infix [priority hf.prio] ⊆ := subset theorem empty_subset (s : hf) : ∅ ⊆ s := begin unfold [empty, subset], rewrite to_finset_of_finset, apply finset.empty_subset (to_finset s) end theorem subset.refl (s : hf) : s ⊆ s := begin unfold [subset], apply finset.subset.refl (to_finset s) end theorem subset.trans {s₁ s₂ s₃ : hf} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := begin unfold [subset], intro h₁ h₂, apply finset.subset.trans h₁ h₂ end theorem mem_of_subset_of_mem {s₁ s₂ : hf} {a : hf} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := begin unfold [subset, mem], intro h₁ h₂, apply finset.mem_of_subset_of_mem h₁ h₂ end theorem subset.antisymm {s₁ s₂ : hf} : s₁ ⊆ s₂ → s₂ ⊆ s₁ → s₁ = s₂ := begin unfold [subset], intro h₁ h₂, apply to_finset_inj (finset.subset.antisymm h₁ h₂) end -- alternative name theorem eq_of_subset_of_subset {s₁ s₂ : hf} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := subset.antisymm H₁ H₂ theorem subset_of_forall {s₁ s₂ : hf} : (∀x, x ∈ s₁ → x ∈ s₂) → s₁ ⊆ s₂ := begin unfold [mem, subset], intro h, apply finset.subset_of_forall h end theorem subset_insert (s : hf) (a : hf) : s ⊆ insert a s := begin unfold [subset, insert], rewrite to_finset_of_finset, apply finset.subset_insert (to_finset s) end theorem eq_empty_of_subset_empty {x : hf} (H : x ⊆ ∅) : x = ∅ := subset.antisymm H (empty_subset x) theorem subset_empty_iff (x : hf) : x ⊆ ∅ ↔ x = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) theorem erase_subset_erase (a : hf) {s t : hf} : s ⊆ t → erase a s ⊆ erase a t := begin unfold [subset, erase], intro h, rewrite *to_finset_of_finset, apply finset.erase_subset_erase a h end theorem erase_subset (a : hf) (s : hf) : erase a s ⊆ s := begin unfold [subset, erase], rewrite to_finset_of_finset, apply finset.erase_subset a (to_finset s) end theorem erase_eq_of_not_mem {a : hf} {s : hf} : a ∉ s → erase a s = s := begin unfold [mem, erase], intro h, rewrite [finset.erase_eq_of_not_mem h, of_finset_to_finset] end theorem erase_insert_subset (a : hf) (s : hf) : erase a (insert a s) ⊆ s := begin unfold [erase, insert, subset], rewrite [*to_finset_of_finset], apply finset.erase_insert_subset a (to_finset s) end theorem erase_subset_of_subset_insert {a : hf} {s t : hf} (H : s ⊆ insert a t) : erase a s ⊆ t := hf.subset.trans (!hf.erase_subset_erase H) (erase_insert_subset a t) theorem insert_erase_subset (a : hf) (s : hf) : s ⊆ insert a (erase a s) := decidable.by_cases (assume ains : a ∈ s, by rewrite [!insert_erase ains]; apply subset.refl) (assume nains : a ∉ s, suffices s ⊆ insert a s, by rewrite [erase_eq_of_not_mem nains]; assumption, subset_insert s a) theorem insert_subset_insert (a : hf) {s t : hf} : s ⊆ t → insert a s ⊆ insert a t := begin unfold [subset, insert], intro h, rewrite *to_finset_of_finset, apply finset.insert_subset_insert a h end theorem subset_insert_of_erase_subset {s t : hf} {a : hf} (H : erase a s ⊆ t) : s ⊆ insert a t := subset.trans (insert_erase_subset a s) (!insert_subset_insert H) theorem subset_insert_iff (s t : hf) (a : hf) : s ⊆ insert a t ↔ erase a s ⊆ t := iff.intro !erase_subset_of_subset_insert !subset_insert_of_erase_subset theorem le_of_subset {s₁ s₂ : hf} : s₁ ⊆ s₂ → s₁ ≤ s₂ := begin revert s₂, induction s₁ with a s₁ nain ih, take s₂, suppose ∅ ⊆ s₂, !zero_le, take s₂, suppose insert a s₁ ⊆ s₂, assert a ∈ s₂, from mem_of_subset_of_mem this !mem_insert, have a ∉ erase a s₂, from !not_mem_erase, have s₁ ⊆ erase a s₂, from subset_of_forall (take x xin, by_cases (suppose x = a, by subst x; contradiction) (suppose x ≠ a, have x ∈ s₂, from mem_of_subset_of_mem `insert a s₁ ⊆ s₂` (mem_insert_of_mem _ `x ∈ s₁`), mem_erase_of_ne_of_mem `x ≠ a` `x ∈ s₂`)), have s₁ ≤ erase a s₂, from ih _ this, assert insert a s₁ ≤ insert a (erase a s₂), from insert_le_insert_of_le (or.inr `a ∉ erase a s₂`) this, by rewrite [insert_erase `a ∈ s₂` at this]; exact this end /- image -/ definition image (f : hf → hf) (s : hf) : hf := of_finset (finset.image f (to_finset s)) theorem image_empty (f : hf → hf) : image f ∅ = ∅ := rfl theorem mem_image_of_mem (f : hf → hf) {s : hf} {a : hf} : a ∈ s → f a ∈ image f s := begin unfold [mem, image], intro h, rewrite to_finset_of_finset, apply finset.mem_image_of_mem f h end theorem mem_image {f : hf → hf} {s : hf} {a : hf} {b : hf} (H1 : a ∈ s) (H2 : f a = b) : b ∈ image f s := eq.subst H2 (mem_image_of_mem f H1) theorem exists_of_mem_image {f : hf → hf} {s : hf} {b : hf} : b ∈ image f s → ∃a, a ∈ s ∧ f a = b := begin unfold [mem, image], rewrite to_finset_of_finset, intro h, apply finset.exists_of_mem_image h end theorem mem_image_iff (f : hf → hf) {s : hf} {y : hf} : y ∈ image f s ↔ ∃x, x ∈ s ∧ f x = y := begin unfold [mem, image], rewrite to_finset_of_finset, apply finset.mem_image_iff end theorem mem_image_eq (f : hf → hf) {s : hf} {y : hf} : y ∈ image f s = ∃x, x ∈ s ∧ f x = y := propext (mem_image_iff f) theorem mem_image_of_mem_image_of_subset {f : hf → hf} {s t : hf} {y : hf} (H1 : y ∈ image f s) (H2 : s ⊆ t) : y ∈ image f t := obtain x `x ∈ s` `f x = y`, from exists_of_mem_image H1, have x ∈ t, from mem_of_subset_of_mem H2 `x ∈ s`, show y ∈ image f t, from mem_image `x ∈ t` `f x = y` theorem image_insert (f : hf → hf) (s : hf) (a : hf) : image f (insert a s) = insert (f a) (image f s) := begin unfold [image, insert], rewrite [*to_finset_of_finset, finset.image_insert] end open function lemma image_compose {f : hf → hf} {g : hf → hf} {s : hf} : image (f∘g) s = image f (image g s) := begin unfold image, rewrite [*to_finset_of_finset, finset.image_compose] end lemma image_subset {a b : hf} (f : hf → hf) : a ⊆ b → image f a ⊆ image f b := begin unfold [subset, image], intro h, rewrite *to_finset_of_finset, apply finset.image_subset f h end theorem image_union (f : hf → hf) (s t : hf) : image f (s ∪ t) = image f s ∪ image f t := begin unfold [image, union], rewrite [*to_finset_of_finset, finset.image_union] end /- powerset -/ definition powerset (s : hf) : hf := of_finset (finset.image of_finset (finset.powerset (to_finset s))) prefix [priority hf.prio] `𝒫`:100 := powerset theorem powerset_empty : 𝒫 ∅ = insert ∅ ∅ := rfl theorem powerset_insert {a : hf} {s : hf} : a ∉ s → 𝒫 (insert a s) = 𝒫 s ∪ image (insert a) (𝒫 s) := begin unfold [mem, powerset, insert, union, image], rewrite [*to_finset_of_finset], intro h, have (λ (x : finset hf), of_finset (finset.insert a x)) = (λ (x : finset hf), of_finset (finset.insert a (to_finset (of_finset x)))), from funext (λ x, by rewrite to_finset_of_finset), rewrite [finset.powerset_insert h, finset.image_union, -*finset.image_compose,↑compose,this] end theorem mem_powerset_iff_subset (s : hf) : ∀ x : hf, x ∈ 𝒫 s ↔ x ⊆ s := begin intro x, unfold [mem, powerset, subset], rewrite [to_finset_of_finset, finset.mem_image_eq], apply iff.intro, suppose (∃ (w : finset hf), finset.mem w (finset.powerset (to_finset s)) ∧ of_finset w = x), obtain w h₁ h₂, from this, begin subst x, rewrite to_finset_of_finset, exact iff.mp !finset.mem_powerset_iff_subset h₁ end, suppose finset.subset (to_finset x) (to_finset s), assert finset.mem (to_finset x) (finset.powerset (to_finset s)), from iff.mpr !finset.mem_powerset_iff_subset this, exists.intro (to_finset x) (and.intro this (of_finset_to_finset x)) end theorem subset_of_mem_powerset {s t : hf} (H : s ∈ 𝒫 t) : s ⊆ t := iff.mp (mem_powerset_iff_subset t s) H theorem mem_powerset_of_subset {s t : hf} (H : s ⊆ t) : s ∈ 𝒫 t := iff.mpr (mem_powerset_iff_subset t s) H theorem empty_mem_powerset (s : hf) : ∅ ∈ 𝒫 s := mem_powerset_of_subset (empty_subset s) /- hf as lists -/ open - [notation] list definition of_list (s : list hf) : hf := @equiv.to_fun _ _ list_nat_equiv_nat s definition to_list (h : hf) : list hf := @equiv.inv _ _ list_nat_equiv_nat h lemma to_list_of_list (s : list hf) : to_list (of_list s) = s := @equiv.left_inv _ _ list_nat_equiv_nat s lemma of_list_to_list (s : hf) : of_list (to_list s) = s := @equiv.right_inv _ _ list_nat_equiv_nat s lemma to_list_inj {s₁ s₂ : hf} : to_list s₁ = to_list s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse of_list_to_list h lemma of_list_inj {s₁ s₂ : list hf} : of_list s₁ = of_list s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse to_list_of_list h definition nil : hf := of_list list.nil lemma empty_eq_nil : ∅ = nil := rfl definition cons (a l : hf) : hf := of_list (list.cons a (to_list l)) infixr :: := cons lemma cons_ne_nil (a l : hf) : a::l ≠ nil := by contradiction lemma head_eq_of_cons_eq {h₁ h₂ t₁ t₂ : hf} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := begin unfold cons, intro h, apply list.head_eq_of_cons_eq (of_list_inj h) end lemma tail_eq_of_cons_eq {h₁ h₂ t₁ t₂ : hf} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := begin unfold cons, intro h, apply to_list_inj (list.tail_eq_of_cons_eq (of_list_inj h)) end lemma cons_inj {a : hf} : injective (cons a) := take l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe /- append -/ definition append (l₁ l₂ : hf) : hf := of_list (list.append (to_list l₁) (to_list l₂)) notation l₁ ++ l₂ := append l₁ l₂ theorem append_nil_left [simp] (t : hf) : nil ++ t = t := begin unfold [nil, append], rewrite [to_list_of_list, list.append_nil_left, of_list_to_list] end theorem append_cons [simp] (x s t : hf) : (x::s) ++ t = x::(s ++ t) := begin unfold [cons, append], rewrite [*to_list_of_list, list.append_cons] end theorem append_nil_right [simp] (t : hf) : t ++ nil = t := begin unfold [nil, append], rewrite [to_list_of_list, list.append_nil_right, of_list_to_list] end theorem append.assoc [simp] (s t u : hf) : s ++ t ++ u = s ++ (t ++ u) := begin unfold append, rewrite [*to_list_of_list, list.append.assoc] end /- length -/ definition length (l : hf) : nat := list.length (to_list l) theorem length_nil [simp] : length nil = 0 := begin unfold [length, nil] end theorem length_cons [simp] (x t : hf) : length (x::t) = length t + 1 := begin unfold [length, cons], rewrite to_list_of_list end theorem length_append [simp] (s t : hf) : length (s ++ t) = length s + length t := begin unfold [length, append], rewrite [to_list_of_list, list.length_append] end theorem eq_nil_of_length_eq_zero {l : hf} : length l = 0 → l = nil := begin unfold [length, nil], intro h, rewrite [-list.eq_nil_of_length_eq_zero h, of_list_to_list] end theorem ne_nil_of_length_eq_succ {l : hf} {n : nat} : length l = succ n → l ≠ nil := begin unfold [length, nil], intro h₁ h₂, subst l, rewrite to_list_of_list at h₁, contradiction end /- head and tail -/ definition head (l : hf) : hf := list.head (to_list l) theorem head_cons [simp] (a l : hf) : head (a::l) = a := begin unfold [head, cons], rewrite to_list_of_list end private lemma to_list_ne_list_nil {s : hf} : s ≠ nil → to_list s ≠ list.nil := begin unfold nil, intro h, suppose to_list s = list.nil, by rewrite [-this at h, of_list_to_list at h]; exact absurd rfl h end theorem head_append [simp] (t : hf) {s : hf} : s ≠ nil → head (s ++ t) = head s := begin unfold [nil, head, append], rewrite to_list_of_list, suppose s ≠ of_list list.nil, by rewrite [list.head_append _ (to_list_ne_list_nil this)] end definition tail (l : hf) : hf := of_list (list.tail (to_list l)) theorem tail_nil [simp] : tail nil = nil := begin unfold [tail, nil] end theorem tail_cons [simp] (a l : hf) : tail (a::l) = l := begin unfold [tail, cons], rewrite [to_list_of_list, list.tail_cons, of_list_to_list] end theorem cons_head_tail {l : hf} : l ≠ nil → (head l)::(tail l) = l := begin unfold [nil, head, tail, cons], suppose l ≠ of_list list.nil, by rewrite [to_list_of_list, list.cons_head_tail (to_list_ne_list_nil this), of_list_to_list] end end hf
d511113140e02d296380dea9138b2f3123fb6c67
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group/defs_auto.lean
e5f4d54f375fa3fc00cbe6184cae10d37eaf5d05
[]
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
15,136
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Simon Hudon, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group.to_additive import Mathlib.tactic.basic import Mathlib.PostPort universes u l namespace Mathlib /-! # Typeclasses for (semi)groups and monoid In this file we define typeclasses for algebraic structures with one binary operation. The classes are named `(add_)?(comm_)?(semigroup|monoid|group)`, where `add_` means that the class uses additive notation and `comm_` means that the class assumes that the binary operation is commutative. The file does not contain any lemmas except for * axioms of typeclasses restated in the root namespace; * lemmas required for instances. For basic lemmas about these classes see `algebra.group.basic`. -/ /- Additive "sister" structures. Example, add_semigroup mirrors semigroup. These structures exist just to help automation. In an alternative design, we could have the binary operation as an extra argument for semigroup, monoid, group, etc. However, the lemmas would be hard to index since they would not contain any constant. For example, mul_assoc would be lemma mul_assoc {α : Type u} {op : α → α → α} [semigroup α op] : ∀ a b c : α, op (op a b) c = op a (op b c) := semigroup.mul_assoc The simplifier cannot effectively use this lemma since the pattern for the left-hand-side would be ?op (?op ?a ?b) ?c Remark: we use a tactic for transporting theorems from the multiplicative fragment to the additive one. -/ /-- `left_mul g` denotes left multiplication by `g` -/ def left_add {G : Type u} [Add G] : G → G → G := fun (g x : G) => g + x /-- `right_mul g` denotes right multiplication by `g` -/ def right_mul {G : Type u} [Mul G] : G → G → G := fun (g x : G) => x * g /-- A semigroup is a type with an associative `(*)`. -/ class semigroup (G : Type u) extends Mul G where mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c) /-- An additive semigroup is a type with an associative `(+)`. -/ class add_semigroup (G : Type u) extends Add G where add_assoc : ∀ (a b c : G), a + b + c = a + (b + c) theorem mul_assoc {G : Type u} [semigroup G] (a : G) (b : G) (c : G) : a * b * c = a * (b * c) := semigroup.mul_assoc protected instance add_semigroup.to_is_associative {G : Type u} [add_semigroup G] : is_associative G Add.add := is_associative.mk add_assoc /-- A commutative semigroup is a type with an associative commutative `(*)`. -/ class comm_semigroup (G : Type u) extends semigroup G where mul_comm : ∀ (a b : G), a * b = b * a /-- A commutative additive semigroup is a type with an associative commutative `(+)`. -/ class add_comm_semigroup (G : Type u) extends add_semigroup G where add_comm : ∀ (a b : G), a + b = b + a theorem mul_comm {G : Type u} [comm_semigroup G] (a : G) (b : G) : a * b = b * a := comm_semigroup.mul_comm protected instance comm_semigroup.to_is_commutative {G : Type u} [comm_semigroup G] : is_commutative G Mul.mul := is_commutative.mk mul_comm /-- A `left_cancel_semigroup` is a semigroup such that `a * b = a * c` implies `b = c`. -/ class left_cancel_semigroup (G : Type u) extends semigroup G where mul_left_cancel : ∀ (a b c : G), a * b = a * c → b = c /-- An `add_left_cancel_semigroup` is an additive semigroup such that `a + b = a + c` implies `b = c`. -/ class add_left_cancel_semigroup (G : Type u) extends add_semigroup G where add_left_cancel : ∀ (a b c : G), a + b = a + c → b = c theorem mul_left_cancel {G : Type u} [left_cancel_semigroup G] {a : G} {b : G} {c : G} : a * b = a * c → b = c := left_cancel_semigroup.mul_left_cancel a b c theorem mul_left_cancel_iff {G : Type u} [left_cancel_semigroup G] {a : G} {b : G} {c : G} : a * b = a * c ↔ b = c := { mp := mul_left_cancel, mpr := congr_arg fun {b : G} => a * b } theorem mul_right_injective {G : Type u} [left_cancel_semigroup G] (a : G) : function.injective (Mul.mul a) := fun (b c : G) => mul_left_cancel @[simp] theorem add_right_inj {G : Type u} [add_left_cancel_semigroup G] (a : G) {b : G} {c : G} : a + b = a + c ↔ b = c := function.injective.eq_iff (add_right_injective a) /-- A `right_cancel_semigroup` is a semigroup such that `a * b = c * b` implies `a = c`. -/ class right_cancel_semigroup (G : Type u) extends semigroup G where mul_right_cancel : ∀ (a b c : G), a * b = c * b → a = c /-- An `add_right_cancel_semigroup` is an additive semigroup such that `a + b = c + b` implies `a = c`. -/ class add_right_cancel_semigroup (G : Type u) extends add_semigroup G where add_right_cancel : ∀ (a b c : G), a + b = c + b → a = c theorem mul_right_cancel {G : Type u} [right_cancel_semigroup G] {a : G} {b : G} {c : G} : a * b = c * b → a = c := right_cancel_semigroup.mul_right_cancel a b c theorem add_right_cancel_iff {G : Type u} [add_right_cancel_semigroup G] {a : G} {b : G} {c : G} : b + a = c + a ↔ b = c := { mp := add_right_cancel, mpr := congr_arg fun {b : G} => b + a } theorem add_left_injective {G : Type u} [add_right_cancel_semigroup G] (a : G) : function.injective fun (x : G) => x + a := fun (b c : G) => add_right_cancel @[simp] theorem add_left_inj {G : Type u} [add_right_cancel_semigroup G] (a : G) {b : G} {c : G} : b + a = c + a ↔ b = c := function.injective.eq_iff (add_left_injective a) /-- A `monoid` is a `semigroup` with an element `1` such that `1 * a = a * 1 = a`. -/ class monoid (M : Type u) extends semigroup M, HasOne M where one_mul : ∀ (a : M), 1 * a = a mul_one : ∀ (a : M), a * 1 = a /-- An `add_monoid` is an `add_semigroup` with an element `0` such that `0 + a = a + 0 = a`. -/ class add_monoid (M : Type u) extends HasZero M, add_semigroup M where zero_add : ∀ (a : M), 0 + a = a add_zero : ∀ (a : M), a + 0 = a @[simp] theorem one_mul {M : Type u} [monoid M] (a : M) : 1 * a = a := monoid.one_mul @[simp] theorem add_zero {M : Type u} [add_monoid M] (a : M) : a + 0 = a := add_monoid.add_zero protected instance monoid_to_is_left_id {M : Type u} [monoid M] : is_left_id M Mul.mul 1 := is_left_id.mk monoid.one_mul protected instance add_monoid_to_is_right_id {M : Type u} [add_monoid M] : is_right_id M Add.add 0 := is_right_id.mk add_monoid.add_zero theorem left_neg_eq_right_neg {M : Type u} [add_monoid M] {a : M} {b : M} {c : M} (hba : b + a = 0) (hac : a + c = 0) : b = c := sorry /-- A commutative monoid is a monoid with commutative `(*)`. -/ class comm_monoid (M : Type u) extends comm_semigroup M, monoid M where /-- An additive commutative monoid is an additive monoid with commutative `(+)`. -/ class add_comm_monoid (M : Type u) extends add_comm_semigroup M, add_monoid M where /-- An additive monoid in which addition is left-cancellative. Main examples are `ℕ` and groups. This is the right typeclass for many sum lemmas, as having a zero is useful to define the sum over the empty set, so `add_left_cancel_semigroup` is not enough. -/ -- TODO: I found 1 (one) lemma assuming `[add_left_cancel_monoid]`. class add_left_cancel_monoid (M : Type u) extends add_left_cancel_semigroup M, add_monoid M where -- Should we port more lemmas to this typeclass? /-- A monoid in which multiplication is left-cancellative. -/ class left_cancel_monoid (M : Type u) extends left_cancel_semigroup M, monoid M where /-- Commutative version of add_left_cancel_monoid. -/ class add_left_cancel_comm_monoid (M : Type u) extends add_left_cancel_monoid M, add_comm_monoid M where /-- Commutative version of left_cancel_monoid. -/ class left_cancel_comm_monoid (M : Type u) extends left_cancel_monoid M, comm_monoid M where /-- An additive monoid in which addition is right-cancellative. Main examples are `ℕ` and groups. This is the right typeclass for many sum lemmas, as having a zero is useful to define the sum over the empty set, so `add_right_cancel_semigroup` is not enough. -/ class add_right_cancel_monoid (M : Type u) extends add_monoid M, add_right_cancel_semigroup M where /-- A monoid in which multiplication is right-cancellative. -/ class right_cancel_monoid (M : Type u) extends right_cancel_semigroup M, monoid M where /-- Commutative version of add_right_cancel_monoid. -/ class add_right_cancel_comm_monoid (M : Type u) extends add_right_cancel_monoid M, add_comm_monoid M where /-- Commutative version of right_cancel_monoid. -/ class right_cancel_comm_monoid (M : Type u) extends right_cancel_monoid M, comm_monoid M where /-- An additive monoid in which addition is cancellative on both sides. Main examples are `ℕ` and groups. This is the right typeclass for many sum lemmas, as having a zero is useful to define the sum over the empty set, so `add_right_cancel_semigroup` is not enough. -/ class add_cancel_monoid (M : Type u) extends add_left_cancel_monoid M, add_right_cancel_monoid M where /-- A monoid in which multiplication is cancellative. -/ class cancel_monoid (M : Type u) extends left_cancel_monoid M, right_cancel_monoid M where /-- Commutative version of add_cancel_monoid. -/ class add_cancel_comm_monoid (M : Type u) extends add_left_cancel_comm_monoid M, add_right_cancel_comm_monoid M where /-- Commutative version of cancel_monoid. -/ class cancel_comm_monoid (M : Type u) extends right_cancel_comm_monoid M, left_cancel_comm_monoid M where /-- `try_refl_tac` solves goals of the form `∀ a b, f a b = g a b`, if they hold by definition. -/ /-- A `div_inv_monoid` is a `monoid` with operations `/` and `⁻¹` satisfying `div_eq_mul_inv : ∀ a b, a / b = a * b⁻¹`. This is the immediate common ancestor of `group` and `group_with_zero`, in order to deduplicate the name `div_eq_mul_inv`. The default for `div` is such that `a / b = a * b⁻¹` holds by definition. Adding `div` as a field rather than defining `a / b := a * b⁻¹` allows us to avoid certain classes of unification failures, for example: Let `foo X` be a type with a `∀ X, has_div (foo X)` instance but no `∀ X, has_inv (foo X)`, e.g. when `foo X` is a `euclidean_domain`. Suppose we also have an instance `∀ X [cromulent X], group_with_zero (foo X)`. Then the `(/)` coming from `group_with_zero_has_div` cannot be definitionally equal to the `(/)` coming from `foo.has_div`. -/ class div_inv_monoid (G : Type u) extends Div G, monoid G, has_inv G where div_eq_mul_inv : autoParam (∀ (a b : G), a / b = a * (b⁻¹)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.try_refl_tac") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "try_refl_tac") []) /-- A `sub_neg_monoid` is an `add_monoid` with unary `-` and binary `-` operations satisfying `sub_eq_add_neg : ∀ a b, a - b = a + -b`. The default for `sub` is such that `a - b = a + -b` holds by definition. Adding `sub` as a field rather than defining `a - b := a + -b` allows us to avoid certain classes of unification failures, for example: Let `foo X` be a type with a `∀ X, has_sub (foo X)` instance but no `∀ X, has_neg (foo X)`. Suppose we also have an instance `∀ X [cromulent X], add_group (foo X)`. Then the `(-)` coming from `add_group.has_sub` cannot be definitionally equal to the `(-)` coming from `foo.has_sub`. -/ class sub_neg_monoid (G : Type u) extends Sub G, Neg G, add_monoid G where sub_eq_add_neg : autoParam (∀ (a b : G), a - b = a + -b) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.try_refl_tac") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "try_refl_tac") []) theorem sub_eq_add_neg {G : Type u} [sub_neg_monoid G] (a : G) (b : G) : a - b = a + -b := sub_neg_monoid.sub_eq_add_neg /-- A `group` is a `monoid` with an operation `⁻¹` satisfying `a⁻¹ * a = 1`. There is also a division operation `/` such that `a / b = a * b⁻¹`, with a default so that `a / b = a * b⁻¹` holds by definition. -/ class group (G : Type u) extends div_inv_monoid G where mul_left_inv : ∀ (a : G), a⁻¹ * a = 1 /-- An `add_group` is an `add_monoid` with a unary `-` satisfying `-a + a = 0`. There is also a binary operation `-` such that `a - b = a + -b`, with a default so that `a - b = a + -b` holds by definition. -/ class add_group (A : Type u) extends sub_neg_monoid A where add_left_neg : ∀ (a : A), -a + a = 0 /-- Abbreviation for `@div_inv_monoid.to_monoid _ (@group.to_div_inv_monoid _ _)`. Useful because it corresponds to the fact that `Grp` is a subcategory of `Mon`. Not an instance since it duplicates `@div_inv_monoid.to_monoid _ (@group.to_div_inv_monoid _ _)`. -/ def group.to_monoid (G : Type u) [group G] : monoid G := div_inv_monoid.to_monoid G @[simp] theorem mul_left_inv {G : Type u} [group G] (a : G) : a⁻¹ * a = 1 := group.mul_left_inv theorem inv_mul_self {G : Type u} [group G] (a : G) : a⁻¹ * a = 1 := mul_left_inv a @[simp] theorem neg_add_cancel_left {G : Type u} [add_group G] (a : G) (b : G) : -a + (a + b) = b := eq.mpr (id (Eq._oldrec (Eq.refl (-a + (a + b) = b)) (Eq.symm (add_assoc (-a) a b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (-a + a + b = b)) (add_left_neg a))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 + b = b)) (zero_add b))) (Eq.refl b))) @[simp] theorem inv_eq_of_mul_eq_one {G : Type u} [group G] {a : G} {b : G} (h : a * b = 1) : a⁻¹ = b := left_inv_eq_right_inv (inv_mul_self a) h @[simp] theorem inv_inv {G : Type u} [group G] (a : G) : a⁻¹⁻¹ = a := inv_eq_of_mul_eq_one (mul_left_inv a) @[simp] theorem add_right_neg {G : Type u} [add_group G] (a : G) : a + -a = 0 := (fun (this : --a + -a = 0) => eq.mp (Eq._oldrec (Eq.refl ( --a + -a = 0)) (neg_neg a)) this) (add_left_neg (-a)) theorem add_neg_self {G : Type u} [add_group G] (a : G) : a + -a = 0 := add_right_neg a @[simp] theorem mul_inv_cancel_right {G : Type u} [group G] (a : G) (b : G) : a * b * (b⁻¹) = a := eq.mpr (id (Eq._oldrec (Eq.refl (a * b * (b⁻¹) = a)) (mul_assoc a b (b⁻¹)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b * (b⁻¹)) = a)) (mul_right_inv b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 1 = a)) (mul_one a))) (Eq.refl a))) protected instance add_group.to_cancel_add_monoid {G : Type u} [add_group G] : add_cancel_monoid G := add_cancel_monoid.mk add_group.add add_group.add_assoc sorry add_group.zero add_group.zero_add add_group.add_zero sorry /-- A commutative group is a group with commutative `(*)`. -/ /-- An additive commutative group is an additive group with commutative `(+)`. -/ class comm_group (G : Type u) extends group G, comm_monoid G where class add_comm_group (G : Type u) extends add_group G, add_comm_monoid G where protected instance comm_group.to_cancel_comm_monoid {G : Type u} [comm_group G] : cancel_comm_monoid G := cancel_comm_monoid.mk comm_group.mul comm_group.mul_assoc sorry comm_group.one comm_group.one_mul comm_group.mul_one comm_group.mul_comm sorry end Mathlib
9087c4a762e2b3d25ca8a80a19074b327438145d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/elabissues/typeclasses_with_umetavariables.lean
e61d4d44cb9ca8a82d62c6ff2d02aaaaac038d27
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,435
lean
/- In constrast to expression metavariables (see: typeclasses_with_emetavariables.lean), typeclass resolution is not stalled due to the presence of universe metavariables. In the current C++ implementation, some (but not all) universe metavariables appearing in typeclass goals are converted to temporary metavariables. -/ class Foo.{u, v} (α : Type.{u}) : Type.{v} class Bar.{u} (α : Type) : Type.{u} @[instance] axiom foo5 : Foo.{0, 5} Unit def synthFoo {X : Type} [inst : Foo X] : Foo X := inst set_option trace.class_instances true set_option pp.all true /- Currently, universe variables in the level params of the *outer-most head symbol* of the class are converted to temporary metavariables.-/ noncomputable def f1 : Foo Unit := synthFoo def synthFooBar.{u, v} {X : Type*} [inst : Foo.{u, v} (Bar.{u} X)] : Foo.{u, v} (Bar.{u} X) := inst @[instance] axiom fooBar5.{u} : Foo.{5, u} (Bar.{5} Unit) /- This *nested* universe parameter is not converted into a temporary metavariable, and so this fails.-/ noncomputable def f2 : Foo (Bar Unit) := synthFooBar /- Here is the trace: << [class_instances] (0) ?x_0 : Foo.{?u_0 ?u_1} (Bar.{?l__fresh.4.77} Unit) := fooBar5.{?u_2} failed is_def_eq [class_instances] (0) ?x_0 : Foo.{?u_0 ?u_1} (Bar.{?l__fresh.4.77} Unit) := foo5 failed is_def_eq >> Note that the universe metavariable in question is converted to a temporary metavariable in only one of the two occurrences. -/
c7e3a957448a9961de68cdcfff5530c7ecf320c5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/default_auto.lean
7f7f6bc367082be763e26ddd2ce310192ce180bc
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,075
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.basic import Mathlib.Lean3Lib.init.data.sigma.default import Mathlib.Lean3Lib.init.data.nat.default import Mathlib.Lean3Lib.init.data.char.default import Mathlib.Lean3Lib.init.data.string.default import Mathlib.Lean3Lib.init.data.list.default import Mathlib.Lean3Lib.init.data.sum.default import Mathlib.Lean3Lib.init.data.subtype.default import Mathlib.Lean3Lib.init.data.int.default import Mathlib.Lean3Lib.init.data.array.default import Mathlib.Lean3Lib.init.data.bool.default import Mathlib.Lean3Lib.init.data.fin.default import Mathlib.Lean3Lib.init.data.unsigned.default import Mathlib.Lean3Lib.init.data.ordering.default import Mathlib.Lean3Lib.init.data.rbtree.default import Mathlib.Lean3Lib.init.data.rbmap.default import Mathlib.Lean3Lib.init.data.option.basic import Mathlib.Lean3Lib.init.data.option.instances namespace Mathlib end Mathlib
898c208f38b34ecc30b5f470ad87688c3ab542cb
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Elab/Term.lean
d2057f0c9833285e12c219fa7870fa61c8dd64cd
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
73,420
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, Sebastian Ullrich -/ import Lean.Meta.AppBuilder import Lean.Meta.CollectMVars import Lean.Meta.Coe import Lean.Linter.Deprecated import Lean.Elab.Config import Lean.Elab.Level import Lean.Elab.DeclModifiers namespace Lean.Elab namespace Term /-- Saved context for postponed terms and tactics to be executed. -/ structure SavedContext where declName? : Option Name options : Options openDecls : List OpenDecl macroStack : MacroStack errToSorry : Bool levelNames : List Name /-- We use synthetic metavariables as placeholders for pending elaboration steps. -/ inductive SyntheticMVarKind where /-- Use typeclass resolution to synthesize value for metavariable. -/ | typeClass /-- Use coercion to synthesize value for the metavariable. if `f?` is `some f`, we produce an application type mismatch error message. Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/ | coe (header? : Option String) (expectedType : Expr) (e : Expr) (f? : Option Expr) /-- Use tactic to synthesize value for metavariable. -/ | tactic (tacticCode : Syntax) (ctx : SavedContext) /-- Metavariable represents a hole whose elaboration has been postponed. -/ | postponed (ctx : SavedContext) deriving Inhabited instance : ToString SyntheticMVarKind where toString | .typeClass => "typeclass" | .coe .. => "coe" | .tactic .. => "tactic" | .postponed .. => "postponed" structure SyntheticMVarDecl where stx : Syntax kind : SyntheticMVarKind deriving Inhabited /-- We can optionally associate an error context with a metavariable (see `MVarErrorInfo`). We have three different kinds of error context. -/ inductive MVarErrorKind where /-- Metavariable for implicit arguments. `ctx` is the parent application. -/ | implicitArg (ctx : Expr) /-- Metavariable for explicit holes provided by the user (e.g., `_` and `?m`) -/ | hole /-- "Custom", `msgData` stores the additional error messages. -/ | custom (msgData : MessageData) deriving Inhabited instance : ToString MVarErrorKind where toString | .implicitArg _ => "implicitArg" | .hole => "hole" | .custom _ => "custom" /-- We can optionally associate an error context with metavariables. -/ structure MVarErrorInfo where mvarId : MVarId ref : Syntax kind : MVarErrorKind argName? : Option Name := none deriving Inhabited /-- Nested `let rec` expressions are eagerly lifted by the elaborator. We store the information necessary for performing the lifting here. -/ structure LetRecToLift where ref : Syntax fvarId : FVarId attrs : Array Attribute shortDeclName : Name declName : Name lctx : LocalContext localInstances : LocalInstances type : Expr val : Expr mvarId : MVarId deriving Inhabited /-- State of the `TermElabM` monad. -/ structure State where levelNames : List Name := [] syntheticMVars : MVarIdMap SyntheticMVarDecl := {} pendingMVars : List MVarId := {} mvarErrorInfos : MVarIdMap MVarErrorInfo := {} letRecsToLift : List LetRecToLift := [] deriving Inhabited end Term namespace Tactic /-- State of the `TacticM` monad. -/ structure State where goals : List MVarId deriving Inhabited /-- Snapshots are used to implement the `save` tactic. This tactic caches the state of the system, and allows us to "replay" expensive proofs efficiently. This is only relevant implementing the LSP server. -/ structure Snapshot where core : Core.State meta : Meta.State term : Term.State tactic : Tactic.State stx : Syntax deriving Inhabited /-- Key for the cache used to implement the `save` tactic. -/ structure CacheKey where mvarId : MVarId -- TODO: should include all goals pos : String.Pos deriving BEq, Hashable, Inhabited /-- Cache for the `save` tactic. -/ structure Cache where pre : PHashMap CacheKey Snapshot := {} post : PHashMap CacheKey Snapshot := {} deriving Inhabited end Tactic namespace Term structure Context where declName? : Option Name := none /-- Map `.auxDecl` local declarations used to encode recursive declarations to their full-names. -/ auxDeclToFullName : FVarIdMap Name := {} macroStack : MacroStack := [] /-- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`. The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in the list of pending synthetic metavariables, and returns `?m`. -/ mayPostpone : Bool := true /-- When `errToSorry` is set to true, the method `elabTerm` catches exceptions and converts them into synthetic `sorry`s. The implementation of choice nodes and overloaded symbols rely on the fact that when `errToSorry` is set to false for an elaboration function `F`, then `errToSorry` remains `false` for all elaboration functions invoked by `F`. That is, it is safe to transition `errToSorry` from `true` to `false`, but we must not set `errToSorry` to `true` when it is currently set to `false`. -/ errToSorry : Bool := true /-- When `autoBoundImplicit` is set to true, instead of producing an "unknown identifier" error for unbound variables, we generate an internal exception. This exception is caught at `elabBinders` and `elabTypeWithUnboldImplicit`. Both methods add implicit declarations for the unbound variable and try again. -/ autoBoundImplicit : Bool := false autoBoundImplicits : PArray Expr := {} /-- A name `n` is only eligible to be an auto implicit name if `autoBoundImplicitForbidden n = false`. We use this predicate to disallow `f` to be considered an auto implicit name in a definition such as ``` def f : f → Bool := fun _ => true ``` -/ autoBoundImplicitForbidden : Name → Bool := fun _ => false /-- Map from user name to internal unique name -/ sectionVars : NameMap Name := {} /-- Map from internal name to fvar -/ sectionFVars : NameMap Expr := {} /-- Enable/disable implicit lambdas feature. -/ implicitLambda : Bool := true /-- Noncomputable sections automatically add the `noncomputable` modifier to any declaration we cannot generate code for -/ isNoncomputableSection : Bool := false /-- When `true` we skip TC failures. We use this option when processing patterns -/ ignoreTCFailures : Bool := false /-- `true` when elaborating patterns. It affects how we elaborate named holes. -/ inPattern : Bool := false /-- Cache for the `save` tactic. It is only `some` in the LSP server. -/ tacticCache? : Option (IO.Ref Tactic.Cache) := none /-- If `true`, we store in the `Expr` the `Syntax` for recursive applications (i.e., applications of free variables tagged with `isAuxDecl`). We store the `Syntax` using `mkRecAppWithSyntax`. We use the `Syntax` object to produce better error messages at `Structural.lean` and `WF.lean`. -/ saveRecAppSyntax : Bool := true /-- If `holesAsSyntheticOpaque` is `true`, then we mark metavariables associated with `_`s as `synthethicOpaque` if they do not occur in patterns. This option is useful when elaborating terms in tactics such as `refine'` where we want holes there to become new goals. See issue #1681, we have `refine' (fun x => _) -/ holesAsSyntheticOpaque : Bool := false abbrev TermElabM := ReaderT Context $ StateRefT State MetaM abbrev TermElab := Syntax → Option Expr → TermElabM Expr /- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the whole monad stack at every use site. May eventually be covered by `deriving`. -/ @[always_inline] instance : Monad TermElabM := let i := inferInstanceAs (Monad TermElabM) { pure := i.pure, bind := i.bind } open Meta instance : Inhabited (TermElabM α) where default := throw default /-- Backtrackable state for the `TermElabM` monad. -/ structure SavedState where meta : Meta.SavedState «elab» : State deriving Inhabited protected def saveState : TermElabM SavedState := return { meta := (← Meta.saveState), «elab» := (← get) } def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do let traceState ← getTraceState -- We never backtrack trace message let infoState ← getInfoState -- We also do not backtrack the info nodes when `restoreInfo == false` s.meta.restore set s.elab setTraceState traceState unless restoreInfo do setInfoState infoState instance : MonadBacktrack SavedState TermElabM where saveState := Term.saveState restoreState b := b.restore abbrev TermElabResult (α : Type) := EStateM.Result Exception SavedState α instance [Inhabited α] : Inhabited (TermElabResult α) where default := EStateM.Result.ok default default /-- Execute `x`, save resulting expression and new state. We remove any `Info` created by `x`. The info nodes are committed when we execute `applyResult`. We use `observing` to implement overloaded notation and decls. We want to save `Info` nodes for the chosen alternative. -/ def observing (x : TermElabM α) : TermElabM (TermElabResult α) := do let s ← saveState try let e ← x let sNew ← saveState s.restore (restoreInfo := true) return EStateM.Result.ok e sNew catch | ex@(.error ..) => let sNew ← saveState s.restore (restoreInfo := true) return .error ex sNew | ex@(.internal id _) => if id == postponeExceptionId then s.restore (restoreInfo := true) throw ex /-- Apply the result/exception and state captured with `observing`. We use this method to implement overloaded notation and symbols. -/ def applyResult (result : TermElabResult α) : TermElabM α := do match result with | .ok a r => r.restore (restoreInfo := true); return a | .error ex r => r.restore (restoreInfo := true); throw ex /-- Execute `x`, but keep state modifications only if `x` did not postpone. This method is useful to implement elaboration functions that cannot decide whether they need to postpone or not without updating the state. -/ def commitIfDidNotPostpone (x : TermElabM α) : TermElabM α := do -- We just reuse the implementation of `observing` and `applyResult`. let r ← observing x applyResult r /-- Return the universe level names explicitly provided by the user. -/ def getLevelNames : TermElabM (List Name) := return (← get).levelNames /-- Given a free variable `fvar`, return its declaration. This function panics if `fvar` is not a free variable. -/ def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do match (← getLCtx).find? fvar.fvarId! with | some d => pure d | none => unreachable! instance : AddErrorMessageContext TermElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack pure (ref, msg) /-- Execute `x` but discard changes performed at `Term.State` and `Meta.State`. Recall that the `Environment` and `InfoState` are at `Core.State`. Thus, any updates to it will be preserved. This method is useful for performing computations where all metavariable must be resolved or discarded. The `InfoTree`s are not discarded, however, and wrapped in `InfoTree.Context` to store their metavariable context. -/ def withoutModifyingElabMetaStateWithInfo (x : TermElabM α) : TermElabM α := do let s ← get let sMeta ← getThe Meta.State try withSaveInfoContext x finally set s set sMeta /-- Execute `x` but discard changes performed to the state. However, the info trees and messages are not discarded. -/ private def withoutModifyingStateWithInfoAndMessagesImpl (x : TermElabM α) : TermElabM α := do let saved ← saveState try withSaveInfoContext x finally let saved := { saved with meta.core.infoState := (← getInfoState), meta.core.messages := (← getThe Core.State).messages } restoreState saved /-- Execute `x` without storing `Syntax` for recursive applications. See `saveRecAppSyntax` field at `Context`. -/ def withoutSavingRecAppSyntax (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with saveRecAppSyntax := false }) x unsafe def mkTermElabAttributeUnsafe (ref : Name) : IO (KeyedDeclsAttribute TermElab) := mkElabAttribute TermElab `builtin_term_elab `term_elab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" ref @[implemented_by mkTermElabAttributeUnsafe] opaque mkTermElabAttribute (ref : Name) : IO (KeyedDeclsAttribute TermElab) builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute decl_name% /-- Auxiliary datatatype for presenting a Lean lvalue modifier. We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`. Example: `a.foo.1` is represented as the `Syntax` `a` and the list `[LVal.fieldName "foo", LVal.fieldIdx 1]`. -/ inductive LVal where | fieldIdx (ref : Syntax) (i : Nat) /-- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name. `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/ | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax) def LVal.getRef : LVal → Syntax | .fieldIdx ref _ => ref | .fieldName ref .. => ref def LVal.isFieldName : LVal → Bool | .fieldName .. => true | _ => false instance : ToString LVal where toString | .fieldIdx _ i => toString i | .fieldName _ n .. => n /-- Return the name of the declaration being elaborated if available. -/ def getDeclName? : TermElabM (Option Name) := return (← read).declName? /-- Return the list of nested `let rec` declarations that need to be lifted. -/ def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift /-- Return the declaration of the given metavariable -/ def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId /-- Execute `x` with `declName? := name`. See `getDeclName? -/ def withDeclName (name : Name) (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with declName? := name }) x /-- Update the universe level parameter names. -/ def setLevelNames (levelNames : List Name) : TermElabM Unit := modify fun s => { s with levelNames := levelNames } /-- Execute `x` using `levelNames` as the universe level parameter names. See `getLevelNames`. -/ def withLevelNames (levelNames : List Name) (x : TermElabM α) : TermElabM α := do let levelNamesSaved ← getLevelNames setLevelNames levelNames try x finally setLevelNames levelNamesSaved /-- Declare an auxiliary local declaration `shortDeclName : type` for elaborating recursive declaration `declName`, update the mapping `auxDeclToFullName`, and then execute `k`. -/ def withAuxDecl (shortDeclName : Name) (type : Expr) (declName : Name) (k : Expr → TermElabM α) : TermElabM α := withLocalDecl shortDeclName .default (kind := .auxDecl) type fun x => withReader (fun ctx => { ctx with auxDeclToFullName := ctx.auxDeclToFullName.insert x.fvarId! declName }) do k x def withoutErrToSorryImp (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with errToSorry := false }) x /-- Execute `x` without converting errors (i.e., exceptions) to `sorry` applications. Recall that when `errToSorry = true`, the method `elabTerm` catches exceptions and convert them into `sorry` applications. -/ def withoutErrToSorry [MonadFunctorT TermElabM m] : m α → m α := monadMap (m := TermElabM) withoutErrToSorryImp /-- For testing `TermElabM` methods. The #eval command will sign the error. -/ def throwErrorIfErrors : TermElabM Unit := do if (← MonadLog.hasErrors) then throwError "Error(s)" def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit := withRef Syntax.missing <| trace cls msg def ppGoal (mvarId : MVarId) : TermElabM Format := Meta.ppGoal mvarId open Level (LevelElabM) def liftLevelM (x : LevelElabM α) : TermElabM α := do let ctx ← read let mctx ← getMCtx let ngen ← getNGen let lvlCtx : Level.Context := { options := (← getOptions), ref := (← getRef), autoBoundImplicit := ctx.autoBoundImplicit } match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with | .ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a | .error ex _ => throw ex def elabLevel (stx : Syntax) : TermElabM Level := liftLevelM <| Level.elabLevel stx /-- Elaborate `x` with `stx` on the macro stack -/ def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α := withMacroExpansionInfo beforeStx afterStx do withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /-- Add the given metavariable to the list of pending synthetic metavariables. The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/ def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do modify fun s => { s with syntheticMVars := s.syntheticMVars.insert mvarId { stx, kind }, pendingMVars := mvarId :: s.pendingMVars } def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do registerSyntheticMVar (← getRef) mvarId kind def registerMVarErrorInfo (mvarErrorInfo : MVarErrorInfo) : TermElabM Unit := modify fun s => { s with mvarErrorInfos := s.mvarErrorInfos.insert mvarErrorInfo.mvarId mvarErrorInfo } def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := registerMVarErrorInfo { mvarId, ref, kind := .hole } def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do registerMVarErrorInfo { mvarId, ref, kind := .implicitArg app } def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do registerMVarErrorInfo { mvarId, ref, kind := .custom msgData } def getMVarErrorInfo? (mvarId : MVarId) : TermElabM (Option MVarErrorInfo) := do return (← get).mvarErrorInfos.find? mvarId def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := match e.getAppFn with | Expr.mvar mvarId => registerMVarErrorCustomInfo mvarId ref msgData | _ => pure () /-- Auxiliary method for reporting errors of the form "... contains metavariables ...". This kind of error is thrown, for example, at `Match.lean` where elaboration cannot continue if there are metavariables in patterns. We only want to log it if we haven't logged any error so far. -/ def throwMVarError (m : MessageData) : TermElabM α := do if (← MonadLog.hasErrors) then throwAbortTerm else throwError m def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do match mvarErrorInfo.kind with | MVarErrorKind.implicitArg app => do let app ← instantiateMVars app let msg := addArgName "don't know how to synthesize implicit argument" let msg := msg ++ m!"{indentExpr app.setAppPPExplicitForExposingMVars}" ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (appendExtra msg) | MVarErrorKind.hole => do let msg := addArgName "don't know how to synthesize placeholder" " for argument" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg) | MVarErrorKind.custom msg => logErrorAt mvarErrorInfo.ref (appendExtra msg) where /-- Append `mvarErrorInfo` argument name (if available) to the message. Remark: if the argument name contains macro scopes we do not append it. -/ addArgName (msg : MessageData) (extra : String := "") : MessageData := match mvarErrorInfo.argName? with | none => msg | some argName => if argName.hasMacroScopes then msg else msg ++ extra ++ m!" '{argName}'" appendExtra (msg : MessageData) : MessageData := match extraMsg? with | none => msg | some extraMsg => msg ++ extraMsg /-- Try to log errors for the unassigned metavariables `pendingMVarIds`. Return `true` if there were "unfilled holes", and we should "abort" declaration. TODO: try to fill "all" holes using synthetic "sorry's" Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/ def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do if pendingMVarIds.isEmpty then return false else let hasOtherErrors ← MonadLog.hasErrors let mut hasNewErrors := false let mut alreadyVisited : MVarIdSet := {} let mut errors : Array MVarErrorInfo := #[] for (_, mvarErrorInfo) in (← get).mvarErrorInfos do let mvarId := mvarErrorInfo.mvarId unless alreadyVisited.contains mvarId do alreadyVisited := alreadyVisited.insert mvarId /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or delayed assigned to another metavariable that is unassigned. -/ let mvarDeps ← getMVars (mkMVar mvarId) if mvarDeps.any pendingMVarIds.contains then do unless hasOtherErrors do errors := errors.push mvarErrorInfo hasNewErrors := true -- To sort the errors by position use -- let sortedErrors := errors.qsort fun e₁ e₂ => e₁.ref.getPos?.getD 0 < e₂.ref.getPos?.getD 0 for error in errors do error.mvarId.withContext do error.logError extraMsg? return hasNewErrors /-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/ def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do let pendingMVarIds ← getMVarsAtDecl decl if (← logUnassignedUsingErrorInfos pendingMVarIds) then throwAbortCommand /-- Execute `x` without allowing it to postpone elaboration tasks. That is, `tryPostpone` is a noop. -/ def withoutPostponing (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with mayPostpone := false }) x /-- Creates syntax for `(` <ident> `:` <type> `)` -/ def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax := mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"] /-- Convert unassigned universe level metavariables into parameters. The new parameter names are fresh names of the form `u_i` with regard to `ctx.levelNames`, which is updated with the new names. -/ def levelMVarToParam (e : Expr) (except : LMVarId → Bool := fun _ => false) : TermElabM Expr := do let levelNames ← getLevelNames let r := (← getMCtx).levelMVarToParam (fun n => levelNames.elem n) except e `u 1 setLevelNames (levelNames ++ r.newParamNames.toList) setMCtx r.mctx return r.expr /-- Auxiliary method for creating fresh binder names. Do not confuse with the method for creating fresh free/meta variable ids. -/ def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name := withFreshMacroScope <| MonadQuotation.addMacroScope `x /-- Auxiliary method for creating a `Syntax.ident` containing a fresh name. This method is intended for creating fresh binder names. It is just a thin layer on top of `mkFreshUserName`. -/ def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) (canonical := false) : m Ident := return mkIdentFrom ref (← mkFreshBinderName) canonical private def applyAttributesCore (declName : Name) (attrs : Array Attribute) (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit := for attr in attrs do withRef attr.stx do withLogging do let env ← getEnv match getAttributeImpl env attr.name with | Except.error errMsg => throwError errMsg | Except.ok attrImpl => let runAttr := attrImpl.add declName attr.stx attr.kind let runAttr := do -- not truly an elaborator, but a sensible target for go-to-definition let elaborator := attrImpl.ref if (← getInfoState).enabled && (← getEnv).contains elaborator then withInfoContext (mkInfo := return .ofCommandInfo { elaborator, stx := attr.stx }) do try runAttr finally if attr.stx[0].isIdent || attr.stx[0].isAtom then -- Add an additional node over the leading identifier if there is one to make it look more function-like. -- Do this last because we want user-created infos to take precedence pushInfoLeaf <| .ofCommandInfo { elaborator, stx := attr.stx[0] } else runAttr match applicationTime? with | none => runAttr | some applicationTime => if applicationTime == attrImpl.applicationTime then runAttr /-- Apply given attributes **at** a given application time -/ def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit := applyAttributesCore declName attrs applicationTime def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit := applyAttributesCore declName attrs none def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do let header : MessageData := match header? with | some header => m!"{header} " | none => m!"type mismatch{indentExpr e}\n" return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}" def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := do /- We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was always of the form: ``` failed to synthesize instance CoeT <eType> <e> <expectedType> ``` We should revisit this decision in the future and decide whether it may contain useful information or not. -/ let extraMsg := Format.nil /- let extraMsg : MessageData := match extraMsg? with | none => Format.nil | some extraMsg => Format.line ++ extraMsg; -/ match f? with | none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}" | some f => Meta.throwAppTypeMismatch f e def withoutMacroStackAtErr (x : TermElabM α) : TermElabM α := withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x namespace ContainsPendingMVar abbrev M := MonadCacheT Expr Unit (OptionT MetaM) /-- See `containsPostponedTerm` -/ partial def visit (e : Expr) : M Unit := do checkCache e fun _ => do match e with | .forallE _ d b _ => visit d; visit b | .lam _ d b _ => visit d; visit b | .letE _ t v b _ => visit t; visit v; visit b | .app f a => visit f; visit a | .mdata _ b => visit b | .proj _ _ b => visit b | .fvar fvarId .. => match (← fvarId.getDecl) with | .cdecl .. => return () | .ldecl (value := v) .. => visit v | .mvar mvarId .. => let e' ← instantiateMVars e if e' != e then visit e' else match (← getDelayedMVarAssignment? mvarId) with | some d => visit (mkMVar d.mvarIdPending) | none => failure | _ => return () end ContainsPendingMVar /-- Return `true` if `e` contains a pending metavariable. Remark: it also visits let-declarations. -/ def containsPendingMVar (e : Expr) : MetaM Bool := do match (← ContainsPendingMVar.visit e |>.run.run) with | some _ => return false | none => return true /-- Try to synthesize metavariable using type class resolution. This method assumes the local context and local instances of `instMVar` coincide with the current local context and local instances. Return `true` if the instance was synthesized successfully, and `false` if the instance contains unassigned metavariables that are blocking the type class resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/ def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do let instMVarDecl ← getMVarDecl instMVar let type := instMVarDecl.type let type ← instantiateMVars type let result ← trySynthInstance type maxResultSize? match result with | LOption.some val => if (← instMVar.isAssigned) then let oldVal ← instantiateMVars (mkMVar instMVar) unless (← isDefEq oldVal val) do if (← containsPendingMVar oldVal <||> containsPendingMVar val) then /- If `val` or `oldVal` contains metavariables directly or indirectly (e.g., in a let-declaration), we return `false` to indicate we should try again later. This is very course grain since the metavariable may not be responsible for the failure. We should refine the test in the future if needed. This check has been added to address dependencies between postponed metavariables. The following example demonstrates the issue fixed by this test. ``` structure Point where x : Nat y : Nat def Point.compute (p : Point) : Point := let p := { p with x := 1 } let p := { p with y := 0 } if (p.x - p.y) > p.x then p else p ``` The `isDefEq` test above fails for `Decidable (p.x - p.y ≤ p.x)` when the structure instance assigned to `p` has not been elaborated yet. -/ return false -- we will try again later let oldValType ← inferType oldVal let valType ← inferType val unless (← isDefEq oldValType valType) do throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}" throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}" else unless (← isDefEq (mkMVar instMVar) val) do throwError "failed to assign synthesized type class instance{indentExpr val}" return true | .undef => return false -- we will try later | .none => if (← read).ignoreTCFailures then return false else throwError "failed to synthesize instance{indentExpr type}" def mkCoe (expectedType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do trace[Elab.coe] "adding coercion for {e} : {← inferType e} =?= {expectedType}" try withoutMacroStackAtErr do match ← coerce? e expectedType with | .some eNew => return eNew | .none => failure | .undef => let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque registerSyntheticMVarWithCurrRef mvarAux.mvarId! (.coe errorMsgHeader? expectedType e f?) return mvarAux catch | .error _ msg => throwTypeMismatchError errorMsgHeader? expectedType (← inferType e) e f? msg | _ => throwTypeMismatchError errorMsgHeader? expectedType (← inferType e) e f? /-- If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal. If they are not, then try coercions. Argument `f?` is used only for generating error messages. -/ def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) (f? : Option Expr := none) : TermElabM Expr := do let some expectedType := expectedType? | return e if (← isDefEq (← inferType e) expectedType) then return e else mkCoe expectedType e f? errorMsgHeader? /-- Create a synthetic sorry for the given expected type. If `expectedType? = none`, then a fresh metavariable is created to represent the type. -/ private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← match expectedType? with | none => mkFreshTypeMVar | some expectedType => pure expectedType mkSyntheticSorry expectedType /-- Log the given exception, and create an synthetic sorry for representing the failed elaboration step with exception `ex`. -/ def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do let syntheticSorry ← mkSyntheticSorryFor expectedType? logException ex pure syntheticSorry /-- If `mayPostpone == true`, throw `Expection.postpone`. -/ def tryPostpone : TermElabM Unit := do if (← read).mayPostpone then throwPostpone /-- Return `true` if `e` reduces (by unfolding only `[reducible]` declarations) to `?m ...` -/ def isMVarApp (e : Expr) : TermElabM Bool := return (← whnfR e).getAppFn.isMVar /-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/ def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do if (← isMVarApp e) then tryPostpone /-- If `e? = some e`, then `tryPostponeIfMVar e`, otherwise it is just `tryPostpone`. -/ def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit := match e? with | some e => tryPostponeIfMVar e | none => tryPostpone /-- Throws `Exception.postpone`, if `expectedType?` contains unassigned metavariables. It is a noop if `mayPostpone == false`. -/ def tryPostponeIfHasMVars? (expectedType? : Option Expr) : TermElabM (Option Expr) := do tryPostponeIfNoneOrMVar expectedType? let some expectedType := expectedType? | return none let expectedType ← instantiateMVars expectedType if expectedType.hasExprMVar then tryPostpone return none return some expectedType /-- Throws `Exception.postpone`, if `expectedType?` contains unassigned metavariables. If `mayPostpone == false`, it throws error `msg`. -/ def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do let some expectedType ← tryPostponeIfHasMVars? expectedType? | throwError "{msg}, expected type contains metavariables{indentD expectedType?}" return expectedType /-- Save relevant context for term elaboration postponement. -/ def saveContext : TermElabM SavedContext := return { macroStack := (← read).macroStack declName? := (← read).declName? options := (← getOptions) openDecls := (← getOpenDecls) errToSorry := (← read).errToSorry levelNames := (← get).levelNames } /-- Execute `x` with the context saved using `saveContext`. -/ def withSavedContext (savedCtx : SavedContext) (x : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <| withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls }) <| withLevelNames savedCtx.levelNames x /-- Delay the elaboration of `stx`, and return a fresh metavariable that works a placeholder. Remark: the caller is responsible for making sure the info tree is properly updated. This method is used only at `elabUsingElabFnsAux`. -/ private def postponeElabTermCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do trace[Elab.postpone] "{stx} : {expectedType?}" let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext)) return mvar def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) := return (← get).syntheticMVars.find? mvarId /-- Create an auxiliary annotation to make sure we create a `Info` even if `e` is a metavariable. See `mkTermInfo`. We use this functions because some elaboration functions elaborate subterms that may not be immediately part of the resulting term. Example: ``` let_mvar% ?m := b; wait_if_type_mvar% ?m; body ``` If the type of `b` is not known, then `wait_if_type_mvar% ?m; body` is postponed and just return a fresh metavariable `?n`. The elaborator for ``` let_mvar% ?m := b; wait_if_type_mvar% ?m; body ``` returns `mkSaveInfoAnnotation ?n` to make sure the info nodes created when elaborating `b` are "saved". This is a bit hackish, but elaborators like `let_mvar%` are rare. -/ def mkSaveInfoAnnotation (e : Expr) : Expr := if e.isMVar then mkAnnotation `save_info e else e def isSaveInfoAnnotation? (e : Expr) : Option Expr := annotation? `save_info e partial def removeSaveInfoAnnotation (e : Expr) : Expr := match isSaveInfoAnnotation? e with | some e => removeSaveInfoAnnotation e | _ => e /-- Return `some mvarId` if `e` corresponds to a hole that is going to be filled "later" by executing a tactic or resuming elaboration. We do not save `ofTermInfo` for this kind of node in the `InfoTree`. -/ def isTacticOrPostponedHole? (e : Expr) : TermElabM (Option MVarId) := do match e with | Expr.mvar mvarId => match (← getSyntheticMVarDecl? mvarId) with | some { kind := .tactic .., .. } => return mvarId | some { kind := .postponed .., .. } => return mvarId | _ => return none | _ => pure none def mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (isBinder := false) : TermElabM (Sum Info MVarId) := do match (← isTacticOrPostponedHole? e) with | some mvarId => return Sum.inr mvarId | none => let e := removeSaveInfoAnnotation e return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (← getLCtx), expr := e, stx, expectedType?, isBinder } /-- Pushes a new leaf node to the info tree associating the expression `e` to the syntax `stx`. As a result, when the user hovers over `stx` they will see the type of `e`, and if `e` is a constant they will see the constant's doc string. * `expectedType?`: the expected type of `e` at the point of elaboration, if available * `lctx?`: the local context in which to interpret `e` (otherwise it will use `← getLCtx`) * `elaborator`: a declaration name used as an alternative target for go-to-definition * `isBinder`: if true, this will be treated as defining `e` (which should be a local constant) for the purpose of go-to-definition on local variables * `force`: In patterns, the effect of `addTermInfo` is usually suppressed and replaced by a `patternWithRef?` annotation which will be turned into a term info on the post-match-elaboration expression. This flag overrides that behavior and adds the term info immediately. (See https://github.com/leanprover/lean4/pull/1664.) -/ def addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) (force := false) : TermElabM Expr := do if (← read).inPattern && !force then return mkPatternWithRef e stx else withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx? isBinder) |> discard return e def addTermInfo' (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) : TermElabM Unit := discard <| addTermInfo stx e expectedType? lctx? elaborator isBinder def withInfoContext' (stx : Syntax) (x : TermElabM Expr) (mkInfo : Expr → TermElabM (Sum Info MVarId)) : TermElabM Expr := do if (← read).inPattern then let e ← x return mkPatternWithRef e stx else Elab.withInfoContext' x mkInfo /-- Postpone the elaboration of `stx`, return a metavariable that acts as a placeholder, and ensures the info tree is updated and a hole id is introduced. When `stx` is elaborated, new info nodes are created and attached to the new hole id in the info tree. -/ def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do withInfoContext' stx (mkInfo := mkTermInfo .anonymous (expectedType? := expectedType?) stx) do postponeElabTermCore stx expectedType? /-- Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or an error is found. -/ private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : List (KeyedDeclsAttribute.AttributeEntry TermElab) → TermElabM Expr | [] => do throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => try -- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`) withInfoContext' stx (mkInfo := mkTermInfo elabFn.declName (expectedType? := expectedType?) stx) (try elabFn.value stx expectedType? catch ex => match ex with | .error .. => if (← read).errToSorry then exceptionToSorry ex expectedType? else throw ex | .internal id _ => if (← read).errToSorry && id == abortTermExceptionId then exceptionToSorry ex expectedType? else if id == unsupportedSyntaxExceptionId then throw ex -- to outer try else if catchExPostpone && id == postponeExceptionId then /- If `elab` threw `Exception.postpone`, we reset any state modifications. For example, we want to make sure pending synthetic metavariables created by `elab` before it threw `Exception.postpone` are discarded. Note that we are also discarding the messages created by `elab`. For example, consider the expression. `((f.x a1).x a2).x a3` Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`. Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone` because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch and new metavariables are created for the nested functions. -/ s.restore postponeElabTermCore stx expectedType? else throw ex) catch ex => match ex with | .internal id _ => if id == unsupportedSyntaxExceptionId then s.restore -- also removes the info tree created above elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns else throw ex | _ => throw ex private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do let s ← saveState let k := stx.getKind match termElabAttribute.getEntries (← getEnv) k with | [] => throwError "elaboration function for '{k}' has not been implemented{indentD stx}" | elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns instance : MonadMacroAdapter TermElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← getThe Core.State).nextMacroScope setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next } private def isExplicit (stx : Syntax) : Bool := match stx with | `(@$_) => true | _ => false private def isExplicitApp (stx : Syntax) : Bool := stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0] /-- Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation. Example: `fun {α} (a : α) => a` -/ private def isLambdaWithImplicit (stx : Syntax) : Bool := match stx with | `(fun $binders* => $_) => binders.raw.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder | _ => false private partial def dropTermParens : Syntax → Syntax := fun stx => match stx with | `(($stx)) => dropTermParens stx | _ => stx private def isHole (stx : Syntax) : Bool := match stx with | `(_) => true | `(? _) => true | `(? $_:ident) => true | _ => false private def isTacticBlock (stx : Syntax) : Bool := match stx with | `(by $_:tacticSeq) => true | _ => false private def isNoImplicitLambda (stx : Syntax) : Bool := match stx with | `(no_implicit_lambda% $_:term) => true | _ => false private def isTypeAscription (stx : Syntax) : Bool := match stx with | `(($_ : $_)) => true | _ => false def hasNoImplicitLambdaAnnotation (type : Expr) : Bool := annotation? `noImplicitLambda type |>.isSome def mkNoImplicitLambdaAnnotation (type : Expr) : Expr := if hasNoImplicitLambdaAnnotation type then type else mkAnnotation `noImplicitLambda type /-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/ def blockImplicitLambda (stx : Syntax) : Bool := let stx := dropTermParens stx -- TODO: make it extensible isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx || isNoImplicitLambda stx || isTypeAscription stx /-- Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and `blockImplicitLambda stx` is not true, else return `none`. Remark: implicit lambdas are not triggered by the strict implicit binder annotation `{{a : α}} → β` -/ private def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) := if blockImplicitLambda stx then return none else match expectedType? with | some expectedType => do if hasNoImplicitLambdaAnnotation expectedType then return none else let expectedType ← whnfForall expectedType match expectedType with | .forallE _ _ _ c => if c.isImplicit || c.isInstImplicit then return some expectedType else return none | _ => return none | _ => return none private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do match ex with | .error ref msg => if impFVars.isEmpty then return Exception.error ref msg else let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lambda feature" for impFVar in impFVars do let auxMsg := m!"{impFVar} : {← inferType impFVar}" let auxMsg ← addMessageContext auxMsg msg := m!"{msg}{indentD auxMsg}" msg := m!"{msg}\nyou can disable implict lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations." return Exception.error ref msg | _ => return ex private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do let body ← elabUsingElabFns stx expectedType catchExPostpone try let body ← ensureHasType expectedType body let r ← mkLambdaFVars impFVars body trace[Elab.implicitForall] r return r catch ex => throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars) private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr := loop type #[] where loop (type : Expr) (fvars : Array Expr) : TermElabM Expr := do match (← whnfForall type) with | .forallE n d b c => if c.isExplicit then elabImplicitLambdaAux stx catchExPostpone type fvars else withFreshMacroScope do let n ← MonadQuotation.addMacroScope n withLocalDecl n c d fun fvar => do let type := b.instantiate1 fvar loop type (fvars.push fvar) | _ => elabImplicitLambdaAux stx catchExPostpone type fvars /-- Main loop for `elabTerm` -/ private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr | .missing => mkSyntheticSorryFor expectedType? | stx => withFreshMacroScope <| withIncRecDepth do withTraceNode `Elab.step (fun _ => return m!"expected type: {expectedType?}, term\n{stx}") do checkMaxHeartbeats "elaborator" let env ← getEnv let result ← match (← liftMacroM (expandMacroImpl? env stx)) with | some (decl, stxNew?) => let stxNew ← liftMacroM <| liftExcept stxNew? withInfoContext' stx (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <| withMacroExpansion stx stxNew <| withRef stxNew <| elabTermAux expectedType? catchExPostpone implicitLambda stxNew | _ => let implicit? ← if implicitLambda && (← read).implicitLambda then useImplicitLambda? stx expectedType? else pure none match implicit? with | some expectedType => elabImplicitLambda stx catchExPostpone expectedType | none => elabUsingElabFns stx expectedType? catchExPostpone trace[Elab.step.result] result pure result /-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/ def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (← getLCtx), elaborator := .anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?) /-- Main function for elaborating terms. It extracts the elaboration methods from the environment using the node kind. Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods. It creates a fresh macro scope for executing the elaboration method. All unlogged trace messages produced by the elaboration method are logged using the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`, the error is logged and a synthetic sorry expression is returned. If the elaboration throws `Exception.postpone` and `catchExPostpone == true`, a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered, and returned. The option `catchExPostpone == false` is used to implement `resumeElabTerm` to prevent the creation of another synthetic metavariable when resuming the elaboration. If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms. We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr := withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do let e ← elabTerm stx expectedType? catchExPostpone implicitLambda withRef stx <| ensureHasType expectedType? e errorMsgHeader? /-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/ def commitIfNoErrors? (x : TermElabM α) : TermElabM (Option α) := do let saved ← saveState Core.resetMessageLog try let a ← x if (← MonadLog.hasErrors) then restoreState saved return none else Core.setMessageLog (saved.meta.core.messages ++ (← Core.getMessageLog)) return a catch _ => restoreState saved return none /-- Adapt a syntax transformation to a regular, term-producing elaborator. -/ def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do let stx' ← exp stx withMacroExpansion stx stx' <| elabTerm stx' expectedType? /-- Create a new metavariable with the given type, and try to synthesize it. It type class resolution cannot be executed (e.g., it is stuck because of metavariables in `type`), register metavariable as a pending one. -/ def mkInstMVar (type : Expr) : TermElabM Expr := do let mvar ← mkFreshExprMVar type MetavarKind.synthetic let mvarId := mvar.mvarId! unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass return mvar /-- Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort` or is unifiable with `Expr.sort`, or can be coerced into one. -/ def ensureType (e : Expr) : TermElabM Expr := do if (← isType e) then return e else let eType ← inferType e let u ← mkFreshLevelMVar if (← isDefEq eType (mkSort u)) then return e else if let some coerced ← coerceToSort? e then return coerced else if (← instantiateMVars e).hasSyntheticSorry then throwAbortTerm throwError "type expected, got\n ({← instantiateMVars e} : {← instantiateMVars eType})" /-- Elaborate `stx` and ensure result is a type. -/ def elabType (stx : Syntax) : TermElabM Expr := do let u ← mkFreshLevelMVar let type ← elabTerm stx (mkSort u) withRef stx <| ensureType type /-- Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught, a new local declaration is created, registered, and `k` is tried to be executed again. -/ partial def withAutoBoundImplicit (k : TermElabM α) : TermElabM α := do let flag := autoImplicit.get (← getOptions) if flag then withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do let rec loop (s : SavedState) : TermElabM α := do try k catch | ex => match isAutoBoundImplicitLocalException? ex with | some n => -- Restore state, declare `n`, and try again s.restore withLocalDecl n .implicit (← mkFreshTypeMVar) fun x => withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do loop (← saveState) | none => throw ex loop (← saveState) else k def withoutAutoBoundImplicit (k : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k partial def withAutoBoundImplicitForbiddenPred (p : Name → Bool) (x : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with autoBoundImplicitForbidden := fun n => p n || ctx.autoBoundImplicitForbidden n }) x /-- Collect unassigned metavariables in `type` that are not already in `init` and not satisfying `except`. -/ partial def collectUnassignedMVars (type : Expr) (init : Array Expr := #[]) (except : MVarId → Bool := fun _ => false) : TermElabM (Array Expr) := do let mvarIds ← getMVars type if mvarIds.isEmpty then return init else go mvarIds.toList init where go (mvarIds : List MVarId) (result : Array Expr) : TermElabM (Array Expr) := do match mvarIds with | [] => return result | mvarId :: mvarIds => do if (← mvarId.isAssigned) then go mvarIds result else if result.contains (mkMVar mvarId) || except mvarId then go mvarIds result else let mvarType := (← getMVarDecl mvarId).type let mvarIdsNew ← getMVars mvarType let mvarIdsNew := mvarIdsNew.filter fun mvarId => !result.contains (mkMVar mvarId) if mvarIdsNew.isEmpty then go mvarIds (result.push (mkMVar mvarId)) else go (mvarIdsNew.toList ++ mvarId :: mvarIds) result /-- Return `autoBoundImplicits ++ xs` This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs`. The `autoBoundImplicits` may contain free variables created by the auto-implicit feature, and unassigned free variables. It avoids the hack used at `autoBoundImplicitsOld`. Remark: we cannot simply replace every occurrence of `addAutoBoundImplicitsOld` with this one because a particular use-case may not be able to handle the metavariables in the array being given to `k`. -/ def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do let autos := (← read).autoBoundImplicits go autos.toList #[] where go (todo : List Expr) (autos : Array Expr) : TermElabM (Array Expr) := do match todo with | [] => for auto in autos do if auto.isFVar then let localDecl ← auto.fvarId!.getDecl for x in xs do if (← localDeclDependsOn localDecl x.fvarId!) then throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'" return autos ++ xs | auto :: todo => let autos ← collectUnassignedMVars (← inferType auto) autos go todo (autos.push auto) /-- Similar to `autoBoundImplicits`, but immediately if the resulting array of expressions contains metavariables, it immediately use `mkForallFVars` + `forallBoundedTelescope` to convert them into free variables. The type `type` is modified during the process if type depends on `xs`. We use this method to simplify the conversion of code using `autoBoundImplicitsOld` to `autoBoundImplicits` -/ def addAutoBoundImplicits' (xs : Array Expr) (type : Expr) (k : Array Expr → Expr → TermElabM α) : TermElabM α := do let xs ← addAutoBoundImplicits xs if xs.all (·.isFVar) then k xs type else forallBoundedTelescope (← mkForallFVars xs type) xs.size fun xs type => k xs type def mkAuxName (suffix : Name) : TermElabM Name := do match (← read).declName? with | none => throwError "auxiliary declaration cannot be created when declaration name is not available" | some declName => Lean.mkAuxName (declName ++ suffix) 1 builtin_initialize registerTraceClass `Elab.letrec /-- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it is delayed assigned to one. -/ def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ ·.mvarId)}" let mvarId ← getDelayedMVarRoot mvarId trace[Elab.letrec] "mvarId root: {mkMVar mvarId}" return (← get).letRecsToLift.any (·.mvarId == mvarId) def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do let lctx ← getLCtx let auxDeclToFullName := (← read).auxDeclToFullName let currNamespace ← getCurrNamespace let view := extractMacroScopes n /- Simple case. "Match" function for regular local declarations. -/ let matchLocalDecl? (localDecl : LocalDecl) (givenName : Name) : Option LocalDecl := do guard (localDecl.userName == givenName) return localDecl /- "Match" function for auxiliary declarations that correspond to recursive definitions being defined. This function is used in the first-pass. Note that we do not check for `localDecl.userName == givenName` in this pass as we do for regular local declarations. Reason: consider the following example ``` mutual inductive Foo | somefoo : Foo | bar : Bar → Foo → Foo inductive Bar | somebar : Bar| foobar : Foo → Bar → Bar end mutual private def Foo.toString : Foo → String | Foo.somefoo => go 2 ++ toString.go 2 ++ Foo.toString.go 2 | Foo.bar b f => toString f ++ Bar.toString b where go (x : Nat) := s!"foo {x}" private def _root_.Ex2.Bar.toString : Bar → String | Bar.somebar => "bar" | Bar.foobar f b => Foo.toString f ++ Bar.toString b end ``` In the example above, we have two local declarations named `toString` in the local context, and we want the `toString f` to be resolved to `Foo.toString f` -/ let matchAuxRecDecl? (localDecl : LocalDecl) (fullDeclName : Name) (givenNameView : MacroScopesView) : Option LocalDecl := do let fullDeclView := extractMacroScopes fullDeclName /- First cleanup private name annotations -/ let fullDeclView := { fullDeclView with name := (privateToUserName? fullDeclView.name).getD fullDeclView.name } let fullDeclName := fullDeclView.review let localDeclNameView := extractMacroScopes localDecl.userName /- If the current namespace is a prefix of the full declaration name, we use a relaxed matching test where we must satisfy the following conditions - The local declaration is a suffix of the given name. - The given name is a suffix of the full declaration. Recall the `let rec`/`where` declaration naming convention. For example, suppose we have ``` def Foo.Bla.f ... := ... go ... where go ... := ... ``` The current namespace is `Foo.Bla`, and the full name for `go` is `Foo.Bla.f.g`, but we want to refer to it using just `go`. It is also accepted to refer to it using `f.go`, `Bla.f.go`, etc. -/ if currNamespace.isPrefixOf fullDeclName then /- Relaxed mode that allows us to access `let rec` declarations using shorter names -/ guard (localDeclNameView.isSuffixOf givenNameView) guard (givenNameView.isSuffixOf fullDeclView) return localDecl else /- It is the standard algorithm we using at `resolveGlobalName` for processing namespaces. The current solution also has a limitation when using `def _root_` in a mutual block. The non `def _root_` declarations may update the namespace. See the following example: ``` mutual def Foo.f ... := ... def _root_.g ... := ... let rec h := ... ... end ``` `def Foo.f` updates the namespace. Then, even when processing `def _root_.g ...` the condition `currNamespace.isPrefixOf fullDeclName` does not hold. This is not a big problem because we are planning to modify how we handle the mutual block in the future. Note that we don't check for `localDecl.userName == givenName` here. -/ let rec go (ns : Name) : Option LocalDecl := do if { givenNameView with name := ns ++ givenNameView.name }.review == fullDeclName then return localDecl match ns with | .str pre .. => go pre | _ => failure return (← go currNamespace) /- Traverse the local context backwards looking for match `givenNameView`. If `skipAuxDecl` we ignore `auxDecl` local declarations. -/ let findLocalDecl? (givenNameView : MacroScopesView) (skipAuxDecl : Bool) : Option LocalDecl := let givenName := givenNameView.review let localDecl? := lctx.decls.findSomeRev? fun localDecl? => do let localDecl ← localDecl? if localDecl.isAuxDecl then guard (not skipAuxDecl) if let some fullDeclName := auxDeclToFullName.find? localDecl.fvarId then matchAuxRecDecl? localDecl fullDeclName givenNameView else matchLocalDecl? localDecl givenName else matchLocalDecl? localDecl givenName if localDecl?.isSome || skipAuxDecl then localDecl? else -- Search auxDecls again trying an exact match of the given name lctx.decls.findSomeRev? fun localDecl? => do let localDecl ← localDecl? guard localDecl.isAuxDecl matchLocalDecl? localDecl givenName /- We use the parameter `globalDeclFound` to decide whether we should skip auxiliary declarations or not. We set it to true if we found a global declaration `n` as we iterate over the `loop`. Without this workaround, we would not be able to elaborate example such as ``` def foo.aux := 1 def foo : Nat → Nat | n => foo.aux -- should not be interpreted as `(foo).bar` ``` See test `aStructPerfIssue.lean` for another example. We skip auxiliary declarations when `projs` is not empty and `globalDeclFound` is true. Remark: we did not use to have the `globalDeclFound` parameter. Without this extra check we failed to elaborate ``` example : Nat := let n := 0 n.succ + (m |>.succ) + m.succ where m := 1 ``` See issue #1850. -/ let rec loop (n : Name) (projs : List String) (globalDeclFound : Bool) := do let givenNameView := { view with name := n } let mut globalDeclFound := globalDeclFound unless globalDeclFound do let r ← resolveGlobalName givenNameView.review let r := r.filter fun (_, fieldList) => fieldList.isEmpty unless r.isEmpty do globalDeclFound := true match findLocalDecl? givenNameView (skipAuxDecl := globalDeclFound && not projs.isEmpty) with | some decl => return some (decl.toExpr, projs) | none => match n with | .str pre s => loop pre (s::projs) globalDeclFound | _ => return none loop view.name [] (globalDeclFound := false) /-- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/ def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val _ => do let r? ← resolveLocalName val match r? with | some (fvar, []) => return some fvar | _ => return none | _ => return none /-- Create an `Expr.const` using the given name and explicit levels. Remark: fresh universe metavariables are created if the constant has more universe parameters than `explicitLevels`. -/ def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do let cinfo ← getConstInfo constName if explicitLevels.length > cinfo.levelParams.length then throwError "too many explicit universe levels for '{constName}'" else let numMissingLevels := cinfo.levelParams.length - explicitLevels.length let us ← mkFreshLevelMVars numMissingLevels return Lean.mkConst constName (explicitLevels ++ us) private def mkConsts (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do candidates.foldlM (init := []) fun result (declName, projs) => do -- TODO: better support for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail. Linter.checkDeprecated declName -- TODO: check is occurring too early if there are multiple alternatives. Fix if it is not ok in practice let const ← mkConst declName explicitLevels return (const, projs) :: result def resolveName (stx : Syntax) (n : Name) (preresolved : List Syntax.Preresolved) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × List String)) := do addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? if let some (e, projs) ← resolveLocalName n then unless explicitLevels.isEmpty do throwError "invalid use of explicit universe parameters, '{e}' is a local" return [(e, projs)] let preresolved := preresolved.filterMap fun | .decl n projs => some (n, projs) | _ => none -- check for section variable capture by a quotation let ctx ← read if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (·, projs) then return [(e, projs)] -- section variables should shadow global decls if preresolved.isEmpty then process (← resolveGlobalName n) else process preresolved where process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do if candidates.isEmpty then if (← read).autoBoundImplicit && !(← read).autoBoundImplicitForbidden n && isValidAutoBoundImplicitName n (relaxedAutoImplicit.get (← getOptions)) then throwAutoBoundImplicitLocal n else throwError "unknown identifier '{Lean.mkConst n}'" mkConsts candidates explicitLevels /-- Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`. Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces `(v.head, id, [f₁, f₂])` where `id` is an identifier for `v.head`, and `f₁` and `f₂` are identifiers for fields `"bla"` and `"boo"`. -/ def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × Syntax × List Syntax)) := do match ident with | .ident _ _ n preresolved => let r ← resolveName ident n preresolved explicitLevels expectedType? r.mapM fun (c, fields) => do let ids := ident.identComponents (nFields? := fields.length) return (c, ids.head!, ids.tail!) | _ => throwError "identifier expected" def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) := match stx with | .ident _ _ val preresolved => do let rs ← try resolveName stx val preresolved [] catch _ => pure [] let rs := rs.filter fun ⟨_, projs⟩ => projs.isEmpty let fs := rs.map fun (f, _) => f match fs with | [] => return none | [f] => let f ← if withInfo then addTermInfo stx f else pure f return some f | _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}" | _ => throwError "identifier expected" def TermElabM.run (x : TermElabM α) (ctx : Context := {}) (s : State := {}) : MetaM (α × State) := withConfig setElabConfig (x ctx |>.run s) @[inline] def TermElabM.run' (x : TermElabM α) (ctx : Context := {}) (s : State := {}) : MetaM α := (·.1) <$> x.run ctx s def TermElabM.toIO (x : TermElabM α) (ctxCore : Core.Context) (sCore : Core.State) (ctxMeta : Meta.Context) (sMeta : Meta.State) (ctx : Context) (s : State) : IO (α × Core.State × Meta.State × State) := do let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta return (a, sCore, sMeta, s) instance [MetaEval α] : MetaEval (TermElabM α) where eval env opts x _ := do let x : TermElabM α := do try x finally (← Core.getMessageLog).forM fun msg => do IO.println (← msg.toString) MetaEval.eval env opts (hideUnit := true) <| x.run' {} /-- Execute `x` and then tries to solve pending universe constraints. Note that, stuck constraints will not be discarded. -/ def universeConstraintsCheckpoint (x : TermElabM α) : TermElabM α := do let a ← x discard <| processPostponed (mayPostpone := true) (exceptionOnFailure := true) return a def expandDeclId (currNamespace : Name) (currLevelNames : List Name) (declId : Syntax) (modifiers : Modifiers) : TermElabM ExpandDeclIdResult := do let r ← Elab.expandDeclId currNamespace currLevelNames declId modifiers if (← read).sectionVars.contains r.shortName then throwError "invalid declaration name '{r.shortName}', there is a section variable with the same name" return r /-- Helper function for "embedding" an `Expr` in `Syntax`. It creates a named hole `?m` and immediately assigns `e` to it. Examples: ```lean let e := mkConst ``Nat.zero `(Nat.succ $(← exprToSyntax e)) ``` -/ def exprToSyntax (e : Expr) : TermElabM Term := withFreshMacroScope do let result ← `(?m) let eType ← inferType e let mvar ← elabTerm result eType mvar.mvarId!.assign e return result end Term open Term in def withoutModifyingStateWithInfoAndMessages [MonadControlT TermElabM m] [Monad m] (x : m α) : m α := do controlAt TermElabM fun runInBase => withoutModifyingStateWithInfoAndMessagesImpl <| runInBase x builtin_initialize registerTraceClass `Elab.postpone registerTraceClass `Elab.coe registerTraceClass `Elab.debug export Term (TermElabM) end Lean.Elab
ce090adc9d4f526d38f66f0375ce0bd55c2180b3
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/private_names.lean
61ecb3c395e238b5deb5b77a93961b15e9b011d4
[ "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
186
lean
namespace bla section private definition foo : inhabited Prop := inhabited.mk false attribute [instance, priority 1000] foo example : default Prop = false := rfl end end bla
b1cb90dac269ebc39792b6a9af4e0909d935f183
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/vector_bundle/hom.lean
96ea682a0be2b666a2036d3f37d6b49a3d87560f
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
16,609
lean
/- Copyright © 2022 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Floris van Doorn -/ import topology.vector_bundle.basic import analysis.normed_space.operator_norm /-! # The vector bundle of continuous (semi)linear maps > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the (topological) vector bundle of continuous (semi)linear maps between two vector bundles over the same base. Given bundles `E₁ E₂ : B → Type*`, normed spaces `F₁` and `F₂`, and a ring-homomorphism `σ` between their respective scalar fields, we define `bundle.continuous_linear_map σ F₁ E₁ F₂ E₂ x` to be a type synonym for `λ x, E₁ x →SL[σ] E₂ x`. If the `E₁` and `E₂` are vector bundles with model fibers `F₁` and `F₂`, then this will be a vector bundle with fiber `F₁ →SL[σ] F₂`. The topology on the total space is constructed from the trivializations for `E₁` and `E₂` and the norm-topology on the model fiber `F₁ →SL[𝕜] F₂` using the `vector_prebundle` construction. This is a bit awkward because it introduces a dependence on the normed space structure of the model fibers, rather than just their topological vector space structure; it is not clear whether this is necessary. Similar constructions should be possible (but are yet to be formalized) for tensor products of topological vector bundles, exterior algebras, and so on, where again the topology can be defined using a norm on the fiber model if this helps. ## Main Definitions * `bundle.continuous_linear_map.vector_bundle`: continuous semilinear maps between vector bundles form a vector bundle. -/ noncomputable theory open_locale bundle open bundle set continuous_linear_map variables {𝕜₁ : Type*} [nontrivially_normed_field 𝕜₁] {𝕜₂ : Type*} [nontrivially_normed_field 𝕜₂] (σ : 𝕜₁ →+* 𝕜₂) [iσ : ring_hom_isometric σ] variables {B : Type*} variables {F₁ : Type*} [normed_add_comm_group F₁] [normed_space 𝕜₁ F₁] (E₁ : B → Type*) [Π x, add_comm_group (E₁ x)] [Π x, module 𝕜₁ (E₁ x)] [topological_space (total_space F₁ E₁)] variables {F₂ : Type*} [normed_add_comm_group F₂] [normed_space 𝕜₂ F₂] (E₂ : B → Type*) [Π x, add_comm_group (E₂ x)] [Π x, module 𝕜₂ (E₂ x)] [topological_space (total_space F₂ E₂)] /-- A reducible type synonym for the bundle of continuous (semi)linear maps. For some reason, it helps with instance search. Porting note: after the port is done, we may want to remove this definition. -/ @[reducible] protected def bundle.continuous_linear_map [∀ x, topological_space (E₁ x)] [∀ x, topological_space (E₂ x)] : Π x : B, Type* := λ x, E₁ x →SL[σ] E₂ x -- Porting note: possibly remove after the port instance bundle.continuous_linear_map.module [∀ x, topological_space (E₁ x)] [∀ x, topological_space (E₂ x)] [∀ x, topological_add_group (E₂ x)] [∀ x, has_continuous_const_smul 𝕜₂ (E₂ x)] : ∀ x, module 𝕜₂ (bundle.continuous_linear_map σ E₁ E₂ x) := λ _, infer_instance variables {E₁ E₂} variables [topological_space B] (e₁ e₁' : trivialization F₁ (π F₁ E₁)) (e₂ e₂' : trivialization F₂ (π F₂ E₂)) namespace pretrivialization /-- Assume `eᵢ` and `eᵢ'` are trivializations of the bundles `Eᵢ` over base `B` with fiber `Fᵢ` (`i ∈ {1,2}`), then `continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂'` is the coordinate change function between the two induced (pre)trivializations `pretrivialization.continuous_linear_map σ e₁ e₂` and `pretrivialization.continuous_linear_map σ e₁' e₂'` of `bundle.continuous_linear_map`. -/ def continuous_linear_map_coord_change [e₁.is_linear 𝕜₁] [e₁'.is_linear 𝕜₁] [e₂.is_linear 𝕜₂] [e₂'.is_linear 𝕜₂] (b : B) : (F₁ →SL[σ] F₂) →L[𝕜₂] F₁ →SL[σ] F₂ := ((e₁'.coord_changeL 𝕜₁ e₁ b).symm.arrow_congrSL (e₂.coord_changeL 𝕜₂ e₂' b) : (F₁ →SL[σ] F₂) ≃L[𝕜₂] F₁ →SL[σ] F₂) variables {σ e₁ e₁' e₂ e₂'} variables [Π x, topological_space (E₁ x)] [fiber_bundle F₁ E₁] variables [Π x, topological_space (E₂ x)] [ita : Π x, topological_add_group (E₂ x)] [fiber_bundle F₂ E₂] include iσ lemma continuous_on_continuous_linear_map_coord_change [vector_bundle 𝕜₁ F₁ E₁] [vector_bundle 𝕜₂ F₂ E₂] [mem_trivialization_atlas e₁] [mem_trivialization_atlas e₁'] [mem_trivialization_atlas e₂] [mem_trivialization_atlas e₂'] : continuous_on (continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂') ((e₁.base_set ∩ e₂.base_set) ∩ (e₁'.base_set ∩ e₂'.base_set)) := begin have h₁ := (compSL F₁ F₂ F₂ σ (ring_hom.id 𝕜₂)).continuous, have h₂ := (continuous_linear_map.flip (compSL F₁ F₁ F₂ (ring_hom.id 𝕜₁) σ)).continuous, have h₃ := (continuous_on_coord_change 𝕜₁ e₁' e₁), have h₄ := (continuous_on_coord_change 𝕜₂ e₂ e₂'), refine ((h₁.comp_continuous_on (h₄.mono _)).clm_comp (h₂.comp_continuous_on (h₃.mono _))).congr _, { mfld_set_tac }, { mfld_set_tac }, { intros b hb, ext L v, simp only [continuous_linear_map_coord_change, continuous_linear_equiv.coe_coe, continuous_linear_equiv.arrow_congrSL_apply, comp_apply, function.comp, compSL_apply, flip_apply, continuous_linear_equiv.symm_symm] }, end omit iσ variables (σ e₁ e₁' e₂ e₂') [e₁.is_linear 𝕜₁] [e₁'.is_linear 𝕜₁] [e₂.is_linear 𝕜₂] [e₂'.is_linear 𝕜₂] /-- Given trivializations `e₁`, `e₂` for vector bundles `E₁`, `E₂` over a base `B`, `pretrivialization.continuous_linear_map σ e₁ e₂` is the induced pretrivialization for the continuous `σ`-semilinear maps from `E₁` to `E₂`. That is, the map which will later become a trivialization, after the bundle of continuous semilinear maps is equipped with the right topological vector bundle structure. -/ def continuous_linear_map : pretrivialization (F₁ →SL[σ] F₂) (π (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ E₁ E₂)) := { to_fun := λ p, ⟨p.1, continuous_linear_map.comp (e₂.continuous_linear_map_at 𝕜₂ p.1) (p.2.comp (e₁.symmL 𝕜₁ p.1 : F₁ →L[𝕜₁] E₁ p.1) : F₁ →SL[σ] E₂ p.1)⟩, inv_fun := λ p, ⟨p.1, continuous_linear_map.comp (e₂.symmL 𝕜₂ p.1) (p.2.comp (e₁.continuous_linear_map_at 𝕜₁ p.1 : E₁ p.1 →L[𝕜₁] F₁) : E₁ p.1 →SL[σ] F₂)⟩, source := (bundle.total_space.proj) ⁻¹' (e₁.base_set ∩ e₂.base_set), target := (e₁.base_set ∩ e₂.base_set) ×ˢ set.univ, map_source' := λ ⟨x, L⟩ h, ⟨h, set.mem_univ _⟩, map_target' := λ ⟨x, f⟩ h, h.1, left_inv' := λ ⟨x, L⟩ ⟨h₁, h₂⟩, begin simp_rw [sigma.mk.inj_iff, eq_self_iff_true, heq_iff_eq, true_and], ext v, simp only [comp_apply, trivialization.symmL_continuous_linear_map_at, h₁, h₂] end, right_inv' := λ ⟨x, f⟩ ⟨⟨h₁, h₂⟩, _⟩, begin simp_rw [prod.mk.inj_iff, eq_self_iff_true, true_and], ext v, simp only [comp_apply, trivialization.continuous_linear_map_at_symmL, h₁, h₂] end, open_target := (e₁.open_base_set.inter e₂.open_base_set).prod is_open_univ, base_set := e₁.base_set ∩ e₂.base_set, open_base_set := e₁.open_base_set.inter e₂.open_base_set, source_eq := rfl, target_eq := rfl, proj_to_fun := λ ⟨x, f⟩ h, rfl } include ita -- porting note: todo: see if Lean 4 can generate this instance without a hint instance continuous_linear_map.is_linear [Π x, has_continuous_add (E₂ x)] [Π x, has_continuous_smul 𝕜₂ (E₂ x)] : (pretrivialization.continuous_linear_map σ e₁ e₂).is_linear 𝕜₂ := { linear := λ x h, { map_add := λ L L', show (e₂.continuous_linear_map_at 𝕜₂ x).comp ((L + L').comp (e₁.symmL 𝕜₁ x)) = _, begin simp_rw [add_comp, comp_add], refl end, map_smul := λ c L, show (e₂.continuous_linear_map_at 𝕜₂ x).comp ((c • L).comp (e₁.symmL 𝕜₁ x)) = _, begin simp_rw [smul_comp, comp_smulₛₗ, ring_hom.id_apply], refl end, } } omit ita lemma continuous_linear_map_apply (p : total_space (F₁ →SL[σ] F₂) (λ x, E₁ x →SL[σ] E₂ x)) : (continuous_linear_map σ e₁ e₂) p = ⟨p.1, continuous_linear_map.comp (e₂.continuous_linear_map_at 𝕜₂ p.1) (p.2.comp (e₁.symmL 𝕜₁ p.1 : F₁ →L[𝕜₁] E₁ p.1) : F₁ →SL[σ] E₂ p.1)⟩ := rfl lemma continuous_linear_map_symm_apply (p : B × (F₁ →SL[σ] F₂)) : (continuous_linear_map σ e₁ e₂).to_local_equiv.symm p = ⟨p.1, continuous_linear_map.comp (e₂.symmL 𝕜₂ p.1) (p.2.comp (e₁.continuous_linear_map_at 𝕜₁ p.1 : E₁ p.1 →L[𝕜₁] F₁) : E₁ p.1 →SL[σ] F₂)⟩ := rfl include ita lemma continuous_linear_map_symm_apply' {b : B} (hb : b ∈ e₁.base_set ∩ e₂.base_set) (L : F₁ →SL[σ] F₂) : (continuous_linear_map σ e₁ e₂).symm b L = (e₂.symmL 𝕜₂ b).comp (L.comp $ e₁.continuous_linear_map_at 𝕜₁ b) := begin rw [symm_apply], refl, exact hb end lemma continuous_linear_map_coord_change_apply (b : B) (hb : b ∈ (e₁.base_set ∩ e₂.base_set) ∩ (e₁'.base_set ∩ e₂'.base_set)) (L : F₁ →SL[σ] F₂) : continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂' b L = (continuous_linear_map σ e₁' e₂' ⟨b, ((continuous_linear_map σ e₁ e₂).symm b L)⟩).2 := begin ext v, simp_rw [continuous_linear_map_coord_change, continuous_linear_equiv.coe_coe, continuous_linear_equiv.arrow_congrSL_apply, continuous_linear_map_apply, continuous_linear_map_symm_apply' σ e₁ e₂ hb.1, comp_apply, continuous_linear_equiv.coe_coe, continuous_linear_equiv.symm_symm, trivialization.continuous_linear_map_at_apply, trivialization.symmL_apply], rw [e₂.coord_changeL_apply e₂', e₁'.coord_changeL_apply e₁, e₁.coe_linear_map_at_of_mem hb.1.1, e₂'.coe_linear_map_at_of_mem hb.2.2], exacts [⟨hb.2.1, hb.1.1⟩, ⟨hb.1.2, hb.2.2⟩] end end pretrivialization open pretrivialization variables (F₁ E₁ F₂ E₂) variables [Π x : B, topological_space (E₁ x)] [fiber_bundle F₁ E₁] [vector_bundle 𝕜₁ F₁ E₁] variables [Π x : B, topological_space (E₂ x)] [fiber_bundle F₂ E₂] [vector_bundle 𝕜₂ F₂ E₂] variables [Π x, topological_add_group (E₂ x)] [Π x, has_continuous_smul 𝕜₂ (E₂ x)] include iσ /-- The continuous `σ`-semilinear maps between two topological vector bundles form a `vector_prebundle` (this is an auxiliary construction for the `vector_bundle` instance, in which the pretrivializations are collated but no topology on the total space is yet provided). -/ def _root_.bundle.continuous_linear_map.vector_prebundle : vector_prebundle 𝕜₂ (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ E₁ E₂) := { pretrivialization_atlas := {e | ∃ (e₁ : trivialization F₁ (π F₁ E₁)) (e₂ : trivialization F₂ (π F₂ E₂)) [mem_trivialization_atlas e₁] [mem_trivialization_atlas e₂], by exactI e = pretrivialization.continuous_linear_map σ e₁ e₂}, pretrivialization_linear' := begin rintro _ ⟨e₁, he₁, e₂, he₂, rfl⟩, apply_instance end, pretrivialization_at := λ x, pretrivialization.continuous_linear_map σ (trivialization_at F₁ E₁ x) (trivialization_at F₂ E₂ x), mem_base_pretrivialization_at := λ x, ⟨mem_base_set_trivialization_at F₁ E₁ x, mem_base_set_trivialization_at F₂ E₂ x⟩, pretrivialization_mem_atlas := λ x, ⟨trivialization_at F₁ E₁ x, trivialization_at F₂ E₂ x, _, _, rfl⟩, exists_coord_change := by { rintro _ ⟨e₁, e₂, he₁, he₂, rfl⟩ _ ⟨e₁', e₂', he₁', he₂', rfl⟩, resetI, exact ⟨continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂', continuous_on_continuous_linear_map_coord_change, continuous_linear_map_coord_change_apply σ e₁ e₁' e₂ e₂'⟩ }, total_space_mk_inducing := begin intros b, let L₁ : E₁ b ≃L[𝕜₁] F₁ := (trivialization_at F₁ E₁ b).continuous_linear_equiv_at 𝕜₁ b (mem_base_set_trivialization_at _ _ _), let L₂ : E₂ b ≃L[𝕜₂] F₂ := (trivialization_at F₂ E₂ b).continuous_linear_equiv_at 𝕜₂ b (mem_base_set_trivialization_at _ _ _), let φ : (E₁ b →SL[σ] E₂ b) ≃L[𝕜₂] (F₁ →SL[σ] F₂) := L₁.arrow_congrSL L₂, have : inducing (λ x, (b, φ x)) := inducing_const_prod.mpr φ.to_homeomorph.inducing, convert this, ext f, { refl }, ext x, dsimp [φ, pretrivialization.continuous_linear_map_apply], rw [trivialization.linear_map_at_def_of_mem _ (mem_base_set_trivialization_at _ _ _)], refl end } /-- Topology on the total space of the continuous `σ`-semilinear_maps between two "normable" vector bundles over the same base. -/ instance bundle.continuous_linear_map.topological_space_total_space : topological_space (total_space (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ E₁ E₂)) := (bundle.continuous_linear_map.vector_prebundle σ F₁ E₁ F₂ E₂).total_space_topology /-- The continuous `σ`-semilinear_maps between two vector bundles form a fiber bundle. -/ instance _root_.bundle.continuous_linear_map.fiber_bundle : fiber_bundle (F₁ →SL[σ] F₂) (λ x, E₁ x →SL[σ] E₂ x) := (bundle.continuous_linear_map.vector_prebundle σ F₁ E₁ F₂ E₂).to_fiber_bundle /-- The continuous `σ`-semilinear_maps between two vector bundles form a vector bundle. -/ instance _root_.bundle.continuous_linear_map.vector_bundle : vector_bundle 𝕜₂ (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ E₁ E₂) := (bundle.continuous_linear_map.vector_prebundle σ F₁ E₁ F₂ E₂).to_vector_bundle variables (e₁ e₂) [he₁ : mem_trivialization_atlas e₁] [he₂ : mem_trivialization_atlas e₂] {F₁ E₁ F₂ E₂} include he₁ he₂ /-- Given trivializations `e₁`, `e₂` in the atlas for vector bundles `E₁`, `E₂` over a base `B`, the induced trivialization for the continuous `σ`-semilinear maps from `E₁` to `E₂`, whose base set is `e₁.base_set ∩ e₂.base_set`. -/ def trivialization.continuous_linear_map : trivialization (F₁ →SL[σ] F₂) (π (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ E₁ E₂)) := vector_prebundle.trivialization_of_mem_pretrivialization_atlas _ ⟨e₁, e₂, he₁, he₂, rfl⟩ instance _root_.bundle.continuous_linear_map.mem_trivialization_atlas : mem_trivialization_atlas (e₁.continuous_linear_map σ e₂ : trivialization (F₁ →SL[σ] F₂) (π (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ E₁ E₂))) := { out := ⟨_, ⟨e₁, e₂, by apply_instance, by apply_instance, rfl⟩, rfl⟩ } variables {e₁ e₂} @[simp] lemma trivialization.base_set_continuous_linear_map : (e₁.continuous_linear_map σ e₂).base_set = e₁.base_set ∩ e₂.base_set := rfl lemma trivialization.continuous_linear_map_apply (p : total_space (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ E₁ E₂)) : e₁.continuous_linear_map σ e₂ p = ⟨p.1, (e₂.continuous_linear_map_at 𝕜₂ p.1 : _ →L[𝕜₂] _).comp (p.2.comp (e₁.symmL 𝕜₁ p.1 : F₁ →L[𝕜₁] E₁ p.1) : F₁ →SL[σ] E₂ p.1)⟩ := rfl omit he₁ he₂ lemma hom_trivialization_at_apply (x₀ : B) (x : total_space (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ E₁ E₂)) : trivialization_at (F₁ →SL[σ] F₂) (λ x, E₁ x →SL[σ] E₂ x) x₀ x = ⟨x.1, in_coordinates F₁ E₁ F₂ E₂ x₀ x.1 x₀ x.1 x.2⟩ := rfl @[simp, mfld_simps] lemma hom_trivialization_at_source (x₀ : B) : (trivialization_at (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ E₁ E₂) x₀).source = π (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ E₁ E₂) ⁻¹' ((trivialization_at F₁ E₁ x₀).base_set ∩ (trivialization_at F₂ E₂ x₀).base_set) := rfl @[simp, mfld_simps] lemma hom_trivialization_at_target (x₀ : B) : (trivialization_at (F₁ →SL[σ] F₂) (λ x, E₁ x →SL[σ] E₂ x) x₀).target = ((trivialization_at F₁ E₁ x₀).base_set ∩ (trivialization_at F₂ E₂ x₀).base_set) ×ˢ set.univ := rfl
722cf7d1d8ee4c2953b5aee5b3d94c587d75d8a1
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/frobenius_number.lean
5d6ce548e546fb79f6783b4335e30199b78ec7a4
[ "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,160
lean
/- Copyright (c) 2021 Alex Zhao. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex Zhao -/ import data.nat.modeq import group_theory.submonoid.basic import group_theory.submonoid.membership /-! # Frobenius Number in Two Variables In this file we first define a predicate for Frobenius numbers, then solve the 2-variable variant of this problem. ## Theorem Statement Given a finite set of relatively prime integers all greater than 1, their Frobenius number is the largest positive integer that cannot be expressed as a sum of nonnegative multiples of these integers. Here we show the Frobenius number of two relatively prime integers `m` and `n` greater than 1 is `m * n - m - n`. This result is also known as the Chicken McNugget Theorem. ## Implementation Notes First we define Frobenius numbers in general using `is_greatest` and `add_submonoid.closure`. Then we proceed to compute the Frobenius number of `m` and `n`. For the upper bound, we begin with an auxiliary lemma showing `m * n` is not attainable, then show `m * n - m - n` is not attainable. Then for the construction, we create a `k_1` which is `k mod n` and `0 mod m`, then show it is at most `k`. Then `k_1` is a multiple of `m`, so `(k-k_1)` is a multiple of n, and we're done. ## Tags frobenius number, chicken mcnugget, chinese remainder theorem, add_submonoid.closure -/ open nat /-- A natural number `n` is the **Frobenius number** of a set of natural numbers `s` if it is an upper bound on the complement of the additive submonoid generated by `s`. In other words, it is the largest number that can not be expressed as a sum of numbers in `s`. -/ def is_frobenius_number (n : ℕ) (s : set ℕ) : Prop := is_greatest {k | k ∉ add_submonoid.closure (s)} n variables {m n : ℕ} /-- The **Chicken Mcnugget theorem** stating that the Frobenius number of positive numbers `m` and `n` is `m * n - m - n`. -/ theorem is_frobenius_number_pair (cop : coprime m n) (hm : 1 < m) (hn : 1 < n) : is_frobenius_number (m * n - m - n) {m, n} := begin simp_rw [is_frobenius_number, add_submonoid.mem_closure_pair], have hmn : m + n ≤ m * n := add_le_mul hm hn, split, { push_neg, intros a b h, apply cop.mul_add_mul_ne_mul (add_one_ne_zero a) (add_one_ne_zero b), simp only [nat.sub_sub, smul_eq_mul] at h, zify at h ⊢, rw [← sub_eq_zero] at h ⊢, rw ← h, ring, }, { intros k hk, dsimp at hk, contrapose! hk, let x := chinese_remainder cop 0 k, have hx : x.val < m * n := chinese_remainder_lt_mul cop 0 k (ne_bot_of_gt hm) (ne_bot_of_gt hn), suffices key : x.1 ≤ k, { obtain ⟨a, ha⟩ := modeq_zero_iff_dvd.mp x.2.1, obtain ⟨b, hb⟩ := (modeq_iff_dvd' key).mp x.2.2, exact ⟨a, b, by rw [mul_comm, ←ha, mul_comm, ←hb, nat.add_sub_of_le key]⟩, }, refine modeq.le_of_lt_add x.2.2 (lt_of_le_of_lt _ (add_lt_add_right hk n)), rw nat.sub_add_cancel (le_tsub_of_add_le_left hmn), exact modeq.le_of_lt_add (x.2.1.trans (modeq_zero_iff_dvd.mpr (nat.dvd_sub' (dvd_mul_right m n) dvd_rfl)).symm) (lt_of_lt_of_le hx le_tsub_add), }, end
4d1008f9b0f8a59f96ba3e282573b5b812e107bc
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/decomposition/unsigned_hahn.lean
f568e2127eac72f37c66f18683b27b4ea5eab8dc
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,727
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import measure_theory.measure.measure_space /-! # Unsigned Hahn decomposition theorem This file proves the unsigned version of the Hahn decomposition theorem. ## Main statements * `hahn_decomposition` : Given two finite measures `μ` and `ν`, there exists a measurable set `s` such that any measurable set `t` included in `s` satisfies `ν t ≤ μ t`, and any measurable set `u` included in the complement of `s` satisfies `μ u ≤ ν u`. ## Tags Hahn decomposition -/ open set filter open_locale classical topological_space ennreal namespace measure_theory variables {α : Type*} [measurable_space α] {μ ν : measure α} -- suddenly this is necessary?! private lemma aux {m : ℕ} {γ d : ℝ} (h : γ - (1 / 2) ^ m < d) : γ - 2 * (1 / 2) ^ m + (1 / 2) ^ m ≤ d := by linarith /-- **Hahn decomposition theorem** -/ lemma hahn_decomposition [is_finite_measure μ] [is_finite_measure ν] : ∃s, measurable_set s ∧ (∀t, measurable_set t → t ⊆ s → ν t ≤ μ t) ∧ (∀t, measurable_set t → t ⊆ sᶜ → μ t ≤ ν t) := begin let d : set α → ℝ := λs, ((μ s).to_nnreal : ℝ) - (ν s).to_nnreal, let c : set ℝ := d '' {s | measurable_set s }, let γ : ℝ := Sup c, have hμ : ∀ s, μ s ≠ ∞ := measure_ne_top μ, have hν : ∀ s, ν s ≠ ∞ := measure_ne_top ν, have to_nnreal_μ : ∀s, ((μ s).to_nnreal : ℝ≥0∞) = μ s := (assume s, ennreal.coe_to_nnreal $ hμ _), have to_nnreal_ν : ∀s, ((ν s).to_nnreal : ℝ≥0∞) = ν s := (assume s, ennreal.coe_to_nnreal $ hν _), have d_empty : d ∅ = 0, { change _ - _ = _, rw [measure_empty, measure_empty, sub_self] }, have d_split : ∀s t, measurable_set s → measurable_set t → d s = d (s \ t) + d (s ∩ t), { assume s t hs ht, simp only [d], rw [← measure_inter_add_diff s ht, ← measure_inter_add_diff s ht, ennreal.to_nnreal_add (hμ _) (hμ _), ennreal.to_nnreal_add (hν _) (hν _), nnreal.coe_add, nnreal.coe_add], simp only [sub_eq_add_neg, neg_add], ac_refl }, have d_Union : ∀(s : ℕ → set α), (∀n, measurable_set (s n)) → monotone s → tendsto (λn, d (s n)) at_top (𝓝 (d (⋃n, s n))), { assume s hs hm, refine tendsto.sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal _).comp $ tendsto_measure_Union hs hm), exact hμ _, exact hν _ }, have d_Inter : ∀(s : ℕ → set α), (∀n, measurable_set (s n)) → (∀n m, n ≤ m → s m ⊆ s n) → tendsto (λn, d (s n)) at_top (𝓝 (d (⋂n, s n))), { assume s hs hm, refine tendsto.sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal $ _).comp $ tendsto_measure_Inter hs hm _), exacts [hμ _, ⟨0, hμ _⟩, hν _, ⟨0, hν _⟩] }, have bdd_c : bdd_above c, { use (μ univ).to_nnreal, rintros r ⟨s, hs, rfl⟩, refine le_trans (sub_le_self _ $ nnreal.coe_nonneg _) _, rw [nnreal.coe_le_coe, ← ennreal.coe_le_coe, to_nnreal_μ, to_nnreal_μ], exact measure_mono (subset_univ _) }, have c_nonempty : c.nonempty := nonempty.image _ ⟨_, measurable_set.empty⟩, have d_le_γ : ∀s, measurable_set s → d s ≤ γ := assume s hs, le_cSup bdd_c ⟨s, hs, rfl⟩, have : ∀n:ℕ, ∃s : set α, measurable_set s ∧ γ - (1/2)^n < d s, { assume n, have : γ - (1/2)^n < γ := sub_lt_self γ (pow_pos (half_pos zero_lt_one) n), rcases exists_lt_of_lt_cSup c_nonempty this with ⟨r, ⟨s, hs, rfl⟩, hlt⟩, exact ⟨s, hs, hlt⟩ }, rcases classical.axiom_of_choice this with ⟨e, he⟩, change ℕ → set α at e, have he₁ : ∀n, measurable_set (e n) := assume n, (he n).1, have he₂ : ∀n, γ - (1/2)^n < d (e n) := assume n, (he n).2, let f : ℕ → ℕ → set α := λn m, (finset.Ico n (m + 1)).inf e, have hf : ∀n m, measurable_set (f n m), { assume n m, simp only [f, finset.inf_eq_infi], exact measurable_set.bInter (countable_encodable _) (assume i _, he₁ _) }, have f_subset_f : ∀{a b c d}, a ≤ b → c ≤ d → f a d ⊆ f b c, { assume a b c d hab hcd, dsimp only [f], rw [finset.inf_eq_infi, finset.inf_eq_infi], exact bInter_subset_bInter_left (finset.Ico_subset_Ico hab $ nat.succ_le_succ hcd) }, have f_succ : ∀n m, n ≤ m → f n (m + 1) = f n m ∩ e (m + 1), { assume n m hnm, have : n ≤ m + 1 := le_of_lt (nat.succ_le_succ hnm), simp only [f], rw [nat.Ico_succ_right_eq_insert_Ico this, finset.inf_insert, set.inter_comm], refl }, have le_d_f : ∀n m, m ≤ n → γ - 2 * ((1 / 2) ^ m) + (1 / 2) ^ n ≤ d (f m n), { assume n m h, refine nat.le_induction _ _ n h, { have := he₂ m, simp only [f], rw [nat.Ico_succ_singleton, finset.inf_singleton], exact aux this }, { assume n (hmn : m ≤ n) ih, have : γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n + 1)) ≤ γ + d (f m (n + 1)), { calc γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n+1)) ≤ γ + (γ - 2 * (1 / 2)^m + ((1 / 2) ^ n - (1/2)^(n+1))) : begin refine add_le_add_left (add_le_add_left _ _) γ, simp only [pow_add, pow_one, le_sub_iff_add_le], linarith end ... = (γ - (1 / 2)^(n+1)) + (γ - 2 * (1 / 2)^m + (1 / 2)^n) : by simp only [sub_eq_add_neg]; ac_refl ... ≤ d (e (n + 1)) + d (f m n) : add_le_add (le_of_lt $ he₂ _) ih ... ≤ d (e (n + 1)) + d (f m n \ e (n + 1)) + d (f m (n + 1)) : by rw [f_succ _ _ hmn, d_split (f m n) (e (n + 1)) (hf _ _) (he₁ _), add_assoc] ... = d (e (n + 1) ∪ f m n) + d (f m (n + 1)) : begin rw [d_split (e (n + 1) ∪ f m n) (e (n + 1)), union_diff_left, union_inter_cancel_left], ac_refl, exact (he₁ _).union (hf _ _), exact (he₁ _) end ... ≤ γ + d (f m (n + 1)) : add_le_add_right (d_le_γ _ $ (he₁ _).union (hf _ _)) _ }, exact (add_le_add_iff_left γ).1 this } }, let s := ⋃ m, ⋂n, f m n, have γ_le_d_s : γ ≤ d s, { have hγ : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 γ), { suffices : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 (γ - 2 * 0)), { simpa }, exact (tendsto_const_nhds.sub $ tendsto_const_nhds.mul $ tendsto_pow_at_top_nhds_0_of_lt_1 (le_of_lt $ half_pos $ zero_lt_one) (half_lt_self zero_lt_one)) }, have hd : tendsto (λm, d (⋂n, f m n)) at_top (𝓝 (d (⋃ m, ⋂ n, f m n))), { refine d_Union _ _ _, { assume n, exact measurable_set.Inter (assume m, hf _ _) }, { exact assume n m hnm, subset_Inter (assume i, subset.trans (Inter_subset (f n) i) $ f_subset_f hnm $ le_refl _) } }, refine le_of_tendsto_of_tendsto' hγ hd (assume m, _), have : tendsto (λn, d (f m n)) at_top (𝓝 (d (⋂ n, f m n))), { refine d_Inter _ _ _, { assume n, exact hf _ _ }, { assume n m hnm, exact f_subset_f (le_refl _) hnm } }, refine ge_of_tendsto this (eventually_at_top.2 ⟨m, assume n hmn, _⟩), change γ - 2 * (1 / 2) ^ m ≤ d (f m n), refine le_trans _ (le_d_f _ _ hmn), exact le_add_of_le_of_nonneg (le_refl _) (pow_nonneg (le_of_lt $ half_pos $ zero_lt_one) _) }, have hs : measurable_set s := measurable_set.Union (assume n, measurable_set.Inter (assume m, hf _ _)), refine ⟨s, hs, _, _⟩, { assume t ht hts, have : 0 ≤ d t := ((add_le_add_iff_left γ).1 $ calc γ + 0 ≤ d s : by rw [add_zero]; exact γ_le_d_s ... = d (s \ t) + d t : by rw [d_split _ _ hs ht, inter_eq_self_of_subset_right hts] ... ≤ γ + d t : add_le_add (d_le_γ _ (hs.diff ht)) (le_refl _)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le_coe], simpa only [d, le_sub_iff_add_le, zero_add] using this }, { assume t ht hts, have : d t ≤ 0, exact ((add_le_add_iff_left γ).1 $ calc γ + d t ≤ d s + d t : add_le_add γ_le_d_s (le_refl _) ... = d (s ∪ t) : begin rw [d_split _ _ (hs.union ht) ht, union_diff_right, union_inter_cancel_right, diff_eq_self.2], exact assume a ⟨hat, has⟩, hts hat has end ... ≤ γ + 0 : by rw [add_zero]; exact d_le_γ _ (hs.union ht)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le_coe], simpa only [d, sub_le_iff_le_add, zero_add] using this } end end measure_theory
1ec437ac059541b35e7a6ffc4ef88abdfa6d8454
618003631150032a5676f229d13a079ac875ff77
/src/control/bifunctor.lean
a65a2ffab8bc6e64debed736012f9153451ff486
[ "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
4,311
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Functors with two arguments -/ import logic.function.basic import tactic.basic universes u₀ u₁ u₂ v₀ v₁ v₂ open function class bifunctor (F : Type u₀ → Type u₁ → Type u₂) := (bimap : Π {α α' β β'}, (α → α') → (β → β') → F α β → F α' β') export bifunctor ( bimap ) class is_lawful_bifunctor (F : Type u₀ → Type u₁ → Type u₂) [bifunctor F] := (id_bimap : Π {α β} (x : F α β), bimap id id x = x) (bimap_bimap : Π {α₀ α₁ α₂ β₀ β₁ β₂} (f : α₀ → α₁) (f' : α₁ → α₂) (g : β₀ → β₁) (g' : β₁ → β₂) (x : F α₀ β₀), bimap f' g' (bimap f g x) = bimap (f' ∘ f) (g' ∘ g) x) export is_lawful_bifunctor (id_bimap bimap_bimap) attribute [higher_order bimap_id_id] id_bimap attribute [higher_order bimap_comp_bimap] bimap_bimap export is_lawful_bifunctor (bimap_id_id bimap_comp_bimap) variables {F : Type u₀ → Type u₁ → Type u₂} [bifunctor F] namespace bifunctor @[reducible] def fst {α α' β} (f : α → α') : F α β → F α' β := bimap f id @[reducible] def snd {α β β'} (f : β → β') : F α β → F α β' := bimap id f variable [is_lawful_bifunctor F] @[higher_order fst_id] lemma id_fst : Π {α β} (x : F α β), fst id x = x := @id_bimap _ _ _ @[higher_order snd_id] lemma id_snd : Π {α β} (x : F α β), snd id x = x := @id_bimap _ _ _ @[higher_order fst_comp_fst] lemma comp_fst {α₀ α₁ α₂ β} (f : α₀ → α₁) (f' : α₁ → α₂) (x : F α₀ β) : fst f' (fst f x) = fst (f' ∘ f) x := by simp [fst,bimap_bimap] @[higher_order fst_comp_snd] lemma fst_snd {α₀ α₁ β₀ β₁} (f : α₀ → α₁) (f' : β₀ → β₁) (x : F α₀ β₀) : fst f (snd f' x) = bimap f f' x := by simp [fst,bimap_bimap] @[higher_order snd_comp_fst] lemma snd_fst {α₀ α₁ β₀ β₁} (f : α₀ → α₁) (f' : β₀ → β₁) (x : F α₀ β₀) : snd f' (fst f x) = bimap f f' x := by simp [snd,bimap_bimap] @[higher_order snd_comp_snd] lemma comp_snd {α β₀ β₁ β₂} (g : β₀ → β₁) (g' : β₁ → β₂) (x : F α β₀) : snd g' (snd g x) = snd (g' ∘ g) x := by simp [snd,bimap_bimap] attribute [functor_norm] bimap_bimap comp_snd comp_fst snd_comp_snd snd_comp_fst fst_comp_snd fst_comp_fst bimap_comp_bimap bimap_id_id fst_id snd_id end bifunctor open functor instance : bifunctor prod := { bimap := @prod.map } instance : is_lawful_bifunctor prod := by refine { .. }; intros; cases x; refl instance bifunctor.const : bifunctor const := { bimap := (λ α α' β β f _, f) } instance is_lawful_bifunctor.const : is_lawful_bifunctor const := by refine { .. }; intros; refl instance bifunctor.flip : bifunctor (flip F) := { bimap := (λ α α' β β' f f' x, (bimap f' f x : F β' α')) } instance is_lawful_bifunctor.flip [is_lawful_bifunctor F] : is_lawful_bifunctor (flip F) := by refine { .. }; intros; simp [bimap] with functor_norm instance : bifunctor sum := { bimap := @sum.map } instance : is_lawful_bifunctor sum := by refine { .. }; intros; cases x; refl open bifunctor functor @[priority 10] instance bifunctor.functor {α} : functor (F α) := { map := λ _ _, snd } @[priority 10] instance bifunctor.is_lawful_functor [is_lawful_bifunctor F] {α} : is_lawful_functor (F α) := by refine {..}; intros; simp [functor.map] with functor_norm section bicompl variables (G : Type* → Type u₀) (H : Type* → Type u₁) [functor G] [functor H] instance : bifunctor (bicompl F G H) := { bimap := λ α α' β β' f f' x, (bimap (map f) (map f') x : F (G α') (H β')) } instance [is_lawful_functor G] [is_lawful_functor H] [is_lawful_bifunctor F] : is_lawful_bifunctor (bicompl F G H) := by constructor; intros; simp [bimap,map_id,map_comp_map] with functor_norm end bicompl section bicompr variables (G : Type u₂ → Type*) [functor G] instance : bifunctor (bicompr G F) := { bimap := λ α α' β β' f f' x, (map (bimap f f') x : G (F α' β')) } instance [is_lawful_functor G] [is_lawful_bifunctor F] : is_lawful_bifunctor (bicompr G F) := by constructor; intros; simp [bimap] with functor_norm end bicompr
8c3e87bd0c50f5de42ef7105448c022a50e91fa3
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/errors2.lean
a4f45d1d3ca0984bb93fbea451672f1b470757d2
[ "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
117
lean
open nat namespace foo definition tst1 (a b : nat) : nat := match a with | 0 := 1 | (n+1) := foo end end foo
25251f3ca1988d5874b24206647916ce72d2d896
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/simp_ext1.lean
2b0e46e723638546f034aff6f79e3afa4fae8e58
[ "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
701
lean
open list tactic option constants (A : Type.{1}) (x y z : A) (Hy : x = y) (Hz : y = z) constants (f₁ : A → A) (f₂ : A → A → A) meta_definition simp_x_to_y : tactic unit := mk_eq_simp_ext $ λ e, do res ← mk_const `y, pf ← mk_const `Hy, return (res, pf) meta_definition simp_y_to_z : tactic unit := mk_eq_simp_ext $ λ e, do res ← mk_const `z, pf ← mk_const `Hz, return (res, pf) register_simp_ext x simp_x_to_y register_simp_ext y simp_y_to_z print [simp_ext] example : x = z := by simp example : f₁ x = f₁ y := by simp example : f₁ (f₂ x y) = f₁ (f₂ z z) := by simp example : f₁ (f₂ x y) = f₁ (f₂ y x) := by simp
774d5fdbd6653c8d6a3d139337e1c22c0bb6e97c
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/size_of1.lean
3601d3cf0c3387109560762d05c072d1d5af6820
[ "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
251
lean
open tactic notation `dec_trivial` := of_as_true (by triv) example : sizeof [tt, tt] < sizeof [tt, ff, tt] := dec_trivial example : sizeof [tt, tt] = sizeof [ff, ff] := dec_trivial example : sizeof (3:nat) < sizeof ([3] : list nat) := dec_trivial
9e3addd3204a4ea5c5d3071fd3d085de90c7b121
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Meta/RecursorInfo.lean
917ae1074bab8a45392c9049e063ec5059a9e97d
[ "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
13,513
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.AuxRecursor import Lean.Util.FindExpr import Lean.Meta.ExprDefEq namespace Lean.Meta inductive RecursorUnivLevelPos where | motive -- marks where the universe of the motive should go | majorType (idx : Nat) -- marks where the #idx universe of the major premise type goes instance : ToString RecursorUnivLevelPos := ⟨fun | RecursorUnivLevelPos.motive => "<motive-univ>" | RecursorUnivLevelPos.majorType idx => toString idx⟩ structure RecursorInfo where recursorName : Name typeName : Name univLevelPos : List RecursorUnivLevelPos depElim : Bool recursive : Bool numArgs : Nat -- Total number of arguments majorPos : Nat paramsPos : List (Option Nat) -- Position of the recursor parameters in the major premise, instance implicit arguments are `none` indicesPos : List Nat -- Position of the recursor indices in the major premise produceMotive : List Bool -- If the i-th element is true then i-th minor premise produces the motive namespace RecursorInfo def numParams (info : RecursorInfo) : Nat := info.paramsPos.length def numIndices (info : RecursorInfo) : Nat := info.indicesPos.length def motivePos (info : RecursorInfo) : Nat := info.numParams def firstIndexPos (info : RecursorInfo) : Nat := info.majorPos - info.numIndices def isMinor (info : RecursorInfo) (pos : Nat) : Bool := if pos ≤ info.motivePos then false else if info.firstIndexPos ≤ pos && pos ≤ info.majorPos then false else true def numMinors (info : RecursorInfo) : Nat := let r := info.numArgs let r := r - info.motivePos - 1 r - (info.majorPos + 1 - info.firstIndexPos) instance : ToString RecursorInfo := ⟨fun info => "{\n" ++ " name := " ++ toString info.recursorName ++ "\n" ++ " type := " ++ toString info.typeName ++ "\n" ++ " univs := " ++ toString info.univLevelPos ++ "\n" ++ " depElim := " ++ toString info.depElim ++ "\n" ++ " recursive := " ++ toString info.recursive ++ "\n" ++ " numArgs := " ++ toString info.numArgs ++ "\n" ++ " numParams := " ++ toString info.numParams ++ "\n" ++ " numIndices := " ++ toString info.numIndices ++ "\n" ++ " numMinors := " ++ toString info.numMinors ++ "\n" ++ " major := " ++ toString info.majorPos ++ "\n" ++ " motive := " ++ toString info.motivePos ++ "\n" ++ " paramsAtMajor := " ++ toString info.paramsPos ++ "\n" ++ " indicesAtMajor := " ++ toString info.indicesPos ++ "\n" ++ " produceMotive := " ++ toString info.produceMotive ++ "\n" ++ "}"⟩ end RecursorInfo private def mkRecursorInfoForKernelRec (declName : Name) (val : RecursorVal) : MetaM RecursorInfo := do let ival ← getConstInfoInduct val.getInduct let numLParams := ival.levelParams.length let univLevelPos := (List.range numLParams).map RecursorUnivLevelPos.majorType let univLevelPos := if val.levelParams.length == numLParams then univLevelPos else RecursorUnivLevelPos.motive :: univLevelPos let produceMotive := List.replicate val.numMinors true let paramsPos := (List.range val.numParams).map some let indicesPos := (List.range val.numIndices).map fun pos => val.numParams + pos let numArgs := val.numIndices + val.numParams + val.numMinors + val.numMotives + 1 pure { recursorName := declName, typeName := val.getInduct, univLevelPos := univLevelPos, majorPos := val.getMajorIdx, depElim := true, recursive := ival.isRec, produceMotive := produceMotive, paramsPos := paramsPos, indicesPos := indicesPos, numArgs := numArgs } private def getMajorPosIfAuxRecursor? (declName : Name) (majorPos? : Option Nat) : MetaM (Option Nat) := if majorPos?.isSome then pure majorPos? else do let env ← getEnv if !isAuxRecursor env declName then pure none else match declName with | Name.str p s _ => if s != recOnSuffix && s != casesOnSuffix && s != brecOnSuffix then pure none else do let val ← getConstInfoRec (mkRecName p) pure $ some (val.numParams + val.numIndices + (if s == casesOnSuffix then 1 else val.numMotives)) | _ => pure none private def checkMotive (declName : Name) (motive : Expr) (motiveArgs : Array Expr) : MetaM Unit := unless motive.isFVar && motiveArgs.all Expr.isFVar do throwError "invalid user defined recursor '{declName}', result type must be of the form (C t), where C is a bound variable, and t is a (possibly empty) sequence of bound variables" /- Compute number of parameters for (user-defined) recursor. We assume a parameter is anything that occurs before the motive -/ private partial def getNumParams (xs : Array Expr) (motive : Expr) (i : Nat) : Nat := if h : i < xs.size then let x := xs.get ⟨i, h⟩ if motive == x then i else getNumParams xs motive (i+1) else i private def getMajorPosDepElim (declName : Name) (majorPos? : Option Nat) (xs : Array Expr) (motive : Expr) (motiveArgs : Array Expr) : MetaM (Expr × Nat × Bool) := do match majorPos? with | some majorPos => if h : majorPos < xs.size then let major := xs.get ⟨majorPos, h⟩ let depElim := motiveArgs.contains major pure (major, majorPos, depElim) else throwError "invalid major premise position for user defined recursor, recursor has only {xs.size} arguments" | none => do if motiveArgs.isEmpty then throwError "invalid user defined recursor, '{declName}' does not support dependent elimination, and position of the major premise was not specified (solution: set attribute '[recursor <pos>]', where <pos> is the position of the major premise)" let major := motiveArgs.back match xs.getIdx? major with | some majorPos => pure (major, majorPos, true) | none => throwError "ill-formed recursor '{declName}'" private def getParamsPos (declName : Name) (xs : Array Expr) (numParams : Nat) (Iargs : Array Expr) : MetaM (List (Option Nat)) := do let mut paramsPos := #[] for i in [:numParams] do let x := xs[i] match (← Iargs.findIdxM? fun Iarg => isDefEq Iarg x) with | some j => paramsPos := paramsPos.push (some j) | none => do let localDecl ← getLocalDecl x.fvarId! if localDecl.binderInfo.isInstImplicit then paramsPos := paramsPos.push none else throwError"invalid user defined recursor '{declName}', type of the major premise does not contain the recursor parameter" pure paramsPos.toList private def getIndicesPos (declName : Name) (xs : Array Expr) (majorPos numIndices : Nat) (Iargs : Array Expr) : MetaM (List Nat) := do let mut indicesPos := #[] for i in [:numIndices] do let i := majorPos - numIndices + i let x := xs[i] match (← Iargs.findIdxM? fun Iarg => isDefEq Iarg x) with | some j => indicesPos := indicesPos.push j | none => throwError "invalid user defined recursor '{declName}', type of the major premise does not contain the recursor index" pure indicesPos.toList private def getMotiveLevel (declName : Name) (motiveResultType : Expr) : MetaM Level := match motiveResultType with | Expr.sort u@(Level.zero _) _ => pure u | Expr.sort u@(Level.param _ _) _ => pure u | _ => throwError "invalid user defined recursor '{declName}', motive result sort must be Prop or (Sort u) where u is a universe level parameter" private def getUnivLevelPos (declName : Name) (lparams : List Name) (motiveLvl : Level) (Ilevels : List Level) : MetaM (List RecursorUnivLevelPos) := do let Ilevels := Ilevels.toArray let mut univLevelPos := #[] for p in lparams do if motiveLvl == mkLevelParam p then univLevelPos := univLevelPos.push RecursorUnivLevelPos.motive else match Ilevels.findIdx? fun u => u == mkLevelParam p with | some i => univLevelPos := univLevelPos.push (RecursorUnivLevelPos.majorType i) | none => throwError "invalid user defined recursor '{declName}', major premise type does not contain universe level parameter '{p}'" pure univLevelPos.toList private def getProduceMotiveAndRecursive (xs : Array Expr) (numParams numIndices majorPos : Nat) (motive : Expr) : MetaM (List Bool × Bool) := do let mut produceMotive := #[] let mut recursor := false for i in [:xs.size] do if i < numParams + 1 then continue --skip parameters and motive if majorPos - numIndices ≤ i && i ≤ majorPos then continue -- skip indices and major premise -- process minor premise let x := xs[i] let xType ← inferType x (produceMotive, recursor) ← forallTelescopeReducing xType fun minorArgs minorResultType => minorResultType.withApp fun res _ => do let produceMotive := produceMotive.push (res == motive) let recursor ← if recursor then pure recursor else minorArgs.anyM fun minorArg => do let minorArgType ← inferType minorArg pure (minorArgType.find? fun e => e == motive).isSome pure (produceMotive, recursor) pure (produceMotive.toList, recursor) private def checkMotiveResultType (declName : Name) (motiveArgs : Array Expr) (motiveResultType : Expr) (motiveTypeParams : Array Expr) : MetaM Unit := do if !motiveResultType.isSort || motiveArgs.size != motiveTypeParams.size then throwError "invalid user defined recursor '{declName}', motive must have a type of the form (C : Pi (i : B A), I A i -> Type), where A is (possibly empty) sequence of variables (aka parameters), (i : B A) is a (possibly empty) telescope (aka indices), and I is a constant" private def mkRecursorInfoAux (cinfo : ConstantInfo) (majorPos? : Option Nat) : MetaM RecursorInfo := do let declName := cinfo.name let majorPos? ← getMajorPosIfAuxRecursor? declName majorPos? forallTelescopeReducing cinfo.type fun xs type => type.withApp fun motive motiveArgs => do checkMotive declName motive motiveArgs let numParams := getNumParams xs motive 0 let (major, majorPos, depElim) ← getMajorPosDepElim declName majorPos? xs motive motiveArgs let numIndices := if depElim then motiveArgs.size - 1 else motiveArgs.size if majorPos < numIndices then throwError "invalid user defined recursor '{declName}', indices must occur before major premise" let majorType ← inferType major majorType.withApp fun I Iargs => match I with | Expr.const Iname Ilevels _ => do let paramsPos ← getParamsPos declName xs numParams Iargs let indicesPos ← getIndicesPos declName xs majorPos numIndices Iargs let motiveType ← inferType motive forallTelescopeReducing motiveType fun motiveTypeParams motiveResultType => do checkMotiveResultType declName motiveArgs motiveResultType motiveTypeParams let motiveLvl ← getMotiveLevel declName motiveResultType let univLevelPos ← getUnivLevelPos declName cinfo.levelParams motiveLvl Ilevels let (produceMotive, recursive) ← getProduceMotiveAndRecursive xs numParams numIndices majorPos motive pure { recursorName := declName, typeName := Iname, univLevelPos := univLevelPos, majorPos := majorPos, depElim := depElim, recursive := recursive, produceMotive := produceMotive, paramsPos := paramsPos, indicesPos := indicesPos, numArgs := xs.size } | _ => throwError "invalid user defined recursor '{declName}', type of the major premise must be of the form (I ...), where I is a constant" /- @[builtinAttrParser] def «recursor» := leading_parser "recursor " >> numLit -/ def Attribute.Recursor.getMajorPos (stx : Syntax) : AttrM Nat := do if stx.getKind == `Lean.Parser.Attr.recursor then let pos := stx[1].isNatLit?.getD 0 if pos == 0 then throwErrorAt stx "major premise position must be greater than zero" return pos - 1 else throwErrorAt stx "unexpected attribute argument, numeral expected" private def mkRecursorInfoCore (declName : Name) (majorPos? : Option Nat := none) : MetaM RecursorInfo := do let cinfo ← getConstInfo declName match cinfo with | ConstantInfo.recInfo val => mkRecursorInfoForKernelRec declName val | _ => mkRecursorInfoAux cinfo majorPos? builtin_initialize recursorAttribute : ParametricAttribute Nat ← registerParametricAttribute { name := `recursor, descr := "user defined recursor, numerical parameter specifies position of the major premise", getParam := fun _ stx => Attribute.Recursor.getMajorPos stx afterSet := fun declName majorPos => do discard <| mkRecursorInfoCore declName (some majorPos) |>.run' } def getMajorPos? (env : Environment) (declName : Name) : Option Nat := recursorAttribute.getParam env declName def mkRecursorInfo (declName : Name) (majorPos? : Option Nat := none) : MetaM RecursorInfo := do let cinfo ← getConstInfo declName match cinfo with | ConstantInfo.recInfo val => mkRecursorInfoForKernelRec declName val | _ => match majorPos? with | none => do mkRecursorInfoAux cinfo (getMajorPos? (← getEnv) declName) | _ => mkRecursorInfoAux cinfo majorPos? end Lean.Meta
7ad1b2684f9fc458d1db7782f7bdb84dfcfc33f9
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/linear_algebra/matrix.lean
f1b87190972779ab20ee2de72272a8e86bd80d84
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
10,663
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Casper Putz The equivalence between matrices and linear maps. -/ import data.matrix.basic import linear_algebra.dimension linear_algebra.tensor_product /-! # Linear maps and matrices This file defines the maps to send matrices to a linear map, and to send linear maps between modules with a finite bases to matrices. This defines a linear equivalence between linear maps between finite-dimensional vector spaces and matrices indexed by the respective bases. Some results are proved about the linear map corresponding to a diagonal matrix (range, ker and rank). ## Main definitions to_lin, to_matrix, linear_equiv_matrix ## Tags linear_map, matrix, linear_equiv, diagonal -/ noncomputable theory open set submodule universes u v w variables {l m n : Type u} [fintype l] [fintype m] [fintype n] namespace matrix variables {R : Type v} [comm_ring R] instance [decidable_eq m] [decidable_eq n] (R) [fintype R] : fintype (matrix m n R) := by unfold matrix; apply_instance /-- Evaluation of matrices gives a linear map from matrix m n R to linear maps (n → R) →ₗ[R] (m → R). -/ def eval : (matrix m n R) →ₗ[R] ((n → R) →ₗ[R] (m → R)) := begin refine linear_map.mk₂ R mul_vec _ _ _ _, { assume M N v, funext x, change finset.univ.sum (λy:n, (M x y + N x y) * v y) = _, simp only [_root_.add_mul, finset.sum_add_distrib], refl }, { assume c M v, funext x, change finset.univ.sum (λy:n, (c * M x y) * v y) = _, simp only [_root_.mul_assoc, finset.mul_sum.symm], refl }, { assume M v w, funext x, change finset.univ.sum (λy:n, M x y * (v y + w y)) = _, simp [_root_.mul_add, finset.sum_add_distrib], refl }, { assume c M v, funext x, change finset.univ.sum (λy:n, M x y * (c * v y)) = _, rw [show (λy:n, M x y * (c * v y)) = (λy:n, c * (M x y * v y)), { funext n, ac_refl }, ← finset.mul_sum], refl } end /-- Evaluation of matrices gives a map from matrix m n R to linear maps (n → R) →ₗ[R] (m → R). -/ def to_lin : matrix m n R → (n → R) →ₗ[R] (m → R) := eval.to_fun lemma to_lin_add (M N : matrix m n R) : (M + N).to_lin = M.to_lin + N.to_lin := matrix.eval.map_add M N @[simp] lemma to_lin_zero : (0 : matrix m n R).to_lin = 0 := matrix.eval.map_zero instance to_lin.is_linear_map : @is_linear_map R (matrix m n R) ((n → R) →ₗ[R] (m → R)) _ _ _ _ _ to_lin := matrix.eval.is_linear instance to_lin.is_add_monoid_hom : @is_add_monoid_hom (matrix m n R) ((n → R) →ₗ[R] (m → R)) _ _ to_lin := { map_zero := to_lin_zero, map_add := to_lin_add } @[simp] lemma to_lin_apply (M : matrix m n R) (v : n → R) : (M.to_lin : (n → R) → (m → R)) v = mul_vec M v := rfl lemma mul_to_lin [decidable_eq l] (M : matrix m n R) (N : matrix n l R) : (M.mul N).to_lin = M.to_lin.comp N.to_lin := begin ext v x, simp [to_lin_apply, mul_vec, matrix.mul, finset.sum_mul, finset.mul_sum], rw [finset.sum_comm], congr, funext x, congr, funext y, rw [mul_assoc] end end matrix namespace linear_map variables {R : Type v} [comm_ring R] /-- The linear map from linear maps (n → R) →ₗ[R] (m → R) to matrix m n R. -/ def to_matrixₗ [decidable_eq n] : ((n → R) →ₗ[R] (m → R)) →ₗ[R] matrix m n R := begin refine linear_map.mk (λ f i j, f (λ n, ite (j = n) 1 0) i) _ _, { assume f g, simp only [add_apply], refl }, { assume f g, simp only [smul_apply], refl } end /-- The map from linear maps (n → R) →ₗ[R] (m → R) to matrix m n R. -/ def to_matrix [decidable_eq n] : ((n → R) →ₗ[R] (m → R)) → matrix m n R := to_matrixₗ.to_fun end linear_map section linear_equiv_matrix variables {R : Type v} [comm_ring R] [decidable_eq n] open finsupp matrix linear_map /-- to_lin is the left inverse of to_matrix. -/ lemma to_matrix_to_lin {f : (n → R) →ₗ[R] (m → R)} : to_lin (to_matrix f) = f := begin ext : 1, -- Show that the two sides are equal by showing that they are equal on a basis convert linear_eq_on (set.range _) _ (is_basis.mem_span (@pi.is_basis_fun R n _ _) _), assume e he, rw [@std_basis_eq_single R _ _ _ 1] at he, cases (set.mem_range.mp he) with i h, ext j, change finset.univ.sum (λ k, (f.to_fun (λ l, ite (k = l) 1 0)) j * (e k)) = _, rw [←h], conv_lhs { congr, skip, funext, rw [mul_comm, ←smul_eq_mul, ←pi.smul_apply, ←linear_map.smul], rw [show _ = ite (i = k) (1:R) 0, by convert single_apply], rw [show f.to_fun (ite (i = k) (1:R) 0 • (λ l, ite (k = l) 1 0)) = ite (i = k) (f.to_fun _) 0, { split_ifs, { rw [one_smul] }, { rw [zero_smul], exact linear_map.map_zero f } }] }, convert finset.sum_eq_single i _ _, { rw [if_pos rfl], convert rfl, ext, congr }, { assume _ _ hbi, rw [if_neg $ ne.symm hbi], refl }, { assume hi, exact false.elim (hi $ finset.mem_univ i) } end /-- to_lin is the right inverse of to_matrix. -/ lemma to_lin_to_matrix {M : matrix m n R} : to_matrix (to_lin M) = M := begin ext, change finset.univ.sum (λ y, M i y * ite (j = y) 1 0) = M i j, have h1 : (λ y, M i y * ite (j = y) 1 0) = (λ y, ite (j = y) (M i y) 0), { ext, split_ifs, exact mul_one _, exact ring.mul_zero _ }, have h2 : finset.univ.sum (λ y, ite (j = y) (M i y) 0) = (finset.singleton j).sum (λ y, ite (j = y) (M i y) 0), { refine (finset.sum_subset _ _).symm, { intros _ H, rwa finset.mem_singleton.1 H, exact finset.mem_univ _ }, { exact λ _ _ H, if_neg (mt (finset.mem_singleton.2 ∘ eq.symm) H) } }, rw [h1, h2, finset.sum_singleton], exact if_pos rfl end /-- Linear maps (n → R) →ₗ[R] (m → R) are linearly equivalent to matrix m n R. -/ def linear_equiv_matrix' : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] matrix m n R := { to_fun := to_matrix, inv_fun := to_lin, right_inv := λ _, to_lin_to_matrix, left_inv := λ _, to_matrix_to_lin, add := to_matrixₗ.add, smul := to_matrixₗ.smul } /-- Given a basis of two modules M₁ and M₂ over a commutative ring R, we get a linear equivalence between linear maps M₁ →ₗ M₂ and matrices over R indexed by the bases. -/ def linear_equiv_matrix {ι κ M₁ M₂ : Type*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [fintype ι] [decidable_eq ι] [fintype κ] [decidable_eq κ] {v₁ : ι → M₁} {v₂ : κ → M₂} (hv₁ : is_basis R v₁) (hv₂ : is_basis R v₂) : (M₁ →ₗ[R] M₂) ≃ₗ[R] matrix κ ι R := linear_equiv.trans (linear_equiv.arrow_congr (equiv_fun_basis hv₁) (equiv_fun_basis hv₂)) linear_equiv_matrix' end linear_equiv_matrix namespace matrix section trace variables {R : Type v} {M : Type w} [ring R] [add_comm_group M] [module R M] /-- The diagonal of a square matrix. -/ def diag : (matrix n n M) →ₗ[R] n → M := { to_fun := λ A i, A i i, add := by { intros, ext, refl, }, smul := by { intros, ext, refl, } } @[simp] lemma diag_one [decidable_eq n] : (diag : (matrix n n R) →ₗ[R] n → R) 1 = λ i, 1 := by { dunfold diag, ext, simp [one_val_eq], } protected lemma smul_sum {α : Type u} {s : finset α} {f : α → M} {c : R} : c • s.sum f = s.sum (λx, c • f x) := (s.sum_hom _).symm /-- The trace of a square matrix. -/ def trace : (matrix n n M) →ₗ[R] M := { to_fun := finset.univ.sum ∘ (diag : (matrix n n M) →ₗ[R] n → M), add := by { intros, apply finset.sum_add_distrib, }, smul := by { intros, simp [matrix.smul_sum], } } @[simp] lemma trace_one [decidable_eq n] : (trace : (matrix n n R) →ₗ[R] R) 1 = fintype.card n := by { have h : @trace n _ R R _ _ _ 1 = finset.univ.sum (@diag n _ R R _ _ _ 1) := rfl, rw [h, diag_one, finset.sum_const, add_monoid.smul_one], refl, } end trace section ring variables {R : Type v} [comm_ring R] open linear_map matrix lemma proj_diagonal [decidable_eq m] (i : m) (w : m → R) : (proj i).comp (to_lin (diagonal w)) = (w i) • proj i := by ext j; simp [mul_vec_diagonal] lemma diagonal_comp_std_basis [decidable_eq n] (w : n → R) (i : n) : (diagonal w).to_lin.comp (std_basis R (λ_:n, R) i) = (w i) • std_basis R (λ_:n, R) i := begin ext a j, simp only [linear_map.comp_apply, smul_apply, to_lin_apply, mul_vec_diagonal, smul_apply, pi.smul_apply, smul_eq_mul], by_cases i = j, { subst h }, { rw [std_basis_ne R (λ_:n, R) _ _ (ne.symm h), _root_.mul_zero, _root_.mul_zero] } end end ring section vector_space variables {K : Type u} [discrete_field K] -- maybe try to relax the universe constraint open linear_map matrix lemma rank_vec_mul_vec [decidable_eq n] (w : m → K) (v : n → K) : rank (vec_mul_vec w v).to_lin ≤ 1 := begin rw [vec_mul_vec_eq, mul_to_lin], refine le_trans (rank_comp_le1 _ _) _, refine le_trans (rank_le_domain _) _, rw [dim_fun', ← cardinal.fintype_card], exact le_refl _ end set_option class.instance_max_depth 100 lemma diagonal_to_lin [decidable_eq m] (w : m → K) : (diagonal w).to_lin = linear_map.pi (λi, w i • linear_map.proj i) := by ext v j; simp [mul_vec_diagonal] lemma ker_diagonal_to_lin [decidable_eq m] (w : m → K) : ker (diagonal w).to_lin = (⨆i∈{i | w i = 0 }, range (std_basis K (λi, K) i)) := begin rw [← comap_bot, ← infi_ker_proj], simp only [comap_infi, (ker_comp _ _).symm, proj_diagonal, ker_smul'], have : univ ⊆ {i : m | w i = 0} ∪ -{i : m | w i = 0}, { rw set.union_compl_self }, exact (supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) (disjoint_compl {i | w i = 0}) this (finite.of_fintype _)).symm end lemma range_diagonal [decidable_eq m] (w : m → K) : (diagonal w).to_lin.range = (⨆ i ∈ {i | w i ≠ 0}, (std_basis K (λi, K) i).range) := begin dsimp only [mem_set_of_eq], rw [← map_top, ← supr_range_std_basis, map_supr], congr, funext i, rw [← linear_map.range_comp, diagonal_comp_std_basis, range_smul'], end lemma rank_diagonal [decidable_eq m] (w : m → K) : rank (diagonal w).to_lin = fintype.card { i // w i ≠ 0 } := begin have hu : univ ⊆ - {i : m | w i = 0} ∪ {i : m | w i = 0}, { rw set.compl_union_self }, have hd : disjoint {i : m | w i ≠ 0} {i : m | w i = 0} := (disjoint_compl {i | w i = 0}).symm, have h₁ := supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) hd hu (finite.of_fintype _), have h₂ := @infi_ker_proj_equiv K _ _ (λi:m, K) _ _ _ _ (by simp; apply_instance) hd hu, rw [rank, range_diagonal, h₁, ←@dim_fun' K], apply linear_equiv.dim_eq, apply h₂, end end vector_space end matrix
b86f840dda0feef3f9198aa63f97bb793c97df76
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/set/intervals/unordered_interval.lean
e95960b9b182997e262de1e02440056111e239fe
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
9,876
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import order.bounds import data.set.intervals.image_preimage /-! # Intervals without endpoints ordering In any decidable linear order `α`, we define the set of elements lying between two elements `a` and `b` as `Icc (min a b) (max a b)`. `Icc a b` requires the assumption `a ≤ b` to be meaningful, which is sometimes inconvenient. The interval as defined in this file is always the set of things lying between `a` and `b`, regardless of the relative order of `a` and `b`. For real numbers, `Icc (min a b) (max a b)` is the same as `segment ℝ a b`. ## Notation We use the localized notation `[a, b]` for `interval a b`. One can open the locale `interval` to make the notation available. -/ universe u open_locale pointwise namespace set section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ c x : α} /-- `interval a b` is the set of elements lying between `a` and `b`, with `a` and `b` included. -/ def interval (a b : α) := Icc (min a b) (max a b) localized "notation `[`a `, ` b `]` := set.interval a b" in interval @[simp] lemma interval_of_le (h : a ≤ b) : [a, b] = Icc a b := by rw [interval, min_eq_left h, max_eq_right h] @[simp] lemma interval_of_ge (h : b ≤ a) : [a, b] = Icc b a := by { rw [interval, min_eq_right h, max_eq_left h] } lemma interval_swap (a b : α) : [a, b] = [b, a] := by rw [interval, interval, min_comm, max_comm] lemma interval_of_lt (h : a < b) : [a, b] = Icc a b := interval_of_le (le_of_lt h) lemma interval_of_gt (h : b < a) : [a, b] = Icc b a := interval_of_ge (le_of_lt h) lemma interval_of_not_le (h : ¬ a ≤ b) : [a, b] = Icc b a := interval_of_gt (lt_of_not_ge h) lemma interval_of_not_ge (h : ¬ b ≤ a) : [a, b] = Icc a b := interval_of_lt (lt_of_not_ge h) @[simp] lemma interval_self : [a, a] = {a} := set.ext $ by simp [le_antisymm_iff, and_comm] @[simp] lemma nonempty_interval : set.nonempty [a, b] := by { simp only [interval, min_le_iff, le_max_iff, nonempty_Icc], left, left, refl } @[simp] lemma left_mem_interval : a ∈ [a, b] := by { rw [interval, mem_Icc], exact ⟨min_le_left _ _, le_max_left _ _⟩ } @[simp] lemma right_mem_interval : b ∈ [a, b] := by { rw interval_swap, exact left_mem_interval } lemma Icc_subset_interval : Icc a b ⊆ [a, b] := by { assume x h, rwa interval_of_le, exact le_trans h.1 h.2 } lemma Icc_subset_interval' : Icc b a ⊆ [a, b] := by { rw interval_swap, apply Icc_subset_interval } lemma mem_interval_of_le (ha : a ≤ x) (hb : x ≤ b) : x ∈ [a, b] := Icc_subset_interval ⟨ha, hb⟩ lemma mem_interval_of_ge (hb : b ≤ x) (ha : x ≤ a) : x ∈ [a, b] := Icc_subset_interval' ⟨hb, ha⟩ lemma not_mem_interval_of_lt (ha : c < a) (hb : c < b) : c ∉ interval a b := not_mem_Icc_of_lt $ lt_min_iff.mpr ⟨ha, hb⟩ lemma not_mem_interval_of_gt (ha : a < c) (hb : b < c) : c ∉ interval a b := not_mem_Icc_of_gt $ max_lt_iff.mpr ⟨ha, hb⟩ lemma interval_subset_interval (h₁ : a₁ ∈ [a₂, b₂]) (h₂ : b₁ ∈ [a₂, b₂]) : [a₁, b₁] ⊆ [a₂, b₂] := Icc_subset_Icc (le_min h₁.1 h₂.1) (max_le h₁.2 h₂.2) lemma interval_subset_Icc (ha : a₁ ∈ Icc a₂ b₂) (hb : b₁ ∈ Icc a₂ b₂) : [a₁, b₁] ⊆ Icc a₂ b₂ := Icc_subset_Icc (le_min ha.1 hb.1) (max_le ha.2 hb.2) lemma interval_subset_interval_iff_mem : [a₁, b₁] ⊆ [a₂, b₂] ↔ a₁ ∈ [a₂, b₂] ∧ b₁ ∈ [a₂, b₂] := iff.intro (λh, ⟨h left_mem_interval, h right_mem_interval⟩) (λ h, interval_subset_interval h.1 h.2) lemma interval_subset_interval_iff_le : [a₁, b₁] ⊆ [a₂, b₂] ↔ min a₂ b₂ ≤ min a₁ b₁ ∧ max a₁ b₁ ≤ max a₂ b₂ := by { rw [interval, interval, Icc_subset_Icc_iff], exact min_le_max } lemma interval_subset_interval_right (h : x ∈ [a, b]) : [x, b] ⊆ [a, b] := interval_subset_interval h right_mem_interval lemma interval_subset_interval_left (h : x ∈ [a, b]) : [a, x] ⊆ [a, b] := interval_subset_interval left_mem_interval h /-- A sort of triangle inequality. -/ lemma interval_subset_interval_union_interval : [a, c] ⊆ [a, b] ∪ [b, c] := begin rintro x hx, obtain hac | hac := le_total a c, { rw interval_of_le hac at hx, obtain hb | hb := le_total x b, { exact or.inl (mem_interval_of_le hx.1 hb) }, { exact or.inr (mem_interval_of_le hb hx.2) } }, { rw interval_of_ge hac at hx, obtain hb | hb := le_total x b, { exact or.inr (mem_interval_of_ge hx.1 hb) }, { exact or.inl (mem_interval_of_ge hb hx.2) } } end lemma bdd_below_bdd_above_iff_subset_interval (s : set α) : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ [a, b] := begin rw [bdd_below_bdd_above_iff_subset_Icc], split, { rintro ⟨a, b, h⟩, exact ⟨a, b, λ x hx, Icc_subset_interval (h hx)⟩ }, { rintro ⟨a, b, h⟩, exact ⟨min a b, max a b, h⟩ } end /-- The open-closed interval with unordered bounds. -/ def interval_oc : α → α → set α := λ a b, Ioc (min a b) (max a b) -- Below is a capital iota localized "notation `Ι` := set.interval_oc" in interval lemma interval_oc_of_le (h : a ≤ b) : Ι a b = Ioc a b := by simp [interval_oc, h] lemma interval_oc_of_lt (h : b < a) : Ι a b = Ioc b a := by simp [interval_oc, le_of_lt h] lemma forall_interval_oc_iff {P : α → Prop} : (∀ x ∈ Ι a b, P x) ↔ (∀ x ∈ Ioc a b, P x) ∧ (∀ x ∈ Ioc b a, P x) := by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] } lemma interval_oc_subset_interval_oc_of_interval_subset_interval {a b c d : α} (h : [a, b] ⊆ [c, d]) : Ι a b ⊆ Ι c d := Ioc_subset_Ioc (interval_subset_interval_iff_le.1 h).1 (interval_subset_interval_iff_le.1 h).2 lemma interval_oc_swap (a b : α) : Ι a b = Ι b a := by simp only [interval_oc, min_comm a b, max_comm a b] end linear_order open_locale interval section ordered_add_comm_group variables {α : Type u} [linear_ordered_add_comm_group α] (a b c x y : α) @[simp] lemma preimage_const_add_interval : (λ x, a + x) ⁻¹' [b, c] = [b - a, c - a] := by simp only [interval, preimage_const_add_Icc, min_sub_sub_right, max_sub_sub_right] @[simp] lemma preimage_add_const_interval : (λ x, x + a) ⁻¹' [b, c] = [b - a, c - a] := by simpa only [add_comm] using preimage_const_add_interval a b c @[simp] lemma preimage_neg_interval : - [a, b] = [-a, -b] := by simp only [interval, preimage_neg_Icc, min_neg_neg, max_neg_neg] @[simp] lemma preimage_sub_const_interval : (λ x, x - a) ⁻¹' [b, c] = [b + a, c + a] := by simp [sub_eq_add_neg] @[simp] lemma preimage_const_sub_interval : (λ x, a - x) ⁻¹' [b, c] = [a - b, a - c] := by { rw [interval, interval, preimage_const_sub_Icc], simp only [sub_eq_add_neg, min_add_add_left, max_add_add_left, min_neg_neg, max_neg_neg], } @[simp] lemma image_const_add_interval : (λ x, a + x) '' [b, c] = [a + b, a + c] := by simp [add_comm] @[simp] lemma image_add_const_interval : (λ x, x + a) '' [b, c] = [b + a, c + a] := by simp @[simp] lemma image_const_sub_interval : (λ x, a - x) '' [b, c] = [a - b, a - c] := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_sub_const_interval : (λ x, x - a) '' [b, c] = [b - a, c - a] := by simp [sub_eq_add_neg, add_comm] lemma image_neg_interval : has_neg.neg '' [a, b] = [-a, -b] := by simp variables {a b c x y} /-- If `[x, y]` is a subinterval of `[a, b]`, then the distance between `x` and `y` is less than or equal to that of `a` and `b` -/ lemma abs_sub_le_of_subinterval (h : [x, y] ⊆ [a, b]) : |y - x| ≤ |b - a| := begin rw [← max_sub_min_eq_abs, ← max_sub_min_eq_abs], rw [interval_subset_interval_iff_le] at h, exact sub_le_sub h.2 h.1, end /-- If `x ∈ [a, b]`, then the distance between `a` and `x` is less than or equal to that of `a` and `b` -/ lemma abs_sub_left_of_mem_interval (h : x ∈ [a, b]) : |x - a| ≤ |b - a| := abs_sub_le_of_subinterval (interval_subset_interval_left h) /-- If `x ∈ [a, b]`, then the distance between `x` and `b` is less than or equal to that of `a` and `b` -/ lemma abs_sub_right_of_mem_interval (h : x ∈ [a, b]) : |b - x| ≤ |b - a| := abs_sub_le_of_subinterval (interval_subset_interval_right h) end ordered_add_comm_group section linear_ordered_field variables {k : Type u} [linear_ordered_field k] {a : k} @[simp] lemma preimage_mul_const_interval (ha : a ≠ 0) (b c : k) : (λ x, x * a) ⁻¹' [b, c] = [b / a, c / a] := (lt_or_gt_of_ne ha).elim (λ ha, by simp [interval, ha, ha.le, min_div_div_right_of_nonpos, max_div_div_right_of_nonpos]) (λ (ha : 0 < a), by simp [interval, ha, ha.le, min_div_div_right, max_div_div_right]) @[simp] lemma preimage_const_mul_interval (ha : a ≠ 0) (b c : k) : (λ x, a * x) ⁻¹' [b, c] = [b / a, c / a] := by simp only [← preimage_mul_const_interval ha, mul_comm] @[simp] lemma preimage_div_const_interval (ha : a ≠ 0) (b c : k) : (λ x, x / a) ⁻¹' [b, c] = [b * a, c * a] := by simp only [div_eq_mul_inv, preimage_mul_const_interval (inv_ne_zero ha), inv_inv₀] @[simp] lemma image_mul_const_interval (a b c : k) : (λ x, x * a) '' [b, c] = [b * a, c * a] := if ha : a = 0 then by simp [ha] else calc (λ x, x * a) '' [b, c] = (λ x, x * a⁻¹) ⁻¹' [b, c] : (units.mk0 a ha).mul_right.image_eq_preimage _ ... = (λ x, x / a) ⁻¹' [b, c] : by simp only [div_eq_mul_inv] ... = [b * a, c * a] : preimage_div_const_interval ha _ _ @[simp] lemma image_const_mul_interval (a b c : k) : (λ x, a * x) '' [b, c] = [a * b, a * c] := by simpa only [mul_comm] using image_mul_const_interval a b c @[simp] lemma image_div_const_interval (a b c : k) : (λ x, x / a) '' [b, c] = [b / a, c / a] := by simp only [div_eq_mul_inv, image_mul_const_interval] end linear_ordered_field end set
c63c41950ff9dca6a9dcbb0e7304deed138520dd
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/set/constructions.lean
cc49bc5c308b5f2a5445a86b3589382fa360c093
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
2,754
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import data.finset.basic /-! # Constructions involving sets of sets. ## Finite Intersections We define a structure `has_finite_inter` which asserts that a set `S` of subsets of `α` is closed under finite intersections. We define `finite_inter_closure` which, given a set `S` of subsets of `α`, is the smallest set of subsets of `α` which is closed under finite intersections. `finite_inter_closure S` is endowed with a term of type `has_finite_inter` using `finite_inter_closure_has_finite_inter`. -/ variables {α : Type*} (S : set (set α)) /-- A structure encapsulating the fact that a set of sets is closed under finite intersection. -/ structure has_finite_inter : Prop := (univ_mem : set.univ ∈ S) (inter_mem : ∀ ⦃s⦄, s ∈ S → ∀ ⦃t⦄, t ∈ S → s ∩ t ∈ S) namespace has_finite_inter /-- The smallest set of sets containing `S` which is closed under finite intersections. -/ inductive finite_inter_closure : set (set α) | basic {s} : s ∈ S → finite_inter_closure s | univ : finite_inter_closure set.univ | inter {s t} : finite_inter_closure s → finite_inter_closure t → finite_inter_closure (s ∩ t) lemma finite_inter_closure_has_finite_inter : has_finite_inter (finite_inter_closure S) := { univ_mem := finite_inter_closure.univ, inter_mem := λ _ h _, finite_inter_closure.inter h } variable {S} lemma finite_inter_mem (cond : has_finite_inter S) (F : finset (set α)) : ↑F ⊆ S → ⋂₀ (↑F : set (set α)) ∈ S := begin classical, refine finset.induction_on F (λ _, _) _, { simp [cond.univ_mem] }, { intros a s h1 h2 h3, suffices : a ∩ ⋂₀ ↑s ∈ S, by simpa, exact cond.inter_mem (h3 (finset.mem_insert_self a s)) (h2 $ λ x hx, h3 $ finset.mem_insert_of_mem hx) } end lemma finite_inter_closure_insert {A : set α} (cond : has_finite_inter S) (P ∈ finite_inter_closure (insert A S)) : P ∈ S ∨ ∃ Q ∈ S, P = A ∩ Q := begin induction H with S h T1 T2 _ _ h1 h2, { cases h, { exact or.inr ⟨set.univ, cond.univ_mem, by simpa⟩ }, { exact or.inl h } }, { exact or.inl cond.univ_mem }, { rcases h1 with (h | ⟨Q, hQ, rfl⟩); rcases h2 with (i | ⟨R, hR, rfl⟩), { exact or.inl (cond.inter_mem h i) }, { exact or.inr ⟨T1 ∩ R, cond.inter_mem h hR, by simp only [ ←set.inter_assoc, set.inter_comm _ A]⟩ }, { exact or.inr ⟨Q ∩ T2, cond.inter_mem hQ i, by simp only [set.inter_assoc]⟩ }, { exact or.inr ⟨Q ∩ R, cond.inter_mem hQ hR, by { ext x, split; simp { contextual := tt} }⟩ } } end end has_finite_inter
9a7bc6afe3d945b1aa1bfa4be5d593947854b4a7
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast7.lean
c391933876d905dc90a42481e28ff7cbddac3701
[ "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
128
lean
set_option blast.init_depth 10 lemma lemma1 (p : Prop) (a b : nat) : a = b → p → p := by blast reveal lemma1 print lemma1
a7bf98b88c3826a010ae436a9c79838b336e080f
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/module/basic.lean
3a77d25cf3081bb6976c7485159b51d8207bedf4
[ "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
19,638
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.big_operators.basic import algebra.group.hom import group_theory.group_action.group import algebra.smul_with_zero /-! # Modules over a ring In this file we define * `module R M` : an additive commutative monoid `M` is a `module` over a `semiring R` if for `r : R` and `x : M` their "scalar multiplication `r • x : M` is defined, and the operation `•` satisfies some natural associativity and distributivity axioms similar to those on a ring. ## Implementation notes In typical mathematical usage, our definition of `module` corresponds to "semimodule", and the word "module" is reserved for `module R M` where `R` is a `ring` and `M` an `add_comm_group`. If `R` is a `field` and `M` an `add_comm_group`, `M` would be called an `R`-vector space. Since those assumptions can be made by changing the typeclasses applied to `R` and `M`, without changing the axioms in `module`, mathlib calls everything a `module`. In older versions of mathlib, we had separate `semimodule` and `vector_space` abbreviations. This caused inference issues in some cases, while not providing any real advantages, so we decided to use a canonical `module` typeclass throughout. ## Tags semimodule, module, vector space -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A module is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `R` and an additive monoid of "vectors" `M`, connected by a "scalar multiplication" operation `r • x : M` (where `r : R` and `x : M`) with some natural associativity and distributivity axioms similar to those on a ring. -/ @[protect_proj] class module (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] extends distrib_mul_action R M := (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (zero_smul : ∀x : M, (0 : R) • x = 0) section add_comm_monoid variables [semiring R] [add_comm_monoid M] [module R M] (r s : R) (x y : M) /-- A module over a semiring automatically inherits a `mul_action_with_zero` structure. -/ @[priority 100] -- see Note [lower instance priority] instance module.to_mul_action_with_zero : mul_action_with_zero R M := { smul_zero := smul_zero, zero_smul := module.zero_smul, ..(infer_instance : mul_action R M) } instance add_comm_monoid.nat_module : module ℕ M := { one_smul := one_nsmul, mul_smul := λ m n a, mul_nsmul a m n, smul_add := λ n a b, nsmul_add a b n, smul_zero := nsmul_zero, zero_smul := zero_nsmul, add_smul := λ r s x, add_nsmul x r s } theorem add_smul : (r + s) • x = r • x + s • x := module.add_smul r s x variables (R) theorem two_smul : (2 : R) • x = x + x := by rw [bit0, add_smul, one_smul] theorem two_smul' : (2 : R) • x = bit0 x := two_smul R x /-- Pullback a `module` structure along an injective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.module [add_comm_monoid M₂] [has_scalar R M₂] (f : M₂ →+ M) (hf : injective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : module R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, hf $ by simp only [smul, f.map_add, add_smul], zero_smul := λ x, hf $ by simp only [smul, zero_smul, f.map_zero], .. hf.distrib_mul_action f smul } /-- Pushforward a `module` structure along a surjective additive monoid homomorphism. -/ protected def function.surjective.module [add_comm_monoid M₂] [has_scalar R M₂] (f : M →+ M₂) (hf : surjective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : module R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, by { rcases hf x with ⟨x, rfl⟩, simp only [add_smul, ← smul, ← f.map_add] }, zero_smul := λ x, by { rcases hf x with ⟨x, rfl⟩, simp only [← f.map_zero, ← smul, zero_smul] }, .. hf.distrib_mul_action f smul } variables {R} (M) /-- Compose a `module` with a `ring_hom`, with action `f s • m`. See note [reducible non-instances]. -/ @[reducible] def module.comp_hom [semiring S] (f : S →+* R) : module S M := { smul := (•) ∘ f, add_smul := λ r s x, by simp [add_smul], .. mul_action_with_zero.comp_hom M f.to_monoid_with_zero_hom, .. distrib_mul_action.comp_hom M (f : S →* R) } variables (R) (M) /-- `(•)` as an `add_monoid_hom`. -/ def smul_add_hom : R →+ M →+ M := { to_fun := const_smul_hom M, map_zero' := add_monoid_hom.ext $ λ r, by simp, map_add' := λ x y, add_monoid_hom.ext $ λ r, by simp [add_smul] } variables {R M} @[simp] lemma smul_add_hom_apply (r : R) (x : M) : smul_add_hom R M r x = r • x := rfl @[simp] lemma smul_add_hom_one {R M : Type*} [semiring R] [add_comm_monoid M] [module R M] : smul_add_hom R M 1 = add_monoid_hom.id _ := const_smul_hom_one lemma module.eq_zero_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : x = 0 := by rw [←one_smul R x, ←zero_eq_one, zero_smul] lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_list_sum l lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_multiset_sum l lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} : (∑ i in s, f i) • x = (∑ i in s, (f i) • x) := ((smul_add_hom R M).flip x).map_sum f s end add_comm_monoid variables (R) /-- An `add_comm_monoid` that is a `module` over a `ring` carries a natural `add_comm_group` structure. -/ def module.add_comm_monoid_to_add_comm_group [ring R] [add_comm_monoid M] [module R M] : add_comm_group M := { neg := λ a, (-1 : R) • a, add_left_neg := λ a, show (-1 : R) • a + a = 0, by { nth_rewrite 1 ← one_smul _ a, rw [← add_smul, add_left_neg, zero_smul] }, ..(infer_instance : add_comm_monoid M), } variables {R} section add_comm_group variables (R M) [semiring R] [add_comm_group M] instance add_comm_group.int_module : module ℤ M := { one_smul := one_gsmul, mul_smul := λ m n a, mul_gsmul a m n, smul_add := λ n a b, gsmul_add a b n, smul_zero := gsmul_zero, zero_smul := zero_gsmul, add_smul := λ r s x, add_gsmul x r s } /-- A structure containing most informations as in a module, except the fields `zero_smul` and `smul_zero`. As these fields can be deduced from the other ones when `M` is an `add_comm_group`, this provides a way to construct a module structure by checking less properties, in `module.of_core`. -/ @[nolint has_inhabited_instance] structure module.core extends has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀x : M, (1 : R) • x = x) variables {R M} /-- Define `module` without proving `zero_smul` and `smul_zero` by using an auxiliary structure `module.core`, when the underlying space is an `add_comm_group`. -/ def module.of_core (H : module.core R M) : module R M := by letI := H.to_has_scalar; exact { zero_smul := λ x, (add_monoid_hom.mk' (λ r : R, r • x) (λ r s, H.add_smul r s x)).map_zero, smul_zero := λ r, (add_monoid_hom.mk' ((•) r) (H.smul_add r)).map_zero, ..H } end add_comm_group /-- To prove two module structures on a fixed `add_comm_monoid` agree, it suffices to check the scalar multiplications agree. -/ -- We'll later use this to show `module ℕ M` and `module ℤ M` are subsingletons. @[ext] lemma module_ext {R : Type*} [semiring R] {M : Type*} [add_comm_monoid M] (P Q : module R M) (w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) : P = Q := begin unfreezingI { rcases P with ⟨⟨⟨⟨P⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨Q⟩⟩⟩⟩ }, congr, funext r m, exact w r m, all_goals { apply proof_irrel_heq }, end section module variables [ring R] [add_comm_group M] [module R M] (r s : R) (x y : M) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) @[simp] theorem units.neg_smul (u : units R) (x : M) : -u • x = - (u • x) := by rw [units.smul_def, units.coe_neg, neg_smul, units.smul_def] variables (R) theorem neg_one_smul (x : M) : (-1 : R) • x = -x := by simp variables {R} theorem sub_smul (r s : R) (y : M) : (r - s) • y = r • y - s • y := by simp [add_smul, sub_eq_add_neg] end module /-- A module over a `subsingleton` semiring is a `subsingleton`. We cannot register this as an instance because Lean has no way to guess `R`. -/ protected theorem module.subsingleton (R M : Type*) [semiring R] [subsingleton R] [add_comm_monoid M] [module R M] : subsingleton M := ⟨λ x y, by rw [← one_smul R x, ← one_smul R y, subsingleton.elim (1:R) 0, zero_smul, zero_smul]⟩ @[priority 910] -- see Note [lower instance priority] instance semiring.to_module [semiring R] : module R R := { smul_add := mul_add, add_smul := add_mul, zero_smul := zero_mul, smul_zero := mul_zero } /-- A ring homomorphism `f : R →+* M` defines a module structure by `r • x = f r * x`. -/ def ring_hom.to_module [semiring R] [semiring S] (f : R →+* S) : module R S := { smul := λ r x, f r * x, smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add], add_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_add, add_mul], mul_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_mul, mul_assoc], one_smul := λ x, show f 1 * x = _, by rw [f.map_one, one_mul], zero_smul := λ x, show f 0 * x = 0, by rw [f.map_zero, zero_mul], smul_zero := λ r, mul_zero (f r) } section add_comm_monoid variables [semiring R] [add_comm_monoid M] [module R M] section variables (R) /-- `nsmul` is equal to any other module structure via a cast. -/ lemma nsmul_eq_smul_cast (n : ℕ) (b : M) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { rw [nat.succ_eq_add_one, nat.cast_succ, add_smul, add_smul, one_smul, ih, one_smul], } end end /-- Convert back any exotic `ℕ`-smul to the canonical instance. This should not be needed since in mathlib all `add_comm_monoid`s should normally have exactly one `ℕ`-module structure by design. -/ lemma nat_smul_eq_nsmul (h : module ℕ M) (n : ℕ) (x : M) : @has_scalar.smul ℕ M h.to_has_scalar n x = n • x := by rw [nsmul_eq_smul_cast ℕ n x, nat.cast_id] /-- All `ℕ`-module structures are equal. Not an instance since in mathlib all `add_comm_monoid` should normally have exactly one `ℕ`-module structure by design. -/ def add_comm_monoid.nat_module.unique : unique (module ℕ M) := { default := by apply_instance, uniq := λ P, module_ext P _ $ λ n, nat_smul_eq_nsmul P n } instance add_comm_monoid.nat_is_scalar_tower : is_scalar_tower ℕ R M := { smul_assoc := λ n x y, nat.rec_on n (by simp only [zero_smul]) (λ n ih, by simp only [nat.succ_eq_add_one, add_smul, one_smul, ih]) } instance add_comm_monoid.nat_smul_comm_class : smul_comm_class ℕ R M := { smul_comm := λ n r m, nat.rec_on n (by simp only [zero_smul, smul_zero]) (λ n ih, by simp only [nat.succ_eq_add_one, add_smul, one_smul, ←ih, smul_add]) } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_comm_monoid.nat_smul_comm_class' : smul_comm_class R ℕ M := smul_comm_class.symm _ _ _ end add_comm_monoid section add_comm_group variables [semiring S] [ring R] [add_comm_group M] [module S M] [module R M] section variables (R) /-- `gsmul` is equal to any other module structure via a cast. -/ lemma gsmul_eq_smul_cast (n : ℤ) (b : M) : n • b = (n : R) • b := begin induction n using int.induction_on with p hp n hn, { rw [int.cast_zero, zero_smul, zero_smul] }, { rw [int.cast_add, int.cast_one, add_smul, add_smul, one_smul, one_smul, hp] }, { rw [int.cast_sub, int.cast_one, sub_smul, sub_smul, one_smul, one_smul, hn] }, end end /-- Convert back any exotic `ℤ`-smul to the canonical instance. This should not be needed since in mathlib all `add_comm_group`s should normally have exactly one `ℤ`-module structure by design. -/ lemma int_smul_eq_gsmul (h : module ℤ M) (n : ℤ) (x : M) : @has_scalar.smul ℤ M h.to_has_scalar n x = n • x := by rw [gsmul_eq_smul_cast ℤ n x, int.cast_id] /-- All `ℤ`-module structures are equal. Not an instance since in mathlib all `add_comm_group` should normally have exactly one `ℤ`-module structure by design. -/ def add_comm_group.int_module.unique : unique (module ℤ M) := { default := by apply_instance, uniq := λ P, module_ext P _ $ λ n, int_smul_eq_gsmul P n } instance add_comm_group.int_is_scalar_tower : is_scalar_tower ℤ R M := { smul_assoc := λ n x y, int.induction_on n (by simp only [zero_smul]) (λ n ih, by simp only [one_smul, add_smul, ih]) (λ n ih, by simp only [one_smul, sub_smul, ih]) } instance add_comm_group.int_smul_comm_class : smul_comm_class ℤ S M := { smul_comm := λ n x y, int.induction_on n (by simp only [zero_smul, smul_zero]) (λ n ih, by simp only [one_smul, add_smul, smul_add, ih]) (λ n ih, by simp only [one_smul, sub_smul, smul_sub, ih]) } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_comm_group.int_smul_comm_class' : smul_comm_class S ℤ M := smul_comm_class.symm _ _ _ end add_comm_group namespace add_monoid_hom lemma map_nat_module_smul [add_comm_monoid M] [add_comm_monoid M₂] (f : M →+ M₂) (x : ℕ) (a : M) : f (x • a) = x • f a := by simp only [f.map_nsmul] lemma map_int_module_smul [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f (x • a) = x • f a := by simp only [f.map_gsmul] lemma map_int_cast_smul [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [←gsmul_eq_smul_cast, f.map_gsmul] lemma map_nat_cast_smul [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →+ M₂) (x : ℕ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [←nsmul_eq_smul_cast, f.map_nsmul] lemma map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] (f : E →+ F) (c : ℚ) (x : E) : f ((c : R) • x) = (c : R) • f x := begin have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x, { intros x n hn, replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn), conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] }, rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat, inv_mul_cancel hn, one_smul] }, refine c.num_denom_cases_on (λ m n hn hmn, _), rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul, rat.cast_coe_int, f.map_int_cast_smul, this _ n hn] end lemma map_rat_module_smul {E : Type*} [add_comm_group E] [module ℚ E] {F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) : f (c • x) = c • f x := rat.cast_id c ▸ f.map_rat_cast_smul c x end add_monoid_hom section no_zero_smul_divisors /-! ### `no_zero_smul_divisors` This section defines the `no_zero_smul_divisors` class, and includes some tests for the vanishing of elements (especially in modules over division rings). -/ /-- `no_zero_smul_divisors R M` states that a scalar multiple is `0` only if either argument is `0`. This a version of saying that `M` is torsion free, without assuming `R` is zero-divisor free. The main application of `no_zero_smul_divisors R M`, when `M` is a module, is the result `smul_eq_zero`: a scalar multiple is `0` iff either argument is `0`. It is a generalization of the `no_zero_divisors` class to heterogeneous multiplication. -/ class no_zero_smul_divisors (R M : Type*) [has_zero R] [has_zero M] [has_scalar R M] : Prop := (eq_zero_or_eq_zero_of_smul_eq_zero : ∀ {c : R} {x : M}, c • x = 0 → c = 0 ∨ x = 0) export no_zero_smul_divisors (eq_zero_or_eq_zero_of_smul_eq_zero) section module variables [semiring R] [add_comm_monoid M] [module R M] instance no_zero_smul_divisors.of_no_zero_divisors [no_zero_divisors R] : no_zero_smul_divisors R R := ⟨λ c x, no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero⟩ @[simp] theorem smul_eq_zero [no_zero_smul_divisors R M] {c : R} {x : M} : c • x = 0 ↔ c = 0 ∨ x = 0 := ⟨eq_zero_or_eq_zero_of_smul_eq_zero, λ h, h.elim (λ h, h.symm ▸ zero_smul R x) (λ h, h.symm ▸ smul_zero c)⟩ theorem smul_ne_zero [no_zero_smul_divisors R M] {c : R} {x : M} : c • x ≠ 0 ↔ c ≠ 0 ∧ x ≠ 0 := by simp only [ne.def, smul_eq_zero, not_or_distrib] section nat variables (R) (M) [no_zero_smul_divisors R M] [char_zero R] include R lemma nat.no_zero_smul_divisors : no_zero_smul_divisors ℕ M := ⟨by { intros c x, rw [nsmul_eq_smul_cast R, smul_eq_zero], simp }⟩ variables {M} lemma eq_zero_of_smul_two_eq_zero {v : M} (hv : 2 • v = 0) : v = 0 := by haveI := nat.no_zero_smul_divisors R M; exact (smul_eq_zero.mp hv).resolve_left (by norm_num) end nat end module section add_comm_group -- `R` can still be a semiring here variables [semiring R] [add_comm_group M] [module R M] section smul_injective variables (M) lemma smul_left_injective [no_zero_smul_divisors R M] {c : R} (hc : c ≠ 0) : function.injective (λ (x : M), c • x) := λ x y h, sub_eq_zero.mp ((smul_eq_zero.mp (calc c • (x - y) = c • x - c • y : smul_sub c x y ... = 0 : sub_eq_zero.mpr h)).resolve_left hc) end smul_injective section nat variables (R) [no_zero_smul_divisors R M] [char_zero R] include R lemma eq_zero_of_eq_neg {v : M} (hv : v = - v) : v = 0 := begin haveI := nat.no_zero_smul_divisors R M, refine eq_zero_of_smul_two_eq_zero R _, rw two_smul, exact add_eq_zero_iff_eq_neg.mpr hv end end nat end add_comm_group section module variables [ring R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] section smul_injective variables (R) lemma smul_right_injective {x : M} (hx : x ≠ 0) : function.injective (λ (c : R), c • x) := λ c d h, sub_eq_zero.mp ((smul_eq_zero.mp (calc (c - d) • x = c • x - d • x : sub_smul c d x ... = 0 : sub_eq_zero.mpr h)).resolve_right hx) end smul_injective section nat variables [char_zero R] lemma ne_neg_of_ne_zero [no_zero_divisors R] {v : R} (hv : v ≠ 0) : v ≠ -v := λ h, hv (eq_zero_of_eq_neg R h) end nat end module section division_ring variables [division_ring R] [add_comm_group M] [module R M] @[priority 100] -- see note [lower instance priority] instance no_zero_smul_divisors.of_division_ring : no_zero_smul_divisors R M := ⟨λ c x h, or_iff_not_imp_left.2 $ λ hc, (smul_eq_zero_iff_eq' hc).1 h⟩ end division_ring end no_zero_smul_divisors @[simp] lemma nat.smul_one_eq_coe {R : Type*} [semiring R] (m : ℕ) : m • (1 : R) = ↑m := by rw [nsmul_eq_mul, mul_one] @[simp] lemma int.smul_one_eq_coe {R : Type*} [ring R] (m : ℤ) : m • (1 : R) = ↑m := by rw [gsmul_eq_mul, mul_one]
eb0c45381e167751186e7292c8473cd6bd9c74de
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/prop_92/extension_profinite.lean
01cbbead738ea582dec2d7628d8dec00637e54ad
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,948
lean
import for_mathlib.is_locally_constant import locally_constant.analysis /-! # Extending a locally constant map to larger profinite sets In this file, we prove that, given a topological embedding `e : X → Y` from a non-empty compact topological space to a profinite set (ie. compact Hausdorff totally disconnected space), every locally constant map `f` from `X` to any type `Z` "extends" to a locally constant map from `Y` to `Z`, ie. there exists `g : Y → Z` locally constant such that `f = g ∘ e`. e X ↪-→ Y | / f | / h ↓ ↙ Z Notes: * this wouldn't work if `X` and `Z` were empty and `Y` weren't. The minimal assumption would be assuming `Z` isn't empty, I'll refactor this soon. * Everything is stated assuming only `X` is compact but the existence of `f` ensures `X` is profinite, we're just saving type-class search (and nothing in the construction or proofs directly use `X` is profinite). The main definition is `embedding.extend {e : X → Y} (he : embedding e) (f : X → Z) : Y → Z` It assumes `X` is compact (and non-empty) and assumes `Y` is profinite but doesn't assume `f` is locally constant, it is simply defined as a constant map if `f` isn't. The announced properties of this extension are `embedding.extend_extends` and `embedding.is_locally_constant_extend`. -/ variables {X : Type*} [topological_space X] noncomputable theory open set variables [compact_space X] {Y : Type*} [topological_space Y] [t2_space Y] [compact_space Y] [totally_disconnected_space Y] lemma embedding.preimage_clopen {f : X → Y} (hf : embedding f) {U : set X} (hU : is_clopen U) : ∃ V : set Y, is_clopen V ∧ U = f ⁻¹' V := begin cases hU with hU hU', have hfU : is_compact (f '' U), from hU'.is_compact.image hf.continuous, obtain ⟨W, W_op, hfW⟩ : ∃ W : set Y, is_open W ∧ f ⁻¹' W = U, { rw hf.to_inducing.induced at hU, exact is_open_induced_iff.mp hU }, obtain ⟨ι, Z : ι → set Y, hWZ : W = ⋃ i, Z i, hZ : ∀ i, is_clopen $ Z i⟩ := is_topological_basis_clopen.open_eq_Union W_op, have : f '' U ⊆ ⋃ i, Z i, { rw [image_subset_iff, ← hWZ, hfW] }, obtain ⟨I, hI⟩ : ∃ I : finset ι, f '' U ⊆ ⋃ i ∈ I, Z i, from hfU.elim_finite_subcover _ (λ i, (hZ i).1) this, refine ⟨⋃ i ∈ I, Z i, _, _⟩, { apply is_clopen_bUnion, tauto }, { apply subset.antisymm, exact image_subset_iff.mp hI, have : (⋃ i ∈ I, Z i) ⊆ ⋃ i, Z i, from bUnion_subset_Union _ _, rw [← hfW, hWZ], mono }, end lemma embedding.ex_discrete_quotient [nonempty X] {f : X → Y} (hf : embedding f) (S : discrete_quotient X) : ∃ (S' : discrete_quotient Y) (g : S ≃ S'), S'.proj ∘ f = g ∘ S.proj := begin classical, inhabit X, haveI : fintype S := discrete_quotient.fintype S, have : ∀ s : S, ∃ V : set Y, is_clopen V ∧ S.proj ⁻¹' {s} = f ⁻¹' V, from λ s, hf.preimage_clopen (S.fiber_clopen {s}), choose V hV using this, rw forall_and_distrib at hV, cases hV with V_cl hV, let s₀ := S.proj (default X), let W : S → set Y := λ s, (V s) \ (⋃ s' (h : s' ≠ s), V s'), have W_dis : ∀ {s s'}, s ≠ s' → disjoint (W s) (W s'), { rintros s s' hss x ⟨⟨hxs_in, hxs_out⟩, ⟨hxs'_in, hxs'_out⟩⟩, apply hxs'_out, rw mem_bUnion_iff', exact ⟨s, hss, hxs_in⟩ }, have hfW : ∀ x, f x ∈ W (S.proj x), { intro x, split, { change x ∈ f ⁻¹' (V $ S.proj x), rw ← hV (S.proj x), exact mem_singleton _ }, { intro h, rcases mem_bUnion_iff'.mp h with ⟨s', hss', hfx : x ∈ f ⁻¹' (V s')⟩, rw ← hV s' at hfx, exact hss' hfx.symm } }, have W_nonempty : ∀ s, (W s).nonempty, { intro s, obtain ⟨x, hx : S.proj x = s⟩ := S.proj_surjective s, use f x, rw ← hx, apply hfW, }, let R : S → set Y := λ s, if s = s₀ then W s₀ ∪ (⋃ s, W s)ᶜ else W s, have W_cl : ∀ s, is_clopen (W s), { intro s, apply (V_cl s).diff, apply is_clopen_Union, intro s', by_cases h : s' = s, simp [h, is_clopen_empty], simp [h, V_cl s'] }, have R_cl : ∀ s, is_clopen (R s), { intro s, dsimp [R], split_ifs, { apply (W_cl s₀).union, apply is_clopen.compl, exact is_clopen_Union W_cl }, { exact W_cl _ }, }, let R_part : indexed_partition R, { apply indexed_partition.mk', { rintros s s' hss x ⟨hxs, hxs'⟩, dsimp [R] at hxs hxs', split_ifs at hxs hxs' with hs hs', { exact (hss (hs.symm ▸ hs' : s = s')).elim }, { cases hxs' with hx hx, { exact W_dis hs' ⟨hxs, hx⟩ }, { apply hx, rw mem_Union, exact ⟨s, hxs⟩ } }, { cases hxs with hx hx, { exact W_dis hs ⟨hxs', hx⟩ }, { apply hx, rw mem_Union, exact ⟨s', hxs'⟩ } }, { exact W_dis hss ⟨hxs, hxs'⟩ } }, { intro s, dsimp [R], split_ifs, { use (W_nonempty s₀).some, left, exact (W_nonempty s₀).some_mem }, { apply W_nonempty } }, { intro y, by_cases hy : ∃ s, y ∈ W s, { cases hy with s hys, use s, dsimp [R], split_ifs, { left, rwa h at hys }, { exact hys } }, { use s₀, simp only [R, if_pos rfl], right, rwa [mem_compl_iff, mem_Union] } } }, let S' := R_part.discrete_quotient R_cl, let g := R_part.discrete_quotient_equiv R_cl, have hR : ∀ x, f x ∈ R (S.proj x), { intros x, by_cases hx : S.proj x = s₀, { simp only [hx, R, if_pos rfl], left, rw ← hx, apply hfW }, { simp only [R, if_neg hx], apply hfW }, }, use [S', g], ext x, change f x ∈ S'.proj ⁻¹' {g (S.proj x)}, rw R_part.discrete_quotient_fiber R_cl, simpa using hR x, end def embedding.discrete_quotient_map [nonempty X] {f : X → Y} (hf : embedding f) (S : discrete_quotient X) : discrete_quotient Y := (hf.ex_discrete_quotient S).some def embedding.discrete_quotient_equiv [nonempty X] {f : X → Y} (hf : embedding f) (S : discrete_quotient X) : S ≃ hf.discrete_quotient_map S := (hf.ex_discrete_quotient S).some_spec.some lemma embedding.discrete_quotient_spec [nonempty X] {f : X → Y} (hf : embedding f) (S : discrete_quotient X) : (hf.discrete_quotient_map S).proj ∘ f = (hf.discrete_quotient_equiv S) ∘ S.proj := (hf.ex_discrete_quotient S).some_spec.some_spec variables {Z : Type*} [inhabited Z] open_locale classical def embedding.extend {e : X → Y} (he : embedding e) (f : X → Z) : Y → Z := if h : is_locally_constant f ∧ nonempty X then by { haveI := h.2, let ff : locally_constant X Z := ⟨f,h.1⟩, let T := he.discrete_quotient_map ff.discrete_quotient, let ee : ff.discrete_quotient ≃ T := he.discrete_quotient_equiv ff.discrete_quotient, exact ff.lift ∘ ee.symm ∘ T.proj } else λ y, default Z /- lemma embedding.extend_eq {e : X → Y} (he : embedding e) {f : X → Z} (hf : is_locally_constant f) : he.extend f = (hf.discrete_quotient_map) ∘ (he.discrete_quotient_equiv hf.discrete_quotient).symm ∘ (he.discrete_quotient_map hf.discrete_quotient).proj := dif_pos hf -/ lemma embedding.extend_extends {e : X → Y} (he : embedding e) {f : X → Z} (hf : is_locally_constant f) : ∀ x, he.extend f (e x) = f x := begin intro x, haveI : nonempty X := ⟨x⟩, let ff : locally_constant X Z := ⟨f,hf⟩, let S := ff.discrete_quotient, let S' := he.discrete_quotient_map S, let barf : S → Z := ff.lift, let g : S ≃ S' := he.discrete_quotient_equiv S, unfold embedding.extend, have h : is_locally_constant f ∧ nonempty X := ⟨hf, ⟨x⟩⟩, rw [dif_pos h], change (barf ∘ g.symm ∘ (S'.proj ∘ e)) x = f x, suffices : (barf ∘ S.proj) x = f x, by simpa [he.discrete_quotient_spec], simpa, end lemma embedding.is_locally_constant_extend {e : X → Y} (he : embedding e) {f : X → Z} : is_locally_constant (he.extend f) := begin unfold embedding.extend, split_ifs, { apply is_locally_constant.comp, apply is_locally_constant.comp, exact discrete_quotient.proj_is_locally_constant _ }, { apply is_locally_constant.const }, end lemma embedding.range_extend {e : X → Y} (he : embedding e) [nonempty X] {Z : Type*} [inhabited Z] {f : X → Z} (hf : is_locally_constant f) : range (he.extend f) = range f := begin ext z, split, { rintro ⟨y, rfl⟩, let ff : locally_constant _ _ := ⟨f,hf⟩, let T := he.discrete_quotient_map ff.discrete_quotient, let ee : ff.discrete_quotient ≃ T := he.discrete_quotient_equiv ff.discrete_quotient, dsimp only [embedding.extend], rw dif_pos, swap, { exact ⟨hf, ‹_›⟩ }, change ff.lift (ee.symm (T.proj y)) ∈ _, rcases ff.discrete_quotient.proj_surjective (ee.symm (T.proj y)) with ⟨w,hz⟩, use w, rw ← hz, refl }, { rintro ⟨x, rfl⟩, exact ⟨e x, he.extend_extends hf _⟩ } end def embedding.locally_constant_extend {e : X → Y} (he : embedding e) (f : locally_constant X Z) : locally_constant Y Z := ⟨he.extend f, he.is_locally_constant_extend⟩ @[simp] lemma embedding.locally_constant_extend_extends {e : X → Y} (he : embedding e) (f : locally_constant X Z) (x : X) : he.locally_constant_extend f (e x) = f x := he.extend_extends f.2 x lemma embedding.comap_locally_constant_extend {e : X → Y} (he : embedding e) (f : locally_constant X Z) : (he.locally_constant_extend f).comap e = f := begin ext x, rw locally_constant.coe_comap _ _ he.continuous, exact he.locally_constant_extend_extends f x end lemma embedding.range_locally_constant_extend {e : X → Y} (he : embedding e) [nonempty X] {Z : Type*} [inhabited Z] (f : locally_constant X Z) : range (he.locally_constant_extend f) = range f := he.range_extend f.2 -- version avec comap_hom pour Z normed group ?
aefa4e77a85ad676f229548a5eccec1358f1b2b1
f68ef9a599ec5575db7b285d4960e63c5d464ccc
/Exercises/Lista 4/vestidos.lean
4f7123948bf7101d3dbf2ad8f411a42d39b060ff
[]
no_license
lucasmoschen/discrete-mathematics
a38d5970cc571b0b9d202bf6a43efeb8ed6f66e3
0f1945cc5eb094814c926cd6ae4a8b4c5c579a1e
refs/heads/master
1,677,111,757,003
1,611,500,097,000
1,611,500,097,000
205,903,359
1
0
null
null
null
null
UTF-8
Lean
false
false
3,245
lean
/- Alunos: - Lucas Resck - Lucas Moschen Formalize em FOL: Três irmãs - Ana, Maria e Cláudia - foram a uma festa com vestidos de cores diferentes. Uma vestia azul, a outra branco e a Terceira preto. Chegando à festa, o anfitrião perguntou quem era cada uma delas. As respostas foram: - A de azul respondeu: “Ana é a que está de branco” - A de branco falou: “Eu sou Maria” - A de preto disse: “Cláudia é quem está de branco” O anfitrião foi capaz de identificar corretamente quem era cada pessoa considerando que: - Ana sempre diz a verdade - Maria às vezes diz a verdade - Cláudia nunca diz a verdade Pensando um pouco sobre o problema, pode-se concluir que a Ana estava com o vestido preto, a Cláudia com o branco e a Maria com o azul. -/ -- I define two import types in the problem constant Colors : Type constant People : Type -- I define the function and some constants quoteds in the problem constant DressColor : People → Colors → Prop constant Ana : People constant Maria : People constant Claudia : People constant Black : Colors constant White : Colors constant Blue : Colors -- The condition that everyone quoted is dressed with only one dress color. variable AnaDressed : ∃ x : Colors, DressColor Ana x ∧ (∀ y: Colors, ¬ (y = x) → ¬ (DressColor Ana y)) variable ClaudiaDressed : ∃ x : Colors, DressColor Claudia x ∧ (∀ y: Colors, ¬ (y = x) → ¬ (DressColor Claudia y)) variable MariaDressed : ∃ x : Colors, DressColor Maria x ∧ (∀ y: Colors, ¬ (y = x) → ¬ (DressColor Maria y)) -- The condition that every color quoted is used by only one person variable BlackUsed : ∃ x : People, DressColor x Black ∧ (∀ y : People, ¬ (y = x) → ¬ (DressColor y Black)) variable WhiteUsed : ∃ x : People, DressColor x White ∧ (∀ y : People, ¬ (y = x) → ¬ (DressColor y White)) variable BlueUsed: ∃ x : People, DressColor x Blue ∧ (∀ y : People, ¬ (y = x) → ¬ (DressColor y Blue)) -- This conditions are importants to use some relations with the dresses in this particular case variable a: (DressColor Ana Black ∨ DressColor Ana White ∨ DressColor Ana Blue) variable c: (DressColor Claudia Black ∨ DressColor Claudia White ∨ DressColor Claudia Blue) variable m: (DressColor Maria Black ∨ DressColor Maria White ∨ DressColor Maria Blue) -- We know Ana always says the truth and Claudia doesn't. variable AnaBlue: DressColor Ana Blue → DressColor Ana White variable AnaWhite: DressColor Ana White → DressColor Maria White variable AnaBlack: DressColor Ana Black → DressColor Claudia Blue variable ClaudiaBlue: DressColor Claudia Blue → ¬ (DressColor Ana White) variable ClaudiaWhite: DressColor Claudia White → ¬ (DressColor Maria White) variable ClaudiaBlack: DressColor Claudia Black → ¬ (DressColor Claudia Blue) -- Note that Maria is not necessary, because we do not know if she says truth -- Variable that needed to be proved def conclusion: Prop := (DressColor Ana Black) ∧ (DressColor Claudia White) ∧ (DressColor Maria Blue)
703e93dc21635e375822656ed5ac76b7e5ee3090
6cc23d886ccf271bfd0c9ca5d29cafb9c0be7bf5
/package.lean
0ddfa1381bcfb1b149b88746a31043cd59bcda55
[]
no_license
Anderssorby/LeanPlay
d39b15dbc3441c2be5a4ea5adf8fe70c4648737b
8fd63d98d02490060323f4c5117b9a7e8da50813
refs/heads/main
1,692,004,930,931
1,633,974,729,000
1,633,974,729,000
368,654,414
0
0
null
null
null
null
UTF-8
Lean
false
false
739
lean
import Lake import Lake.Package import Lake.BuildTargets open Lake System def cDir : FilePath := "c" def addSrc := cDir / "add.cpp" def buildDir := defaultBuildDir def addO := buildDir / cDir / "add.o" def cLib := buildDir / cDir / "libadd.a" def addOTarget (pkgDir : FilePath) : FileTarget := oFileTarget (pkgDir / addO) (pkgDir / addSrc : FilePath) def cLibTarget (pkgDir : FilePath) : FileTarget := staticLibTarget (pkgDir / cLib) #[addOTarget pkgDir] def package : Packager := fun pkgDir args => { name := "LeanPlay" version := "0.1" -- customize layout srcDir := "lib" moduleRoot := `Add binName := "add" binRoot := `Main -- specify the lib as an additional target moreLibTargets := #[cLibTarget pkgDir] }
bc436930a193bc89e41298502c1570855b0021b8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/finsupp.lean
c1785d2160d0157900e536c6b4ae6568f3edf775
[]
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
23,507
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.finsupp.basic import Mathlib.linear_algebra.basic import Mathlib.PostPort universes u_1 u_2 u_4 u_3 u_5 u_6 namespace Mathlib /-! # Properties of the semimodule `α →₀ M` Given an `R`-semimodule `M`, the `R`-semimodule structure on `α →₀ M` is defined in `data.finsupp.basic`. In this file we define `finsupp.supported s` to be the set `{f : α →₀ M | f.support ⊆ s}` interpreted as a submodule of `α →₀ M`. We also define `linear_map` versions of various maps: * `finsupp.lsingle a : M →ₗ[R] ι →₀ M`: `finsupp.single a` as a linear map; * `finsupp.lapply a : (ι →₀ M) →ₗ[R] M`: the map `λ f, f a` as a linear map; * `finsupp.lsubtype_domain (s : set α) : (α →₀ M) →ₗ[R] (s →₀ M)`: restriction to a subtype as a linear map; * `finsupp.restrict_dom`: `finsupp.filter` as a linear map to `finsupp.supported s`; * `finsupp.lsum`: `finsupp.sum` or `finsupp.lift_add_hom` as a `linear_map`; * `finsupp.total α M R (v : ι → M)`: sends `l : ι → R` to the linear combination of `v i` with coefficients `l i`; * `finsupp.total_on`: a restricted version of `finsupp.total` with domain `finsupp.supported R R s` and codomain `submodule.span R (v '' s)`; * `finsupp.supported_equiv_finsupp`: a linear equivalence between the functions `α →₀ M` supported on `s` and the functions `s →₀ M`; * `finsupp.lmap_domain`: a linear map version of `finsupp.map_domain`; * `finsupp.dom_lcongr`: a `linear_equiv` version of `finsupp.dom_congr`; * `finsupp.congr`: if the sets `s` and `t` are equivalent, then `supported M R s` is equivalent to `supported M R t`; * `finsupp.lcongr`: a `linear_equiv`alence between `α →₀ M` and `β →₀ N` constructed using `e : α ≃ β` and `e' : M ≃ₗ[R] N`. ## Tags function with finite support, semimodule, linear algebra -/ namespace finsupp /-- Interpret `finsupp.single a` as a linear map. -/ def lsingle {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (a : α) : linear_map R M (α →₀ M) := linear_map.mk (add_monoid_hom.to_fun (single_add_hom a)) sorry sorry /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. -/ theorem lhom_ext {α : Type u_1} {M : Type u_2} {N : Type u_3} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] {φ : linear_map R (α →₀ M) N} {ψ : linear_map R (α →₀ M) N} (h : ∀ (a : α) (b : M), coe_fn φ (single a b) = coe_fn ψ (single a b)) : φ = ψ := linear_map.to_add_monoid_hom_injective (add_hom_ext h) /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)` so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ theorem lhom_ext' {α : Type u_1} {M : Type u_2} {N : Type u_3} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] {φ : linear_map R (α →₀ M) N} {ψ : linear_map R (α →₀ M) N} (h : ∀ (a : α), linear_map.comp φ (lsingle a) = linear_map.comp ψ (lsingle a)) : φ = ψ := lhom_ext fun (a : α) => linear_map.congr_fun (h a) /-- Interpret `λ (f : α →₀ M), f a` as a linear map. -/ def lapply {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (a : α) : linear_map R (α →₀ M) M := linear_map.mk (add_monoid_hom.to_fun (apply_add_hom a)) sorry sorry /-- Interpret `finsupp.subtype_domain s` as a linear map. -/ def lsubtype_domain {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) : linear_map R (α →₀ M) (↥s →₀ M) := linear_map.mk (subtype_domain fun (x : α) => x ∈ s) sorry sorry theorem lsubtype_domain_apply {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) (f : α →₀ M) : coe_fn (lsubtype_domain s) f = subtype_domain (fun (x : α) => x ∈ s) f := rfl @[simp] theorem lsingle_apply {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (a : α) (b : M) : coe_fn (lsingle a) b = single a b := rfl @[simp] theorem lapply_apply {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (a : α) (f : α →₀ M) : coe_fn (lapply a) f = coe_fn f a := rfl @[simp] theorem ker_lsingle {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (a : α) : linear_map.ker (lsingle a) = ⊥ := linear_map.ker_eq_bot_of_injective (single_injective a) theorem lsingle_range_le_ker_lapply {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) (t : set α) (h : disjoint s t) : (supr fun (a : α) => supr fun (H : a ∈ s) => linear_map.range (lsingle a)) ≤ infi fun (a : α) => infi fun (H : a ∈ t) => linear_map.ker (lapply a) := sorry theorem infi_ker_lapply_le_bot {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] : (infi fun (a : α) => linear_map.ker (lapply a)) ≤ ⊥ := sorry theorem supr_lsingle_range {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] : (supr fun (a : α) => linear_map.range (lsingle a)) = ⊤ := sorry theorem disjoint_lsingle_lsingle {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) (t : set α) (hs : disjoint s t) : disjoint (supr fun (a : α) => supr fun (H : a ∈ s) => linear_map.range (lsingle a)) (supr fun (a : α) => supr fun (H : a ∈ t) => linear_map.range (lsingle a)) := sorry theorem span_single_image {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (s : set M) (a : α) : submodule.span R (single a '' s) = submodule.map (lsingle a) (submodule.span R s) := sorry /-- `finsupp.supported M R s` is the `R`-submodule of all `p : α →₀ M` such that `p.support ⊆ s`. -/ def supported {α : Type u_1} (M : Type u_2) (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) : submodule R (α →₀ M) := submodule.mk (set_of fun (p : α →₀ M) => ↑(support p) ⊆ s) sorry sorry sorry theorem mem_supported {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {s : set α} (p : α →₀ M) : p ∈ supported M R s ↔ ↑(support p) ⊆ s := iff.rfl theorem mem_supported' {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {s : set α} (p : α →₀ M) : p ∈ supported M R s ↔ ∀ (x : α), ¬x ∈ s → coe_fn p x = 0 := sorry theorem single_mem_supported {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {s : set α} {a : α} (b : M) (h : a ∈ s) : single a b ∈ supported M R s := set.subset.trans support_single_subset (iff.mpr finset.singleton_subset_set_iff h) theorem supported_eq_span_single {α : Type u_1} (R : Type u_4) [semiring R] (s : set α) : supported R R s = submodule.span R ((fun (i : α) => single i 1) '' s) := sorry /-- Interpret `finsupp.filter s` as a linear map from `α →₀ M` to `supported M R s`. -/ def restrict_dom {α : Type u_1} (M : Type u_2) (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) : linear_map R (α →₀ M) ↥(supported M R s) := linear_map.cod_restrict (supported M R s) (linear_map.mk (filter fun (_x : α) => _x ∈ s) sorry sorry) sorry @[simp] theorem restrict_dom_apply {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) (l : α →₀ M) : ↑(coe_fn (restrict_dom M R s) l) = filter (fun (_x : α) => _x ∈ s) l := rfl theorem restrict_dom_comp_subtype {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) : linear_map.comp (restrict_dom M R s) (submodule.subtype (supported M R s)) = linear_map.id := sorry theorem range_restrict_dom {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) : linear_map.range (restrict_dom M R s) = ⊤ := sorry theorem supported_mono {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] {s : set α} {t : set α} (st : s ⊆ t) : supported M R s ≤ supported M R t := fun (l : α →₀ M) (h : l ∈ supported M R s) => set.subset.trans h st @[simp] theorem supported_empty {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] : supported M R ∅ = ⊥ := sorry @[simp] theorem supported_univ {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] : supported M R set.univ = ⊤ := iff.mpr eq_top_iff fun (l : α →₀ M) (_x : l ∈ ⊤) => set.subset_univ ↑(support l) theorem supported_Union {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] {δ : Type u_3} (s : δ → set α) : supported M R (set.Union fun (i : δ) => s i) = supr fun (i : δ) => supported M R (s i) := sorry theorem supported_union {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) (t : set α) : supported M R (s ∪ t) = supported M R s ⊔ supported M R t := sorry theorem supported_Inter {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] {ι : Type u_3} (s : ι → set α) : supported M R (set.Inter fun (i : ι) => s i) = infi fun (i : ι) => supported M R (s i) := sorry theorem supported_inter {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) (t : set α) : supported M R (s ∩ t) = supported M R s ⊓ supported M R t := sorry theorem disjoint_supported_supported {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] {s : set α} {t : set α} (h : disjoint s t) : disjoint (supported M R s) (supported M R t) := sorry theorem disjoint_supported_supported_iff {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] [nontrivial M] {s : set α} {t : set α} : disjoint (supported M R s) (supported M R t) ↔ disjoint s t := sorry /-- Interpret `finsupp.restrict_support_equiv` as a linear equivalence between `supported M R s` and `s →₀ M`. -/ def supported_equiv_finsupp {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] (s : set α) : linear_equiv R (↥(supported M R s)) (↥s →₀ M) := let F : ↥(supported M R s) ≃ (↥s →₀ M) := restrict_support_equiv s M; equiv.to_linear_equiv F sorry /-- Lift a family of linear maps `M →ₗ[R] N` indexed by `x : α` to a linear map from `α →₀ M` to `N` using `finsupp.sum`. This is an upgraded version of `finsupp.lift_add_hom`. We define this as an additive equivalence. For a commutative `R`, this equivalence can be upgraded further to a linear equivalence. -/ def lsum {α : Type u_1} {M : Type u_2} {N : Type u_3} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] : (α → linear_map R M N) ≃+ linear_map R (α →₀ M) N := add_equiv.mk (fun (F : α → linear_map R M N) => linear_map.mk (fun (d : α →₀ M) => sum d fun (i : α) => ⇑(F i)) sorry sorry) (fun (F : linear_map R (α →₀ M) N) (x : α) => linear_map.comp F (lsingle x)) sorry sorry sorry @[simp] theorem coe_lsum {α : Type u_1} {M : Type u_2} {N : Type u_3} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] (f : α → linear_map R M N) : ⇑(coe_fn lsum f) = fun (d : α →₀ M) => sum d fun (i : α) => ⇑(f i) := rfl theorem lsum_apply {α : Type u_1} {M : Type u_2} {N : Type u_3} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] (f : α → linear_map R M N) (l : α →₀ M) : coe_fn (coe_fn lsum f) l = sum l fun (b : α) => ⇑(f b) := rfl theorem lsum_single {α : Type u_1} {M : Type u_2} {N : Type u_3} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] (f : α → linear_map R M N) (i : α) (m : M) : coe_fn (coe_fn lsum f) (single i m) = coe_fn (f i) m := sum_single_index (linear_map.map_zero (f i)) theorem lsum_symm_apply {α : Type u_1} {M : Type u_2} {N : Type u_3} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] (f : linear_map R (α →₀ M) N) (x : α) : coe_fn (add_equiv.symm lsum) f x = linear_map.comp f (lsingle x) := rfl /-- Interpret `finsupp.lmap_domain` as a linear map. -/ def lmap_domain {α : Type u_1} (M : Type u_2) (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {α' : Type u_5} (f : α → α') : linear_map R (α →₀ M) (α' →₀ M) := linear_map.mk (map_domain f) sorry map_domain_smul @[simp] theorem lmap_domain_apply {α : Type u_1} (M : Type u_2) (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {α' : Type u_5} (f : α → α') (l : α →₀ M) : coe_fn (lmap_domain M R f) l = map_domain f l := rfl @[simp] theorem lmap_domain_id {α : Type u_1} (M : Type u_2) (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] : lmap_domain M R id = linear_map.id := linear_map.ext fun (l : α →₀ M) => map_domain_id theorem lmap_domain_comp {α : Type u_1} (M : Type u_2) (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {α' : Type u_5} {α'' : Type u_6} (f : α → α') (g : α' → α'') : lmap_domain M R (g ∘ f) = linear_map.comp (lmap_domain M R g) (lmap_domain M R f) := linear_map.ext fun (l : α →₀ M) => map_domain_comp theorem supported_comap_lmap_domain {α : Type u_1} (M : Type u_2) (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {α' : Type u_5} (f : α → α') (s : set α') : supported M R (f ⁻¹' s) ≤ submodule.comap (lmap_domain M R f) (supported M R s) := sorry theorem lmap_domain_supported {α : Type u_1} (M : Type u_2) (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {α' : Type u_5} [Nonempty α] (f : α → α') (s : set α) : submodule.map (lmap_domain M R f) (supported M R s) = supported M R (f '' s) := sorry theorem lmap_domain_disjoint_ker {α : Type u_1} (M : Type u_2) (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {α' : Type u_5} (f : α → α') {s : set α} (H : ∀ (a b : α), a ∈ s → b ∈ s → f a = f b → a = b) : disjoint (supported M R s) (linear_map.ker (lmap_domain M R f)) := sorry /-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and evaluates this linear combination. -/ protected def total (α : Type u_1) (M : Type u_2) (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] (v : α → M) : linear_map R (α →₀ R) M := coe_fn lsum fun (i : α) => linear_map.smul_right linear_map.id (v i) theorem total_apply {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {v : α → M} (l : α →₀ R) : coe_fn (finsupp.total α M R v) l = sum l fun (i : α) (a : R) => a • v i := rfl theorem total_apply_of_mem_supported {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {v : α → M} {l : α →₀ R} {s : finset α} (hs : l ∈ supported R R ↑s) : coe_fn (finsupp.total α M R v) l = finset.sum s fun (i : α) => coe_fn l i • v i := sorry @[simp] theorem total_single {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {v : α → M} (c : R) (a : α) : coe_fn (finsupp.total α M R v) (single a c) = c • v a := sorry theorem total_unique {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] [unique α] (l : α →₀ R) (v : α → M) : coe_fn (finsupp.total α M R v) l = coe_fn l Inhabited.default • v Inhabited.default := sorry theorem total_range {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {v : α → M} (h : function.surjective v) : linear_map.range (finsupp.total α M R v) = ⊤ := sorry theorem range_total {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {v : α → M} : linear_map.range (finsupp.total α M R v) = submodule.span R (set.range v) := sorry theorem lmap_domain_total {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {α' : Type u_5} {M' : Type u_6} [add_comm_monoid M'] [semimodule R M'] {v : α → M} {v' : α' → M'} (f : α → α') (g : linear_map R M M') (h : ∀ (i : α), coe_fn g (v i) = v' (f i)) : linear_map.comp (finsupp.total α' M' R v') (lmap_domain R R f) = linear_map.comp g (finsupp.total α M R v) := sorry theorem total_emb_domain {α : Type u_1} (R : Type u_4) [semiring R] {α' : Type u_5} {M' : Type u_6} [add_comm_monoid M'] [semimodule R M'] {v' : α' → M'} (f : α ↪ α') (l : α →₀ R) : coe_fn (finsupp.total α' M' R v') (emb_domain f l) = coe_fn (finsupp.total α M' R (v' ∘ ⇑f)) l := sorry theorem total_map_domain {α : Type u_1} (R : Type u_4) [semiring R] {α' : Type u_5} {M' : Type u_6} [add_comm_monoid M'] [semimodule R M'] {v' : α' → M'} (f : α → α') (hf : function.injective f) (l : α →₀ R) : coe_fn (finsupp.total α' M' R v') (map_domain f l) = coe_fn (finsupp.total α M' R (v' ∘ f)) l := sorry theorem span_eq_map_total {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {v : α → M} (s : set α) : submodule.span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) := sorry theorem mem_span_iff_total {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {v : α → M} {s : set α} {x : M} : x ∈ submodule.span R (v '' s) ↔ ∃ (l : α →₀ R), ∃ (H : l ∈ supported R R s), coe_fn (finsupp.total α M R v) l = x := sorry /-- `finsupp.total_on M v s` interprets `p : α →₀ R` as a linear combination of a subset of the vectors in `v`, mapping it to the span of those vectors. The subset is indicated by a set `s : set α` of indices. -/ protected def total_on (α : Type u_1) (M : Type u_2) (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] (v : α → M) (s : set α) : linear_map R ↥(supported R R s) ↥(submodule.span R (v '' s)) := linear_map.cod_restrict (submodule.span R (v '' s)) (linear_map.comp (finsupp.total α M R v) (submodule.subtype (supported R R s))) sorry theorem total_on_range {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {v : α → M} (s : set α) : linear_map.range (finsupp.total_on α M R v s) = ⊤ := sorry theorem total_comp {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {α' : Type u_5} {v : α → M} (f : α' → α) : finsupp.total α' M R (v ∘ f) = linear_map.comp (finsupp.total α M R v) (lmap_domain R R f) := sorry theorem total_comap_domain {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {α' : Type u_5} {v : α → M} (f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑(support l))) : coe_fn (finsupp.total α M R v) (comap_domain f l hf) = finset.sum (finset.preimage (support l) f hf) fun (i : α) => coe_fn l (f i) • v i := sorry theorem total_on_finset {α : Type u_1} {M : Type u_2} (R : Type u_4) [semiring R] [add_comm_monoid M] [semimodule R M] {s : finset α} {f : α → R} (g : α → M) (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) : coe_fn (finsupp.total α M R g) (on_finset s f hf) = finset.sum s fun (x : α) => f x • g x := sorry /-- An equivalence of domains induces a linear equivalence of finitely supported functions. -/ protected def dom_lcongr {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] {α₁ : Type u_1} {α₂ : Type u_3} (e : α₁ ≃ α₂) : linear_equiv R (α₁ →₀ M) (α₂ →₀ M) := add_equiv.to_linear_equiv (finsupp.dom_congr e) sorry @[simp] theorem dom_lcongr_single {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] {α₁ : Type u_1} {α₂ : Type u_3} (e : α₁ ≃ α₂) (i : α₁) (m : M) : coe_fn (finsupp.dom_lcongr e) (single i m) = single (coe_fn e i) m := sorry /-- An equivalence of sets induces a linear equivalence of `finsupp`s supported on those sets. -/ def congr {α : Type u_1} {M : Type u_2} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] {α' : Type u_3} (s : set α) (t : set α') (e : ↥s ≃ ↥t) : linear_equiv R ↥(supported M R s) ↥(supported M R t) := linear_equiv.trans (supported_equiv_finsupp s) (linear_equiv.trans (finsupp.dom_lcongr e) (linear_equiv.symm (supported_equiv_finsupp t))) /-- An equivalence of domain and a linear equivalence of codomain induce a linear equivalence of the corresponding finitely supported functions. -/ def lcongr {M : Type u_2} {N : Type u_3} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] {ι : Type u_1} {κ : Type u_5} (e₁ : ι ≃ κ) (e₂ : linear_equiv R M N) : linear_equiv R (ι →₀ M) (κ →₀ N) := linear_equiv.trans (finsupp.dom_lcongr e₁) (linear_equiv.mk (map_range (⇑e₂) (linear_equiv.map_zero e₂)) sorry sorry (map_range ⇑(linear_equiv.symm e₂) sorry) sorry sorry) @[simp] theorem lcongr_single {M : Type u_2} {N : Type u_3} {R : Type u_4} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] {ι : Type u_1} {κ : Type u_5} (e₁ : ι ≃ κ) (e₂ : linear_equiv R M N) (i : ι) (m : M) : coe_fn (lcongr e₁ e₂) (single i m) = single (coe_fn e₁ i) (coe_fn e₂ m) := sorry end finsupp theorem linear_map.map_finsupp_total {R : Type u_1} {M : Type u_2} {N : Type u_3} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] (f : linear_map R M N) {ι : Type u_4} {g : ι → M} (l : ι →₀ R) : coe_fn f (coe_fn (finsupp.total ι M R g) l) = coe_fn (finsupp.total ι N R (⇑f ∘ g)) l := sorry theorem submodule.exists_finset_of_mem_supr {R : Type u_1} {M : Type u_2} [semiring R] [add_comm_monoid M] [semimodule R M] {ι : Type u_3} (p : ι → submodule R M) {m : M} (hm : m ∈ supr fun (i : ι) => p i) : ∃ (s : finset ι), m ∈ supr fun (i : ι) => supr fun (H : i ∈ s) => p i := sorry theorem mem_span_finset {R : Type u_1} {M : Type u_2} [semiring R] [add_comm_monoid M] [semimodule R M] {s : finset M} {x : M} : x ∈ submodule.span R ↑s ↔ ∃ (f : M → R), (finset.sum s fun (i : M) => f i • i) = x := sorry
91abfde07916044fa674ddbf427f675209b29e4c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/vector/basic.lean
d958b566e2f0c73ba1bc5636a6a107e531b0790d
[ "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
21,909
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 data.vector import data.list.nodup import data.list.of_fn import control.applicative import meta.univs /-! # Additional theorems and definitions about the `vector` type This file introduces the infix notation `::ᵥ` for `vector.cons`. -/ universes u variables {n : ℕ} namespace vector variables {α : Type*} infixr ` ::ᵥ `:67 := vector.cons attribute [simp] head_cons tail_cons instance [inhabited α] : inhabited (vector α n) := ⟨of_fn default⟩ theorem to_list_injective : function.injective (@to_list α n) := subtype.val_injective /-- Two `v w : vector α n` are equal iff they are equal at every single index. -/ @[ext] theorem ext : ∀ {v w : vector α n} (h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w | ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw]) (λ m hm hn, h ⟨m, hv ▸ hm⟩)) /-- The empty `vector` is a `subsingleton`. -/ instance zero_subsingleton : subsingleton (vector α 0) := ⟨λ _ _, vector.ext (λ m, fin.elim0 m)⟩ @[simp] theorem cons_val (a : α) : ∀ (v : vector α n), (a ::ᵥ v).val = a :: v.val | ⟨_, _⟩ := rfl @[simp] theorem cons_head (a : α) : ∀ (v : vector α n), (a ::ᵥ v).head = a | ⟨_, _⟩ := rfl @[simp] theorem cons_tail (a : α) : ∀ (v : vector α n), (a ::ᵥ v).tail = v | ⟨_, _⟩ := rfl lemma eq_cons_iff (a : α) (v : vector α n.succ) (v' : vector α n) : v = a ::ᵥ v' ↔ v.head = a ∧ v.tail = v' := ⟨λ h, h.symm ▸ ⟨head_cons a v', tail_cons a v'⟩, λ h, trans (cons_head_tail v).symm (by rw [h.1, h.2])⟩ lemma ne_cons_iff (a : α) (v : vector α n.succ) (v' : vector α n) : v ≠ a ::ᵥ v' ↔ v.head ≠ a ∨ v.tail ≠ v' := by rw [ne.def, eq_cons_iff a v v', not_and_distrib] lemma exists_eq_cons (v : vector α n.succ) : ∃ (a : α) (as : vector α n), v = a ::ᵥ as := ⟨v.head, v.tail, (eq_cons_iff v.head v v.tail).2 ⟨rfl, rfl⟩⟩ @[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f | 0 f := rfl | (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn] @[simp] theorem mk_to_list : ∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v | ⟨l, h₁⟩ h₂ := rfl @[simp] lemma length_coe (v : vector α n) : ((coe : { l : list α // l.length = n } → list α) v).length = n := v.2 @[simp] lemma to_list_map {β : Type*} (v : vector α n) (f : α → β) : (v.map f).to_list = v.to_list.map f := by cases v; refl @[simp] lemma head_map {β : Type*} (v : vector α (n + 1)) (f : α → β) : (v.map f).head = f v.head := begin obtain ⟨a, v', h⟩ := vector.exists_eq_cons v, rw [h, map_cons, head_cons, head_cons], end @[simp] lemma tail_map {β : Type*} (v : vector α (n + 1)) (f : α → β) : (v.map f).tail = v.tail.map f := begin obtain ⟨a, v', h⟩ := vector.exists_eq_cons v, rw [h, map_cons, tail_cons, tail_cons], end theorem nth_eq_nth_le : ∀ (v : vector α n) (i), nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2) | ⟨l, h⟩ i := rfl @[simp] lemma nth_repeat (a : α) (i : fin n) : (vector.repeat a n).nth i = a := by apply list.nth_le_repeat @[simp] lemma nth_map {β : Type*} (v : vector α n) (f : α → β) (i : fin n) : (v.map f).nth i = f (v.nth i) := by simp [nth_eq_nth_le] @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i := by rw [nth_eq_nth_le, ← list.nth_le_of_fn f]; congr; apply to_list_of_fn @[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v := begin rcases v with ⟨l, rfl⟩, apply to_list_injective, change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i, simpa only [to_list_of_fn] using list.of_fn_nth_le _ end /-- The natural equivalence between length-`n` vectors and functions from `fin n`. -/ def _root_.equiv.vector_equiv_fin (α : Type*) (n : ℕ) : vector α n ≃ (fin n → α) := ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩ theorem nth_tail (x : vector α n) (i) : x.tail.nth i = x.nth ⟨i.1 + 1, lt_tsub_iff_right.mp i.2⟩ := by { rcases x with ⟨_|_, h⟩; refl, } @[simp] theorem nth_tail_succ : ∀ (v : vector α n.succ) (i : fin n), nth (tail v) i = nth v i.succ | ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl @[simp] theorem tail_val : ∀ (v : vector α n.succ), v.tail.val = v.val.tail | ⟨a::l, e⟩ := rfl /-- The `tail` of a `nil` vector is `nil`. -/ @[simp] lemma tail_nil : (@nil α).tail = nil := rfl /-- The `tail` of a vector made up of one element is `nil`. -/ @[simp] lemma singleton_tail (v : vector α 1) : v.tail = vector.nil := by simp only [←cons_head_tail, eq_iff_true_of_subsingleton] @[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) : tail (of_fn f) = of_fn (λ i, f i.succ) := (of_fn_nth _).symm.trans $ by { congr, funext i, cases i, simp, } @[simp] theorem to_list_empty (v : vector α 0) : v.to_list = [] := list.length_eq_zero.mp v.2 /-- The list that makes up a `vector` made up of a single element, retrieved via `to_list`, is equal to the list of that single element. -/ @[simp] lemma to_list_singleton (v : vector α 1) : v.to_list = [v.head] := begin rw ←v.cons_head_tail, simp only [to_list_cons, to_list_nil, cons_head, eq_self_iff_true, and_self, singleton_tail] end @[simp] lemma empty_to_list_eq_ff (v : vector α (n + 1)) : v.to_list.empty = ff := match v with | ⟨a :: as, _⟩ := rfl end lemma not_empty_to_list (v : vector α (n + 1)) : ¬ v.to_list.empty := by simp only [empty_to_list_eq_ff, coe_sort_ff, not_false_iff] /-- Mapping under `id` does not change a vector. -/ @[simp] lemma map_id {n : ℕ} (v : vector α n) : vector.map id v = v := vector.eq _ _ (by simp only [list.map_id, vector.to_list_map]) lemma nodup_iff_nth_inj {v : vector α n} : v.to_list.nodup ↔ function.injective v.nth := begin cases v with l hl, subst hl, simp only [list.nodup_iff_nth_le_inj], split, { intros h i j hij, cases i, cases j, ext, apply h, simpa }, { intros h i j hi hj hij, have := @h ⟨i, hi⟩ ⟨j, hj⟩, simp [nth_eq_nth_le] at *, tauto } end theorem head'_to_list : ∀ (v : vector α n.succ), (to_list v).head' = some (head v) | ⟨a::l, e⟩ := rfl /-- Reverse a vector. -/ def reverse (v : vector α n) : vector α n := ⟨v.to_list.reverse, by simp⟩ /-- The `list` of a vector after a `reverse`, retrieved by `to_list` is equal to the `list.reverse` after retrieving a vector's `to_list`. -/ lemma to_list_reverse {v : vector α n} : v.reverse.to_list = v.to_list.reverse := rfl @[simp] lemma reverse_reverse {v : vector α n} : v.reverse.reverse = v := by { cases v, simp [vector.reverse], } @[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v | ⟨a::l, e⟩ := rfl @[simp] theorem head_of_fn {n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 := by rw [← nth_zero, nth_of_fn] @[simp] theorem nth_cons_zero (a : α) (v : vector α n) : nth (a ::ᵥ v) 0 = a := by simp [nth_zero] /-- Accessing the `nth` element of a vector made up of one element `x : α` is `x` itself. -/ @[simp] lemma nth_cons_nil {ix : fin 1} (x : α) : nth (x ::ᵥ nil) ix = x := by convert nth_cons_zero x nil @[simp] theorem nth_cons_succ (a : α) (v : vector α n) (i : fin n) : nth (a ::ᵥ v) i.succ = nth v i := by rw [← nth_tail_succ, tail_cons] /-- The last element of a `vector`, given that the vector is at least one element. -/ def last (v : vector α (n + 1)) : α := v.nth (fin.last n) /-- The last element of a `vector`, given that the vector is at least one element. -/ lemma last_def {v : vector α (n + 1)} : v.last = v.nth (fin.last n) := rfl /-- The `last` element of a vector is the `head` of the `reverse` vector. -/ lemma reverse_nth_zero {v : vector α (n + 1)} : v.reverse.head = v.last := begin have : 0 = v.to_list.length - 1 - n, { simp only [nat.add_succ_sub_one, add_zero, to_list_length, tsub_self, list.length_reverse] }, rw [←nth_zero, last_def, nth_eq_nth_le, nth_eq_nth_le], simp_rw [to_list_reverse, fin.val_eq_coe, fin.coe_last, fin.coe_zero, this], rw list.nth_le_reverse, end section scan variables {β : Type*} variables (f : β → α → β) (b : β) variables (v : vector α n) /-- Construct a `vector β (n + 1)` from a `vector α n` by scanning `f : β → α → β` from the "left", that is, from 0 to `fin.last n`, using `b : β` as the starting value. -/ def scanl : vector β (n + 1) := ⟨list.scanl f b v.to_list, by rw [list.length_scanl, to_list_length]⟩ /-- Providing an empty vector to `scanl` gives the starting value `b : β`. -/ @[simp] lemma scanl_nil : scanl f b nil = b ::ᵥ nil := rfl /-- The recursive step of `scanl` splits a vector `x ::ᵥ v : vector α (n + 1)` into the provided starting value `b : β` and the recursed `scanl` `f b x : β` as the starting value. This lemma is the `cons` version of `scanl_nth`. -/ @[simp] lemma scanl_cons (x : α) : scanl f b (x ::ᵥ v) = b ::ᵥ scanl f (f b x) v := by simpa only [scanl, to_list_cons] /-- The underlying `list` of a `vector` after a `scanl` is the `list.scanl` of the underlying `list` of the original `vector`. -/ @[simp] lemma scanl_val : ∀ {v : vector α n}, (scanl f b v).val = list.scanl f b v.val | ⟨l, hl⟩ := rfl /-- The `to_list` of a `vector` after a `scanl` is the `list.scanl` of the `to_list` of the original `vector`. -/ @[simp] lemma to_list_scanl : (scanl f b v).to_list = list.scanl f b v.to_list := rfl /-- The recursive step of `scanl` splits a vector made up of a single element `x ::ᵥ nil : vector α 1` into a `vector` of the provided starting value `b : β` and the mapped `f b x : β` as the last value. -/ @[simp] lemma scanl_singleton (v : vector α 1) : scanl f b v = b ::ᵥ f b v.head ::ᵥ nil := begin rw [←cons_head_tail v], simp only [scanl_cons, scanl_nil, cons_head, singleton_tail] end /-- The first element of `scanl` of a vector `v : vector α n`, retrieved via `head`, is the starting value `b : β`. -/ @[simp] lemma scanl_head : (scanl f b v).head = b := begin cases n, { have : v = nil := by simp only [eq_iff_true_of_subsingleton], simp only [this, scanl_nil, cons_head] }, { rw ←cons_head_tail v, simp only [←nth_zero, nth_eq_nth_le, to_list_scanl, to_list_cons, list.scanl, fin.val_zero', list.nth_le] } end /-- For an index `i : fin n`, the `nth` element of `scanl` of a vector `v : vector α n` at `i.succ`, is equal to the application function `f : β → α → β` of the `i.cast_succ` element of `scanl f b v` and `nth v i`. This lemma is the `nth` version of `scanl_cons`. -/ @[simp] lemma scanl_nth (i : fin n) : (scanl f b v).nth i.succ = f ((scanl f b v).nth i.cast_succ) (v.nth i) := begin cases n, { exact fin_zero_elim i }, induction n with n hn generalizing b, { have i0 : i = 0 := by simp only [eq_iff_true_of_subsingleton], simpa only [scanl_singleton, i0, nth_zero] }, { rw [←cons_head_tail v, scanl_cons, nth_cons_succ], refine fin.cases _ _ i, { simp only [nth_zero, scanl_head, fin.cast_succ_zero, cons_head] }, { intro i', simp only [hn, fin.cast_succ_fin_succ, nth_cons_succ] } } end end scan /-- Monadic analog of `vector.of_fn`. Given a monadic function on `fin n`, return a `vector α n` inside the monad. -/ def m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n) | 0 f := pure nil | (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a ::ᵥ v) theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} : ∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f) | 0 f := rfl | (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn] /-- Apply a monadic function to each component of a vector, returning a vector inside the monad. -/ def mmap {m} [monad m] {α} {β : Type u} (f : α → m β) : ∀ {n}, vector α n → m (vector β n) | 0 xs := pure nil | (n+1) xs := do h' ← f xs.head, t' ← @mmap n xs.tail, pure (h' ::ᵥ t') @[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) : mmap f nil = pure nil := rfl @[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) : ∀ {n} (v : vector α n), mmap f (a ::ᵥ v) = do h' ← f a, t' ← mmap f v, pure (h' ::ᵥ t') | _ ⟨l, rfl⟩ := rfl /-- Define `C v` by induction on `v : vector α n`. This function has two arguments: `h_nil` handles the base case on `C nil`, and `h_cons` defines the inductive step using `∀ x : α, C w → C (x ::ᵥ w)`. This can be used as `induction v using vector.induction_on`. -/ @[elab_as_eliminator] def induction_on {C : Π {n : ℕ}, vector α n → Sort*} {n : ℕ} (v : vector α n) (h_nil : C nil) (h_cons : ∀ {n : ℕ} {x : α} {w : vector α n}, C w → C (x ::ᵥ w)) : C v := begin induction n with n ih generalizing v, { rcases v with ⟨_|⟨-,-⟩,-|-⟩, exact h_nil, }, { rcases v with ⟨_|⟨a,v⟩,_⟩, cases v_property, apply @h_cons n _ ⟨v, (add_left_inj 1).mp v_property⟩, apply ih, } end -- check that the above works with `induction ... using` example (v : vector α n) : true := by induction v using vector.induction_on; trivial variables {β γ : Type*} /-- Define `C v w` by induction on a pair of vectors `v : vector α n` and `w : vector β n`. -/ @[elab_as_eliminator] def induction_on₂ {C : Π {n}, vector α n → vector β n → Sort*} (v : vector α n) (w : vector β n) (h_nil : C nil nil) (h_cons : ∀ {n a b} {x : vector α n} {y}, C x y → C (a ::ᵥ x) (b ::ᵥ y)) : C v w := begin induction n with n ih generalizing v w, { rcases v with ⟨_|⟨-,-⟩,-|-⟩, rcases w with ⟨_|⟨-,-⟩,-|-⟩, exact h_nil, }, { rcases v with ⟨_|⟨a,v⟩,_⟩, cases v_property, rcases w with ⟨_|⟨b,w⟩,_⟩, cases w_property, apply @h_cons n _ _ ⟨v, (add_left_inj 1).mp v_property⟩ ⟨w, (add_left_inj 1).mp w_property⟩, apply ih, } end /-- Define `C u v w` by induction on a triplet of vectors `u : vector α n`, `v : vector β n`, and `w : vector γ b`. -/ @[elab_as_eliminator] def induction_on₃ {C : Π {n}, vector α n → vector β n → vector γ n → Sort*} (u : vector α n) (v : vector β n) (w : vector γ n) (h_nil : C nil nil nil) (h_cons : ∀ {n a b c} {x : vector α n} {y z}, C x y z → C (a ::ᵥ x) (b ::ᵥ y) (c ::ᵥ z)) : C u v w := begin induction n with n ih generalizing u v w, { rcases u with ⟨_|⟨-,-⟩,-|-⟩, rcases v with ⟨_|⟨-,-⟩,-|-⟩, rcases w with ⟨_|⟨-,-⟩,-|-⟩, exact h_nil, }, { rcases u with ⟨_|⟨a,u⟩,_⟩, cases u_property, rcases v with ⟨_|⟨b,v⟩,_⟩, cases v_property, rcases w with ⟨_|⟨c,w⟩,_⟩, cases w_property, apply @h_cons n _ _ _ ⟨u, (add_left_inj 1).mp u_property⟩ ⟨v, (add_left_inj 1).mp v_property⟩ ⟨w, (add_left_inj 1).mp w_property⟩, apply ih, } end /-- Cast a vector to an array. -/ def to_array : vector α n → array n α | ⟨xs, h⟩ := cast (by rw h) xs.to_array section insert_nth variable {a : α} /-- `v.insert_nth a i` inserts `a` into the vector `v` at position `i` (and shifting later components to the right). -/ def insert_nth (a : α) (i : fin (n+1)) (v : vector α n) : vector α (n+1) := ⟨v.1.insert_nth i a, begin rw [list.length_insert_nth, v.2], rw [v.2, ← nat.succ_le_succ_iff], exact i.2 end⟩ lemma insert_nth_val {i : fin (n+1)} {v : vector α n} : (v.insert_nth a i).val = v.val.insert_nth i.1 a := rfl @[simp] lemma remove_nth_val {i : fin n} : ∀{v : vector α n}, (remove_nth i v).val = v.val.remove_nth i | ⟨l, hl⟩ := rfl lemma remove_nth_insert_nth {v : vector α n} {i : fin (n+1)} : remove_nth i (insert_nth a i v) = v := subtype.eq $ list.remove_nth_insert_nth i.1 v.1 lemma remove_nth_insert_nth' {v : vector α (n+1)} : ∀{i : fin (n+1)} {j : fin (n+2)}, remove_nth (j.succ_above i) (insert_nth a j v) = insert_nth a (i.pred_above j) (remove_nth i v) | ⟨i, hi⟩ ⟨j, hj⟩ := begin dsimp [insert_nth, remove_nth, fin.succ_above, fin.pred_above], simp only [subtype.mk_eq_mk], split_ifs, { convert (list.insert_nth_remove_nth_of_ge i (j-1) _ _ _).symm, { convert (nat.succ_pred_eq_of_pos _).symm, exact lt_of_le_of_lt (zero_le _) h, }, { apply remove_nth_val, }, { convert hi, exact v.2, }, { exact nat.le_pred_of_lt h, }, }, { convert (list.insert_nth_remove_nth_of_le i j _ _ _).symm, { apply remove_nth_val, }, { convert hi, exact v.2, }, { simpa using h, }, } end lemma insert_nth_comm (a b : α) (i j : fin (n+1)) (h : i ≤ j) : ∀(v : vector α n), (v.insert_nth a i).insert_nth b j.succ = (v.insert_nth b j).insert_nth a i.cast_succ | ⟨l, hl⟩ := begin refine subtype.eq _, simp only [insert_nth_val, fin.coe_succ, fin.cast_succ, fin.val_eq_coe, fin.coe_cast_add], apply list.insert_nth_comm, { assumption }, { rw hl, exact nat.le_of_succ_le_succ j.2 } end end insert_nth section update_nth /-- `update_nth v n a` replaces the `n`th element of `v` with `a` -/ def update_nth (v : vector α n) (i : fin n) (a : α) : vector α n := ⟨v.1.update_nth i.1 a, by rw [list.update_nth_length, v.2]⟩ @[simp] lemma to_list_update_nth (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).to_list = v.to_list.update_nth i a := rfl @[simp] lemma nth_update_nth_same (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).nth i = a := by cases v; cases i; simp [vector.update_nth, vector.nth_eq_nth_le] lemma nth_update_nth_of_ne {v : vector α n} {i j : fin n} (h : i ≠ j) (a : α) : (v.update_nth i a).nth j = v.nth j := by cases v; cases i; cases j; simp [vector.update_nth, vector.nth_eq_nth_le, list.nth_le_update_nth_of_ne (fin.vne_of_ne h)] lemma nth_update_nth_eq_if {v : vector α n} {i j : fin n} (a : α) : (v.update_nth i a).nth j = if i = j then a else v.nth j := by split_ifs; try {simp *}; try {rw nth_update_nth_of_ne}; assumption @[to_additive] lemma prod_update_nth [monoid α] (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).to_list.prod = (v.take i).to_list.prod * a * (v.drop (i + 1)).to_list.prod := begin refine (list.prod_update_nth v.to_list i a).trans _, have : ↑i < v.to_list.length := lt_of_lt_of_le i.2 (le_of_eq v.2.symm), simp * at * end @[to_additive] lemma prod_update_nth' [comm_group α] (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).to_list.prod = v.to_list.prod * (v.nth i)⁻¹ * a := begin refine (list.prod_update_nth' v.to_list i a).trans _, have : ↑i < v.to_list.length := lt_of_lt_of_le i.2 (le_of_eq v.2.symm), simp [this, nth_eq_nth_le, mul_assoc], end end update_nth end vector namespace vector section traverse variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) nat private def traverse_aux {α β : Type u} (f : α → F β) : Π (x : list α), F (vector β x.length) | [] := pure vector.nil | (x::xs) := vector.cons <$> f x <*> traverse_aux xs /-- Apply an applicative function to each component of a vector. -/ protected def traverse {α β : Type u} (f : α → F β) : vector α n → F (vector β n) | ⟨v, Hv⟩ := cast (by rw Hv) $ traverse_aux f v section variables {α β : Type u} @[simp] protected lemma traverse_def (f : α → F β) (x : α) : ∀ (xs : vector α n), (x ::ᵥ xs).traverse f = cons <$> f x <*> xs.traverse f := by rintro ⟨xs, rfl⟩; refl protected lemma id_traverse : ∀ (x : vector α n), x.traverse id.mk = x := begin rintro ⟨x, rfl⟩, dsimp [vector.traverse, cast], induction x with x xs IH, {refl}, simp! [IH], refl end end open function variables [is_lawful_applicative F] [is_lawful_applicative G] variables {α β γ : Type u} -- We need to turn off the linter here as -- the `is_lawful_traversable` instance below expects a particular signature. @[nolint unused_arguments] protected lemma comp_traverse (f : β → F γ) (g : α → G β) : ∀ (x : vector α n), vector.traverse (comp.mk ∘ functor.map f ∘ g) x = comp.mk (vector.traverse f <$> vector.traverse g x) := by rintro ⟨x, rfl⟩; dsimp [vector.traverse, cast]; induction x with x xs; simp! [cast, *] with functor_norm; [refl, simp [(∘)]] protected lemma traverse_eq_map_id {α β} (f : α → β) : ∀ (x : vector α n), x.traverse (id.mk ∘ f) = id.mk (map f x) := by rintro ⟨x, rfl⟩; simp!; induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β : Type*} (f : α → F β) : ∀ (x : vector α n), η (x.traverse f) = x.traverse (@η _ ∘ f) := by rintro ⟨x, rfl⟩; simp! [cast]; induction x with x xs IH; simp! * with functor_norm end traverse instance : traversable.{u} (flip vector n) := { traverse := @vector.traverse n, map := λ α β, @vector.map.{u u} α β n } instance : is_lawful_traversable.{u} (flip vector n) := { id_traverse := @vector.id_traverse n, comp_traverse := @vector.comp_traverse n, traverse_eq_map_id := @vector.traverse_eq_map_id n, naturality := @vector.naturality n, id_map := by intros; cases x; simp! [(<$>)], comp_map := by intros; cases x; simp! [(<$>)] } meta instance reflect [reflected_univ.{u}] {α : Type u} [has_reflect α] [reflected _ α] {n : ℕ} : has_reflect (vector α n) := λ v, @vector.induction_on α (λ n, reflected _) n v ((by reflect_name : reflected _ @vector.nil.{u}).subst `(α)) (λ n x xs ih, (by reflect_name : reflected _ @vector.cons.{u}).subst₄ `(α) `(n) `(x) ih) end vector
4d9fb6f11fd4eb5af3f9fb5f0fc7ad7554bff93e
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Data/Lsp/Diagnostics.lean
f11525c9329d39551d5971f51c0f4d8e5495d6e6
[ "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
3,073
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Json import Lean.Data.Lsp.Basic import Lean.Data.Lsp.Utf16 import Lean.Message /-! Definitions and functionality for emitting diagnostic information such as errors, warnings and #command outputs from the LSP server. -/ namespace Lean namespace Lsp open Json inductive DiagnosticSeverity where | error | warning | information | hint deriving Inhabited, BEq instance : FromJson DiagnosticSeverity := ⟨fun j => match j.getNat? with | Except.ok 1 => return DiagnosticSeverity.error | Except.ok 2 => return DiagnosticSeverity.warning | Except.ok 3 => return DiagnosticSeverity.information | Except.ok 4 => return DiagnosticSeverity.hint | _ => throw s!"unknown DiagnosticSeverity '{j}'"⟩ instance : ToJson DiagnosticSeverity := ⟨fun | DiagnosticSeverity.error => 1 | DiagnosticSeverity.warning => 2 | DiagnosticSeverity.information => 3 | DiagnosticSeverity.hint => 4⟩ inductive DiagnosticCode where | int (i : Int) | string (s : String) deriving Inhabited, BEq instance : FromJson DiagnosticCode := ⟨fun | num (i : Int) => return DiagnosticCode.int i | str s => return DiagnosticCode.string s | j => throw s!"expected string or integer diagnostic code, got '{j}'"⟩ instance : ToJson DiagnosticCode := ⟨fun | DiagnosticCode.int i => i | DiagnosticCode.string s => s⟩ inductive DiagnosticTag where | unnecessary | deprecated deriving Inhabited, BEq instance : FromJson DiagnosticTag := ⟨fun j => match j.getNat? with | Except.ok 1 => return DiagnosticTag.unnecessary | Except.ok 2 => return DiagnosticTag.deprecated | _ => throw "unknown DiagnosticTag"⟩ instance : ToJson DiagnosticTag := ⟨fun | DiagnosticTag.unnecessary => (1 : Nat) | DiagnosticTag.deprecated => (2 : Nat)⟩ structure DiagnosticRelatedInformation where location : Location message : String deriving Inhabited, BEq, ToJson, FromJson structure DiagnosticWith (α : Type) where range : Range /-- Extension: preserve semantic range of errors when truncating them for display purposes. -/ fullRange : Range := range severity? : Option DiagnosticSeverity := none code? : Option DiagnosticCode := none source? : Option String := none /-- Parametrised by the type of message data. LSP diagnostics use `String`, whereas in Lean's interactive diagnostics we use the type of widget-enriched text. See `Lean.Widget.InteractiveDiagnostic`. -/ message : α tags? : Option (Array DiagnosticTag) := none relatedInformation? : Option (Array DiagnosticRelatedInformation) := none deriving Inhabited, BEq, ToJson, FromJson abbrev Diagnostic := DiagnosticWith String structure PublishDiagnosticsParams where uri : DocumentUri version? : Option Int := none diagnostics : Array Diagnostic deriving Inhabited, BEq, ToJson, FromJson end Lsp end Lean
425e6e6d15a4b8168ba4a61f3fe23e0500f6681d
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/order/directed.lean
cdf89aabf778c31e770cf1191f33b8c2d41db65d
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
3,188
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.set.basic universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} (r : α → α → Prop) local infix ` ≼ ` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, x ≼ z ∧ y ≼ z variables {r} theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) := by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl) alias directed_on_iff_directed ↔ directed_on.directed_coe _ theorem directed_on_image {s} {f : β → α} : directed_on r (f '' s) ↔ directed_on (f ⁻¹'o r) s := by simp only [directed_on, set.ball_image_iff, set.bex_image_iff, order.preimage] theorem directed_on.mono {s : set α} (h : directed_on r s) {r' : α → α → Prop} (H : ∀ {a b}, r a b → r' a b) : directed_on r' s := λ x hx y hy, let ⟨z, zs, xz, yz⟩ := h x hx y hy in ⟨z, zs, H xz, H yz⟩ theorem directed_comp {ι} {f : ι → β} {g : β → α} : directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl theorem directed.mono {s : α → α → Prop} {ι} {f : ι → α} (H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f := λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩ theorem directed.mono_comp {ι} {rb : β → β → Prop} {g : α → β} {f : ι → α} (hg : ∀ ⦃x y⦄, x ≼ y → rb (g x) (g y)) (hf : directed r f) : directed rb (g ∘ f) := directed_comp.2 $ hf.mono hg /-- A monotone function on a sup-semilattice is directed. -/ lemma directed_of_sup [semilattice_sup α] {f : α → β} {r : β → β → Prop} (H : ∀ ⦃i j⦄, i ≤ j → r (f i) (f j)) : directed r f := λ a b, ⟨a ⊔ b, H le_sup_left, H le_sup_right⟩ lemma monotone.directed_le [semilattice_sup α] [preorder β] {f : α → β} : monotone f → directed (≤) f := directed_of_sup /-- An antimonotone function on an inf-semilattice is directed. -/ lemma directed_of_inf [semilattice_inf α] {r : β → β → Prop} {f : α → β} (hf : ∀a₁ a₂, a₁ ≤ a₂ → r (f a₂) (f a₁)) : directed r f := assume x y, ⟨x ⊓ y, hf _ _ inf_le_left, hf _ _ inf_le_right⟩ /-- A `preorder` is a `directed_order` if for any two elements `i`, `j` there is an element `k` such that `i ≤ k` and `j ≤ k`. -/ class directed_order (α : Type u) extends preorder α := (directed : ∀ i j : α, ∃ k, i ≤ k ∧ j ≤ k) @[priority 100] -- see Note [lower instance priority] instance linear_order.to_directed_order (α) [linear_order α] : directed_order α := ⟨λ i j, or.cases_on (le_total i j) (λ hij, ⟨j, hij, le_refl j⟩) (λ hji, ⟨i, le_refl i, hji⟩)⟩
2d8bc7151680db255ff57a85faa353dc7404ea05
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/charpoly/basic.lean
fe2808b92391285d631cefe118422e0cfba797a7
[ "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
3,667
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import linear_algebra.free_module.finite.basic import linear_algebra.matrix.charpoly.coeff import field_theory.minpoly /-! # Characteristic polynomial We define the characteristic polynomial of `f : M →ₗ[R] M`, where `M` is a finite and free `R`-module. The proof that `f.charpoly` is the characteristic polynomial of the matrix of `f` in any basis is in `linear_algebra/charpoly/to_matrix`. ## Main definition * `linear_map.charpoly f` : the characteristic polynomial of `f : M →ₗ[R] M`. -/ universes u v w variables {R : Type u} {M : Type v} [comm_ring R] [nontrivial R] variables [add_comm_group M] [module R M] [module.free R M] [module.finite R M] (f : M →ₗ[R] M) open_locale classical matrix polynomial noncomputable theory open module.free polynomial matrix namespace linear_map section basic /-- The characteristic polynomial of `f : M →ₗ[R] M`. -/ def charpoly : R[X] := (to_matrix (choose_basis R M) (choose_basis R M) f).charpoly lemma charpoly_def : f.charpoly = (to_matrix (choose_basis R M) (choose_basis R M) f).charpoly := rfl end basic section coeff lemma charpoly_monic : f.charpoly.monic := charpoly_monic _ end coeff section cayley_hamilton /-- The **Cayley-Hamilton Theorem**, that the characteristic polynomial of a linear map, applied to the linear map itself, is zero. See `matrix.aeval_self_charpoly` for the equivalent statement about matrices. -/ lemma aeval_self_charpoly : aeval f f.charpoly = 0 := begin apply (linear_equiv.map_eq_zero_iff (alg_equiv_matrix (choose_basis R M)).to_linear_equiv).1, rw [alg_equiv.to_linear_equiv_apply, ← alg_equiv.coe_alg_hom, ← polynomial.aeval_alg_hom_apply _ _ _, charpoly_def], exact aeval_self_charpoly _, end lemma is_integral : is_integral R f := ⟨f.charpoly, ⟨charpoly_monic f, aeval_self_charpoly f⟩⟩ lemma minpoly_dvd_charpoly {K : Type u} {M : Type v} [field K] [add_comm_group M] [module K M] [finite_dimensional K M] (f : M →ₗ[K] M) : minpoly K f ∣ f.charpoly := minpoly.dvd _ _ (aeval_self_charpoly f) /-- Any endomorphism polynomial `p` is equivalent under evaluation to `p %ₘ f.charpoly`; that is, `p` is equivalent to a polynomial with degree less than the dimension of the module. -/ lemma aeval_eq_aeval_mod_charpoly (p : R[X]) : aeval f p = aeval f (p %ₘ f.charpoly) := (aeval_mod_by_monic_eq_self_of_root f.charpoly_monic f.aeval_self_charpoly).symm /-- Any endomorphism power can be computed as the sum of endomorphism powers less than the dimension of the module. -/ lemma pow_eq_aeval_mod_charpoly (k : ℕ) : f^k = aeval f (X^k %ₘ f.charpoly) := by rw [←aeval_eq_aeval_mod_charpoly, map_pow, aeval_X] variable {f} lemma minpoly_coeff_zero_of_injective (hf : function.injective f) : (minpoly R f).coeff 0 ≠ 0 := begin intro h, obtain ⟨P, hP⟩ := X_dvd_iff.2 h, have hdegP : P.degree < (minpoly R f).degree, { rw [hP, mul_comm], refine degree_lt_degree_mul_X (λ h, _), rw [h, mul_zero] at hP, exact minpoly.ne_zero (is_integral f) hP }, have hPmonic : P.monic, { suffices : (minpoly R f).monic, { rwa [monic.def, hP, mul_comm, leading_coeff_mul_X, ← monic.def] at this }, exact minpoly.monic (is_integral f) }, have hzero : aeval f (minpoly R f) = 0 := minpoly.aeval _ _, simp only [hP, mul_eq_comp, ext_iff, hf, aeval_X, map_eq_zero_iff, coe_comp, alg_hom.map_mul, zero_apply] at hzero, exact not_le.2 hdegP (minpoly.min _ _ hPmonic (ext hzero)), end end cayley_hamilton end linear_map
d799ac4b4561e90a7c348b094ae531c3ec83a987
4727251e0cd73359b15b664c3170e5d754078599
/src/data/pfunctor/univariate/basic.lean
fb0e3efaa3844dab53c23aa949270bac54c03919
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
6,306
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.W.basic /-! # Polynomial functors This file defines polynomial functors and the W-type construction as a polynomial functor. (For the M-type construction, see pfunctor/M.lean.) -/ universe u /-- A polynomial functor `P` is given by a type `A` and a family `B` of types over `A`. `P` maps any type `α` to a new type `P.obj α`, which is defined as the sigma type `Σ x, P.B x → α`. An element of `P.obj α` is a pair `⟨a, f⟩`, where `a` is an element of a type `A` and `f : B a → α`. Think of `a` as the shape of the object and `f` as an index to the relevant elements of `α`. -/ structure pfunctor := (A : Type u) (B : A → Type u) namespace pfunctor instance : inhabited pfunctor := ⟨⟨default, default⟩⟩ variables (P : pfunctor) {α β : Type u} /-- Applying `P` to an object of `Type` -/ def obj (α : Type*) := Σ x : P.A, P.B x → α /-- Applying `P` to a morphism of `Type` -/ def map {α β : Type*} (f : α → β) : P.obj α → P.obj β := λ ⟨a, g⟩, ⟨a, f ∘ g⟩ instance obj.inhabited [inhabited P.A] [inhabited α] : inhabited (P.obj α) := ⟨ ⟨ default, λ _, default ⟩ ⟩ instance : functor P.obj := {map := @map P} protected theorem map_eq {α β : Type*} (f : α → β) (a : P.A) (g : P.B a → α) : @functor.map P.obj _ _ _ f ⟨a, g⟩ = ⟨a, f ∘ g⟩ := rfl protected theorem id_map {α : Type*} : ∀ x : P.obj α, id <$> x = id x := λ ⟨a, b⟩, rfl protected theorem comp_map {α β γ : Type*} (f : α → β) (g : β → γ) : ∀ x : P.obj α, (g ∘ f) <$> x = g <$> (f <$> x) := λ ⟨a, b⟩, rfl instance : is_lawful_functor P.obj := {id_map := @pfunctor.id_map P, comp_map := @pfunctor.comp_map P} /-- re-export existing definition of W-types and adapt it to a packaged definition of polynomial functor -/ def W := _root_.W_type P.B /- inhabitants of W types is awkward to encode as an instance assumption because there needs to be a value `a : P.A` such that `P.B a` is empty to yield a finite tree -/ attribute [nolint has_inhabited_instance] W variables {P} /-- root element of a W tree -/ def W.head : W P → P.A | ⟨a, f⟩ := a /-- children of the root of a W tree -/ def W.children : Π x : W P, P.B (W.head x) → W P | ⟨a, f⟩ := f /-- destructor for W-types -/ def W.dest : W P → P.obj (W P) | ⟨a, f⟩ := ⟨a, f⟩ /-- constructor for W-types -/ def W.mk : P.obj (W P) → W P | ⟨a, f⟩ := ⟨a, f⟩ @[simp] theorem W.dest_mk (p : P.obj (W P)) : W.dest (W.mk p) = p := by cases p; reflexivity @[simp] theorem W.mk_dest (p : W P) : W.mk (W.dest p) = p := by cases p; reflexivity variables (P) /-- `Idx` identifies a location inside the application of a pfunctor. For `F : pfunctor`, `x : F.obj α` and `i : F.Idx`, `i` can designate one part of `x` or is invalid, if `i.1 ≠ x.1` -/ def Idx := Σ x : P.A, P.B x instance Idx.inhabited [inhabited P.A] [inhabited (P.B default)] : inhabited P.Idx := ⟨ ⟨default, default⟩ ⟩ variables {P} /-- `x.iget i` takes the component of `x` designated by `i` if any is or returns a default value -/ def obj.iget [decidable_eq P.A] {α} [inhabited α] (x : P.obj α) (i : P.Idx) : α := if h : i.1 = x.1 then x.2 (cast (congr_arg _ h) i.2) else default @[simp] lemma fst_map {α β : Type u} (x : P.obj α) (f : α → β) : (f <$> x).1 = x.1 := by { cases x; refl } @[simp] lemma iget_map [decidable_eq P.A] {α β : Type u} [inhabited α] [inhabited β] (x : P.obj α) (f : α → β) (i : P.Idx) (h : i.1 = x.1) : (f <$> x).iget i = f (x.iget i) := by { simp only [obj.iget, fst_map, *, dif_pos, eq_self_iff_true], cases x, refl } end pfunctor /- Composition of polynomial functors. -/ namespace pfunctor /-- functor composition for polynomial functors -/ def comp (P₂ P₁ : pfunctor.{u}) : pfunctor.{u} := ⟨ Σ a₂ : P₂.1, P₂.2 a₂ → P₁.1, λ a₂a₁, Σ u : P₂.2 a₂a₁.1, P₁.2 (a₂a₁.2 u) ⟩ /-- constructor for composition -/ def comp.mk (P₂ P₁ : pfunctor.{u}) {α : Type} (x : P₂.obj (P₁.obj α)) : (comp P₂ P₁).obj α := ⟨ ⟨ x.1, sigma.fst ∘ x.2 ⟩, λ a₂a₁, (x.2 a₂a₁.1).2 a₂a₁.2 ⟩ /-- destructor for composition -/ def comp.get (P₂ P₁ : pfunctor.{u}) {α : Type} (x : (comp P₂ P₁).obj α) : P₂.obj (P₁.obj α) := ⟨ x.1.1, λ a₂, ⟨x.1.2 a₂, λ a₁, x.2 ⟨a₂,a₁⟩ ⟩ ⟩ end pfunctor /- Lifting predicates and relations. -/ namespace pfunctor variables {P : pfunctor.{u}} open functor theorem liftp_iff {α : Type u} (p : α → Prop) (x : P.obj α) : liftp p x ↔ ∃ a f, x = ⟨a, f⟩ ∧ ∀ i, p (f i) := begin split, { rintros ⟨y, hy⟩, cases h : y with a f, refine ⟨a, λ i, (f i).val, _, λ i, (f i).property⟩, rw [←hy, h, pfunctor.map_eq] }, rintros ⟨a, f, xeq, pf⟩, use ⟨a, λ i, ⟨f i, pf i⟩⟩, rw [xeq], reflexivity end theorem liftp_iff' {α : Type u} (p : α → Prop) (a : P.A) (f : P.B a → α) : @liftp.{u} P.obj _ α p ⟨a,f⟩ ↔ ∀ i, p (f i) := begin simp only [liftp_iff, sigma.mk.inj_iff]; split; intro, { casesm* [Exists _, _ ∧ _], subst_vars, assumption }, repeat { constructor <|> assumption } end theorem liftr_iff {α : Type u} (r : α → α → Prop) (x y : P.obj α) : liftr r x y ↔ ∃ a f₀ f₁, x = ⟨a, f₀⟩ ∧ y = ⟨a, f₁⟩ ∧ ∀ i, r (f₀ i) (f₁ i) := begin split, { rintros ⟨u, xeq, yeq⟩, cases h : u with a f, use [a, λ i, (f i).val.fst, λ i, (f i).val.snd], split, { rw [←xeq, h], refl }, split, { rw [←yeq, h], refl }, intro i, exact (f i).property }, rintros ⟨a, f₀, f₁, xeq, yeq, h⟩, use ⟨a, λ i, ⟨(f₀ i, f₁ i), h i⟩⟩, split, { rw [xeq], refl }, rw [yeq], refl end open set theorem supp_eq {α : Type u} (a : P.A) (f : P.B a → α) : @supp.{u} P.obj _ α (⟨a,f⟩ : P.obj α) = f '' univ := begin ext, simp only [supp, image_univ, mem_range, mem_set_of_eq], split; intro h, { apply @h (λ x, ∃ (y : P.B a), f y = x), rw liftp_iff', intro, refine ⟨_,rfl⟩ }, { simp only [liftp_iff'], cases h, subst x, tauto } end end pfunctor
281d2ed12dce5c5510eec1aa4ca59f5580576723
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/eq22.lean
dd313877ed71036c34e5e5e2ca8dc640454a2f5c
[ "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
248
lean
import data.list open list definition head {A : Type} : Π (l : list A), l ≠ nil → A | head nil h := absurd rfl h | head (a :: l) _ := a theorem head_cons {A : Type} (a : A) (l : list A) (h : a :: l ≠ nil) : head (a :: l) h = a := rfl
e29d76eddf75049dff6e1d63cf5c040a3426a240
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/run/tactic11.lean
f5c0df5985e77839d2d7b381bdac419649099e10
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
537
lean
import logic theorem tst (a b : Prop) (H : a ↔ b) : b ↔ a := have H1 [visible] : a → b, -- We need to mark H1 as fact, otherwise it is not visible by tactics from iff.elim_left H, by apply iff.intro; intro Hb; apply (iff.elim_right H Hb); intro Ha; apply (H1 Ha) theorem tst2 (a b : Prop) (H : a ↔ b) : b ↔ a := have H1 [visible] : a → b, from iff.elim_left H, begin apply iff.intro, intro Hb; apply (iff.elim_right H Hb), intro Ha; apply (H1 Ha) end
d46ae7ffd2a9566a270950b4d026386fa9e4e905
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/maps.lean
979f7b47509ded2eaee453cc00eda7dd06e9adcc
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
15,704
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.order /-! # Specific classes of maps between topological spaces This file introduces the following properties of a map `f : X → Y` between topological spaces: * `is_open_map f` means the image of an open set under `f` is open. * `is_closed_map f` means the image of a closed set under `f` is closed. (Open and closed maps need not be continuous.) * `inducing f` means the topology on `X` is the one induced via `f` from the topology on `Y`. These behave like embeddings except they need not be injective. Instead, points of `X` which are identified by `f` are also indistinguishable in the topology on `X`. * `embedding f` means `f` is inducing and also injective. Equivalently, `f` identifies `X` with a subspace of `Y`. * `open_embedding f` means `f` is an embedding with open image, so it identifies `X` with an open subspace of `Y`. Equivalently, `f` is an embedding and an open map. * `closed_embedding f` similarly means `f` is an embedding with closed image, so it identifies `X` with a closed subspace of `Y`. Equivalently, `f` is an embedding and a closed map. * `quotient_map f` is the dual condition to `embedding f`: `f` is surjective and the topology on `Y` is the one coinduced via `f` from the topology on `X`. Equivalently, `f` identifies `Y` with a quotient of `X`. Quotient maps are also sometimes known as identification maps. ## References * <https://en.wikipedia.org/wiki/Open_and_closed_maps> * <https://en.wikipedia.org/wiki/Embedding#General_topology> * <https://en.wikipedia.org/wiki/Quotient_space_(topology)#Quotient_map> ## Tags open map, closed map, embedding, quotient map, identification map -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section inducing structure inducing [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := (induced : tα = tβ.induced f) variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma inducing_id : inducing (@id α) := ⟨induced_id.symm⟩ protected lemma inducing.comp {g : β → γ} {f : α → β} (hg : inducing g) (hf : inducing f) : inducing (g ∘ f) := ⟨by rw [hf.induced, hg.induced, induced_compose]⟩ lemma inducing_of_inducing_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : inducing (g ∘ f)) : inducing f := ⟨le_antisymm (by rwa ← continuous_iff_le_induced) (by { rw [hgf.induced, ← continuous_iff_le_induced], apply hg.comp continuous_induced_dom })⟩ lemma inducing_open {f : α → β} {s : set α} (hf : inducing f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.induced] at hs; exact hs in have is_open (t ∩ range f), from is_open_inter ht h, h_eq ▸ by rwa [image_preimage_eq_inter_range] lemma inducing_is_closed {f : α → β} {s : set α} (hf : inducing f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.induced, is_closed_induced_iff] at hs; exact hs in have is_closed (t ∩ range f), from is_closed_inter ht h, h_eq.symm ▸ by rwa [image_preimage_eq_inter_range] lemma inducing.nhds_eq_comap {f : α → β} (hf : inducing f) : ∀ (a : α), 𝓝 a = comap f (𝓝 $ f a) := (induced_iff_nhds_eq f).1 hf.induced lemma inducing.map_nhds_eq {f : α → β} (hf : inducing f) (a : α) (h : range f ∈ 𝓝 (f a)) : (𝓝 a).map f = 𝓝 (f a) := hf.induced.symm ▸ map_nhds_induced_eq h lemma inducing.tendsto_nhds_iff {ι : Type*} {f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : inducing g) : tendsto f a (𝓝 b) ↔ tendsto (g ∘ f) a (𝓝 (g b)) := by rw [tendsto, tendsto, hg.induced, nhds_induced, ← map_le_iff_le_comap, filter.map_map] lemma inducing.continuous_iff {f : α → β} {g : β → γ} (hg : inducing g) : continuous f ↔ continuous (g ∘ f) := by simp [continuous_iff_continuous_at, continuous_at, inducing.tendsto_nhds_iff hg] lemma inducing.continuous {f : α → β} (hf : inducing f) : continuous f := hf.continuous_iff.mp continuous_id end inducing section embedding /-- A function between topological spaces is an embedding if it is injective, and for all `s : set α`, `s` is open iff it is the preimage of an open set. -/ structure embedding [tα : topological_space α] [tβ : topological_space β] (f : α → β) extends inducing f : Prop := (inj : function.injective f) variables [topological_space α] [topological_space β] [topological_space γ] lemma embedding.mk' (f : α → β) (inj : function.injective f) (induced : ∀a, comap f (𝓝 (f a)) = 𝓝 a) : embedding f := ⟨⟨(induced_iff_nhds_eq f).2 (λ a, (induced a).symm)⟩, inj⟩ lemma embedding_id : embedding (@id α) := ⟨inducing_id, assume a₁ a₂ h, h⟩ lemma embedding.comp {g : β → γ} {f : α → β} (hg : embedding g) (hf : embedding f) : embedding (g ∘ f) := { inj:= assume a₁ a₂ h, hf.inj $ hg.inj h, ..hg.to_inducing.comp hf.to_inducing } lemma embedding_of_embedding_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : embedding (g ∘ f)) : embedding f := { induced := (inducing_of_inducing_compose hf hg hgf.to_inducing).induced, inj := assume a₁ a₂ h, hgf.inj $ by simp [h, (∘)] } lemma embedding_open {f : α → β} {s : set α} (hf : embedding f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) := inducing_open hf.1 h hs lemma embedding_is_closed {f : α → β} {s : set α} (hf : embedding f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) := inducing_is_closed hf.1 h hs lemma embedding.map_nhds_eq {f : α → β} (hf : embedding f) (a : α) (h : range f ∈ 𝓝 (f a)) : (𝓝 a).map f = 𝓝 (f a) := inducing.map_nhds_eq hf.1 a h lemma embedding.tendsto_nhds_iff {ι : Type*} {f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : embedding g) : tendsto f a (𝓝 b) ↔ tendsto (g ∘ f) a (𝓝 (g b)) := by rw [tendsto, tendsto, hg.induced, nhds_induced, ← map_le_iff_le_comap, filter.map_map] lemma embedding.continuous_iff {f : α → β} {g : β → γ} (hg : embedding g) : continuous f ↔ continuous (g ∘ f) := inducing.continuous_iff hg.1 lemma embedding.continuous {f : α → β} (hf : embedding f) : continuous f := inducing.continuous hf.1 lemma embedding.closure_eq_preimage_closure_image {e : α → β} (he : embedding e) (s : set α) : closure s = e ⁻¹' closure (e '' s) := by { ext x, rw [set.mem_preimage, ← closure_induced he.inj, he.induced] } end embedding /-- A function between topological spaces is a quotient map if it is surjective, and for all `s : set β`, `s` is open iff its preimage is an open set. -/ def quotient_map {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := function.surjective f ∧ tβ = tα.coinduced f namespace quotient_map variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] protected lemma id : quotient_map (@id α) := ⟨assume a, ⟨a, rfl⟩, coinduced_id.symm⟩ protected lemma comp {g : β → γ} {f : α → β} (hg : quotient_map g) (hf : quotient_map f) : quotient_map (g ∘ f) := ⟨function.surjective_comp hg.left hf.left, by rw [hg.right, hf.right, coinduced_compose]⟩ protected lemma of_quotient_map_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : quotient_map (g ∘ f)) : quotient_map g := ⟨assume b, let ⟨a, h⟩ := hgf.left b in ⟨f a, h⟩, le_antisymm (by rw [hgf.right, ← continuous_iff_coinduced_le]; apply continuous_coinduced_rng.comp hf) (by rwa ← continuous_iff_coinduced_le)⟩ protected lemma continuous_iff {f : α → β} {g : β → γ} (hf : quotient_map f) : continuous g ↔ continuous (g ∘ f) := by rw [continuous_iff_coinduced_le, continuous_iff_coinduced_le, hf.right, coinduced_compose] protected lemma continuous {f : α → β} (hf : quotient_map f) : continuous f := hf.continuous_iff.mp continuous_id end quotient_map /-- A map `f : α → β` is said to be an *open map*, if the image of any open `U : set α` is open in `β`. -/ def is_open_map [topological_space α] [topological_space β] (f : α → β) := ∀ U : set α, is_open U → is_open (f '' U) namespace is_open_map variables [topological_space α] [topological_space β] [topological_space γ] open function protected lemma id : is_open_map (@id α) := assume s hs, by rwa [image_id] protected lemma comp {g : β → γ} {f : α → β} (hg : is_open_map g) (hf : is_open_map f) : is_open_map (g ∘ f) := by intros s hs; rw [image_comp]; exact hg _ (hf _ hs) lemma is_open_range {f : α → β} (hf : is_open_map f) : is_open (range f) := by { rw ← image_univ, exact hf _ is_open_univ } lemma image_mem_nhds {f : α → β} (hf : is_open_map f) {x : α} {s : set α} (hx : s ∈ 𝓝 x) : f '' s ∈ 𝓝 (f x) := let ⟨t, hts, ht, hxt⟩ := mem_nhds_sets_iff.1 hx in mem_sets_of_superset (mem_nhds_sets (hf t ht) (mem_image_of_mem _ hxt)) (image_subset _ hts) lemma nhds_le {f : α → β} (hf : is_open_map f) (a : α) : 𝓝 (f a) ≤ (𝓝 a).map f := le_map $ λ s, hf.image_mem_nhds lemma of_inverse {f : α → β} {f' : β → α} (h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') : is_open_map f := assume s hs, have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv], this ▸ h s hs lemma to_quotient_map {f : α → β} (open_map : is_open_map f) (cont : continuous f) (surj : function.surjective f) : quotient_map f := ⟨ surj, begin ext s, show is_open s ↔ is_open (f ⁻¹' s), split, { exact cont s }, { assume h, rw ← @image_preimage_eq _ _ _ s surj, exact open_map _ h } end⟩ end is_open_map lemma is_open_map_iff_nhds_le [topological_space α] [topological_space β] {f : α → β} : is_open_map f ↔ ∀(a:α), 𝓝 (f a) ≤ (𝓝 a).map f := begin refine ⟨λ hf, hf.nhds_le, λ h s hs, is_open_iff_mem_nhds.2 _⟩, rintros b ⟨a, ha, rfl⟩, exact h _ (filter.image_mem_map $ mem_nhds_sets hs ha) end section is_closed_map variables [topological_space α] [topological_space β] def is_closed_map (f : α → β) := ∀ U : set α, is_closed U → is_closed (f '' U) end is_closed_map namespace is_closed_map variables [topological_space α] [topological_space β] [topological_space γ] open function protected lemma id : is_closed_map (@id α) := assume s hs, by rwa image_id protected lemma comp {g : β → γ} {f : α → β} (hg : is_closed_map g) (hf : is_closed_map f) : is_closed_map (g ∘ f) := by { intros s hs, rw image_comp, exact hg _ (hf _ hs) } lemma of_inverse {f : α → β} {f' : β → α} (h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') : is_closed_map f := assume s hs, have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv], this ▸ continuous_iff_is_closed.mp h s hs end is_closed_map section open_embedding variables [topological_space α] [topological_space β] [topological_space γ] /-- An open embedding is an embedding with open image. -/ structure open_embedding (f : α → β) extends embedding f : Prop := (open_range : is_open $ range f) lemma open_embedding.open_iff_image_open {f : α → β} (hf : open_embedding f) {s : set α} : is_open s ↔ is_open (f '' s) := ⟨embedding_open hf.to_embedding hf.open_range, λ h, begin convert ←hf.to_embedding.continuous _ h, apply preimage_image_eq _ hf.inj end⟩ lemma open_embedding.is_open_map {f : α → β} (hf : open_embedding f) : is_open_map f := λ s, hf.open_iff_image_open.mp lemma open_embedding.continuous {f : α → β} (hf : open_embedding f) : continuous f := hf.to_embedding.continuous lemma open_embedding.open_iff_preimage_open {f : α → β} (hf : open_embedding f) {s : set β} (hs : s ⊆ range f) : is_open s ↔ is_open (f ⁻¹' s) := begin convert ←hf.open_iff_image_open.symm, rwa [image_preimage_eq_inter_range, inter_eq_self_of_subset_left] end lemma open_embedding_of_embedding_open {f : α → β} (h₁ : embedding f) (h₂ : is_open_map f) : open_embedding f := ⟨h₁, by convert h₂ univ is_open_univ; simp⟩ lemma open_embedding_of_continuous_injective_open {f : α → β} (h₁ : continuous f) (h₂ : function.injective f) (h₃ : is_open_map f) : open_embedding f := begin refine open_embedding_of_embedding_open ⟨⟨_⟩, h₂⟩ h₃, apply le_antisymm (continuous_iff_le_induced.mp h₁) _, intro s, change is_open _ ≤ is_open _, rw is_open_induced_iff, refine λ hs, ⟨f '' s, h₃ s hs, _⟩, rw preimage_image_eq _ h₂ end lemma open_embedding_id : open_embedding (@id α) := ⟨embedding_id, by convert is_open_univ; apply range_id⟩ lemma open_embedding.comp {g : β → γ} {f : α → β} (hg : open_embedding g) (hf : open_embedding f) : open_embedding (g ∘ f) := ⟨hg.1.comp hf.1, show is_open (range (g ∘ f)), by rw [range_comp, ←hg.open_iff_image_open]; exact hf.2⟩ end open_embedding section closed_embedding variables [topological_space α] [topological_space β] [topological_space γ] /-- A closed embedding is an embedding with closed image. -/ structure closed_embedding (f : α → β) extends embedding f : Prop := (closed_range : is_closed $ range f) variables {f : α → β} lemma closed_embedding.continuous (hf : closed_embedding f) : continuous f := hf.to_embedding.continuous lemma closed_embedding.closed_iff_image_closed (hf : closed_embedding f) {s : set α} : is_closed s ↔ is_closed (f '' s) := ⟨embedding_is_closed hf.to_embedding hf.closed_range, λ h, begin convert ←continuous_iff_is_closed.mp hf.continuous _ h, apply preimage_image_eq _ hf.inj end⟩ lemma closed_embedding.is_closed_map (hf : closed_embedding f) : is_closed_map f := λ s, hf.closed_iff_image_closed.mp lemma closed_embedding.closed_iff_preimage_closed (hf : closed_embedding f) {s : set β} (hs : s ⊆ range f) : is_closed s ↔ is_closed (f ⁻¹' s) := begin convert ←hf.closed_iff_image_closed.symm, rwa [image_preimage_eq_inter_range, inter_eq_self_of_subset_left] end lemma closed_embedding_of_embedding_closed (h₁ : embedding f) (h₂ : is_closed_map f) : closed_embedding f := ⟨h₁, by convert h₂ univ is_closed_univ; simp⟩ lemma closed_embedding_of_continuous_injective_closed (h₁ : continuous f) (h₂ : function.injective f) (h₃ : is_closed_map f) : closed_embedding f := begin refine closed_embedding_of_embedding_closed ⟨⟨_⟩, h₂⟩ h₃, apply le_antisymm (continuous_iff_le_induced.mp h₁) _, intro s', change is_open _ ≤ is_open _, rw [←is_closed_compl_iff, ←is_closed_compl_iff], generalize : -s' = s, rw is_closed_induced_iff, refine λ hs, ⟨f '' s, h₃ s hs, _⟩, rw preimage_image_eq _ h₂ end lemma closed_embedding_id : closed_embedding (@id α) := ⟨embedding_id, by convert is_closed_univ; apply range_id⟩ lemma closed_embedding.comp {g : β → γ} {f : α → β} (hg : closed_embedding g) (hf : closed_embedding f) : closed_embedding (g ∘ f) := ⟨hg.to_embedding.comp hf.to_embedding, show is_closed (range (g ∘ f)), by rw [range_comp, ←hg.closed_iff_image_closed]; exact hf.closed_range⟩ end closed_embedding
65550f958e1074433861c29e8af3f8fcb88f2d18
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/lvl1.lean
68449f95fb1985243fcd5ef7e6385db96026e089
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,338
lean
import Init.Lean.Level namespace Lean namespace Level def mkMax (xs : Array Level) : Level := xs.foldlFrom mkLevelMax (xs.get! 0) 1 #eval toString $ normalize $ mkLevelSucc $ mkLevelSucc $ mkMax #[levelZero, mkLevelParam `w, mkLevelSucc (mkLevelSucc (mkLevelSucc (mkLevelParam `z))), levelOne, mkLevelSucc (mkLevelSucc (mkLevelParam `x)), levelZero, mkLevelParam `x, mkLevelParam `y, mkLevelParam `x, mkLevelParam `z, mkLevelSucc levelOne, mkLevelParam `w, mkLevelSucc (mkLevelParam `x)] #eval toString $ normalize $ mkLevelMax levelZero (mkLevelParam `x) #eval toString $ normalize $ mkLevelMax (mkLevelParam `x) levelZero #eval toString $ normalize $ mkLevelMax levelZero levelOne #eval toString $ normalize $ mkLevelSucc (mkLevelMax (mkLevelParam `x) (mkLevelParam `x)) #eval toString $ normalize $ mkLevelMax (mkLevelIMax (mkLevelParam `x) levelOne) (mkLevelMax (mkLevelSucc (mkLevelParam `x)) (mkLevelParam `x)) #eval toString $ normalize $ mkLevelIMax (mkLevelIMax (mkLevelParam `x) levelOne) (mkLevelMax (mkLevelSucc (mkLevelParam `x)) (mkLevelParam `x)) #eval toString $ #[levelZero, mkLevelSucc (mkLevelSucc (mkLevelParam `z)), levelOne, mkLevelSucc (mkLevelSucc (mkLevelParam `x)), levelZero, mkLevelParam `x, mkLevelParam `y, mkLevelParam `x, mkLevelParam `z, mkLevelSucc (mkLevelParam `x)].qsort normLt end Level end Lean
26eadecd52eb7158aa362d1b3fcf387341881ad4
baee66b4ec736ac53d31be2288b426225753edd4
/lean-project/src/definitions.lean
c45443bd87c974b243838d06cda2bb1efbf633d4
[]
no_license
jvap2/EUTXO-Lean
8c909a15aefb70bb0c7ba25ddf081ab4a5419e4d
c3fbfc33622b865b52d4cdc46198da1404304354
refs/heads/main
1,688,331,241,458
1,627,747,120,000
1,627,747,120,000
392,048,140
0
0
null
1,627,927,548,000
1,627,927,547,000
null
UTF-8
Lean
false
false
700
lean
import tactic -- Start by putting together the definitions for the model -- UTxO model first def Value : Type := sorry def Address : Type := sorry def Id : Type := sorry structure Input : Type := (id : Id) -- the index of a previous transaction to which this input refers (index : ℕ) -- indicates which of the referred transaction's outputs should be spent structure Output : Type := (address : Address) -- the address that owns this output (value : Value) -- the value of this output structure UTXO_transaction : Type := (inputs : set Input) (outputs : list Output) (forge : Value) (fee : Value) #check UTXO_transaction def Ledger := list UTXO_transaction
cfe2fc9993c22a1f24eb2392e4264df160e20218
c76cc4eaee3c806716844e49b5175747d1aa170a
/src/solutions_sheet_three.lean
db80b07512523932600ad18ede195a5baa6ab770
[]
no_license
ImperialCollegeLondon/M40002
0fb55848adbb0d8bc4a65ca5d7ed6edd18764c28
a499db70323bd5ccae954c680ec9afbf15ffacca
refs/heads/master
1,674,878,059,748
1,607,624,828,000
1,607,624,828,000
309,696,750
3
0
null
null
null
null
UTF-8
Lean
false
false
5,753
lean
import data.real.basic import data.pnat.basic import solutions_sheet_two local notation `|` x `|` := abs x def is_limit (a : ℕ+ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε def is_convergent (a : ℕ+ → ℝ) : Prop := ∃ l : ℝ, is_limit a l def is_not_convergent (a : ℕ+ → ℝ) : Prop := ¬ is_convergent a /-! # Q1 -/ /- Which of the following sequences are convergent and which are not? What's the limit of the convergent ones? -/ theorem Q1a : is_limit (λ n, (n+7)/n) 1 := begin intros ε hε, use (ceil ((37 : ℝ) / ε)).nat_abs, { apply int.nat_abs_pos_of_ne_zero, apply norm_num.ne_zero_of_pos, rw ceil_pos, refine div_pos _ hε, norm_num }, rintros ⟨n, hn0⟩ hn, simp only [pnat.mk_coe, coe_coe], rw add_div, rw div_self (show (n : ℝ) ≠ 0, by norm_cast; linarith), simp only [add_sub_cancel'], rw abs_lt, split, { refine lt_trans (show -ε < 0, by linarith) _, refine div_pos (by norm_num) _, assumption_mod_cast }, { rw div_lt_iff, swap, assumption_mod_cast, simp at hn, replace hn := le_trans int.le_nat_abs (int.coe_nat_le.mpr hn), rw ceil_le at hn, norm_cast at hn, rw div_le_iff hε at hn, linarith } end theorem Q1b : is_limit (λ n, n/(n+7)) 1 := begin sorry end theorem Q1c : is_limit (λ n, (n^2+5*n+6)/(n^3-2)) 0 := begin sorry end theorem Q1d : is_not_convergent (λ n, (n^3-2)/(n^2+5*n+6)) := begin sorry end def is_cauchy (a : ℕ+ → ℝ) : Prop := ∀ ε > 0, ∃ N : ℕ+, ∀ m n ≥ N, |a m - a n| < ε theorem is_cauchy_of_is_convergent {a : ℕ+ → ℝ} : is_convergent a → is_cauchy a := begin rintro ⟨l, hl⟩, intros ε hε, specialize hl (ε/2) (by linarith), rcases hl with ⟨B, hB1⟩, use B, intros m n hmB hnB, have hm := hB1 m hmB, have hn := hB1 n hnB, have h := abs_add (a m - l) (l - a n), have h2 : a m - l + (l - a n) = a m - a n := by ring, rw h2 at h, rw abs_sub l at h, linarith, end theorem Q1e : is_not_convergent (λ n, (1 - n*(-1)^n.1)/n) := begin intro h, replace h := is_cauchy_of_is_convergent h, -- 1/n + (-1)^{n+1} specialize h 0.1 (by linarith), cases h with N hN, have htemp : N ≤ N + 1, cases N with N hN, change N ≤ _, simp, specialize hN N (N + 1) (le_refl N) htemp, rw abs_lt at hN, dsimp only at hN, cases hN with hN1 hN2, cases N with N hN, simp at *, sorry end /-! # Q3 -/ /- Let a_n be a sequence converging to a ∈ ℝ. Suppose b_n is another sequence which is different than a_n but only differs from a_n in finitely many terms, that is the set {n : ℕ | a_n ≠ b_n} is non-empty and finite. Prove b_n converges to a -/ theorem Q3 (a : ℕ+ → ℝ) (b : ℕ+ → ℝ) (h_never_used : {n : ℕ+ | a n ≠ b n}.nonempty) (h : {n : ℕ+ | a n ≠ b n}.finite) (l : ℝ) (ha : is_limit a l) : is_limit b l := begin intros ε hε, cases ha ε hε with B hB, let S : finset ℕ+ := h.to_finset, have hS : S.nonempty, simp only [h_never_used, set.finite.to_finset.nonempty], let m := finset.max' S hS, use max B (m + 1), intros n hn, convert hB n _, { suffices : n ∉ {n | a n ≠ b n}, symmetry, by_contra htemp, apply this, exact htemp, intro htemp, have hS : n ∈ S, simp [htemp], exact htemp, have ZZZ : n ≤ m := finset.le_max' S n hS, change max _ _ ≤ n at hn, rw max_le_iff at hn, cases hn, have YYY := le_trans hn_right ZZZ, change m.1 + 1 ≤ m.1 at YYY, linarith }, change _ ≤ _ at hn, rw max_le_iff at hn, exact hn.1, end /-! # Q4 -/ /- Let S ⊆ ℝ be a nonempty bounded above set. show that there exists a sequence of numbers s_n ∈ S, n = 1, 2, 3,… such that sₙ → Sup S -/ --theorem useful_lemma {S : set ℝ} {a : ℝ} (haS : is_lub S a) (t : ℝ) -- (ht : t < a) : ∃ s, s ∈ S ∧ t < s := theorem useful_lemma2 (S : set ℝ) (hS1 : S.nonempty) (hS2 : bdd_above S) : is_lub S (Sup S) := begin cases hS1 with a ha, cases hS2 with b hb, apply real.is_lub_Sup ha hb, end theorem pnat_aux_lemma {ε : ℝ} (hε : 0 < ε) {a : ℝ} (ha : 0 < a) : 0 < ⌈a / ε⌉.nat_abs := begin apply int.nat_abs_pos_of_ne_zero, apply norm_num.ne_zero_of_pos, rw ceil_pos, refine div_pos _ hε, exact ha, end theorem Q4 (S : set ℝ) (hS1 : S.nonempty) (hS2 : bdd_above S) : ∃ s : ℕ+ → ℝ, (∀ n, s n ∈ S) ∧ is_limit s (Sup S) := begin have h := useful_lemma (useful_lemma2 S hS1 hS2), -- by_contra h2, -- unfold is_limit at h2, -- push_neg at h2, let s : ℕ+ → ℝ := λ n, classical.some (h (Sup S - 1/n) (show Sup S - 1/n < Sup S, from _)), have hs : ∀ n : ℕ+, _ := λ n, classical.some_spec (h (Sup S - 1/n) (show Sup S - 1/n < Sup S, from _)), use s, swap, { cases n with n hn, rw sub_lt_self_iff, rw one_div_pos, simp [hn] }, have hs2 : ∀ (n : ℕ+), s n ∈ S, { intro n, dsimp at hs, exact (hs n).1 }, use hs2, intros ε hε, use (ceil (2/ε)).nat_abs, exact pnat_aux_lemma hε (show (0 : ℝ) < 2, by norm_num), intros n hn, have hn2 : Sup S - 1/n < s n, exact (hs n).2, rw sub_lt at hn2, have hS3 := useful_lemma2 S hS1 hS2, rw abs_lt, split, { suffices : (1 : ℝ) / n < ε, linarith, cases n with n hn3, -- show (1 : ℝ) / n < _, rw div_lt_iff (show 0 < (n : ℝ), by assumption_mod_cast), simp at hn, replace hn := le_trans (int.le_nat_abs) (int.coe_nat_le.mpr hn), rw ceil_le at hn, norm_cast at hn, rw div_le_iff at hn; linarith }, { refine lt_of_le_of_lt _ hε, specialize hs2 n, rw sub_nonpos, cases hS3 with hS4 hS5, apply hS4 hs2 }, end
2cb5e872329dc196b708127b51d3331e3ebe9119
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Elab/Syntax.lean
a539d08bf6884324472da4dda54e103e58036bc6
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,319
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 import Init.Lean.Elab.Command import Init.Lean.Elab.Quotation namespace Lean namespace Elab namespace Term /- Expand `optional «precedence»` where «precedence» := parser! " : " >> precedenceLit precedenceLit : Parser := numLit <|> maxPrec maxPrec := parser! nonReservedSymbol "max" -/ private def expandOptPrecedence (stx : Syntax) : Option Nat := if stx.isNone then none else match ((stx.getArg 0).getArg 1).isNatLit? with | some v => some v | _ => some Parser.appPrec private def mkParserSeq (ds : Array Syntax) : TermElabM Syntax := if ds.size == 0 then throwUnsupportedSyntax else if ds.size == 1 then pure $ ds.get! 0 else ds.foldlFromM (fun r d => `(ParserDescr.andthen $r $d)) (ds.get! 0) 1 structure ToParserDescrContext := (catName : Name) (first : Bool) (leftRec : Bool) -- true iff left recursion is allowed /- When `leadingIdentAsSymbol == true` we convert `Lean.Parser.Syntax.atom` into `Lean.ParserDescr.nonReservedSymbol` See comment at `Parser.ParserCategory`. -/ (leadingIdentAsSymbol : Bool) abbrev ToParserDescrM := ReaderT ToParserDescrContext (StateT Bool TermElabM) private def markAsTrailingParser : ToParserDescrM Unit := set true @[inline] private def withNotFirst {α} (x : ToParserDescrM α) : ToParserDescrM α := adaptReader (fun (ctx : ToParserDescrContext) => { ctx with first := false }) x @[inline] private def withoutLeftRec {α} (x : ToParserDescrM α) : ToParserDescrM α := adaptReader (fun (ctx : ToParserDescrContext) => { ctx with leftRec := false }) x def checkLeftRec (stx : Syntax) : ToParserDescrM Bool := do ctx ← read; if ctx.first && stx.getKind == `Lean.Parser.Syntax.cat then do let cat := (stx.getIdAt 0).eraseMacroScopes; if cat == ctx.catName then do let rbp? : Option Nat := expandOptPrecedence (stx.getArg 1); unless rbp?.isNone $ liftM $ throwError (stx.getArg 1) ("invalid occurrence of ':<num>' modifier in head"); unless ctx.leftRec $ liftM $ throwError (stx.getArg 3) ("invalid occurrence of '" ++ cat ++ "', parser algorithm does not allow this form of left recursion"); markAsTrailingParser; -- mark as trailing par pure true else pure false else pure false partial def toParserDescrAux : Syntax → ToParserDescrM Syntax | stx => let kind := stx.getKind; if kind == nullKind then do let args := stx.getArgs; condM (checkLeftRec (stx.getArg 0)) (do when (args.size == 1) $ liftM $ throwError stx "invalid atomic left recursive syntax"; let args := args.eraseIdx 0; args ← args.mapIdxM $ fun i arg => withNotFirst $ toParserDescrAux arg; liftM $ mkParserSeq args) (do args ← args.mapIdxM $ fun i arg => withNotFirst $ toParserDescrAux arg; liftM $ mkParserSeq args) else if kind == choiceKind then do toParserDescrAux (stx.getArg 0) else if kind == `Lean.Parser.Syntax.paren then toParserDescrAux (stx.getArg 1) else if kind == `Lean.Parser.Syntax.cat then do let cat := (stx.getIdAt 0).eraseMacroScopes; ctx ← read; if ctx.first && cat == ctx.catName then liftM $ throwError stx "invalid atomic left recursive syntax" else do let rbp? : Option Nat := expandOptPrecedence (stx.getArg 1); env ← liftM getEnv; unless (Parser.isParserCategory env cat) $ liftM $ throwError (stx.getArg 3) ("unknown category '" ++ cat ++ "'"); let rbp := rbp?.getD 0; `(ParserDescr.parser $(quote cat) $(quote rbp)) else if kind == `Lean.Parser.Syntax.atom then do match (stx.getArg 0).isStrLit? with | some atom => do let rbp? : Option Nat := expandOptPrecedence (stx.getArg 1); ctx ← read; if ctx.leadingIdentAsSymbol && rbp?.isNone then `(ParserDescr.nonReservedSymbol $(quote atom) false) else `(ParserDescr.symbol $(quote atom) $(quote rbp?)) | none => liftM throwUnsupportedSyntax else if kind == `Lean.Parser.Syntax.num then `(ParserDescr.numLit) else if kind == `Lean.Parser.Syntax.str then `(ParserDescr.strLit) else if kind == `Lean.Parser.Syntax.char then `(ParserDescr.charLit) else if kind == `Lean.Parser.Syntax.ident then `(ParserDescr.ident) else if kind == `Lean.Parser.Syntax.try then do d ← withoutLeftRec $ toParserDescrAux (stx.getArg 1); `(ParserDescr.try $d) else if kind == `Lean.Parser.Syntax.lookahead then do d ← withoutLeftRec $ toParserDescrAux (stx.getArg 1); `(ParserDescr.lookahead $d) else if kind == `Lean.Parser.Syntax.sepBy then do d₁ ← withoutLeftRec $ toParserDescrAux (stx.getArg 1); d₂ ← withoutLeftRec $ toParserDescrAux (stx.getArg 2); `(ParserDescr.sepBy $d₁ $d₂) else if kind == `Lean.Parser.Syntax.sepBy1 then do d₁ ← withoutLeftRec $ toParserDescrAux (stx.getArg 1); d₂ ← withoutLeftRec $ toParserDescrAux (stx.getArg 2); `(ParserDescr.sepBy1 $d₁ $d₂) else if kind == `Lean.Parser.Syntax.many then do d ← withoutLeftRec $ toParserDescrAux (stx.getArg 0); `(ParserDescr.many $d) else if kind == `Lean.Parser.Syntax.many1 then do d ← withoutLeftRec $ toParserDescrAux (stx.getArg 0); `(ParserDescr.many1 $d) else if kind == `Lean.Parser.Syntax.optional then do d ← withoutLeftRec $ toParserDescrAux (stx.getArg 0); `(ParserDescr.optional $d) else if kind == `Lean.Parser.Syntax.orelse then do d₁ ← withoutLeftRec $ toParserDescrAux (stx.getArg 0); d₂ ← withoutLeftRec $ toParserDescrAux (stx.getArg 2); `(ParserDescr.orelse $d₁ $d₂) else liftM $ throwError stx $ "unexpected syntax kind of category `syntax`: " ++ kind /-- Given a `stx` of category `syntax`, return a pair `(newStx, trailingParser)`, where `newStx` is of category `term`. After elaboration, `newStx` should have type `TrailingParserDescr` if `trailingParser == true`, and `ParserDescr` otherwise. -/ def toParserDescr (stx : Syntax) (catName : Name) : TermElabM (Syntax × Bool) := do env ← getEnv; let leadingIdentAsSymbol := Parser.leadingIdentAsSymbol env catName; (toParserDescrAux stx { catName := catName, first := true, leftRec := true, leadingIdentAsSymbol := leadingIdentAsSymbol }).run false end Term namespace Command @[builtinCommandElab syntaxCat] def elabDeclareSyntaxCat : CommandElab := fun stx => do let catName := stx.getIdAt 1; let attrName := catName.appendAfter "Parser"; env ← getEnv; env ← liftIO stx $ Parser.registerParserCategory env attrName catName; setEnv env def mkKindName (catName : Name) : Name := `_kind ++ catName def mkFreshKind (catName : Name) : CommandElabM Name := do scp ← getCurrMacroScope; mainModule ← getMainModule; pure $ Lean.addMacroScope mainModule (mkKindName catName) scp def Macro.mkFreshKind (catName : Name) : MacroM Name := Macro.addMacroScope (mkKindName catName) private def elabKind (stx : Syntax) (catName : Name) : CommandElabM Name := do if stx.isNone then mkFreshKind catName else let kind := stx.getIdAt 1; if kind.hasMacroScopes then pure kind else do currNamespace ← getCurrNamespace; pure (currNamespace ++ kind) @[builtinCommandElab «syntax»] def elabSyntax : CommandElab := fun stx => do env ← getEnv; let cat := (stx.getIdAt 4).eraseMacroScopes; unless (Parser.isParserCategory env cat) $ throwError (stx.getArg 4) ("unknown category '" ++ cat ++ "'"); kind ← elabKind (stx.getArg 1) cat; let catParserId := mkIdentFrom stx (cat.appendAfter "Parser"); (val, trailingParser) ← runTermElabM none $ fun _ => Term.toParserDescr (stx.getArg 2) cat; d ← if trailingParser then `(@[$catParserId:ident] def myParser : Lean.TrailingParserDescr := ParserDescr.trailingNode $(quote kind) $val) else `(@[$catParserId:ident] def myParser : Lean.ParserDescr := ParserDescr.node $(quote kind) $val); trace `Elab stx $ fun _ => d; withMacroExpansion stx d $ elabCommand d def elabMacroRulesAux (k : SyntaxNodeKind) (alts : Array Syntax) : CommandElabM Syntax := do alts ← alts.mapSepElemsM $ fun alt => do { let lhs := alt.getArg 0; let pat := lhs.getArg 0; match_syntax pat with | `(`($quot)) => let k' := quot.getKind; if k' == k then pure alt else if k' == choiceKind then do match quot.getArgs.find? $ fun quotAlt => quotAlt.getKind == k with | none => throwError alt ("invalid macro_rules alternative, expected syntax node kind '" ++ k ++ "'") | some quot => do pat ← `(`($quot)); let lhs := lhs.setArg 0 pat; pure $ alt.setArg 0 lhs else throwError alt ("invalid macro_rules alternative, unexpected syntax node kind '" ++ k' ++ "'") | stx => throwUnsupportedSyntax }; `(@[macro $(Lean.mkIdent k)] def myMacro : Macro := fun stx => match_syntax stx with $alts:matchAlt* | _ => throw Lean.Macro.Exception.unsupportedSyntax) def inferMacroRulesAltKind (alt : Syntax) : CommandElabM SyntaxNodeKind := match_syntax (alt.getArg 0).getArg 0 with | `(`($quot)) => pure quot.getKind | stx => throwUnsupportedSyntax def elabNoKindMacroRulesAux (alts : Array Syntax) : CommandElabM Syntax := do k ← inferMacroRulesAltKind (alts.get! 0); if k == choiceKind then throwError (alts.get! 0) "invalid macro_rules alternative, multiple interpretations for pattern (solution: specify node kind using `macro_rules [<kind>] ...`)" else do altsK ← alts.filterSepElemsM (fun alt => do k' ← inferMacroRulesAltKind alt; pure $ k == k'); altsNotK ← alts.filterSepElemsM (fun alt => do k' ← inferMacroRulesAltKind alt; pure $ k != k'); defCmd ← elabMacroRulesAux k altsK; if altsNotK.isEmpty then pure defCmd else `($defCmd:command macro_rules $altsNotK:matchAlt*) @[builtinCommandElab «macro_rules»] def elabMacroRules : CommandElab := adaptExpander $ fun stx => match_syntax stx with | `(macro_rules $alts:matchAlt*) => elabNoKindMacroRulesAux alts | `(macro_rules | $alts:matchAlt*) => elabNoKindMacroRulesAux alts | `(macro_rules [$kind] $alts:matchAlt*) => elabMacroRulesAux kind.getId alts | `(macro_rules [$kind] | $alts:matchAlt*) => elabMacroRulesAux kind.getId alts | _ => throwUnsupportedSyntax /- We just ignore Lean3 notation declaration commands. -/ @[builtinCommandElab «mixfix»] def elabMixfix : CommandElab := fun _ => pure () @[builtinCommandElab «reserve»] def elabReserve : CommandElab := fun _ => pure () /- Wrap all occurrences of the given `ident` nodes in antiquotations -/ private partial def antiquote (vars : Array Syntax) : Syntax → Syntax | stx => match_syntax stx with | `($id:ident) => if (vars.findIdx? (fun var => var.getId == id.getId)).isSome then Syntax.node `antiquot #[mkAtom "$", mkNullNode, id, mkNullNode, mkNullNode] else stx | _ => match stx with | Syntax.node k args => Syntax.node k (args.map antiquote) | stx => stx /- Convert `notation` command lhs item into a `syntax` command item -/ def expandNotationItemIntoSyntaxItem (stx : Syntax) : MacroM Syntax := let k := stx.getKind; if k == `Lean.Parser.Command.identPrec then pure $ Syntax.node `Lean.Parser.Syntax.cat #[mkIdentFrom stx `term, stx.getArg 1] else if k == `Lean.Parser.Command.quotedSymbolPrec then match (stx.getArg 0).getArg 1 with | Syntax.atom info val => pure $ Syntax.node `Lean.Parser.Syntax.atom #[mkStxStrLit val info, stx.getArg 1] | _ => Macro.throwUnsupported else if k == `Lean.Parser.Command.strLitPrec then pure $ Syntax.node `Lean.Parser.Syntax.atom stx.getArgs else Macro.throwUnsupported def strLitPrecToPattern (stx: Syntax) : MacroM Syntax := match (stx.getArg 0).isStrLit? with | some str => pure $ mkAtomFrom stx str | none => Macro.throwUnsupported /- Convert `notation` command lhs item a pattern element -/ def expandNotationItemIntoPattern (stx : Syntax) : MacroM Syntax := let k := stx.getKind; if k == `Lean.Parser.Command.identPrec then let item := stx.getArg 0; pure $ mkNode `antiquot #[mkAtom "$", mkNullNode, item, mkNullNode, mkNullNode] else if k == `Lean.Parser.Command.quotedSymbolPrec then pure $ (stx.getArg 0).getArg 1 else if k == `Lean.Parser.Command.strLitPrec then strLitPrecToPattern stx else Macro.throwUnsupported @[builtinMacro Lean.Parser.Command.notation] def expandNotation : Macro := fun stx => match_syntax stx with | `(notation $items* => $rhs) => do kind ← Macro.mkFreshKind `term; -- build parser syntaxParts ← items.mapM expandNotationItemIntoSyntaxItem; let cat := mkIdentFrom stx `term; -- build macro rules let vars := items.filter $ fun item => item.getKind == `Lean.Parser.Command.identPrec; let vars := vars.map $ fun var => var.getArg 0; let rhs := antiquote vars rhs; patArgs ← items.mapM expandNotationItemIntoPattern; let pat := Syntax.node kind patArgs; `(syntax [$(mkIdentFrom stx kind)] $syntaxParts* : $cat macro_rules | `($pat) => `($rhs)) | _ => Macro.throwUnsupported /- Convert `macro` argument into a `syntax` command item -/ def expandMacroArgIntoSyntaxItem (stx : Syntax) : MacroM Syntax := let k := stx.getKind; if k == `Lean.Parser.Command.macroArgSimple then let argType := stx.getArg 2; match argType with | Syntax.atom _ "ident" => pure $ Syntax.node `Lean.Parser.Syntax.ident #[argType] | Syntax.atom _ "num" => pure $ Syntax.node `Lean.Parser.Syntax.num #[argType] | Syntax.atom _ "str" => pure $ Syntax.node `Lean.Parser.Syntax.str #[argType] | Syntax.atom _ "char" => pure $ Syntax.node `Lean.Parser.Syntax.char #[argType] | Syntax.ident _ _ _ _ => pure $ Syntax.node `Lean.Parser.Syntax.cat #[stx.getArg 2, stx.getArg 3] | _ => Macro.throwUnsupported else if k == `Lean.Parser.Command.strLitPrec then pure $ Syntax.node `Lean.Parser.Syntax.atom stx.getArgs else Macro.throwUnsupported /- Convert `macro` head into a `syntax` command item -/ def expandMacroHeadIntoSyntaxItem (stx : Syntax) : MacroM Syntax := let k := stx.getKind; if k == `Lean.Parser.Command.identPrec then let info := stx.getHeadInfo.getD {}; let id := (stx.getArg 0).getId; pure $ Syntax.node `Lean.Parser.Syntax.atom #[mkStxStrLit (toString id) info, stx.getArg 1] else expandMacroArgIntoSyntaxItem stx /- Convert `macro` arg into a pattern element -/ def expandMacroArgIntoPattern (stx : Syntax) : MacroM Syntax := let k := stx.getKind; if k == `Lean.Parser.Command.macroArgSimple then let item := stx.getArg 0; pure $ mkNode `antiquot #[mkAtom "$", mkNullNode, item, mkNullNode, mkNullNode] else if k == `Lean.Parser.Command.strLitPrec then strLitPrecToPattern stx else Macro.throwUnsupported /- Convert `macro` head into a pattern element -/ def expandMacroHeadIntoPattern (stx : Syntax) : MacroM Syntax := let k := stx.getKind; if k == `Lean.Parser.Command.identPrec then let str := toString (stx.getArg 0).getId; pure $ mkAtomFrom stx str else expandMacroArgIntoPattern stx @[builtinMacro Lean.Parser.Command.macro] def expandMacro : Macro := fun stx => do let head := stx.getArg 1; let args := (stx.getArg 2).getArgs; let cat := stx.getArg 4; kind ← Macro.mkFreshKind (cat.getId).eraseMacroScopes; -- build parser stxPart ← expandMacroHeadIntoSyntaxItem head; stxParts ← args.mapM expandMacroArgIntoSyntaxItem; let stxParts := #[stxPart] ++ stxParts; -- build macro rules patHead ← expandMacroHeadIntoPattern head; patArgs ← args.mapM expandMacroArgIntoPattern; let pat := Syntax.node kind (#[patHead] ++ patArgs); if stx.getArgs.size == 7 then -- `stx` is of the form `macro $head $args* : $cat => term` let rhs := stx.getArg 6; `(syntax [$(mkIdentFrom stx kind)] $stxParts* : $cat macro_rules | `($pat) => $rhs) else -- `stx` is of the form `macro $head $args* : $cat => `( $body )` let rhsBody := stx.getArg 7; `(syntax [$(mkIdentFrom stx kind)] $stxParts* : $cat macro_rules | `($pat) => `($rhsBody)) @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.syntax; pure () end Command end Elab end Lean
60bd389e40f66529fa564570b15446603c88bfef
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/covering/besicovitch.lean
55bc5ce327c6e2dc0350311933bd353d32df9d1c
[ "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
60,352
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.covering.differentiation import measure_theory.covering.vitali_family import measure_theory.integral.lebesgue import measure_theory.measure.regular import set_theory.ordinal.arithmetic import topology.metric_space.basic /-! # Besicovitch covering theorems > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The topological Besicovitch covering theorem ensures that, in a nice metric space, there exists a number `N` such that, from any family of balls with bounded radii, one can extract `N` families, each made of disjoint balls, covering together all the centers of the initial family. By "nice metric space", we mean a technical property stated as follows: there exists no satellite configuration of `N + 1` points (with a given parameter `τ > 1`). Such a configuration is a family of `N + 1` balls, where the first `N` balls all intersect the last one, but none of them contains the center of another one and their radii are controlled. This property is for instance satisfied by finite-dimensional real vector spaces. In this file, we prove the topological Besicovitch covering theorem, in `besicovitch.exist_disjoint_covering_families`. The measurable Besicovitch theorem ensures that, in the same class of metric spaces, if at every point one considers a class of balls of arbitrarily small radii, called admissible balls, then one can cover almost all the space by a family of disjoint admissible balls. It is deduced from the topological Besicovitch theorem, and proved in `besicovitch.exists_disjoint_closed_ball_covering_ae`. This implies that balls of small radius form a Vitali family in such spaces. Therefore, theorems on differentiation of measures hold as a consequence of general results. We restate them in this context to make them more easily usable. ## Main definitions and results * `satellite_config α N τ` is the type of all satellite configurations of `N + 1` points in the metric space `α`, with parameter `τ`. * `has_besicovitch_covering` is a class recording that there exist `N` and `τ > 1` such that there is no satellite configuration of `N + 1` points with parameter `τ`. * `exist_disjoint_covering_families` is the topological Besicovitch covering theorem: from any family of balls one can extract finitely many disjoint subfamilies covering the same set. * `exists_disjoint_closed_ball_covering` is the measurable Besicovitch covering theorem: from any family of balls with arbitrarily small radii at every point, one can extract countably many disjoint balls covering almost all the space. While the value of `N` is relevant for the precise statement of the topological Besicovitch theorem, it becomes irrelevant for the measurable one. Therefore, this statement is expressed using the `Prop`-valued typeclass `has_besicovitch_covering`. We also restate the following specialized versions of general theorems on differentiation of measures: * `besicovitch.ae_tendsto_rn_deriv` ensures that `ρ (closed_ball x r) / μ (closed_ball x r)` tends almost surely to the Radon-Nikodym derivative of `ρ` with respect to `μ` at `x`. * `besicovitch.ae_tendsto_measure_inter_div` states that almost every point in an arbitrary set `s` is a Lebesgue density point, i.e., `μ (s ∩ closed_ball x r) / μ (closed_ball x r)` tends to `1` as `r` tends to `0`. A stronger version for measurable sets is given in `besicovitch.ae_tendsto_measure_inter_div_of_measurable_set`. ## Implementation #### Sketch of proof of the topological Besicovitch theorem: We choose balls in a greedy way. First choose a ball with maximal radius (or rather, since there is no guarantee the maximal radius is realized, a ball with radius within a factor `τ` of the supremum). Then, remove all balls whose center is covered by the first ball, and choose among the remaining ones a ball with radius close to maximum. Go on forever until there is no available center (this is a transfinite induction in general). Then define inductively a coloring of the balls. A ball will be of color `i` if it intersects already chosen balls of color `0`, ..., `i - 1`, but none of color `i`. In this way, balls of the same color form a disjoint family, and the space is covered by the families of the different colors. The nontrivial part is to show that at most `N` colors are used. If one needs `N + 1` colors, consider the first time this happens. Then the corresponding ball intersects `N` balls of the different colors. Moreover, the inductive construction ensures that the radii of all the balls are controlled: they form a satellite configuration with `N + 1` balls (essentially by definition of satellite configurations). Since we assume that there are no such configurations, this is a contradiction. #### Sketch of proof of the measurable Besicovitch theorem: From the topological Besicovitch theorem, one can find a disjoint countable family of balls covering a proportion `> 1 / (N + 1)` of the space. Taking a large enough finite subset of these balls, one gets the same property for finitely many balls. Their union is closed. Therefore, any point in the complement has around it an admissible ball not intersecting these finitely many balls. Applying again the topological Besicovitch theorem, one extracts from these a disjoint countable subfamily covering a proportion `> 1 / (N + 1)` of the remaining points, and then even a disjoint finite subfamily. Then one goes on again and again, covering at each step a positive proportion of the remaining points, while remaining disjoint from the already chosen balls. The union of all these balls is the desired almost everywhere covering. -/ noncomputable theory universe u open metric set filter fin measure_theory topological_space open_locale topology classical big_operators ennreal measure_theory nnreal /-! ### Satellite configurations -/ /-- A satellite configuration is a configuration of `N+1` points that shows up in the inductive construction for the Besicovitch covering theorem. It depends on some parameter `τ ≥ 1`. This is a family of balls (indexed by `i : fin N.succ`, with center `c i` and radius `r i`) such that the last ball intersects all the other balls (condition `inter`), and given any two balls there is an order between them, ensuring that the first ball does not contain the center of the other one, and the radius of the second ball can not be larger than the radius of the first ball (up to a factor `τ`). This order corresponds to the order of choice in the inductive construction: otherwise, the second ball would have been chosen before. This is the condition `h`. Finally, the last ball is chosen after all the other ones, meaning that `h` can be strengthened by keeping only one side of the alternative in `hlast`. -/ structure besicovitch.satellite_config (α : Type*) [metric_space α] (N : ℕ) (τ : ℝ) := (c : fin N.succ → α) (r : fin N.succ → ℝ) (rpos : ∀ i, 0 < r i) (h : ∀ i j, i ≠ j → (r i ≤ dist (c i) (c j) ∧ r j ≤ τ * r i) ∨ (r j ≤ dist (c j) (c i) ∧ r i ≤ τ * r j)) (hlast : ∀ i < last N, r i ≤ dist (c i) (c (last N)) ∧ r (last N) ≤ τ * r i) (inter : ∀ i < last N, dist (c i) (c (last N)) ≤ r i + r (last N)) /-- A metric space has the Besicovitch covering property if there exist `N` and `τ > 1` such that there are no satellite configuration of parameter `τ` with `N+1` points. This is the condition that guarantees that the measurable Besicovitch covering theorem holds. It is satified by finite-dimensional real vector spaces. -/ class has_besicovitch_covering (α : Type*) [metric_space α] : Prop := (no_satellite_config [] : ∃ (N : ℕ) (τ : ℝ), 1 < τ ∧ is_empty (besicovitch.satellite_config α N τ)) /-- There is always a satellite configuration with a single point. -/ instance {α : Type*} {τ : ℝ} [inhabited α] [metric_space α] : inhabited (besicovitch.satellite_config α 0 τ) := ⟨{ c := default, r := λ i, 1, rpos := λ i, zero_lt_one, h := λ i j hij, (hij (subsingleton.elim i j)).elim, hlast := λ i hi, by { rw subsingleton.elim i (last 0) at hi, exact (lt_irrefl _ hi).elim }, inter := λ i hi, by { rw subsingleton.elim i (last 0) at hi, exact (lt_irrefl _ hi).elim } }⟩ namespace besicovitch namespace satellite_config variables {α : Type*} [metric_space α] {N : ℕ} {τ : ℝ} (a : satellite_config α N τ) lemma inter' (i : fin N.succ) : dist (a.c i) (a.c (last N)) ≤ a.r i + a.r (last N) := begin rcases lt_or_le i (last N) with H|H, { exact a.inter i H }, { have I : i = last N := top_le_iff.1 H, have := (a.rpos (last N)).le, simp only [I, add_nonneg this this, dist_self] } end lemma hlast' (i : fin N.succ) (h : 1 ≤ τ) : a.r (last N) ≤ τ * a.r i := begin rcases lt_or_le i (last N) with H|H, { exact (a.hlast i H).2 }, { have : i = last N := top_le_iff.1 H, rw this, exact le_mul_of_one_le_left (a.rpos _).le h } end end satellite_config /-! ### Extracting disjoint subfamilies from a ball covering -/ /-- A ball package is a family of balls in a metric space with positive bounded radii. -/ structure ball_package (β : Type*) (α : Type*) := (c : β → α) (r : β → ℝ) (rpos : ∀ b, 0 < r b) (r_bound : ℝ) (r_le : ∀ b, r b ≤ r_bound) /-- The ball package made of unit balls. -/ def unit_ball_package (α : Type*) : ball_package α α := { c := id, r := λ _, 1, rpos := λ _, zero_lt_one, r_bound := 1, r_le := λ _, le_rfl } instance (α : Type*) : inhabited (ball_package α α) := ⟨unit_ball_package α⟩ /-- A Besicovitch tau-package is a family of balls in a metric space with positive bounded radii, together with enough data to proceed with the Besicovitch greedy algorithm. We register this in a single structure to make sure that all our constructions in this algorithm only depend on one variable. -/ structure tau_package (β : Type*) (α : Type*) extends ball_package β α := (τ : ℝ) (one_lt_tau : 1 < τ) instance (α : Type*) : inhabited (tau_package α α) := ⟨{ τ := 2, one_lt_tau := one_lt_two, .. unit_ball_package α }⟩ variables {α : Type*} [metric_space α] {β : Type u} namespace tau_package variables [nonempty β] (p : tau_package β α) include p /-- Choose inductively large balls with centers that are not contained in the union of already chosen balls. This is a transfinite induction. -/ noncomputable def index : ordinal.{u} → β | i := -- `Z` is the set of points that are covered by already constructed balls let Z := ⋃ (j : {j // j < i}), ball (p.c (index j)) (p.r (index j)), -- `R` is the supremum of the radii of balls with centers not in `Z` R := supr (λ b : {b : β // p.c b ∉ Z}, p.r b) in -- return an index `b` for which the center `c b` is not in `Z`, and the radius is at -- least `R / τ`, if such an index exists (and garbage otherwise). classical.epsilon (λ b : β, p.c b ∉ Z ∧ R ≤ p.τ * p.r b) using_well_founded {dec_tac := `[exact j.2]} /-- The set of points that are covered by the union of balls selected at steps `< i`. -/ def Union_up_to (i : ordinal.{u}) : set α := ⋃ (j : {j // j < i}), ball (p.c (p.index j)) (p.r (p.index j)) lemma monotone_Union_up_to : monotone p.Union_up_to := begin assume i j hij, simp only [Union_up_to], exact Union_mono' (λ r, ⟨⟨r, r.2.trans_le hij⟩, subset.rfl⟩), end /-- Supremum of the radii of balls whose centers are not yet covered at step `i`. -/ def R (i : ordinal.{u}) : ℝ := supr (λ b : {b : β // p.c b ∉ p.Union_up_to i}, p.r b) /-- Group the balls into disjoint families, by assigning to a ball the smallest color for which it does not intersect any already chosen ball of this color. -/ noncomputable def color : ordinal.{u} → ℕ | i := let A : set ℕ := ⋃ (j : {j // j < i}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty), {color j} in Inf (univ \ A) using_well_founded {dec_tac := `[exact j.2]} /-- `p.last_step` is the first ordinal where the construction stops making sense, i.e., `f` returns garbage since there is no point left to be chosen. We will only use ordinals before this step. -/ def last_step : ordinal.{u} := Inf {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b} lemma last_step_nonempty : {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b}.nonempty := begin by_contra, suffices H : function.injective p.index, from not_injective_of_ordinal p.index H, assume x y hxy, wlog x_le_y : x ≤ y generalizing x y, { exact (this hxy.symm (le_of_not_le x_le_y)).symm }, rcases eq_or_lt_of_le x_le_y with rfl|H, { refl }, simp only [nonempty_def, not_exists, exists_prop, not_and, not_lt, not_le, mem_set_of_eq, not_forall] at h, specialize h y, have A : p.c (p.index y) ∉ p.Union_up_to y, { have : p.index y = classical.epsilon (λ b : β, p.c b ∉ p.Union_up_to y ∧ p.R y ≤ p.τ * p.r b), by { rw [tau_package.index], refl }, rw this, exact (classical.epsilon_spec h).1 }, simp only [Union_up_to, not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_le, subtype.exists, subtype.coe_mk] at A, specialize A x H, simp [hxy] at A, exact (lt_irrefl _ ((p.rpos (p.index y)).trans_le A)).elim end /-- Every point is covered by chosen balls, before `p.last_step`. -/ lemma mem_Union_up_to_last_step (x : β) : p.c x ∈ p.Union_up_to p.last_step := begin have A : ∀ (z : β), p.c z ∈ p.Union_up_to p.last_step ∨ p.τ * p.r z < p.R p.last_step, { have : p.last_step ∈ {i | ¬ ∃ (b : β), p.c b ∉ p.Union_up_to i ∧ p.R i ≤ p.τ * p.r b} := Inf_mem p.last_step_nonempty, simpa only [not_exists, mem_set_of_eq, not_and_distrib, not_le, not_not_mem] }, by_contra, rcases A x with H|H, { exact h H }, have Rpos : 0 < p.R p.last_step, { apply lt_trans (mul_pos (_root_.zero_lt_one.trans p.one_lt_tau) (p.rpos _)) H }, have B : p.τ⁻¹ * p.R p.last_step < p.R p.last_step, { conv_rhs { rw ← one_mul (p.R p.last_step) }, exact mul_lt_mul (inv_lt_one p.one_lt_tau) le_rfl Rpos zero_le_one }, obtain ⟨y, hy1, hy2⟩ : ∃ (y : β), p.c y ∉ p.Union_up_to p.last_step ∧ (p.τ)⁻¹ * p.R p.last_step < p.r y, { simpa only [exists_prop, mem_range, exists_exists_and_eq_and, subtype.exists, subtype.coe_mk] using exists_lt_of_lt_cSup _ B, rw [← image_univ, nonempty_image_iff], exact ⟨⟨_, h⟩, mem_univ _⟩ }, rcases A y with Hy|Hy, { exact hy1 Hy }, { rw ← div_eq_inv_mul at hy2, have := (div_le_iff' (_root_.zero_lt_one.trans p.one_lt_tau)).1 hy2.le, exact lt_irrefl _ (Hy.trans_le this) } end /-- If there are no configurations of satellites with `N+1` points, one never uses more than `N` distinct families in the Besicovitch inductive construction. -/ lemma color_lt {i : ordinal.{u}} (hi : i < p.last_step) {N : ℕ} (hN : is_empty (satellite_config α N p.τ)) : p.color i < N := begin /- By contradiction, consider the first ordinal `i` for which one would have `p.color i = N`. Choose for each `k < N` a ball with color `k` that intersects the ball at color `i` (there is such a ball, otherwise one would have used the color `k` and not `N`). Then this family of `N+1` balls forms a satellite configuration, which is forbidden by the assumption `hN`. -/ induction i using ordinal.induction with i IH, let A : set ℕ := ⋃ (j : {j // j < i}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty), {p.color j}, have color_i : p.color i = Inf (univ \ A), by rw [color], rw color_i, have N_mem : N ∈ univ \ A, { simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, mem_closed_ball, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk], assume j ji hj, exact (IH j ji (ji.trans hi)).ne' }, suffices : Inf (univ \ A) ≠ N, { rcases (cInf_le (order_bot.bdd_below (univ \ A)) N_mem).lt_or_eq with H|H, { exact H }, { exact (this H).elim } }, assume Inf_eq_N, have : ∀ k, k < N → ∃ j, j < i ∧ (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index i)) (p.r (p.index i))).nonempty ∧ k = p.color j, { assume k hk, rw ← Inf_eq_N at hk, have : k ∈ A, by simpa only [true_and, mem_univ, not_not, mem_diff] using nat.not_mem_of_lt_Inf hk, simp at this, simpa only [exists_prop, mem_Union, mem_singleton_iff, mem_closed_ball, subtype.exists, subtype.coe_mk] }, choose! g hg using this, -- Choose for each `k < N` an ordinal `G k < i` giving a ball of color `k` intersecting -- the last ball. let G : ℕ → ordinal := λ n, if n = N then i else g n, have color_G : ∀ n, n ≤ N → p.color (G n) = n, { assume n hn, unfreezingI { rcases hn.eq_or_lt with rfl|H }, { simp only [G], simp only [color_i, Inf_eq_N, if_true, eq_self_iff_true] }, { simp only [G], simp only [H.ne, (hg n H).right.right.symm, if_false] } }, have G_lt_last : ∀ n, n ≤ N → G n < p.last_step, { assume n hn, unfreezingI { rcases hn.eq_or_lt with rfl|H }, { simp only [G], simp only [hi, if_true, eq_self_iff_true], }, { simp only [G], simp only [H.ne, (hg n H).left.trans hi, if_false] } }, have fGn : ∀ n, n ≤ N → p.c (p.index (G n)) ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r (p.index (G n)), { assume n hn, have: p.index (G n) = classical.epsilon (λ t, p.c t ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r t), by { rw index, refl }, rw this, have : ∃ t, p.c t ∉ p.Union_up_to (G n) ∧ p.R (G n) ≤ p.τ * p.r t, by simpa only [not_exists, exists_prop, not_and, not_lt, not_le, mem_set_of_eq, not_forall] using not_mem_of_lt_cInf (G_lt_last n hn) (order_bot.bdd_below _), exact classical.epsilon_spec this }, -- the balls with indices `G k` satisfy the characteristic property of satellite configurations. have Gab : ∀ (a b : fin (nat.succ N)), G a < G b → p.r (p.index (G a)) ≤ dist (p.c (p.index (G a))) (p.c (p.index (G b))) ∧ p.r (p.index (G b)) ≤ p.τ * p.r (p.index (G a)), { assume a b G_lt, have ha : (a : ℕ) ≤ N := nat.lt_succ_iff.1 a.2, have hb : (b : ℕ) ≤ N := nat.lt_succ_iff.1 b.2, split, { have := (fGn b hb).1, simp only [Union_up_to, not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_le, subtype.exists, subtype.coe_mk] at this, simpa only [dist_comm, mem_ball, not_lt] using this (G a) G_lt }, { apply le_trans _ (fGn a ha).2, have B : p.c (p.index (G b)) ∉ p.Union_up_to (G a), { assume H, exact (fGn b hb).1 (p.monotone_Union_up_to G_lt.le H) }, let b' : {t // p.c t ∉ p.Union_up_to (G a)} := ⟨p.index (G b), B⟩, apply @le_csupr _ _ _ (λ t : {t // p.c t ∉ p.Union_up_to (G a)}, p.r t) _ b', refine ⟨p.r_bound, λ t ht, _⟩, simp only [exists_prop, mem_range, subtype.exists, subtype.coe_mk] at ht, rcases ht with ⟨u, hu⟩, rw ← hu.2, exact p.r_le _ } }, -- therefore, one may use them to construct a satellite configuration with `N+1` points let sc : satellite_config α N p.τ := { c := λ k, p.c (p.index (G k)), r := λ k, p.r (p.index (G k)), rpos := λ k, p.rpos (p.index (G k)), h := begin assume a b a_ne_b, wlog G_le : G a ≤ G b generalizing a b, { exact (this b a a_ne_b.symm (le_of_not_le G_le)).symm }, have G_lt : G a < G b, { rcases G_le.lt_or_eq with H|H, { exact H }, have A : (a : ℕ) ≠ b := fin.coe_injective.ne a_ne_b, rw [← color_G a (nat.lt_succ_iff.1 a.2), ← color_G b (nat.lt_succ_iff.1 b.2), H] at A, exact (A rfl).elim }, exact or.inl (Gab a b G_lt), end, hlast := begin assume a ha, have I : (a : ℕ) < N := ha, have : G a < G (fin.last N), by { dsimp [G], simp [I.ne, (hg a I).1] }, exact Gab _ _ this, end, inter := begin assume a ha, have I : (a : ℕ) < N := ha, have J : G (fin.last N) = i, by { dsimp [G], simp only [if_true, eq_self_iff_true], }, have K : G a = g a, { dsimp [G], simp [I.ne, (hg a I).1] }, convert dist_le_add_of_nonempty_closed_ball_inter_closed_ball (hg _ I).2.1, end }, -- this is a contradiction exact (hN.false : _) sc end end tau_package open tau_package /-- The topological Besicovitch covering theorem: there exist finitely many families of disjoint balls covering all the centers in a package. More specifically, one can use `N` families if there are no satellite configurations with `N+1` points. -/ theorem exist_disjoint_covering_families {N : ℕ} {τ : ℝ} (hτ : 1 < τ) (hN : is_empty (satellite_config α N τ)) (q : ball_package β α) : ∃ s : fin N → set β, (∀ (i : fin N), (s i).pairwise_disjoint (λ j, closed_ball (q.c j) (q.r j))) ∧ (range q.c ⊆ ⋃ (i : fin N), ⋃ (j ∈ s i), ball (q.c j) (q.r j)) := begin -- first exclude the trivial case where `β` is empty (we need non-emptiness for the transfinite -- induction, to be able to choose garbage when there is no point left). casesI is_empty_or_nonempty β, { refine ⟨λ i, ∅, λ i, pairwise_disjoint_empty, _⟩, rw [← image_univ, eq_empty_of_is_empty (univ : set β)], simp }, -- Now, assume `β` is nonempty. let p : tau_package β α := { τ := τ, one_lt_tau := hτ, .. q }, -- we use for `s i` the balls of color `i`. let s := λ (i : fin N), ⋃ (k : ordinal.{u}) (hk : k < p.last_step) (h'k : p.color k = i), ({p.index k} : set β), refine ⟨s, λ i, _, _⟩, { -- show that balls of the same color are disjoint assume x hx y hy x_ne_y, obtain ⟨jx, jx_lt, jxi, rfl⟩ : ∃ (jx : ordinal), jx < p.last_step ∧ p.color jx = i ∧ x = p.index jx, by simpa only [exists_prop, mem_Union, mem_singleton_iff] using hx, obtain ⟨jy, jy_lt, jyi, rfl⟩ : ∃ (jy : ordinal), jy < p.last_step ∧ p.color jy = i ∧ y = p.index jy, by simpa only [exists_prop, mem_Union, mem_singleton_iff] using hy, wlog jxy : jx ≤ jy generalizing jx jy, { exact (this jy jy_lt jyi hy jx jx_lt jxi hx x_ne_y.symm (le_of_not_le jxy)).symm }, replace jxy : jx < jy, by { rcases lt_or_eq_of_le jxy with H|rfl, { exact H }, { exact (x_ne_y rfl).elim } }, let A : set ℕ := ⋃ (j : {j // j < jy}) (hj : (closed_ball (p.c (p.index j)) (p.r (p.index j)) ∩ closed_ball (p.c (p.index jy)) (p.r (p.index jy))).nonempty), {p.color j}, have color_j : p.color jy = Inf (univ \ A), by rw [tau_package.color], have : p.color jy ∈ univ \ A, { rw color_j, apply Inf_mem, refine ⟨N, _⟩, simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk], assume k hk H, exact (p.color_lt (hk.trans jy_lt) hN).ne' }, simp only [not_exists, true_and, exists_prop, mem_Union, mem_singleton_iff, not_and, mem_univ, mem_diff, subtype.exists, subtype.coe_mk] at this, specialize this jx jxy, contrapose! this, simpa only [jxi, jyi, and_true, eq_self_iff_true, ← not_disjoint_iff_nonempty_inter] }, { -- show that the balls of color at most `N` cover every center. refine range_subset_iff.2 (λ b, _), obtain ⟨a, ha⟩ : ∃ (a : ordinal), a < p.last_step ∧ dist (p.c b) (p.c (p.index a)) < p.r (p.index a), by simpa only [Union_up_to, exists_prop, mem_Union, mem_ball, subtype.exists, subtype.coe_mk] using p.mem_Union_up_to_last_step b, simp only [exists_prop, mem_Union, mem_ball, mem_singleton_iff, bUnion_and', exists_eq_left, Union_exists, exists_and_distrib_left], exact ⟨⟨p.color a, p.color_lt ha.1 hN⟩, a, rfl, ha⟩ } end /-! ### The measurable Besicovitch covering theorem -/ open_locale nnreal variables [second_countable_topology α] [measurable_space α] [opens_measurable_space α] /-- Consider, for each `x` in a set `s`, a radius `r x ∈ (0, 1]`. Then one can find finitely many disjoint balls of the form `closed_ball x (r x)` covering a proportion `1/(N+1)` of `s`, if there are no satellite configurations with `N+1` points. -/ lemma exist_finset_disjoint_balls_large_measure (μ : measure α) [is_finite_measure μ] {N : ℕ} {τ : ℝ} (hτ : 1 < τ) (hN : is_empty (satellite_config α N τ)) (s : set α) (r : α → ℝ) (rpos : ∀ x ∈ s, 0 < r x) (rle : ∀ x ∈ s, r x ≤ 1) : ∃ (t : finset α), (↑t ⊆ s) ∧ μ (s \ (⋃ (x ∈ t), closed_ball x (r x))) ≤ N/(N+1) * μ s ∧ (t : set α).pairwise_disjoint (λ x, closed_ball x (r x)) := begin -- exclude the trivial case where `μ s = 0`. rcases le_or_lt (μ s) 0 with hμs|hμs, { have : μ s = 0 := le_bot_iff.1 hμs, refine ⟨∅, by simp only [finset.coe_empty, empty_subset], _, _⟩, { simp only [this, diff_empty, Union_false, Union_empty, nonpos_iff_eq_zero, mul_zero] }, { simp only [finset.coe_empty, pairwise_disjoint_empty], } }, casesI is_empty_or_nonempty α, { simp only [eq_empty_of_is_empty s, measure_empty] at hμs, exact (lt_irrefl _ hμs).elim }, have Npos : N ≠ 0, { unfreezingI { rintros rfl }, inhabit α, exact (not_is_empty_of_nonempty _) hN }, -- introduce a measurable superset `o` with the same measure, for measure computations obtain ⟨o, so, omeas, μo⟩ : ∃ (o : set α), s ⊆ o ∧ measurable_set o ∧ μ o = μ s := exists_measurable_superset μ s, /- We will apply the topological Besicovitch theorem, giving `N` disjoint subfamilies of balls covering `s`. Among these, one of them covers a proportion at least `1/N` of `s`. A large enough finite subfamily will then cover a proportion at least `1/(N+1)`. -/ let a : ball_package s α := { c := λ x, x, r := λ x, r x, rpos := λ x, rpos x x.2, r_bound := 1, r_le := λ x, rle x x.2 }, rcases exist_disjoint_covering_families hτ hN a with ⟨u, hu, hu'⟩, have u_count : ∀ i, (u i).countable, { assume i, refine (hu i).countable_of_nonempty_interior (λ j hj, _), have : (ball (j : α) (r j)).nonempty := nonempty_ball.2 (a.rpos _), exact this.mono ball_subset_interior_closed_ball }, let v : fin N → set α := λ i, ⋃ (x : s) (hx : x ∈ u i), closed_ball x (r x), have : ∀ i, measurable_set (v i) := λ i, measurable_set.bUnion (u_count i) (λ b hb, measurable_set_closed_ball), have A : s = ⋃ (i : fin N), s ∩ v i, { refine subset.antisymm _ (Union_subset (λ i, inter_subset_left _ _)), assume x hx, obtain ⟨i, y, hxy, h'⟩ : ∃ (i : fin N) (i_1 : ↥s) (i : i_1 ∈ u i), x ∈ ball ↑i_1 (r ↑i_1), { have : x ∈ range a.c, by simpa only [subtype.range_coe_subtype, set_of_mem_eq], simpa only [mem_Union] using hu' this }, refine mem_Union.2 ⟨i, ⟨hx, _⟩⟩, simp only [v, exists_prop, mem_Union, set_coe.exists, exists_and_distrib_right, subtype.coe_mk], exact ⟨y, ⟨y.2, by simpa only [subtype.coe_eta]⟩, ball_subset_closed_ball h'⟩ }, have S : ∑ (i : fin N), μ s / N ≤ ∑ i, μ (s ∩ v i) := calc ∑ (i : fin N), μ s / N = μ s : begin simp only [finset.card_fin, finset.sum_const, nsmul_eq_mul], rw ennreal.mul_div_cancel', { simp only [Npos, ne.def, nat.cast_eq_zero, not_false_iff] }, { exact (ennreal.nat_ne_top _) } end ... ≤ ∑ i, μ (s ∩ v i) : by { conv_lhs { rw A }, apply measure_Union_fintype_le }, -- choose an index `i` of a subfamily covering at least a proportion `1/N` of `s`. obtain ⟨i, -, hi⟩ : ∃ (i : fin N) (hi : i ∈ finset.univ), μ s / N ≤ μ (s ∩ v i), { apply ennreal.exists_le_of_sum_le _ S, exact ⟨⟨0, bot_lt_iff_ne_bot.2 Npos⟩, finset.mem_univ _⟩ }, replace hi : μ s / (N + 1) < μ (s ∩ v i), { apply lt_of_lt_of_le _ hi, apply (ennreal.mul_lt_mul_left hμs.ne' (measure_lt_top μ s).ne).2, rw ennreal.inv_lt_inv, conv_lhs {rw ← add_zero (N : ℝ≥0∞) }, exact ennreal.add_lt_add_left (ennreal.nat_ne_top N) zero_lt_one }, have B : μ (o ∩ v i) = ∑' (x : u i), μ (o ∩ closed_ball x (r x)), { have : o ∩ v i = ⋃ (x : s) (hx : x ∈ u i), o ∩ closed_ball x (r x), by simp only [inter_Union], rw [this, measure_bUnion (u_count i)], { refl }, { exact (hu i).mono (λ k, inter_subset_right _ _) }, { exact λ b hb, omeas.inter measurable_set_closed_ball } }, -- A large enough finite subfamily of `u i` will also cover a proportion `> 1/(N+1)` of `s`. -- Since `s` might not be measurable, we express this in terms of the measurable superset `o`. obtain ⟨w, hw⟩ : ∃ (w : finset (u i)), μ s / (N + 1) < ∑ (x : u i) in w, μ (o ∩ closed_ball (x : α) (r (x : α))), { have C : has_sum (λ (x : u i), μ (o ∩ closed_ball x (r x))) (μ (o ∩ v i)), by { rw B, exact ennreal.summable.has_sum }, have : μ s / (N+1) < μ (o ∩ v i) := hi.trans_le (measure_mono (inter_subset_inter_left _ so)), exact ((tendsto_order.1 C).1 _ this).exists }, -- Bring back the finset `w i` of `↑(u i)` to a finset of `α`, and check that it works by design. refine ⟨finset.image (λ (x : u i), x) w, _, _, _⟩, -- show that the finset is included in `s`. { simp only [image_subset_iff, coe_coe, finset.coe_image], assume y hy, simp only [subtype.coe_prop, mem_preimage] }, -- show that it covers a large enough proportion of `s`. For measure computations, we do not -- use `s` (which might not be measurable), but its measurable superset `o`. Since their measures -- are the same, this does not spoil the estimates { suffices H : μ (o \ ⋃ x ∈ w, closed_ball ↑x (r ↑x)) ≤ N/(N+1) * μ s, { rw [finset.set_bUnion_finset_image], exact le_trans (measure_mono (diff_subset_diff so (subset.refl _))) H }, rw [← diff_inter_self_eq_diff, measure_diff_le_iff_le_add _ (inter_subset_right _ _) ((measure_lt_top μ _).ne)], swap, { apply measurable_set.inter _ omeas, haveI : encodable (u i) := (u_count i).to_encodable, exact measurable_set.Union (λ b, measurable_set.Union (λ hb, measurable_set_closed_ball)) }, calc μ o = 1/(N+1) * μ s + N/(N+1) * μ s : by { rw [μo, ← add_mul, ennreal.div_add_div_same, add_comm, ennreal.div_self, one_mul]; simp } ... ≤ μ ((⋃ (x ∈ w), closed_ball ↑x (r ↑x)) ∩ o) + N/(N+1) * μ s : begin refine add_le_add _ le_rfl, rw [div_eq_mul_inv, one_mul, mul_comm, ← div_eq_mul_inv], apply hw.le.trans (le_of_eq _), rw [← finset.set_bUnion_coe, inter_comm _ o, inter_Union₂, finset.set_bUnion_coe, measure_bUnion_finset], { have : (w : set (u i)).pairwise_disjoint (λ (b : u i), closed_ball (b : α) (r (b : α))), by { assume k hk l hl hkl, exact hu i k.2 l.2 (subtype.coe_injective.ne hkl) }, exact this.mono (λ k, inter_subset_right _ _) }, { assume b hb, apply omeas.inter measurable_set_closed_ball } end }, -- show that the balls are disjoint { assume k hk l hl hkl, obtain ⟨k', k'w, rfl⟩ : ∃ (k' : u i), k' ∈ w ∧ ↑↑k' = k, by simpa only [mem_image, finset.mem_coe, coe_coe, finset.coe_image] using hk, obtain ⟨l', l'w, rfl⟩ : ∃ (l' : u i), l' ∈ w ∧ ↑↑l' = l, by simpa only [mem_image, finset.mem_coe, coe_coe, finset.coe_image] using hl, have k'nel' : (k' : s) ≠ l', by { assume h, rw h at hkl, exact hkl rfl }, exact hu i k'.2 l'.2 k'nel' } end variable [has_besicovitch_covering α] /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. This version requires that the underlying measure is finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). It expresses the conclusion in a slightly awkward form (with a subset of `α × ℝ`) coming from the proof technique. For a version assuming that the measure is sigma-finite, see `exists_disjoint_closed_ball_covering_ae_aux`. For a version giving the conclusion in a nicer form, see `exists_disjoint_closed_ball_covering_ae`. -/ theorem exists_disjoint_closed_ball_covering_ae_of_finite_measure_aux (μ : measure α) [is_finite_measure μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) : ∃ (t : set (α × ℝ)), t.countable ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1) ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)) = 0 ∧ t.pairwise_disjoint (λ p, closed_ball p.1 p.2) := begin rcases has_besicovitch_covering.no_satellite_config α with ⟨N, τ, hτ, hN⟩, /- Introduce a property `P` on finsets saying that we have a nice disjoint covering of a subset of `s` by admissible balls. -/ let P : finset (α × ℝ) → Prop := λ t, (t : set (α × ℝ)).pairwise_disjoint (λ p, closed_ball p.1 p.2) ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1), /- Given a finite good covering of a subset `s`, one can find a larger finite good covering, covering additionally a proportion at least `1/(N+1)` of leftover points. This follows from `exist_finset_disjoint_balls_large_measure` applied to balls not intersecting the initial covering. -/ have : ∀ (t : finset (α × ℝ)), P t → ∃ (u : finset (α × ℝ)), t ⊆ u ∧ P u ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ u), closed_ball p.1 p.2)) ≤ N/(N+1) * μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)), { assume t ht, set B := ⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2 with hB, have B_closed : is_closed B := is_closed_bUnion (finset.finite_to_set _) (λ i hi, is_closed_ball), set s' := s \ B with hs', have : ∀ x ∈ s', ∃ r ∈ f x ∩ Ioo 0 1, disjoint B (closed_ball x r), { assume x hx, have xs : x ∈ s := ((mem_diff x).1 hx).1, rcases eq_empty_or_nonempty B with hB|hB, { have : (0 : ℝ) < 1 := zero_lt_one, rcases hf x xs 1 zero_lt_one with ⟨r, hr, h'r⟩, exact ⟨r, ⟨hr, h'r⟩, by simp only [hB, empty_disjoint]⟩ }, { let R := inf_dist x B, have : 0 < min R 1 := lt_min ((B_closed.not_mem_iff_inf_dist_pos hB).1 ((mem_diff x).1 hx).2) zero_lt_one, rcases hf x xs _ this with ⟨r, hr, h'r⟩, refine ⟨r, ⟨hr, ⟨h'r.1, h'r.2.trans_le (min_le_right _ _)⟩⟩, _⟩, rw disjoint.comm, exact disjoint_closed_ball_of_lt_inf_dist (h'r.2.trans_le (min_le_left _ _)) } }, choose! r hr using this, obtain ⟨v, vs', hμv, hv⟩ : ∃ (v : finset α), ↑v ⊆ s' ∧ μ (s' \ ⋃ (x ∈ v), closed_ball x (r x)) ≤ N/(N+1) * μ s' ∧ (v : set α).pairwise_disjoint (λ (x : α), closed_ball x (r x)), { have rI : ∀ x ∈ s', r x ∈ Ioo (0 : ℝ) 1 := λ x hx, (hr x hx).1.2, exact exist_finset_disjoint_balls_large_measure μ hτ hN s' r (λ x hx, (rI x hx).1) (λ x hx, (rI x hx).2.le) }, refine ⟨t ∪ (finset.image (λ x, (x, r x)) v), finset.subset_union_left _ _, ⟨_, _, _⟩, _⟩, { simp only [finset.coe_union, pairwise_disjoint_union, ht.1, true_and, finset.coe_image], split, { assume p hp q hq hpq, rcases (mem_image _ _ _).1 hp with ⟨p', p'v, rfl⟩, rcases (mem_image _ _ _).1 hq with ⟨q', q'v, rfl⟩, refine hv p'v q'v (λ hp'q', _), rw [hp'q'] at hpq, exact hpq rfl }, { assume p hp q hq hpq, rcases (mem_image _ _ _).1 hq with ⟨q', q'v, rfl⟩, apply disjoint_of_subset_left _ (hr q' (vs' q'v)).2, rw [hB, ← finset.set_bUnion_coe], exact subset_bUnion_of_mem hp } }, { assume p hp, rcases finset.mem_union.1 hp with h'p|h'p, { exact ht.2.1 p h'p }, { rcases finset.mem_image.1 h'p with ⟨p', p'v, rfl⟩, exact ((mem_diff _).1 (vs' (finset.mem_coe.2 p'v))).1 } }, { assume p hp, rcases finset.mem_union.1 hp with h'p|h'p, { exact ht.2.2 p h'p }, { rcases finset.mem_image.1 h'p with ⟨p', p'v, rfl⟩, exact (hr p' (vs' p'v)).1.1 } }, { convert hμv using 2, rw [finset.set_bUnion_union, ← diff_diff, finset.set_bUnion_finset_image] } }, /- Define `F` associating to a finite good covering the above enlarged good covering, covering a proportion `1/(N+1)` of leftover points. Iterating `F`, one will get larger and larger good coverings, missing in the end only a measure-zero set. -/ choose! F hF using this, let u := λ n, F^[n] ∅, have u_succ : ∀ (n : ℕ), u n.succ = F (u n) := λ n, by simp only [u, function.comp_app, function.iterate_succ'], have Pu : ∀ n, P (u n), { assume n, induction n with n IH, { simp only [u, P, prod.forall, id.def, function.iterate_zero], simp only [finset.not_mem_empty, is_empty.forall_iff, finset.coe_empty, forall_2_true_iff, and_self, pairwise_disjoint_empty] }, { rw u_succ, exact (hF (u n) IH).2.1 } }, refine ⟨⋃ n, u n, countable_Union (λ n, (u n).countable_to_set), _, _, _, _⟩, { assume p hp, rcases mem_Union.1 hp with ⟨n, hn⟩, exact (Pu n).2.1 p (finset.mem_coe.1 hn) }, { assume p hp, rcases mem_Union.1 hp with ⟨n, hn⟩, exact (Pu n).2.2 p (finset.mem_coe.1 hn) }, { have A : ∀ n, μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ ⋃ (n : ℕ), (u n : set (α × ℝ))), closed_ball p.fst p.snd) ≤ μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd), { assume n, apply measure_mono, apply diff_subset_diff (subset.refl _), exact bUnion_subset_bUnion_left (subset_Union (λ i, (u i : set (α × ℝ))) n) }, have B : ∀ n, μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd) ≤ (N/(N+1))^n * μ s, { assume n, induction n with n IH, { simp only [le_refl, diff_empty, one_mul, Union_false, Union_empty, pow_zero] }, calc μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n.succ), closed_ball p.fst p.snd) ≤ (N/(N+1)) * μ (s \ ⋃ (p : α × ℝ) (hp : p ∈ u n), closed_ball p.fst p.snd) : by { rw u_succ, exact (hF (u n) (Pu n)).2.2 } ... ≤ (N/(N+1))^n.succ * μ s : by { rw [pow_succ, mul_assoc], exact mul_le_mul_left' IH _ } }, have C : tendsto (λ (n : ℕ), ((N : ℝ≥0∞)/(N+1))^n * μ s) at_top (𝓝 (0 * μ s)), { apply ennreal.tendsto.mul_const _ (or.inr (measure_lt_top μ s).ne), apply ennreal.tendsto_pow_at_top_nhds_0_of_lt_1, rw [ennreal.div_lt_iff, one_mul], { conv_lhs {rw ← add_zero (N : ℝ≥0∞) }, exact ennreal.add_lt_add_left (ennreal.nat_ne_top N) zero_lt_one }, { simp only [true_or, add_eq_zero_iff, ne.def, not_false_iff, one_ne_zero, and_false] }, { simp only [ennreal.nat_ne_top, ne.def, not_false_iff, or_true] } }, rw zero_mul at C, apply le_bot_iff.1, exact le_of_tendsto_of_tendsto' tendsto_const_nhds C (λ n, (A n).trans (B n)) }, { refine (pairwise_disjoint_Union _).2 (λ n, (Pu n).1), apply (monotone_nat_of_le_succ (λ n, _)).directed_le, rw u_succ, exact (hF (u n) (Pu n)).1 } end /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. This version requires that the underlying measure is sigma-finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). It expresses the conclusion in a slightly awkward form (with a subset of `α × ℝ`) coming from the proof technique. For a version giving the conclusion in a nicer form, see `exists_disjoint_closed_ball_covering_ae`. -/ theorem exists_disjoint_closed_ball_covering_ae_aux (μ : measure α) [sigma_finite μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) : ∃ (t : set (α × ℝ)), t.countable ∧ (∀ (p : α × ℝ), p ∈ t → p.1 ∈ s) ∧ (∀ (p : α × ℝ), p ∈ t → p.2 ∈ f p.1) ∧ μ (s \ (⋃ (p : α × ℝ) (hp : p ∈ t), closed_ball p.1 p.2)) = 0 ∧ t.pairwise_disjoint (λ p, closed_ball p.1 p.2) := begin /- This is deduced from the finite measure case, by using a finite measure with respect to which the initial sigma-finite measure is absolutely continuous. -/ unfreezingI { rcases exists_absolutely_continuous_is_finite_measure μ with ⟨ν, hν, hμν⟩ }, rcases exists_disjoint_closed_ball_covering_ae_of_finite_measure_aux ν f s hf with ⟨t, t_count, ts, tr, tν, tdisj⟩, exact ⟨t, t_count, ts, tr, hμν tν, tdisj⟩, end /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. We can even require that the radius at `x` is bounded by a given function `R x`. (Take `R = 1` if you don't need this additional feature). This version requires that the underlying measure is sigma-finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). -/ theorem exists_disjoint_closed_ball_covering_ae (μ : measure α) [sigma_finite μ] (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) (R : α → ℝ) (hR : ∀ x ∈ s, 0 < R x): ∃ (t : set α) (r : α → ℝ), t.countable ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ f x ∩ Ioo 0 (R x)) ∧ μ (s \ (⋃ (x ∈ t), closed_ball x (r x))) = 0 ∧ t.pairwise_disjoint (λ x, closed_ball x (r x)) := begin let g := λ x, f x ∩ Ioo 0 (R x), have hg : ∀ x ∈ s, ∀ δ > 0, (g x ∩ Ioo 0 δ).nonempty, { assume x hx δ δpos, rcases hf x hx (min δ (R x)) (lt_min δpos (hR x hx)) with ⟨r, hr⟩, exact ⟨r, ⟨⟨hr.1, hr.2.1, hr.2.2.trans_le (min_le_right _ _)⟩, ⟨hr.2.1, hr.2.2.trans_le (min_le_left _ _)⟩⟩⟩ }, rcases exists_disjoint_closed_ball_covering_ae_aux μ g s hg with ⟨v, v_count, vs, vg, μv, v_disj⟩, let t := prod.fst '' v, have : ∀ x ∈ t, ∃ (r : ℝ), (x, r) ∈ v, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact ⟨q, hp⟩ }, choose! r hr using this, have im_t : (λ x, (x, r x)) '' t = v, { have I : ∀ (p : α × ℝ), p ∈ v → 0 ≤ p.2 := λ p hp, (vg p hp).2.1.le, apply subset.antisymm, { simp only [image_subset_iff], rintros ⟨x, p⟩ hxp, simp only [mem_preimage], exact hr _ (mem_image_of_mem _ hxp) }, { rintros ⟨x, p⟩ hxp, have hxrx : (x, r x) ∈ v := hr _ (mem_image_of_mem _ hxp), have : p = r x, { by_contra, have A : (x, p) ≠ (x, r x), by simpa only [true_and, prod.mk.inj_iff, eq_self_iff_true, ne.def] using h, have H := v_disj hxp hxrx A, contrapose H, rw not_disjoint_iff_nonempty_inter, refine ⟨x, by simp [I _ hxp, I _ hxrx]⟩ }, rw this, apply mem_image_of_mem, exact mem_image_of_mem _ hxp } }, refine ⟨t, r, v_count.image _, _, _, _, _⟩, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact vs _ hp }, { assume x hx, rcases (mem_image _ _ _).1 hx with ⟨⟨p, q⟩, hp, rfl⟩, exact vg _ (hr _ hx) }, { have : (⋃ (x : α) (H : x ∈ t), closed_ball x (r x)) = (⋃ (p : α × ℝ) (H : p ∈ (λ x, (x, r x)) '' t), closed_ball p.1 p.2), by conv_rhs { rw bUnion_image }, rw [this, im_t], exact μv }, { have A : inj_on (λ x : α, (x, r x)) t, by simp only [inj_on, prod.mk.inj_iff, implies_true_iff, eq_self_iff_true] {contextual := tt}, rwa [← im_t, A.pairwise_disjoint_image] at v_disj } end /-- In a space with the Besicovitch property, any set `s` can be covered with balls whose measures add up to at most `μ s + ε`, for any positive `ε`. This works even if one restricts the set of allowed radii around a point `x` to a set `f x` which accumulates at `0`. -/ theorem exists_closed_ball_covering_tsum_measure_le (μ : measure α) [sigma_finite μ] [measure.outer_regular μ] {ε : ℝ≥0∞} (hε : ε ≠ 0) (f : α → set ℝ) (s : set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).nonempty) : ∃ (t : set α) (r : α → ℝ), t.countable ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ f x) ∧ s ⊆ (⋃ (x ∈ t), closed_ball x (r x)) ∧ ∑' (x : t), μ (closed_ball x (r x)) ≤ μ s + ε := begin /- For the proof, first cover almost all `s` with disjoint balls thanks to the usual Besicovitch theorem. Taking the balls included in a well-chosen open neighborhood `u` of `s`, one may ensure that their measures add at most to `μ s + ε / 2`. Let `s'` be the remaining set, of measure `0`. Applying the other version of Besicovitch, one may cover it with at most `N` disjoint subfamilies. Making sure that they are all included in a neighborhood `v` of `s'` of measure at most `ε / (2 N)`, the sum of their measures is at most `ε / 2`, completing the proof. -/ obtain ⟨u, su, u_open, μu⟩ : ∃ U ⊇ s, is_open U ∧ μ U ≤ μ s + ε / 2 := set.exists_is_open_le_add _ _ (by simpa only [or_false, ne.def, ennreal.div_zero_iff, ennreal.one_ne_top, ennreal.bit0_eq_top_iff] using hε), have : ∀ x ∈ s, ∃ R > 0, ball x R ⊆ u := λ x hx, metric.mem_nhds_iff.1 (u_open.mem_nhds (su hx)), choose! R hR using this, obtain ⟨t0, r0, t0_count, t0s, hr0, μt0, t0_disj⟩ : ∃ (t0 : set α) (r0 : α → ℝ), t0.countable ∧ t0 ⊆ s ∧ (∀ x ∈ t0, r0 x ∈ f x ∩ Ioo 0 (R x)) ∧ μ (s \ (⋃ (x ∈ t0), closed_ball x (r0 x))) = 0 ∧ t0.pairwise_disjoint (λ x, closed_ball x (r0 x)) := exists_disjoint_closed_ball_covering_ae μ f s hf R (λ x hx, (hR x hx).1), -- we have constructed an almost everywhere covering of `s` by disjoint balls. Let `s'` be the -- remaining set. let s' := s \ (⋃ (x ∈ t0), closed_ball x (r0 x)), have s's : s' ⊆ s := diff_subset _ _, obtain ⟨N, τ, hτ, H⟩ : ∃ N τ, 1 < τ ∧ is_empty (besicovitch.satellite_config α N τ) := has_besicovitch_covering.no_satellite_config α, obtain ⟨v, s'v, v_open, μv⟩ : ∃ v ⊇ s', is_open v ∧ μ v ≤ μ s' + (ε / 2) / N := set.exists_is_open_le_add _ _ (by simp only [hε, ennreal.nat_ne_top, with_top.mul_eq_top_iff, ne.def, ennreal.div_zero_iff, ennreal.one_ne_top, not_false_iff, and_false, false_and, or_self, ennreal.bit0_eq_top_iff]), have : ∀ x ∈ s', ∃ r1 ∈ (f x ∩ Ioo (0 : ℝ) 1), closed_ball x r1 ⊆ v, { assume x hx, rcases metric.mem_nhds_iff.1 (v_open.mem_nhds (s'v hx)) with ⟨r, rpos, hr⟩, rcases hf x (s's hx) (min r 1) (lt_min rpos zero_lt_one) with ⟨R', hR'⟩, exact ⟨R', ⟨hR'.1, hR'.2.1, hR'.2.2.trans_le (min_le_right _ _)⟩, subset.trans (closed_ball_subset_ball (hR'.2.2.trans_le (min_le_left _ _))) hr⟩, }, choose! r1 hr1 using this, let q : ball_package s' α := { c := λ x, x, r := λ x, r1 x, rpos := λ x, (hr1 x.1 x.2).1.2.1, r_bound := 1, r_le := λ x, (hr1 x.1 x.2).1.2.2.le }, -- by Besicovitch, we cover `s'` with at most `N` families of disjoint balls, all included in -- a suitable neighborhood `v` of `s'`. obtain ⟨S, S_disj, hS⟩ : ∃ S : fin N → set s', (∀ (i : fin N), (S i).pairwise_disjoint (λ j, closed_ball (q.c j) (q.r j))) ∧ (range q.c ⊆ ⋃ (i : fin N), ⋃ (j ∈ S i), ball (q.c j) (q.r j)) := exist_disjoint_covering_families hτ H q, have S_count : ∀ i, (S i).countable, { assume i, apply (S_disj i).countable_of_nonempty_interior (λ j hj, _), have : (ball (j : α) (r1 j)).nonempty := nonempty_ball.2 (q.rpos _), exact this.mono ball_subset_interior_closed_ball }, let r := λ x, if x ∈ s' then r1 x else r0 x, have r_t0 : ∀ x ∈ t0, r x = r0 x, { assume x hx, have : ¬ (x ∈ s'), { simp only [not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_lt, not_le, mem_diff, not_forall], assume h'x, refine ⟨x, hx, _⟩, rw dist_self, exact (hr0 x hx).2.1.le }, simp only [r, if_neg this] }, -- the desired covering set is given by the union of the families constructed in the first and -- second steps. refine ⟨t0 ∪ (⋃ (i : fin N), (coe : s' → α) '' (S i)), r, _, _, _, _, _⟩, -- it remains to check that they have the desired properties { exact t0_count.union (countable_Union (λ i, (S_count i).image _)) }, { simp only [t0s, true_and, union_subset_iff, image_subset_iff, Union_subset_iff], assume i x hx, exact s's x.2 }, { assume x hx, cases hx, { rw r_t0 x hx, exact (hr0 _ hx).1 }, { have h'x : x ∈ s', { simp only [mem_Union, mem_image] at hx, rcases hx with ⟨i, y, ySi, rfl⟩, exact y.2 }, simp only [r, if_pos h'x, (hr1 x h'x).1.1] } }, { assume x hx, by_cases h'x : x ∈ s', { obtain ⟨i, y, ySi, xy⟩ : ∃ (i : fin N) (y : ↥s') (ySi : y ∈ S i), x ∈ ball (y : α) (r1 y), { have A : x ∈ range q.c, by simpa only [not_exists, exists_prop, mem_Union, mem_closed_ball, not_and, not_le, mem_set_of_eq, subtype.range_coe_subtype, mem_diff] using h'x, simpa only [mem_Union, mem_image] using hS A }, refine mem_Union₂.2 ⟨y, or.inr _, _⟩, { simp only [mem_Union, mem_image], exact ⟨i, y, ySi, rfl⟩ }, { have : (y : α) ∈ s' := y.2, simp only [r, if_pos this], exact ball_subset_closed_ball xy } }, { obtain ⟨y, yt0, hxy⟩ : ∃ (y : α), y ∈ t0 ∧ x ∈ closed_ball y (r0 y), by simpa [hx, -mem_closed_ball] using h'x, refine mem_Union₂.2 ⟨y, or.inl yt0, _⟩, rwa r_t0 _ yt0 } }, -- the only nontrivial property is the measure control, which we check now { -- the sets in the first step have measure at most `μ s + ε / 2` have A : ∑' (x : t0), μ (closed_ball x (r x)) ≤ μ s + ε / 2 := calc ∑' (x : t0), μ (closed_ball x (r x)) = ∑' (x : t0), μ (closed_ball x (r0 x)) : by { congr' 1, ext x, rw r_t0 x x.2 } ... = μ (⋃ (x : t0), closed_ball x (r0 x)) : begin haveI : encodable t0 := t0_count.to_encodable, rw measure_Union, { exact (pairwise_subtype_iff_pairwise_set _ _).2 t0_disj }, { exact λ i, measurable_set_closed_ball } end ... ≤ μ u : begin apply measure_mono, simp only [set_coe.forall, subtype.coe_mk, Union_subset_iff], assume x hx, apply subset.trans (closed_ball_subset_ball (hr0 x hx).2.2) (hR x (t0s hx)).2, end ... ≤ μ s + ε / 2 : μu, -- each subfamily in the second step has measure at most `ε / (2 N)`. have B : ∀ (i : fin N), ∑' (x : (coe : s' → α) '' (S i)), μ (closed_ball x (r x)) ≤ (ε / 2) / N := λ i, calc ∑' (x : (coe : s' → α) '' (S i)), μ (closed_ball x (r x)) = ∑' (x : S i), μ (closed_ball x (r x)) : begin have : inj_on (coe : s' → α) (S i) := subtype.coe_injective.inj_on _, let F : S i ≃ (coe : s' → α) '' (S i) := this.bij_on_image.equiv _, exact (F.tsum_eq (λ x, μ (closed_ball x (r x)))).symm, end ... = ∑' (x : S i), μ (closed_ball x (r1 x)) : by { congr' 1, ext x, have : (x : α) ∈ s' := x.1.2, simp only [r, if_pos this] } ... = μ (⋃ (x : S i), closed_ball x (r1 x)) : begin haveI : encodable (S i) := (S_count i).to_encodable, rw measure_Union, { exact (pairwise_subtype_iff_pairwise_set _ _).2 (S_disj i) }, { exact λ i, measurable_set_closed_ball } end ... ≤ μ v : begin apply measure_mono, simp only [set_coe.forall, subtype.coe_mk, Union_subset_iff], assume x xs' xSi, exact (hr1 x xs').2, end ... ≤ (ε / 2) / N : by { have : μ s' = 0 := μt0, rwa [this, zero_add] at μv }, -- add up all these to prove the desired estimate calc ∑' (x : (t0 ∪ ⋃ (i : fin N), (coe : s' → α) '' S i)), μ (closed_ball x (r x)) ≤ ∑' (x : t0), μ (closed_ball x (r x)) + ∑' (x : ⋃ (i : fin N), (coe : s' → α) '' S i), μ (closed_ball x (r x)) : ennreal.tsum_union_le (λ x, μ (closed_ball x (r x))) _ _ ... ≤ ∑' (x : t0), μ (closed_ball x (r x)) + ∑ (i : fin N), ∑' (x : (coe : s' → α) '' S i), μ (closed_ball x (r x)) : add_le_add le_rfl (ennreal.tsum_Union_le (λ x, μ (closed_ball x (r x))) _) ... ≤ (μ s + ε / 2) + ∑ (i : fin N), (ε / 2) / N : begin refine add_le_add A _, refine finset.sum_le_sum _, assume i hi, exact B i end ... ≤ (μ s + ε / 2) + ε / 2 : begin refine add_le_add le_rfl _, simp only [finset.card_fin, finset.sum_const, nsmul_eq_mul, ennreal.mul_div_le], end ... = μ s + ε : by rw [add_assoc, ennreal.add_halves] } end /-! ### Consequences on differentiation of measures -/ /-- In a space with the Besicovitch covering property, the set of closed balls with positive radius forms a Vitali family. This is essentially a restatement of the measurable Besicovitch theorem. -/ protected def vitali_family (μ : measure α) [sigma_finite μ] : vitali_family μ := { sets_at := λ x, (λ (r : ℝ), closed_ball x r) '' (Ioi (0 : ℝ)), measurable_set' := begin assume x y hy, obtain ⟨r, rpos, rfl⟩ : ∃ (r : ℝ), 0 < r ∧ closed_ball x r = y, by simpa only [mem_image, mem_Ioi] using hy, exact is_closed_ball.measurable_set end, nonempty_interior := begin assume x y hy, obtain ⟨r, rpos, rfl⟩ : ∃ (r : ℝ), 0 < r ∧ closed_ball x r = y, by simpa only [mem_image, mem_Ioi] using hy, simp only [nonempty.mono ball_subset_interior_closed_ball, rpos, nonempty_ball], end, nontrivial := λ x ε εpos, ⟨closed_ball x ε, mem_image_of_mem _ εpos, subset.refl _⟩, covering := begin assume s f fsubset ffine, let g : α → set ℝ := λ x, {r | 0 < r ∧ closed_ball x r ∈ f x}, have A : ∀ x ∈ s, ∀ δ > 0, (g x ∩ Ioo 0 δ).nonempty, { assume x xs δ δpos, obtain ⟨t, tf, ht⟩ : ∃ (t : set α) (H : t ∈ f x), t ⊆ closed_ball x (δ/2) := ffine x xs (δ/2) (half_pos δpos), obtain ⟨r, rpos, rfl⟩ : ∃ (r : ℝ), 0 < r ∧ closed_ball x r = t, by simpa using fsubset x xs tf, rcases le_total r (δ/2) with H|H, { exact ⟨r, ⟨rpos, tf⟩, ⟨rpos, H.trans_lt (half_lt_self δpos)⟩⟩ }, { have : closed_ball x r = closed_ball x (δ/2) := subset.antisymm ht (closed_ball_subset_closed_ball H), rw this at tf, refine ⟨δ/2, ⟨half_pos δpos, tf⟩, ⟨half_pos δpos, half_lt_self δpos⟩⟩ } }, obtain ⟨t, r, t_count, ts, tg, μt, tdisj⟩ : ∃ (t : set α) (r : α → ℝ), t.countable ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ g x ∩ Ioo 0 1) ∧ μ (s \ (⋃ (x ∈ t), closed_ball x (r x))) = 0 ∧ t.pairwise_disjoint (λ x, closed_ball x (r x)) := exists_disjoint_closed_ball_covering_ae μ g s A (λ _, 1) (λ _ _, zero_lt_one), let F : α → α × set α := λ x, (x, closed_ball x (r x)), refine ⟨F '' t, _, _, _, _⟩, { rintros - ⟨x, hx, rfl⟩, exact ts hx }, { rintros p ⟨x, hx, rfl⟩ q ⟨y, hy, rfl⟩ hxy, exact tdisj hx hy (ne_of_apply_ne F hxy) }, { rintros - ⟨x, hx, rfl⟩, exact (tg x hx).1.2 }, { rwa bUnion_image } end } /-- The main feature of the Besicovitch Vitali family is that its filter at a point `x` corresponds to convergence along closed balls. We record one of the two implications here, which will enable us to deduce specific statements on differentiation of measures in this context from the general versions. -/ lemma tendsto_filter_at (μ : measure α) [sigma_finite μ] (x : α) : tendsto (λ r, closed_ball x r) (𝓝[>] 0) ((besicovitch.vitali_family μ).filter_at x) := begin assume s hs, simp only [mem_map], obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ (a : set α), a ∈ (besicovitch.vitali_family μ).sets_at x → a ⊆ closed_ball x ε → a ∈ s := (vitali_family.mem_filter_at_iff _).1 hs, have : Ioc (0 : ℝ) ε ∈ 𝓝[>] (0 : ℝ) := Ioc_mem_nhds_within_Ioi ⟨le_rfl, εpos⟩, filter_upwards [this] with _ hr, apply hε, { exact mem_image_of_mem _ hr.1 }, { exact closed_ball_subset_closed_ball hr.2 } end variables [metric_space β] [measurable_space β] [borel_space β] [second_countable_topology β] [has_besicovitch_covering β] /-- In a space with the Besicovitch covering property, the ratio of the measure of balls converges almost surely to to the Radon-Nikodym derivative. -/ lemma ae_tendsto_rn_deriv (ρ μ : measure β) [is_locally_finite_measure μ] [is_locally_finite_measure ρ] : ∀ᵐ x ∂μ, tendsto (λ r, ρ (closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 (ρ.rn_deriv μ x)) := begin filter_upwards [vitali_family.ae_tendsto_rn_deriv (besicovitch.vitali_family μ) ρ] with x hx, exact hx.comp (tendsto_filter_at μ x) end /-- Given a measurable set `s`, then `μ (s ∩ closed_ball x r) / μ (closed_ball x r)` converges when `r` tends to `0`, for almost every `x`. The limit is `1` for `x ∈ s` and `0` for `x ∉ s`. This shows that almost every point of `s` is a Lebesgue density point for `s`. A version for non-measurable sets holds, but it only gives the first conclusion, see `ae_tendsto_measure_inter_div`. -/ lemma ae_tendsto_measure_inter_div_of_measurable_set (μ : measure β) [is_locally_finite_measure μ] {s : set β} (hs : measurable_set s) : ∀ᵐ x ∂μ, tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 (s.indicator 1 x)) := begin filter_upwards [vitali_family.ae_tendsto_measure_inter_div_of_measurable_set (besicovitch.vitali_family μ) hs], assume x hx, exact hx.comp (tendsto_filter_at μ x) end /-- Given an arbitrary set `s`, then `μ (s ∩ closed_ball x r) / μ (closed_ball x r)` converges to `1` when `r` tends to `0`, for almost every `x` in `s`. This shows that almost every point of `s` is a Lebesgue density point for `s`. A stronger version holds for measurable sets, see `ae_tendsto_measure_inter_div_of_measurable_set`. See also `is_unif_loc_doubling_measure.ae_tendsto_measure_inter_div`. -/ lemma ae_tendsto_measure_inter_div (μ : measure β) [is_locally_finite_measure μ] (s : set β) : ∀ᵐ x ∂(μ.restrict s), tendsto (λ r, μ (s ∩ (closed_ball x r)) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 1) := by filter_upwards [vitali_family.ae_tendsto_measure_inter_div (besicovitch.vitali_family μ)] with x hx using hx.comp (tendsto_filter_at μ x) end besicovitch
bdcdc82eebb7340962f7aedc5ed067f979f2bf12
80746c6dba6a866de5431094bf9f8f841b043d77
/src/ring_theory/algebra.lean
210025e63aff59af26c38c9a047f12189d33720b
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
18,079
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Algebra over Commutative Ring (under category) -/ import data.polynomial import linear_algebra.multivariate_polynomial import linear_algebra.tensor_product import ring_theory.subring universes u v w u₁ v₁ open lattice local infix ` ⊗ `:100 := tensor_product /-- The category of R-algebras where R is a commutative ring is the under category R ↓ CRing. In the categorical setting we have a forgetful functor R-Alg ⥤ R-Mod. However here it extends module in order to preserve definitional equality in certain cases. -/ class algebra (R : Type u) (A : Type v) [comm_ring R] [ring A] extends module R A := (to_fun : R → A) [hom : is_ring_hom to_fun] (commutes' : ∀ r x, x * to_fun r = to_fun r * x) (smul_def' : ∀ r x, r • x = to_fun r * x) attribute [instance] algebra.hom def algebra_map {R : Type u} (A : Type v) [comm_ring R] [ring A] [algebra R A] (x : R) : A := algebra.to_fun A x namespace algebra variables {R : Type u} {S : Type v} {A : Type w} variables [comm_ring R] [comm_ring S] [ring A] [algebra R A] /-- The codomain of an algebra. -/ instance : module R A := infer_instance instance : has_scalar R A := infer_instance instance {F : Type u} {K : Type v} [discrete_field F] [ring K] [algebra F K] : vector_space F K := @vector_space.mk F _ _ _ algebra.module include R instance : is_ring_hom (algebra_map A : R → A) := algebra.hom _ A variables (A) @[simp] lemma map_add (r s : R) : algebra_map A (r + s) = algebra_map A r + algebra_map A s := is_ring_hom.map_add _ @[simp] lemma map_neg (r : R) : algebra_map A (-r) = -algebra_map A r := is_ring_hom.map_neg _ @[simp] lemma map_sub (r s : R) : algebra_map A (r - s) = algebra_map A r - algebra_map A s := is_ring_hom.map_sub _ @[simp] lemma map_mul (r s : R) : algebra_map A (r * s) = algebra_map A r * algebra_map A s := is_ring_hom.map_mul _ variables (R) @[simp] lemma map_zero : algebra_map A (0 : R) = 0 := is_ring_hom.map_zero _ @[simp] lemma map_one : algebra_map A (1 : R) = 1 := is_ring_hom.map_one _ variables {R A} /-- Creating an algebra from a morphism in CRing. -/ def of_ring_hom (i : R → S) (hom : is_ring_hom i) : algebra R S := { smul := λ c x, i c * x, smul_zero := λ x, mul_zero (i x), smul_add := λ r x y, mul_add (i r) x y, add_smul := λ r s x, show i (r + s) * x = _, by rw [hom.3, add_mul], mul_smul := λ r s x, show i (r * s) * x = _, by rw [hom.2, mul_assoc], one_smul := λ x, show i 1 * x = _, by rw [hom.1, one_mul], zero_smul := λ x, show i 0 * x = _, by rw [@@is_ring_hom.map_zero _ _ i hom, zero_mul], to_fun := i, commutes' := λ _ _, mul_comm _ _, smul_def' := λ c x, rfl } theorem smul_def (r : R) (x : A) : r • x = algebra_map A r * x := algebra.smul_def' r x theorem commutes (r : R) (x : A) : x * algebra_map A r = algebra_map A r * x := algebra.commutes' r x theorem left_comm (r : R) (x y : A) : x * (algebra_map A r * y) = algebra_map A r * (x * y) := by rw [← mul_assoc, commutes, mul_assoc] @[simp] lemma mul_smul_comm (s : R) (x y : A) : x * (s • y) = s • (x * y) := by rw [smul_def, smul_def, left_comm] @[simp] lemma smul_mul_assoc (r : R) (x y : A) : (r • x) * y = r • (x * y) := by rw [smul_def, smul_def, mul_assoc] /-- R[X] is the generator of the category R-Alg. -/ instance polynomial (R : Type u) [comm_ring R] [decidable_eq R] : algebra R (polynomial R) := { to_fun := polynomial.C, commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, (polynomial.C_mul' c p).symm, .. polynomial.module } /-- The algebra of multivariate polynomials. -/ instance mv_polynomial (R : Type u) [comm_ring R] [decidable_eq R] (ι : Type v) [decidable_eq ι] : algebra R (mv_polynomial ι R) := { to_fun := mv_polynomial.C, commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, (mv_polynomial.C_mul' c p).symm, .. mv_polynomial.module } /-- Creating an algebra from a subring. This is the dual of ring extension. -/ instance of_subring (S : set R) [is_subring S] : algebra S R := of_ring_hom subtype.val ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩ variables (R A) /-- The multiplication in an algebra is a bilinear map. -/ def lmul : A →ₗ A →ₗ A := linear_map.mk₂ R (*) (λ x y z, add_mul x y z) (λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (λ x y z, mul_add x y z) (λ c x y, by rw [smul_def, smul_def, left_comm]) set_option class.instance_max_depth 37 def lmul_left (r : A) : A →ₗ A := lmul R A r def lmul_right (r : A) : A →ₗ A := (lmul R A).flip r variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl @[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl end algebra /-- Defining the homomorphism in the category R-Alg. -/ structure alg_hom {R : Type u} (A : Type v) (B : Type w) [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] := (to_fun : A → B) [hom : is_ring_hom to_fun] (commutes' : ∀ r : R, to_fun (algebra_map A r) = algebra_map B r) infixr ` →ₐ `:25 := alg_hom notation A ` →ₐ[`:25 R `] ` B := @alg_hom R A B _ _ _ _ _ namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} variables [comm_ring R] [ring A] [ring B] [ring C] [ring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] include R instance : has_coe_to_fun (A →ₐ[R] B) := ⟨λ _, A → B, to_fun⟩ variables (φ : A →ₐ[R] B) instance : is_ring_hom ⇑φ := hom φ @[extensionality] theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := by cases φ₁; cases φ₂; congr' 1; ext; apply H theorem commutes (r : R) : φ (algebra_map A r) = algebra_map B r := φ.commutes' r @[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s := is_ring_hom.map_add _ @[simp] lemma map_zero : φ 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma map_neg (x) : φ (-x) = -φ x := is_ring_hom.map_neg _ @[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y := is_ring_hom.map_sub _ @[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y := is_ring_hom.map_mul _ @[simp] lemma map_one : φ 1 = 1 := is_ring_hom.map_one _ /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ B := { to_fun := φ, add := φ.map_add, smul := λ c x, by rw [algebra.smul_def, φ.map_mul, φ.commutes c, algebra.smul_def] } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ := ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H variables (R A) protected def id : A →ₐ[R] A := { to_fun := id, commutes' := λ _, rfl } variables {R A} @[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ C := { to_fun := φ₁ ∘ φ₂, commutes' := λ r, by rw [function.comp_apply, φ₂.commutes, φ₁.commutes] } @[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl end alg_hom namespace algebra variables (R : Type u) (S : Type v) (A : Type w) variables [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A] include R S A def comap : Type w := A def comap.to_comap : A → comap R S A := id def comap.of_comap : comap R S A → A := id omit R S A instance comap.ring : ring (comap R S A) := _inst_3 instance comap.comm_ring (R : Type u) (S : Type v) (A : Type w) [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] : comm_ring (comap R S A) := _inst_8 instance comap.module : module S (comap R S A) := _inst_5.to_module instance comap.has_scalar : has_scalar S (comap R S A) := _inst_5.to_module.to_has_scalar /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ instance comap.algebra : algebra R (comap R S A) := { smul := λ r x, (algebra_map S r • x : A), smul_add := λ _ _ _, smul_add _ _ _, add_smul := λ _ _ _, by simp only [algebra.map_add]; from add_smul _ _ _, mul_smul := λ _ _ _, by simp only [algebra.map_mul]; from mul_smul _ _ _, one_smul := λ _, by simp only [algebra.map_one]; from one_smul _ _, zero_smul := λ _, by simp only [algebra.map_zero]; from zero_smul _ _, smul_zero := λ _, smul_zero _, to_fun := (algebra_map A : S → A) ∘ algebra_map S, hom := by letI : is_ring_hom (algebra_map A) := _inst_5.hom; apply_instance, commutes' := λ r x, algebra.commutes _ _, smul_def' := λ _ _, algebra.smul_def _ _ } def to_comap : S →ₐ[R] comap R S A := { to_fun := (algebra_map A : S → A), hom := _inst_5.hom, commutes' := λ r, rfl } theorem to_comap_apply (x) : to_comap R S A x = (algebra_map A : S → A) x := rfl end algebra namespace alg_hom variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁} variables [comm_ring R] [comm_ring S] [ring A] [ring B] variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B) include R /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B := { to_fun := φ, hom := alg_hom.is_ring_hom _, commutes' := λ r, φ.commutes (algebra_map S r) } end alg_hom namespace polynomial variables (R : Type u) (A : Type v) variables [comm_ring R] [comm_ring A] [algebra R A] variables [decidable_eq R] (x : A) /-- A → Hom[R-Alg](R[X],A) -/ def aeval : polynomial R →ₐ[R] A := { to_fun := eval₂ (algebra_map A) x, hom := ⟨eval₂_one _ x, λ _ _, eval₂_mul _ x, λ _ _, eval₂_add _ x⟩, commutes' := λ r, eval₂_C _ _ } theorem aeval_def (p : polynomial R) : aeval R A x p = eval₂ (algebra_map A) x p := rfl instance aeval.is_ring_hom : is_ring_hom (aeval R A x) := alg_hom.hom _ theorem eval_unique (φ : polynomial R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map A) (φ X) p := begin apply polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [is_ring_hom.map_add φ, ih1, ih2, eval₂_add] }, { intros n r ih, rw [pow_succ', ← mul_assoc, is_ring_hom.map_mul φ, eval₂_mul (algebra_map A : R → A), eval₂_X, ih] } end end polynomial namespace mv_polynomial variables (R : Type u) (A : Type v) variables [comm_ring R] [comm_ring A] [algebra R A] variables [decidable_eq R] [decidable_eq A] (σ : set A) /-- (ι → A) → Hom[R-Alg](R[ι],A) -/ def aeval : mv_polynomial σ R →ₐ[R] A := { to_fun := eval₂ (algebra_map A) subtype.val, hom := ⟨eval₂_one _ _, λ _ _, eval₂_mul _ _, λ _ _, eval₂_add _ _⟩, commutes' := λ r, eval₂_C _ _ _ } theorem aeval_def (p : mv_polynomial σ R) : aeval R A σ p = eval₂ (algebra_map A) subtype.val p := rfl instance aeval.is_ring_hom : is_ring_hom (aeval R A σ) := alg_hom.hom _ variables (ι : Type w) [decidable_eq ι] theorem eval_unique (φ : mv_polynomial ι R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map A) (φ ∘ X) p := begin apply mv_polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [is_ring_hom.map_add φ, ih1, ih2, eval₂_add] }, { intros p j ih, rw [is_ring_hom.map_mul φ, eval₂_mul, eval₂_X, ih] } end end mv_polynomial section variables (R : Type*) [comm_ring R] /-- CRing ⥤ ℤ-Alg -/ def ring.to_ℤ_algebra : algebra ℤ R := algebra.of_ring_hom coe $ by constructor; intros; simp /-- CRing ⥤ ℤ-Alg -/ def is_ring_hom.to_ℤ_alg_hom {R : Type u} [comm_ring R] (iR : algebra ℤ R) {S : Type v} [comm_ring S] (iS : algebra ℤ S) (f : R → S) [is_ring_hom f] : R →ₐ[ℤ] S := { to_fun := f, hom := by apply_instance, commutes' := λ i, int.induction_on i (by rw [algebra.map_zero, algebra.map_zero, is_ring_hom.map_zero f]) (λ i ih, by rw [algebra.map_add, algebra.map_add, algebra.map_one, algebra.map_one]; rw [is_ring_hom.map_add f, is_ring_hom.map_one f, ih]) (λ i ih, by rw [algebra.map_sub, algebra.map_sub, algebra.map_one, algebra.map_one]; rw [is_ring_hom.map_sub f, is_ring_hom.map_one f, ih]) } instance : ring (polynomial ℤ) := comm_ring.to_ring _ end structure subalgebra (R : Type u) (A : Type v) [comm_ring R] [ring A] [algebra R A] : Type v := (carrier : set A) [subring : is_subring carrier] (range_le : set.range (algebra_map A : R → A) ≤ carrier) attribute [instance] subalgebra.subring namespace subalgebra variables {R : Type u} {A : Type v} variables [comm_ring R] [ring A] [algebra R A] include R instance : has_coe (subalgebra R A) (set A) := ⟨λ S, S.carrier⟩ instance : has_mem A (subalgebra R A) := ⟨λ x S, x ∈ S.carrier⟩ variables {A} theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s := iff.rfl @[extensionality] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := by cases S; cases T; congr; ext x; exact h x variables (S : subalgebra R A) instance : is_subring (S : set A) := S.subring instance : ring S := @@subtype.ring _ S.is_subring instance (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring instance algebra : algebra R S := { smul := λ (c:R) x, ⟨c • x.1, by rw algebra.smul_def; exact @@is_submonoid.mul_mem _ S.2.2 (S.3 ⟨c, rfl⟩) x.2⟩, smul_add := λ c x y, subtype.eq $ by apply _inst_3.1.1.2, add_smul := λ c x y, subtype.eq $ by apply _inst_3.1.1.3, mul_smul := λ c x y, subtype.eq $ by apply _inst_3.1.1.4, one_smul := λ x, subtype.eq $ by apply _inst_3.1.1.5, zero_smul := λ x, subtype.eq $ by apply _inst_3.1.1.6, smul_zero := λ x, subtype.eq $ by apply _inst_3.1.1.7, to_fun := λ r, ⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩, hom := ⟨subtype.eq $ algebra.map_one R A, λ x y, subtype.eq $ algebra.map_mul A x y, λ x y, subtype.eq $ algebra.map_add A x y⟩, commutes' := λ c x, subtype.eq $ by apply _inst_3.4, smul_def' := λ c x, subtype.eq $ by apply _inst_3.5 } instance to_algebra (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : algebra S A := algebra.of_subring _ def val : S →ₐ[R] A := { to_fun := subtype.val, hom := ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩, commutes' := λ r, rfl } def to_submodule : submodule R A := { carrier := S.carrier, zero := (0:S).2, add := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2, smul := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 } instance to_submodule.is_subring : is_subring (S.to_submodule : set A) := S.2 instance : partial_order (subalgebra R A) := { le := λ S T, S.carrier ≤ T.carrier, le_refl := λ _, le_refl _, le_trans := λ _ _ _, le_trans, le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ } def comap {R : Type u} {S : Type v} {A : Type w} [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A] (iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) := { carrier := (iSB : set A), subring := iSB.is_subring, range_le := λ a ⟨r, hr⟩, hr ▸ iSB.range_le ⟨_, rfl⟩ } def under {R : Type u} {A : Type v} [comm_ring R] [comm_ring A] {i : algebra R A} (S : subalgebra R A) (T : subalgebra S A) : subalgebra R A := { carrier := T, range_le := (λ a ⟨r, hr⟩, hr ▸ T.range_le ⟨⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩, rfl⟩) } end subalgebra namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) protected def range : subalgebra R B := { carrier := set.range φ, subring := { one_mem := ⟨1, φ.map_one⟩, mul_mem := λ y₁ y₂ ⟨x₁, hx₁⟩ ⟨x₂, hx₂⟩, ⟨x₁ * x₂, hx₁ ▸ hx₂ ▸ φ.map_mul x₁ x₂⟩ }, range_le := λ y ⟨r, hr⟩, ⟨algebra_map A r, hr ▸ φ.commutes r⟩ } end alg_hom namespace algebra variables {R : Type u} (A : Type v) variables [comm_ring R] [ring A] [algebra R A] include R variables (R) instance id : algebra R R := algebra.of_ring_hom id $ by apply_instance def of_id : R →ₐ A := { to_fun := algebra_map A, commutes' := λ _, rfl } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map A r := rfl variables (R) {A} def adjoin (s : set A) : subalgebra R A := { carrier := ring.closure (set.range (algebra_map A : R → A) ∪ s), range_le := le_trans (set.subset_union_left _ _) ring.subset_closure } variables {R} protected def gc : galois_connection (adjoin R : set A → subalgebra R A) coe := λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) ring.subset_closure) H, λ H, ring.closure_subset $ set.union_subset S.range_le H⟩ protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe := { choice := λ s hs, adjoin R s, gc := algebra.gc, le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (subalgebra R A) := galois_insertion.lift_complete_lattice algebra.gi theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map A : R → A) := suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl, le_antisymm bot_le $ subalgebra.range_le _ theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) := ring.mem_closure $ or.inr trivial def to_top : A →ₐ[R] (⊤ : subalgebra R A) := { to_fun := λ x, ⟨x, mem_top⟩, hom := ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩, commutes' := λ _, rfl } end algebra
9d9ff70b117baa6d2770277aa68cbbc8f27fbce8
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/quote_error_pos.lean
138d9ed4af1339bc54e8d9afb553f621a1750053
[ "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
365
lean
open tactic meta def apply_zero_add (a : pexpr) : tactic unit := to_expr ``(zero_add %%a) >>= exact example (a : nat) : 0 + a = a := begin apply_zero_add ``(tt), -- Error should be here end meta def apply_zero_add2 (a : pexpr) : tactic unit := `[apply zero_add %%a] example (a : nat) : 0 + a = a := begin apply_zero_add2 ``(tt), -- Error should be here end
8e3cf30f3cfc836cd0ed12049a0578bf6418e6ca
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/topology/continuous_map.lean
4995598077f5b64e786628356337450e62ef6c43
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,863
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import topology.subset_properties import topology.tactic /-! # Continuous bundled map In this file we define the type `continuous_map` of continuous bundled maps. -/ /-- Bundled continuous maps. -/ @[protect_proj] structure continuous_map (α : Type*) (β : Type*) [topological_space α] [topological_space β] := (to_fun : α → β) (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') notation `C(` α `, ` β `)` := continuous_map α β namespace continuous_map attribute [continuity] continuous_map.continuous_to_fun variables {α : Type*} {β : Type*} {γ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] instance : has_coe_to_fun (C(α, β)) := ⟨_, continuous_map.to_fun⟩ variables {α β} {f g : continuous_map α β} protected lemma continuous (f : C(α, β)) : continuous f := f.continuous_to_fun @[continuity] lemma coe_continuous : continuous (f : α → β) := f.continuous_to_fun @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H instance [inhabited β] : inhabited C(α, β) := ⟨{ to_fun := λ _, default _, }⟩ lemma coe_inj ⦃f g : C(α, β)⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[simp] lemma coe_mk (f : α → β) (h : continuous f) : ⇑(⟨f, h⟩ : continuous_map α β) = f := rfl /-- The identity as a continuous map. -/ def id : C(α, α) := ⟨id⟩ /-- The composition of continuous maps, as a continuous map. -/ def comp (f : C(β, γ)) (g : C(α, β)) : C(α, γ) := ⟨f ∘ g⟩ /-- Constant map as a continuous map -/ def const (b : β) : C(α, β) := ⟨λ x, b⟩ end continuous_map
bb0778ea89c8825b9eef27352d5cf1dc5c1206ca
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/preadditive/biproducts.lean
b8f5b129a0e76477a46b782732b4957d0e7c7e0e
[ "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
11,571
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 tactic.abel import category_theory.limits.shapes.biproducts import category_theory.preadditive /-! # Basic facts about morphisms between biproducts in preadditive categories. * In any category (with zero morphisms), if `biprod.map f g` is an isomorphism, then both `f` and `g` are isomorphisms. The remaining lemmas hold in any preadditive category. * If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. * As a corollary of the previous two facts, if we have an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, we can construct an isomorphism `X₂ ≅ Y₂`. * If `f : W ⊞ X ⟶ Y ⊞ Z` is an isomorphism, either `𝟙 W = 0`, or at least one of the component maps `W ⟶ Y` and `W ⟶ Z` is nonzero. * If `f : ⨁ S ⟶ ⨁ T` is an isomorphism, then every column (corresponding to a nonzero summand in the domain) has some nonzero matrix entry. -/ open category_theory open category_theory.preadditive open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] section variables [has_zero_morphisms.{v} C] [has_binary_biproducts.{v} C] /-- If ``` (f 0) (0 g) ``` is invertible, then `f` is invertible. -/ def is_iso_left_of_is_iso_biprod_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [is_iso (biprod.map f g)] : is_iso f := { inv := biprod.inl ≫ inv (biprod.map f g) ≫ biprod.fst, hom_inv_id' := begin have t := congr_arg (λ p : W ⊞ X ⟶ W ⊞ X, biprod.inl ≫ p ≫ biprod.fst) (is_iso.hom_inv_id (biprod.map f g)), simp only [category.id_comp, category.assoc, biprod.inl_map_assoc] at t, simp [t], end, inv_hom_id' := begin have t := congr_arg (λ p : Y ⊞ Z ⟶ Y ⊞ Z, biprod.inl ≫ p ≫ biprod.fst) (is_iso.inv_hom_id (biprod.map f g)), simp only [category.id_comp, category.assoc, biprod.map_fst] at t, simp only [category.assoc], simp [t], end } /-- If ``` (f 0) (0 g) ``` is invertible, then `g` is invertible. -/ def is_iso_right_of_is_iso_biprod_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [is_iso (biprod.map f g)] : is_iso g := begin letI : is_iso (biprod.map g f) := by { rw [←biprod.braiding_map_braiding], apply_instance, }, exact is_iso_left_of_is_iso_biprod_map g f, end end section variables [preadditive.{v} C] [has_binary_biproducts.{v} C] variables {X₁ X₂ Y₁ Y₂ : C} variables (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂) /-- The "matrix" morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` with specified components. -/ def biprod.of_components : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂ := biprod.fst ≫ f₁₁ ≫ biprod.inl + biprod.fst ≫ f₁₂ ≫ biprod.inr + biprod.snd ≫ f₂₁ ≫ biprod.inl + biprod.snd ≫ f₂₂ ≫ biprod.inr @[simp] lemma biprod.inl_of_components : biprod.inl ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ = f₁₁ ≫ biprod.inl + f₁₂ ≫ biprod.inr := by simp [biprod.of_components] @[simp] lemma biprod.inr_of_components : biprod.inr ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ = f₂₁ ≫ biprod.inl + f₂₂ ≫ biprod.inr := by simp [biprod.of_components] @[simp] lemma biprod.of_components_fst : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.fst = biprod.fst ≫ f₁₁ + biprod.snd ≫ f₂₁ := by simp [biprod.of_components] @[simp] lemma biprod.of_components_snd : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.snd = biprod.fst ≫ f₁₂ + biprod.snd ≫ f₂₂ := by simp [biprod.of_components] @[simp] lemma biprod.of_components_eq (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) : biprod.of_components (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd) (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd) = f := begin ext; simp, end @[simp] lemma biprod.of_components_comp {X₁ X₂ Y₁ Y₂ Z₁ Z₂ : C} (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂) (g₁₁ : Y₁ ⟶ Z₁) (g₁₂ : Y₁ ⟶ Z₂) (g₂₁ : Y₂ ⟶ Z₁) (g₂₂ : Y₂ ⟶ Z₂) : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.of_components g₁₁ g₁₂ g₂₁ g₂₂ = biprod.of_components (f₁₁ ≫ g₁₁ + f₁₂ ≫ g₂₁) (f₁₁ ≫ g₁₂ + f₁₂ ≫ g₂₂) (f₂₁ ≫ g₁₁ + f₂₂ ≫ g₂₁) (f₂₁ ≫ g₁₂ + f₂₂ ≫ g₂₂) := begin dsimp [biprod.of_components], apply biprod.hom_ext; apply biprod.hom_ext'; simp only [add_comp, comp_add, add_comp_assoc, add_zero, zero_add, biprod.inl_fst, biprod.inl_snd, biprod.inr_fst, biprod.inr_snd, biprod.inl_fst_assoc, biprod.inl_snd_assoc, biprod.inr_fst_assoc, biprod.inr_snd_assoc, has_zero_morphisms.comp_zero, has_zero_morphisms.zero_comp, has_zero_morphisms.zero_comp_assoc, category.comp_id, category.assoc], end /-- The unipotent upper triangular matrix ``` (1 r) (0 1) ``` as an isomorphism. -/ @[simps] def biprod.unipotent_upper {X₁ X₂ : C} (r : X₁ ⟶ X₂) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ := { hom := biprod.of_components (𝟙 _) r 0 (𝟙 _), inv := biprod.of_components (𝟙 _) (-r) 0 (𝟙 _), } /-- The unipotent lower triangular matrix ``` (1 0) (r 1) ``` as an isomorphism. -/ @[simps] def biprod.unipotent_lower {X₁ X₂ : C} (r : X₂ ⟶ X₁) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ := { hom := biprod.of_components (𝟙 _) 0 r (𝟙 _), inv := biprod.of_components (𝟙 _) 0 (-r) (𝟙 _), } /-- If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. (This is the version of `biprod.gaussian` written in terms of components.) -/ def biprod.gaussian' [is_iso f₁₁] : Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂), L.hom ≫ (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂) ≫ R.hom = biprod.map f₁₁ g₂₂ := ⟨biprod.unipotent_lower (-(f₂₁ ≫ inv f₁₁)), biprod.unipotent_upper (-(inv f₁₁ ≫ f₁₂)), f₂₂ - f₂₁ ≫ (inv f₁₁) ≫ f₁₂, by ext; simp; abel⟩ /-- If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. -/ def biprod.gaussian (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f ≫ biprod.fst)] : Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂), L.hom ≫ f ≫ R.hom = biprod.map (biprod.inl ≫ f ≫ biprod.fst) g₂₂ := begin let := biprod.gaussian' (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd) (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd), simpa [biprod.of_components_eq], end /-- If `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` via a two-by-two matrix whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination. -/ def biprod.iso_elim' [is_iso f₁₁] [is_iso (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂)] : X₂ ≅ Y₂ := begin obtain ⟨L, R, g, w⟩ := biprod.gaussian' f₁₁ f₁₂ f₂₁ f₂₂, letI : is_iso (biprod.map f₁₁ g) := by { rw ←w, apply_instance, }, letI : is_iso g := (is_iso_right_of_is_iso_biprod_map f₁₁ g), exact as_iso g, end /-- If `f` is an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination. -/ def biprod.iso_elim (f : X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f.hom ≫ biprod.fst)] : X₂ ≅ Y₂ := begin letI : is_iso (biprod.of_components (biprod.inl ≫ f.hom ≫ biprod.fst) (biprod.inl ≫ f.hom ≫ biprod.snd) (biprod.inr ≫ f.hom ≫ biprod.fst) (biprod.inr ≫ f.hom ≫ biprod.snd)) := by { simp only [biprod.of_components_eq], apply_instance, }, exact biprod.iso_elim' (biprod.inl ≫ f.hom ≫ biprod.fst) (biprod.inl ≫ f.hom ≫ biprod.snd) (biprod.inr ≫ f.hom ≫ biprod.fst) (biprod.inr ≫ f.hom ≫ biprod.snd) end lemma biprod.column_nonzero_of_iso {W X Y Z : C} (f : W ⊞ X ⟶ Y ⊞ Z) [is_iso f] : 𝟙 W = 0 ∨ biprod.inl ≫ f ≫ biprod.fst ≠ 0 ∨ biprod.inl ≫ f ≫ biprod.snd ≠ 0 := begin classical, by_contradiction, rw [not_or_distrib, not_or_distrib, not_not, not_not] at a, rcases a with ⟨nz, a₁, a₂⟩, set x := biprod.inl ≫ f ≫ inv f ≫ biprod.fst, have h₁ : x = 𝟙 W, by simp [x], have h₀ : x = 0, { dsimp [x], rw [←category.id_comp (inv f), category.assoc, ←biprod.total], conv_lhs { slice 2 3, rw [comp_add], }, simp only [category.assoc], rw [comp_add_assoc, add_comp], conv_lhs { congr, skip, slice 1 3, rw a₂, }, simp only [has_zero_morphisms.zero_comp, add_zero], conv_lhs { slice 1 3, rw a₁, }, simp only [has_zero_morphisms.zero_comp], }, exact nz (h₁.symm.trans h₀), end end variables [preadditive.{v} C] lemma biproduct.column_nonzero_of_iso' {σ τ : Type v} [decidable_eq σ] [decidable_eq τ] [fintype τ] {S : σ → C} [has_biproduct.{v} S] {T : τ → C} [has_biproduct.{v} T] (s : σ) (f : ⨁ S ⟶ ⨁ T) [is_iso f] : (∀ t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t = 0) → 𝟙 (S s) = 0 := begin intro z, set x := biproduct.ι S s ≫ f ≫ inv f ≫ biproduct.π S s, have h₁ : x = 𝟙 (S s), by simp [x], have h₀ : x = 0, { dsimp [x], rw [←category.id_comp (inv f), category.assoc, ←biproduct.total], simp only [comp_sum_assoc], conv_lhs { congr, apply_congr, skip, simp only [reassoc_of z], }, simp, }, exact h₁.symm.trans h₀, end /-- If `f : ⨁ S ⟶ ⨁ T` is an isomorphism, and `s` is a non-trivial summand of the source, then there is some `t` in the target so that the `s, t` matrix entry of `f` is nonzero. -/ def biproduct.column_nonzero_of_iso {σ τ : Type v} [decidable_eq σ] [decidable_eq τ] [fintype τ] {S : σ → C} [has_biproduct.{v} S] {T : τ → C} [has_biproduct.{v} T] (s : σ) (nz : 𝟙 (S s) ≠ 0) [∀ t, decidable_eq (S s ⟶ T t)] (f : ⨁ S ⟶ ⨁ T) [is_iso f] : trunc (Σ' t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t ≠ 0) := begin apply trunc_sigma_of_exists, -- Do this before we run `classical`, so we get the right `decidable_eq` instances. have t := biproduct.column_nonzero_of_iso'.{v} s f, classical, by_contradiction, simp only [not_exists_not] at a, exact nz (t a) end end category_theory
0c62b482fb25ec18426b4715b5bc4cef429a392a
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Data/HashSet.lean
30be96338eefce929119fca7328a50e4acd80e72
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,308
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.HashMap universes u v structure HashSet (α : Type u) [HasBeq α] [Hashable α] := (set : HashMap α Unit) def mkHashSet {α : Type u} [HasBeq α] [Hashable α] (nbuckets := 8) : HashSet α := { set := mkHashMap nbuckets } namespace HashSet variables {α : Type u} [HasBeq α] [Hashable α] instance : Inhabited (HashSet α) := ⟨mkHashSet⟩ instance : HasEmptyc (HashSet α) := ⟨mkHashSet⟩ @[inline] def insert (s : HashSet α) (a : α) : HashSet α := { set := s.set.insert a () } @[inline] def erase (s : HashSet α) (a : α) : HashSet α := { set := s.set.erase a } @[inline] def contains (s : HashSet α) (a : α) : Bool := s.set.contains a @[inline] def size (s : HashSet α) : Nat := s.set.size @[inline] def isEmpty (s : HashSet α) : Bool := s.set.isEmpty @[inline] def empty : HashSet α := mkHashSet @[inline] def foldM {β : Type v} {m : Type v → Type v} [Monad m] (f : β → α → m β) (d : β) (s : HashSet α) : m β := s.set.foldM (fun d a _ => f d a) d @[inline] def fold {β : Type v} (f : β → α → β) (d : β) (s : HashSet α) : β := Id.run $ s.foldM f d end HashSet
3813095298954b24bd974650a5b02c7f20a7e880
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/squarefree.lean
8febe5da5e7cdbdcc63a9d0686e158d4775fb82f
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,651
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import ring_theory.unique_factorization_domain import ring_theory.int.basic import number_theory.divisors /-! # Squarefree elements of monoids An element of a monoid is squarefree when it is not divisible by any squares except the squares of units. ## Main Definitions - `squarefree r` indicates that `r` is only divisible by `x * x` if `x` is a unit. ## Main Results - `multiplicity.squarefree_iff_multiplicity_le_one`: `x` is `squarefree` iff for every `y`, either `multiplicity y x ≤ 1` or `is_unit y`. - `unique_factorization_monoid.squarefree_iff_nodup_factors`: A nonzero element `x` of a unique factorization monoid is squarefree iff `factors x` has no duplicate factors. - `nat.squarefree_iff_nodup_factors`: A positive natural number `x` is squarefree iff the list `factors x` has no duplicate factors. ## Tags squarefree, multiplicity -/ variables {R : Type*} /-- An element of a monoid is squarefree if the only squares that divide it are the squares of units. -/ def squarefree [monoid R] (r : R) : Prop := ∀ x : R, x * x ∣ r → is_unit x @[simp] lemma is_unit.squarefree [comm_monoid R] {x : R} (h : is_unit x) : squarefree x := λ y hdvd, is_unit_of_mul_is_unit_left (is_unit_of_dvd_unit hdvd h) @[simp] lemma squarefree_one [comm_monoid R] : squarefree (1 : R) := is_unit_one.squarefree @[simp] lemma not_squarefree_zero [monoid_with_zero R] [nontrivial R] : ¬ squarefree (0 : R) := begin erw [not_forall], exact ⟨0, (by simp)⟩, end @[simp] lemma irreducible.squarefree [comm_monoid R] {x : R} (h : irreducible x) : squarefree x := begin rintros y ⟨z, hz⟩, rw mul_assoc at hz, rcases h.is_unit_or_is_unit hz with hu | hu, { exact hu }, { apply is_unit_of_mul_is_unit_left hu }, end @[simp] lemma prime.squarefree [comm_cancel_monoid_with_zero R] {x : R} (h : prime x) : squarefree x := (irreducible_of_prime h).squarefree lemma squarefree_of_dvd_of_squarefree [comm_monoid R] {x y : R} (hdvd : x ∣ y) (hsq : squarefree y) : squarefree x := λ a h, hsq _ (dvd.trans h hdvd) namespace multiplicity variables [comm_monoid R] [decidable_rel (has_dvd.dvd : R → R → Prop)] lemma squarefree_iff_multiplicity_le_one (r : R) : squarefree r ↔ ∀ x : R, multiplicity x r ≤ 1 ∨ is_unit x := begin refine forall_congr (λ a, _), rw [← pow_two, pow_dvd_iff_le_multiplicity, or_iff_not_imp_left, not_le, imp_congr], swap, { refl }, convert enat.add_one_le_iff_lt (enat.coe_ne_top _), norm_cast, end end multiplicity namespace unique_factorization_monoid variables [comm_cancel_monoid_with_zero R] [nontrivial R] [unique_factorization_monoid R] variables [normalization_monoid R] lemma squarefree_iff_nodup_factors [decidable_eq R] {x : R} (x0 : x ≠ 0) : squarefree x ↔ multiset.nodup (factors x) := begin have drel : decidable_rel (has_dvd.dvd : R → R → Prop), { classical, apply_instance, }, haveI := drel, rw [multiplicity.squarefree_iff_multiplicity_le_one, multiset.nodup_iff_count_le_one], split; intros h a, { by_cases hmem : a ∈ factors x, { have ha := irreducible_of_factor _ hmem, rcases h a with h | h, { rw ← normalize_factor _ hmem, rw [multiplicity_eq_count_factors ha x0] at h, assumption_mod_cast }, { have := ha.1, contradiction, } }, { simp [multiset.count_eq_zero_of_not_mem hmem] } }, { rw or_iff_not_imp_right, intro hu, by_cases h0 : a = 0, { simp [h0, x0] }, rcases wf_dvd_monoid.exists_irreducible_factor hu h0 with ⟨b, hib, hdvd⟩, apply le_trans (multiplicity.multiplicity_le_multiplicity_of_dvd_left hdvd), rw [multiplicity_eq_count_factors hib x0], specialize h (normalize b), assumption_mod_cast } end lemma dvd_pow_iff_dvd_of_squarefree {x y : R} {n : ℕ} (hsq : squarefree x) (h0 : n ≠ 0) : x ∣ y ^ n ↔ x ∣ y := begin classical, by_cases hx : x = 0, { simp [hx, pow_eq_zero_iff (nat.pos_of_ne_zero h0)] }, by_cases hy : y = 0, { simp [hy, zero_pow (nat.pos_of_ne_zero h0)] }, refine ⟨λ h, _, λ h, dvd_pow h h0⟩, rw [dvd_iff_factors_le_factors hx (pow_ne_zero n hy), factors_pow, ((squarefree_iff_nodup_factors hx).1 hsq).le_nsmul_iff_le h0] at h, rwa dvd_iff_factors_le_factors hx hy, end end unique_factorization_monoid namespace nat lemma squarefree_iff_nodup_factors {n : ℕ} (h0 : n ≠ 0) : squarefree n ↔ n.factors.nodup := begin rw [unique_factorization_monoid.squarefree_iff_nodup_factors h0, nat.factors_eq], simp, end instance : decidable_pred (squarefree : ℕ → Prop) | 0 := is_false not_squarefree_zero | (n + 1) := decidable_of_iff _ (squarefree_iff_nodup_factors (nat.succ_ne_zero n)).symm open unique_factorization_monoid lemma divisors_filter_squarefree {n : ℕ} (h0 : n ≠ 0) : (n.divisors.filter squarefree).val = (unique_factorization_monoid.factors n).to_finset.powerset.val.map (λ x, x.val.prod) := begin rw multiset.nodup_ext (finset.nodup _) (multiset.nodup_map_on _ (finset.nodup _)), { intro a, simp only [multiset.mem_filter, id.def, multiset.mem_map, finset.filter_val, ← finset.mem_def, mem_divisors], split, { rintro ⟨⟨an, h0⟩, hsq⟩, use (unique_factorization_monoid.factors a).to_finset, simp only [id.def, finset.mem_powerset], rcases an with ⟨b, rfl⟩, rw mul_ne_zero_iff at h0, rw unique_factorization_monoid.squarefree_iff_nodup_factors h0.1 at hsq, rw [multiset.to_finset_subset, multiset.to_finset_val, multiset.erase_dup_eq_self.2 hsq, ← associated_iff_eq, factors_mul h0.1 h0.2], exact ⟨multiset.subset_of_le (multiset.le_add_right _ _), factors_prod h0.1⟩ }, { rintro ⟨s, hs, rfl⟩, rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hs, have hs0 : s.val.prod ≠ 0, { rw [ne.def, multiset.prod_eq_zero_iff], simp only [exists_prop, id.def, exists_eq_right], intro con, apply not_irreducible_zero (irreducible_of_factor 0 (multiset.mem_erase_dup.1 (multiset.mem_of_le hs con))) }, rw [dvd_iff_dvd_of_rel_right (factors_prod h0).symm], refine ⟨⟨multiset.prod_dvd_prod (le_trans hs (multiset.erase_dup_le _)), h0⟩, _⟩, have h := unique_factorization_monoid.factors_unique irreducible_of_factor (λ x hx, irreducible_of_factor x (multiset.mem_of_le (le_trans hs (multiset.erase_dup_le _)) hx)) (factors_prod hs0), rw [associated_eq_eq, multiset.rel_eq] at h, rw [unique_factorization_monoid.squarefree_iff_nodup_factors hs0, h], apply s.nodup } }, { intros x hx y hy h, rw [← finset.val_inj, ← multiset.rel_eq, ← associated_eq_eq], rw [← finset.mem_def, finset.mem_powerset] at hx hy, apply unique_factorization_monoid.factors_unique _ _ (associated_iff_eq.2 h), { intros z hz, apply irreducible_of_factor z, rw ← multiset.mem_to_finset, apply hx hz }, { intros z hz, apply irreducible_of_factor z, rw ← multiset.mem_to_finset, apply hy hz } } end open_locale big_operators lemma sum_divisors_filter_squarefree {n : ℕ} (h0 : n ≠ 0) {α : Type*} [add_comm_monoid α] {f : ℕ → α} : ∑ i in (n.divisors.filter squarefree), f i = ∑ i in (unique_factorization_monoid.factors n).to_finset.powerset, f (i.val.prod) := by rw [finset.sum_eq_multiset_sum, divisors_filter_squarefree h0, multiset.map_map, finset.sum_eq_multiset_sum] end nat
4f200f61540eacb5cdf9e00cd3b1ccc6ddf27b1f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/unifHintAndTC.lean
578e3abb6087eb665d42cdf983c438d8f6f1115f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,404
lean
structure Magma where carrier : Type u mul : carrier → carrier → carrier instance : CoeSort Magma (Type u) where coe m := m.carrier def mul {s : Magma} (a b : s) : s := s.mul a b infixl:70 (priority := high) " * " => mul example {S : Magma} (a b c : S) : b = c → a * b = a * c := by intro h; rw [h] def Nat.Magma : Magma where carrier := Nat mul a b := Nat.mul a b unif_hint (s : Magma) where s =?= Nat.Magma |- s.carrier =?= Nat example (x : Nat) : Nat := x * x def Prod.Magma (m : Magma) (n : Magma) : Magma where carrier := m.carrier × n.carrier mul a b := (a.1 * b.1, a.2 * b.2) unif_hint (s : Magma) (m : Magma) (n : Magma) (β : Type u) (δ : Type v) where m.carrier =?= β n.carrier =?= δ s =?= Prod.Magma m n |- s.carrier =?= β × δ def f2 (x y : Nat) : Nat × Nat := (x, y) * (x, y) #eval f2 10 20 def f3 (x y : Nat) : Nat × Nat × Nat := (x, y, y) * (x, y, y) #eval f3 7 24 def magmaOfMul (α : Type u) [Mul α] : Magma where -- Bridge between `Mul α` and `Magma` carrier := α mul a b := Mul.mul a b unif_hint (s : Magma) (α : Type u) [Mul α] where s =?= magmaOfMul α |- s.carrier =?= α def g (x y : Int) : Int := x * y -- Note that we don't have a hint connecting Magma's carrier and Int set_option pp.all true #print g -- magmaOfMul is used def h (x y : UInt32) : UInt32 := let f z w := z * w * z f x y
6c27d8baef13c57b9a6f7db807cb78217b9275ed
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/continuous_on_auto.lean
9e3f1b755fb71ee4ea5837d018481ddbc3ae561f
[]
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
42,250
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.constructions import Mathlib.PostPort universes u_1 u_2 u_3 u_4 namespace Mathlib /-! # Neighborhoods and continuity relative to a subset This file defines relative versions * `nhds_within` of `nhds` * `continuous_on` of `continuous` * `continuous_within_at` of `continuous_at` and proves their basic properties, including the relationships between these restricted notions and the corresponding notions for the subtype equipped with the subspace topology. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`. -/ /-- The "neighborhood within" filter. Elements of `𝓝[s] a` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within {α : Type u_1} [topological_space α] (a : α) (s : set α) : filter α := nhds a ⊓ filter.principal s @[simp] theorem nhds_bind_nhds_within {α : Type u_1} [topological_space α] {a : α} {s : set α} : (filter.bind (nhds a) fun (x : α) => nhds_within x s) = nhds_within a s := Eq.trans filter.bind_inf_principal (congr_arg2 has_inf.inf nhds_bind_nhds rfl) @[simp] theorem eventually_nhds_nhds_within {α : Type u_1} [topological_space α] {a : α} {s : set α} {p : α → Prop} : filter.eventually (fun (y : α) => filter.eventually (fun (x : α) => p x) (nhds_within y s)) (nhds a) ↔ filter.eventually (fun (x : α) => p x) (nhds_within a s) := iff.mp filter.ext_iff nhds_bind_nhds_within (set_of fun (x : α) => p x) theorem eventually_nhds_within_iff {α : Type u_1} [topological_space α] {a : α} {s : set α} {p : α → Prop} : filter.eventually (fun (x : α) => p x) (nhds_within a s) ↔ filter.eventually (fun (x : α) => x ∈ s → p x) (nhds a) := filter.eventually_inf_principal @[simp] theorem eventually_nhds_within_nhds_within {α : Type u_1} [topological_space α] {a : α} {s : set α} {p : α → Prop} : filter.eventually (fun (y : α) => filter.eventually (fun (x : α) => p x) (nhds_within y s)) (nhds_within a s) ↔ filter.eventually (fun (x : α) => p x) (nhds_within a s) := sorry theorem nhds_within_eq {α : Type u_1} [topological_space α] (a : α) (s : set α) : nhds_within a s = infi fun (t : set α) => infi fun (H : t ∈ set_of fun (t : set α) => a ∈ t ∧ is_open t) => filter.principal (t ∩ s) := filter.has_basis.eq_binfi (filter.has_basis.inf_principal (nhds_basis_opens a) s) theorem nhds_within_univ {α : Type u_1} [topological_space α] (a : α) : nhds_within a set.univ = nhds a := eq.mpr (id (Eq._oldrec (Eq.refl (nhds_within a set.univ = nhds a)) (nhds_within.equations._eqn_1 a set.univ))) (eq.mpr (id (Eq._oldrec (Eq.refl (nhds a ⊓ filter.principal set.univ = nhds a)) filter.principal_univ)) (eq.mpr (id (Eq._oldrec (Eq.refl (nhds a ⊓ ⊤ = nhds a)) inf_top_eq)) (Eq.refl (nhds a)))) theorem nhds_within_has_basis {α : Type u_1} {β : Type u_2} [topological_space α] {p : β → Prop} {s : β → set α} {a : α} (h : filter.has_basis (nhds a) p s) (t : set α) : filter.has_basis (nhds_within a t) p fun (i : β) => s i ∩ t := filter.has_basis.inf_principal h t theorem nhds_within_basis_open {α : Type u_1} [topological_space α] (a : α) (t : set α) : filter.has_basis (nhds_within a t) (fun (u : set α) => a ∈ u ∧ is_open u) fun (u : set α) => u ∩ t := nhds_within_has_basis (nhds_basis_opens a) t theorem mem_nhds_within {α : Type u_1} [topological_space α] {t : set α} {a : α} {s : set α} : t ∈ nhds_within a s ↔ ∃ (u : set α), is_open u ∧ a ∈ u ∧ u ∩ s ⊆ t := sorry theorem mem_nhds_within_iff_exists_mem_nhds_inter {α : Type u_1} [topological_space α] {t : set α} {a : α} {s : set α} : t ∈ nhds_within a s ↔ ∃ (u : set α), ∃ (H : u ∈ nhds a), u ∩ s ⊆ t := filter.has_basis.mem_iff (nhds_within_has_basis (filter.basis_sets (nhds a)) s) theorem diff_mem_nhds_within_compl {X : Type u_1} [topological_space X] {x : X} {s : set X} (hs : s ∈ nhds x) (t : set X) : s \ t ∈ nhds_within x (tᶜ) := filter.diff_mem_inf_principal_compl hs t theorem nhds_of_nhds_within_of_nhds {α : Type u_1} [topological_space α] {s : set α} {t : set α} {a : α} (h1 : s ∈ nhds a) (h2 : t ∈ nhds_within a s) : t ∈ nhds a := sorry theorem mem_nhds_within_of_mem_nhds {α : Type u_1} [topological_space α] {s : set α} {t : set α} {a : α} (h : s ∈ nhds a) : s ∈ nhds_within a t := filter.mem_inf_sets_of_left h theorem self_mem_nhds_within {α : Type u_1} [topological_space α] {a : α} {s : set α} : s ∈ nhds_within a s := filter.mem_inf_sets_of_right (filter.mem_principal_self s) theorem inter_mem_nhds_within {α : Type u_1} [topological_space α] (s : set α) {t : set α} {a : α} (h : t ∈ nhds a) : s ∩ t ∈ nhds_within a s := filter.inter_mem_sets (filter.mem_inf_sets_of_right (filter.mem_principal_self s)) (filter.mem_inf_sets_of_left h) theorem nhds_within_mono {α : Type u_1} [topological_space α] (a : α) {s : set α} {t : set α} (h : s ⊆ t) : nhds_within a s ≤ nhds_within a t := inf_le_inf_left (nhds a) (iff.mpr filter.principal_mono h) theorem pure_le_nhds_within {α : Type u_1} [topological_space α] {a : α} {s : set α} (ha : a ∈ s) : pure a ≤ nhds_within a s := le_inf (pure_le_nhds a) (iff.mpr filter.le_principal_iff ha) theorem mem_of_mem_nhds_within {α : Type u_1} [topological_space α] {a : α} {s : set α} {t : set α} (ha : a ∈ s) (ht : t ∈ nhds_within a s) : a ∈ t := pure_le_nhds_within ha ht theorem filter.eventually.self_of_nhds_within {α : Type u_1} [topological_space α] {p : α → Prop} {s : set α} {x : α} (h : filter.eventually (fun (y : α) => p y) (nhds_within x s)) (hx : x ∈ s) : p x := mem_of_mem_nhds_within hx h theorem tendsto_const_nhds_within {α : Type u_1} {β : Type u_2} [topological_space α] {l : filter β} {s : set α} {a : α} (ha : a ∈ s) : filter.tendsto (fun (x : β) => a) l (nhds_within a s) := filter.tendsto.mono_right filter.tendsto_const_pure (pure_le_nhds_within ha) theorem nhds_within_restrict'' {α : Type u_1} [topological_space α] {a : α} (s : set α) {t : set α} (h : t ∈ nhds_within a s) : nhds_within a s = nhds_within a (s ∩ t) := le_antisymm (le_inf inf_le_left (iff.mpr filter.le_principal_iff (filter.inter_mem_sets self_mem_nhds_within h))) (inf_le_inf_left (nhds a) (iff.mpr filter.principal_mono (set.inter_subset_left s t))) theorem nhds_within_restrict' {α : Type u_1} [topological_space α] {a : α} (s : set α) {t : set α} (h : t ∈ nhds a) : nhds_within a s = nhds_within a (s ∩ t) := nhds_within_restrict'' s (filter.mem_inf_sets_of_left h) theorem nhds_within_restrict {α : Type u_1} [topological_space α] {a : α} (s : set α) {t : set α} (h₀ : a ∈ t) (h₁ : is_open t) : nhds_within a s = nhds_within a (s ∩ t) := nhds_within_restrict' s (mem_nhds_sets h₁ h₀) theorem nhds_within_le_of_mem {α : Type u_1} [topological_space α] {a : α} {s : set α} {t : set α} (h : s ∈ nhds_within a t) : nhds_within a t ≤ nhds_within a s := sorry theorem nhds_within_eq_nhds_within {α : Type u_1} [topological_space α] {a : α} {s : set α} {t : set α} {u : set α} (h₀ : a ∈ s) (h₁ : is_open s) (h₂ : t ∩ s = u ∩ s) : nhds_within a t = nhds_within a u := sorry theorem nhds_within_eq_of_open {α : Type u_1} [topological_space α] {a : α} {s : set α} (h₀ : a ∈ s) (h₁ : is_open s) : nhds_within a s = nhds a := iff.mpr inf_eq_left (iff.mpr filter.le_principal_iff (mem_nhds_sets h₁ h₀)) @[simp] theorem nhds_within_empty {α : Type u_1} [topological_space α] (a : α) : nhds_within a ∅ = ⊥ := eq.mpr (id (Eq._oldrec (Eq.refl (nhds_within a ∅ = ⊥)) (nhds_within.equations._eqn_1 a ∅))) (eq.mpr (id (Eq._oldrec (Eq.refl (nhds a ⊓ filter.principal ∅ = ⊥)) filter.principal_empty)) (eq.mpr (id (Eq._oldrec (Eq.refl (nhds a ⊓ ⊥ = ⊥)) inf_bot_eq)) (Eq.refl ⊥))) theorem nhds_within_union {α : Type u_1} [topological_space α] (a : α) (s : set α) (t : set α) : nhds_within a (s ∪ t) = nhds_within a s ⊔ nhds_within a t := sorry theorem nhds_within_inter {α : Type u_1} [topological_space α] (a : α) (s : set α) (t : set α) : nhds_within a (s ∩ t) = nhds_within a s ⊓ nhds_within a t := sorry theorem nhds_within_inter' {α : Type u_1} [topological_space α] (a : α) (s : set α) (t : set α) : nhds_within a (s ∩ t) = nhds_within a s ⊓ filter.principal t := sorry @[simp] theorem nhds_within_singleton {α : Type u_1} [topological_space α] (a : α) : nhds_within a (singleton a) = pure a := sorry @[simp] theorem nhds_within_insert {α : Type u_1} [topological_space α] (a : α) (s : set α) : nhds_within a (insert a s) = pure a ⊔ nhds_within a s := sorry theorem mem_nhds_within_insert {α : Type u_1} [topological_space α] {a : α} {s : set α} {t : set α} : t ∈ nhds_within a (insert a s) ↔ a ∈ t ∧ t ∈ nhds_within a s := sorry theorem insert_mem_nhds_within_insert {α : Type u_1} [topological_space α] {a : α} {s : set α} {t : set α} (h : t ∈ nhds_within a s) : insert a t ∈ nhds_within a (insert a s) := sorry theorem nhds_within_prod_eq {α : Type u_1} [topological_space α] {β : Type u_2} [topological_space β] (a : α) (b : β) (s : set α) (t : set β) : nhds_within (a, b) (set.prod s t) = filter.prod (nhds_within a s) (nhds_within b t) := sorry theorem nhds_within_prod {α : Type u_1} [topological_space α] {β : Type u_2} [topological_space β] {s : set α} {u : set α} {t : set β} {v : set β} {a : α} {b : β} (hu : u ∈ nhds_within a s) (hv : v ∈ nhds_within b t) : set.prod u v ∈ nhds_within (a, b) (set.prod s t) := eq.mpr (id (Eq._oldrec (Eq.refl (set.prod u v ∈ nhds_within (a, b) (set.prod s t))) (nhds_within_prod_eq a b s t))) (filter.prod_mem_prod hu hv) theorem tendsto_if_nhds_within {α : Type u_1} {β : Type u_2} [topological_space α] {f : α → β} {g : α → β} {p : α → Prop} [decidable_pred p] {a : α} {s : set α} {l : filter β} (h₀ : filter.tendsto f (nhds_within a (s ∩ p)) l) (h₁ : filter.tendsto g (nhds_within a (s ∩ set_of fun (x : α) => ¬p x)) l) : filter.tendsto (fun (x : α) => ite (p x) (f x) (g x)) (nhds_within a s) l := sorry theorem map_nhds_within {α : Type u_1} {β : Type u_2} [topological_space α] (f : α → β) (a : α) (s : set α) : filter.map f (nhds_within a s) = infi fun (t : set α) => infi fun (H : t ∈ set_of fun (t : set α) => a ∈ t ∧ is_open t) => filter.principal (f '' (t ∩ s)) := filter.has_basis.eq_binfi (filter.has_basis.map f (nhds_within_basis_open a s)) theorem tendsto_nhds_within_mono_left {α : Type u_1} {β : Type u_2} [topological_space α] {f : α → β} {a : α} {s : set α} {t : set α} {l : filter β} (hst : s ⊆ t) (h : filter.tendsto f (nhds_within a t) l) : filter.tendsto f (nhds_within a s) l := filter.tendsto.mono_left h (nhds_within_mono a hst) theorem tendsto_nhds_within_mono_right {α : Type u_1} {β : Type u_2} [topological_space α] {f : β → α} {l : filter β} {a : α} {s : set α} {t : set α} (hst : s ⊆ t) (h : filter.tendsto f l (nhds_within a s)) : filter.tendsto f l (nhds_within a t) := filter.tendsto.mono_right h (nhds_within_mono a hst) theorem tendsto_nhds_within_of_tendsto_nhds {α : Type u_1} {β : Type u_2} [topological_space α] {f : α → β} {a : α} {s : set α} {l : filter β} (h : filter.tendsto f (nhds a) l) : filter.tendsto f (nhds_within a s) l := filter.tendsto.mono_left h inf_le_left theorem principal_subtype {α : Type u_1} (s : set α) (t : set (Subtype fun (x : α) => x ∈ s)) : filter.principal t = filter.comap coe (filter.principal (coe '' t)) := sorry theorem mem_closure_iff_nhds_within_ne_bot {α : Type u_1} [topological_space α] {s : set α} {x : α} : x ∈ closure s ↔ filter.ne_bot (nhds_within x s) := mem_closure_iff_cluster_pt theorem nhds_within_ne_bot_of_mem {α : Type u_1} [topological_space α] {s : set α} {x : α} (hx : x ∈ s) : filter.ne_bot (nhds_within x s) := iff.mp mem_closure_iff_nhds_within_ne_bot (subset_closure hx) theorem is_closed.mem_of_nhds_within_ne_bot {α : Type u_1} [topological_space α] {s : set α} (hs : is_closed s) {x : α} (hx : filter.ne_bot (nhds_within x s)) : x ∈ s := sorry theorem dense_range.nhds_within_ne_bot {α : Type u_1} [topological_space α] {ι : Type u_2} {f : ι → α} (h : dense_range f) (x : α) : filter.ne_bot (nhds_within x (set.range f)) := iff.mp mem_closure_iff_cluster_pt (h x) theorem eventually_eq_nhds_within_iff {α : Type u_1} {β : Type u_2} [topological_space α] {f : α → β} {g : α → β} {s : set α} {a : α} : filter.eventually_eq (nhds_within a s) f g ↔ filter.eventually (fun (x : α) => x ∈ s → f x = g x) (nhds a) := filter.mem_inf_principal theorem eventually_eq_nhds_within_of_eq_on {α : Type u_1} {β : Type u_2} [topological_space α] {f : α → β} {g : α → β} {s : set α} {a : α} (h : set.eq_on f g s) : filter.eventually_eq (nhds_within a s) f g := filter.mem_inf_sets_of_right h theorem set.eq_on.eventually_eq_nhds_within {α : Type u_1} {β : Type u_2} [topological_space α] {f : α → β} {g : α → β} {s : set α} {a : α} (h : set.eq_on f g s) : filter.eventually_eq (nhds_within a s) f g := eventually_eq_nhds_within_of_eq_on h theorem tendsto_nhds_within_congr {α : Type u_1} {β : Type u_2} [topological_space α] {f : α → β} {g : α → β} {s : set α} {a : α} {l : filter β} (hfg : ∀ (x : α), x ∈ s → f x = g x) (hf : filter.tendsto f (nhds_within a s) l) : filter.tendsto g (nhds_within a s) l := iff.mp (filter.tendsto_congr' (eventually_eq_nhds_within_of_eq_on hfg)) hf theorem eventually_nhds_with_of_forall {α : Type u_1} [topological_space α] {s : set α} {a : α} {p : α → Prop} (h : ∀ (x : α), x ∈ s → p x) : filter.eventually (fun (x : α) => p x) (nhds_within a s) := filter.mem_inf_sets_of_right h theorem tendsto_nhds_within_of_tendsto_nhds_of_eventually_within {α : Type u_1} [topological_space α] {β : Type u_2} {a : α} {l : filter β} {s : set α} (f : β → α) (h1 : filter.tendsto f l (nhds a)) (h2 : filter.eventually (fun (x : β) => f x ∈ s) l) : filter.tendsto f l (nhds_within a s) := iff.mpr filter.tendsto_inf { left := h1, right := iff.mpr filter.tendsto_principal h2 } theorem filter.eventually_eq.eq_of_nhds_within {α : Type u_1} {β : Type u_2} [topological_space α] {s : set α} {f : α → β} {g : α → β} {a : α} (h : filter.eventually_eq (nhds_within a s) f g) (hmem : a ∈ s) : f a = g a := filter.eventually.self_of_nhds_within h hmem theorem eventually_nhds_within_of_eventually_nhds {α : Type u_1} [topological_space α] {s : set α} {a : α} {p : α → Prop} (h : filter.eventually (fun (x : α) => p x) (nhds a)) : filter.eventually (fun (x : α) => p x) (nhds_within a s) := mem_nhds_within_of_mem_nhds h /-! ### `nhds_within` and subtypes -/ theorem mem_nhds_within_subtype {α : Type u_1} [topological_space α] {s : set α} {a : Subtype fun (x : α) => x ∈ s} {t : set (Subtype fun (x : α) => x ∈ s)} {u : set (Subtype fun (x : α) => x ∈ s)} : t ∈ nhds_within a u ↔ t ∈ filter.comap coe (nhds_within (↑a) (coe '' u)) := sorry theorem nhds_within_subtype {α : Type u_1} [topological_space α] (s : set α) (a : Subtype fun (x : α) => x ∈ s) (t : set (Subtype fun (x : α) => x ∈ s)) : nhds_within a t = filter.comap coe (nhds_within (↑a) (coe '' t)) := filter.ext fun (u : set (Subtype fun (x : α) => x ∈ s)) => mem_nhds_within_subtype theorem nhds_within_eq_map_subtype_coe {α : Type u_1} [topological_space α] {s : set α} {a : α} (h : a ∈ s) : nhds_within a s = filter.map coe (nhds { val := a, property := h }) := sorry theorem tendsto_nhds_within_iff_subtype {α : Type u_1} {β : Type u_2} [topological_space α] {s : set α} {a : α} (h : a ∈ s) (f : α → β) (l : filter β) : filter.tendsto f (nhds_within a s) l ↔ filter.tendsto (set.restrict f s) (nhds { val := a, property := h }) l := sorry /-- A function between topological spaces is continuous at a point `x₀` within a subset `s` if `f x` tends to `f x₀` when `x` tends to `x₀` while staying within `s`. -/ def continuous_within_at {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (f : α → β) (s : set α) (x : α) := filter.tendsto f (nhds_within x s) (nhds (f x)) /-- If a function is continuous within `s` at `x`, then it tends to `f x` within `s` by definition. We register this fact for use with the dot notation, especially to use `tendsto.comp` as `continuous_within_at.comp` will have a different meaning. -/ theorem continuous_within_at.tendsto {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) : filter.tendsto f (nhds_within x s) (nhds (f x)) := h /-- A function between topological spaces is continuous on a subset `s` when it's continuous at every point of `s` within `s`. -/ def continuous_on {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (f : α → β) (s : set α) := ∀ (x : α), x ∈ s → continuous_within_at f s x theorem continuous_on.continuous_within_at {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {x : α} (hf : continuous_on f s) (hx : x ∈ s) : continuous_within_at f s x := hf x hx theorem continuous_within_at_univ {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (f : α → β) (x : α) : continuous_within_at f set.univ x ↔ continuous_at f x := sorry theorem continuous_within_at_iff_continuous_at_restrict {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (f : α → β) {x : α} {s : set α} (h : x ∈ s) : continuous_within_at f s x ↔ continuous_at (set.restrict f s) { val := x, property := h } := tendsto_nhds_within_iff_subtype h f (nhds (f x)) theorem continuous_within_at.tendsto_nhds_within {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : set.maps_to f s t) : filter.tendsto f (nhds_within x s) (nhds_within (f x) t) := iff.mpr filter.tendsto_inf { left := h, right := iff.mpr filter.tendsto_principal (filter.mem_inf_sets_of_right (iff.mpr filter.mem_principal_sets ht)) } theorem continuous_within_at.tendsto_nhds_within_image {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {x : α} {s : set α} (h : continuous_within_at f s x) : filter.tendsto f (nhds_within x s) (nhds_within (f x) (f '' s)) := continuous_within_at.tendsto_nhds_within h (set.maps_to_image f s) theorem continuous_within_at.prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] {f : α → γ} {g : β → δ} {s : set α} {t : set β} {x : α} {y : β} (hf : continuous_within_at f s x) (hg : continuous_within_at g t y) : continuous_within_at (prod.map f g) (set.prod s t) (x, y) := sorry theorem continuous_on_iff {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} : continuous_on f s ↔ ∀ (x : α), x ∈ s → ∀ (t : set β), is_open t → f x ∈ t → ∃ (u : set α), is_open u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' t := sorry theorem continuous_on_iff_continuous_restrict {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} : continuous_on f s ↔ continuous (set.restrict f s) := sorry theorem continuous_on_iff' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} : continuous_on f s ↔ ∀ (t : set β), is_open t → ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := sorry theorem continuous_on_iff_is_closed {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} : continuous_on f s ↔ ∀ (t : set β), is_closed t → ∃ (u : set α), is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s := sorry theorem continuous_on.prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] {f : α → γ} {g : β → δ} {s : set α} {t : set β} (hf : continuous_on f s) (hg : continuous_on g t) : continuous_on (prod.map f g) (set.prod s t) := sorry theorem continuous_on_empty {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (f : α → β) : continuous_on f ∅ := fun (x : α) => false.elim theorem nhds_within_le_comap {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {x : α} {s : set α} {f : α → β} (ctsf : continuous_within_at f s x) : nhds_within x s ≤ filter.comap f (nhds_within (f x) (f '' s)) := iff.mp filter.map_le_iff_le_comap (continuous_within_at.tendsto_nhds_within_image ctsf) theorem continuous_within_at_iff_ptendsto_res {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (f : α → β) {x : α} {s : set α} : continuous_within_at f s x ↔ filter.ptendsto (pfun.res f s) (nhds x) (nhds (f x)) := filter.tendsto_iff_ptendsto (nhds x) (nhds (f x)) s f theorem continuous_iff_continuous_on_univ {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} : continuous f ↔ continuous_on f set.univ := sorry theorem continuous_within_at.mono {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {t : set α} {x : α} (h : continuous_within_at f t x) (hs : s ⊆ t) : continuous_within_at f s x := filter.tendsto.mono_left h (nhds_within_mono x hs) theorem continuous_within_at.mono_of_mem {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {t : set α} {x : α} (h : continuous_within_at f t x) (hs : t ∈ nhds_within x s) : continuous_within_at f s x := filter.tendsto.mono_left h (nhds_within_le_of_mem hs) theorem continuous_within_at_inter' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {t : set α} {x : α} (h : t ∈ nhds_within x s) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := sorry theorem continuous_within_at_inter {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {t : set α} {x : α} (h : t ∈ nhds x) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := sorry theorem continuous_within_at_union {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {t : set α} {x : α} : continuous_within_at f (s ∪ t) x ↔ continuous_within_at f s x ∧ continuous_within_at f t x := sorry theorem continuous_within_at.union {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {t : set α} {x : α} (hs : continuous_within_at f s x) (ht : continuous_within_at f t x) : continuous_within_at f (s ∪ t) x := iff.mpr continuous_within_at_union { left := hs, right := ht } theorem continuous_within_at.mem_closure_image {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := mem_closure_of_tendsto h (filter.mem_sets_of_superset self_mem_nhds_within (set.subset_preimage_image f s)) theorem continuous_within_at.mem_closure {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {x : α} {A : set β} (h : continuous_within_at f s x) (hx : x ∈ closure s) (hA : s ⊆ f ⁻¹' A) : f x ∈ closure A := closure_mono (iff.mpr set.image_subset_iff hA) (continuous_within_at.mem_closure_image h hx) theorem continuous_within_at.image_closure {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} (hf : ∀ (x : α), x ∈ closure s → continuous_within_at f s x) : f '' closure s ⊆ closure (f '' s) := sorry @[simp] theorem continuous_within_at_singleton {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {x : α} : continuous_within_at f (singleton x) x := sorry @[simp] theorem continuous_within_at_insert_self {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {x : α} {s : set α} : continuous_within_at f (insert x s) x ↔ continuous_within_at f s x := sorry theorem continuous_within_at.insert_self {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {x : α} {s : set α} : continuous_within_at f s x → continuous_within_at f (insert x s) x := iff.mpr continuous_within_at_insert_self theorem continuous_within_at.diff_iff {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {t : set α} {x : α} (ht : continuous_within_at f t x) : continuous_within_at f (s \ t) x ↔ continuous_within_at f s x := sorry @[simp] theorem continuous_within_at_diff_self {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {x : α} : continuous_within_at f (s \ singleton x) x ↔ continuous_within_at f s x := continuous_within_at.diff_iff continuous_within_at_singleton theorem is_open_map.continuous_on_image_of_left_inv_on {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} (h : is_open_map (set.restrict f s)) {finv : β → α} (hleft : set.left_inv_on finv f s) : continuous_on finv (f '' s) := sorry theorem is_open_map.continuous_on_range_of_left_inverse {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} (hf : is_open_map f) {finv : β → α} (hleft : function.left_inverse finv f) : continuous_on finv (set.range f) := eq.mpr (id (Eq._oldrec (Eq.refl (continuous_on finv (set.range f))) (Eq.symm set.image_univ))) (is_open_map.continuous_on_image_of_left_inv_on (is_open_map.restrict hf is_open_univ) fun (x : α) (_x : x ∈ set.univ) => hleft x) theorem continuous_on.congr_mono {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {g : α → β} {s : set α} {s₁ : set α} (h : continuous_on f s) (h' : set.eq_on g f s₁) (h₁ : s₁ ⊆ s) : continuous_on g s₁ := sorry theorem continuous_on.congr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {g : α → β} {s : set α} (h : continuous_on f s) (h' : set.eq_on g f s) : continuous_on g s := continuous_on.congr_mono h h' (set.subset.refl s) theorem continuous_on_congr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {g : α → β} {s : set α} (h' : set.eq_on g f s) : continuous_on g s ↔ continuous_on f s := { mp := fun (h : continuous_on g s) => continuous_on.congr h (set.eq_on.symm h'), mpr := fun (h : continuous_on f s) => continuous_on.congr h h' } theorem continuous_at.continuous_within_at {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {x : α} (h : continuous_at f x) : continuous_within_at f s x := continuous_within_at.mono (iff.mpr (continuous_within_at_univ f x) h) (set.subset_univ s) theorem continuous_within_at.continuous_at {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hs : s ∈ nhds x) : continuous_at f x := sorry theorem continuous_on.continuous_at {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {x : α} (h : continuous_on f s) (hx : s ∈ nhds x) : continuous_at f x := continuous_within_at.continuous_at (h x (mem_of_nhds hx)) hx theorem continuous_within_at.comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) (h : s ⊆ f ⁻¹' t) : continuous_within_at (g ∘ f) s x := sorry theorem continuous_within_at.comp' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) : continuous_within_at (g ∘ f) (s ∩ f ⁻¹' t) x := continuous_within_at.comp hg (continuous_within_at.mono hf (set.inter_subset_left s (f ⁻¹' t))) (set.inter_subset_right s (f ⁻¹' t)) theorem continuous_on.comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) (h : s ⊆ f ⁻¹' t) : continuous_on (g ∘ f) s := fun (x : α) (hx : x ∈ s) => continuous_within_at.comp (hg (f x) (h hx)) (hf x hx) h theorem continuous_on.mono {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {t : set α} (hf : continuous_on f s) (h : t ⊆ s) : continuous_on f t := fun (x : α) (hx : x ∈ t) => filter.tendsto.mono_left (hf x (h hx)) (nhds_within_mono x h) theorem continuous_on.comp' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) : continuous_on (g ∘ f) (s ∩ f ⁻¹' t) := continuous_on.comp hg (continuous_on.mono hf (set.inter_subset_left s (f ⁻¹' t))) (set.inter_subset_right s (f ⁻¹' t)) theorem continuous.continuous_on {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} (h : continuous f) : continuous_on f s := continuous_on.mono (eq.mp (Eq._oldrec (Eq.refl (continuous f)) (propext continuous_iff_continuous_on_univ)) h) (set.subset_univ s) theorem continuous.continuous_within_at {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {x : α} (h : continuous f) : continuous_within_at f s x := continuous_at.continuous_within_at (continuous.continuous_at h) theorem continuous.comp_continuous_on {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {g : β → γ} {f : α → β} {s : set α} (hg : continuous g) (hf : continuous_on f s) : continuous_on (g ∘ f) s := continuous_on.comp (continuous.continuous_on hg) hf set.subset_preimage_univ theorem continuous_on.comp_continuous {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {g : β → γ} {f : α → β} {s : set β} (hg : continuous_on g s) (hf : continuous f) (hs : ∀ (x : α), f x ∈ s) : continuous (g ∘ f) := eq.mpr (id (Eq._oldrec (Eq.refl (continuous (g ∘ f))) (propext continuous_iff_continuous_on_univ))) (continuous_on.comp hg (eq.mp (Eq._oldrec (Eq.refl (continuous f)) (propext continuous_iff_continuous_on_univ)) hf) fun (x : α) (_x : x ∈ set.univ) => hs x) theorem continuous_within_at.preimage_mem_nhds_within {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ nhds (f x)) : f ⁻¹' t ∈ nhds_within x s := h ht theorem continuous_within_at.preimage_mem_nhds_within' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ nhds_within (f x) (f '' s)) : f ⁻¹' t ∈ nhds_within x s := sorry theorem continuous_within_at.congr_of_eventually_eq {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : filter.eventually_eq (nhds_within x s) f₁ f) (hx : f₁ x = f x) : continuous_within_at f₁ s x := sorry theorem continuous_within_at.congr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : ∀ (y : α), y ∈ s → f₁ y = f y) (hx : f₁ x = f x) : continuous_within_at f₁ s x := continuous_within_at.congr_of_eventually_eq h (filter.mem_sets_of_superset self_mem_nhds_within h₁) hx theorem continuous_within_at.congr_mono {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {g : α → β} {s : set α} {s₁ : set α} {x : α} (h : continuous_within_at f s x) (h' : set.eq_on g f s₁) (h₁ : s₁ ⊆ s) (hx : g x = f x) : continuous_within_at g s₁ x := continuous_within_at.congr (continuous_within_at.mono h h₁) h' hx theorem continuous_on_const {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {s : set α} {c : β} : continuous_on (fun (x : α) => c) s := continuous.continuous_on continuous_const theorem continuous_within_at_const {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {b : β} {s : set α} {x : α} : continuous_within_at (fun (_x : α) => b) s x := continuous.continuous_within_at continuous_const theorem continuous_on_id {α : Type u_1} [topological_space α] {s : set α} : continuous_on id s := continuous.continuous_on continuous_id theorem continuous_within_at_id {α : Type u_1} [topological_space α] {s : set α} {x : α} : continuous_within_at id s x := continuous.continuous_within_at continuous_id theorem continuous_on_open_iff {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} (hs : is_open s) : continuous_on f s ↔ ∀ (t : set β), is_open t → is_open (s ∩ f ⁻¹' t) := sorry theorem continuous_on.preimage_open_of_open {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) (ht : is_open t) : is_open (s ∩ f ⁻¹' t) := iff.mp (continuous_on_open_iff hs) hf t ht theorem continuous_on.preimage_closed_of_closed {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_closed s) (ht : is_closed t) : is_closed (s ∩ f ⁻¹' t) := sorry theorem continuous_on.preimage_interior_subset_interior_preimage {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) : s ∩ f ⁻¹' interior t ⊆ s ∩ interior (f ⁻¹' t) := sorry theorem continuous_on_of_locally_continuous_on {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} (h : ∀ (x : α), x ∈ s → ∃ (t : set α), is_open t ∧ x ∈ t ∧ continuous_on f (s ∩ t)) : continuous_on f s := sorry theorem continuous_on_open_of_generate_from {α : Type u_1} [topological_space α] {β : Type u_2} {s : set α} {T : set (set β)} {f : α → β} (hs : is_open s) (h : ∀ (t : set β), t ∈ T → is_open (s ∩ f ⁻¹' t)) : continuous_on f s := sorry theorem continuous_within_at.prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {f : α → β} {g : α → γ} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (fun (x : α) => (f x, g x)) s x := filter.tendsto.prod_mk_nhds hf hg theorem continuous_on.prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {f : α → β} {g : α → γ} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (fun (x : α) => (f x, g x)) s := fun (x : α) (hx : x ∈ s) => continuous_within_at.prod (hf x hx) (hg x hx) theorem inducing.continuous_on_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {f : α → β} {g : β → γ} (hg : inducing g) {s : set α} : continuous_on f s ↔ continuous_on (g ∘ f) s := sorry theorem embedding.continuous_on_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {f : α → β} {g : β → γ} (hg : embedding g) {s : set α} : continuous_on f s ↔ continuous_on (g ∘ f) s := inducing.continuous_on_iff (embedding.to_inducing hg) theorem continuous_within_at_of_not_mem_closure {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {f : α → β} {s : set α} {x : α} : ¬x ∈ closure s → continuous_within_at f s x := sorry theorem continuous_on_if' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {s : set α} {p : α → Prop} {f : α → β} {g : α → β} {h : (a : α) → Decidable (p a)} (hpf : ∀ (a : α), a ∈ s ∩ frontier (set_of fun (a : α) => p a) → filter.tendsto f (nhds_within a (s ∩ set_of fun (a : α) => p a)) (nhds (ite (p a) (f a) (g a)))) (hpg : ∀ (a : α), a ∈ s ∩ frontier (set_of fun (a : α) => p a) → filter.tendsto g (nhds_within a (s ∩ set_of fun (a : α) => ¬p a)) (nhds (ite (p a) (f a) (g a)))) (hf : continuous_on f (s ∩ set_of fun (a : α) => p a)) (hg : continuous_on g (s ∩ set_of fun (a : α) => ¬p a)) : continuous_on (fun (a : α) => ite (p a) (f a) (g a)) s := sorry theorem continuous_on_if {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {p : α → Prop} {h : (a : α) → Decidable (p a)} {s : set α} {f : α → β} {g : α → β} (hp : ∀ (a : α), a ∈ s ∩ frontier (set_of fun (a : α) => p a) → f a = g a) (hf : continuous_on f (s ∩ closure (set_of fun (a : α) => p a))) (hg : continuous_on g (s ∩ closure (set_of fun (a : α) => ¬p a))) : continuous_on (fun (a : α) => ite (p a) (f a) (g a)) s := sorry theorem continuous_if' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {p : α → Prop} {f : α → β} {g : α → β} {h : (a : α) → Decidable (p a)} (hpf : ∀ (a : α), a ∈ frontier (set_of fun (x : α) => p x) → filter.tendsto f (nhds_within a (set_of fun (x : α) => p x)) (nhds (ite (p a) (f a) (g a)))) (hpg : ∀ (a : α), a ∈ frontier (set_of fun (x : α) => p x) → filter.tendsto g (nhds_within a (set_of fun (x : α) => ¬p x)) (nhds (ite (p a) (f a) (g a)))) (hf : continuous_on f (set_of fun (x : α) => p x)) (hg : continuous_on g (set_of fun (x : α) => ¬p x)) : continuous fun (a : α) => ite (p a) (f a) (g a) := sorry theorem continuous_on_fst {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {s : set (α × β)} : continuous_on prod.fst s := continuous.continuous_on continuous_fst theorem continuous_within_at_fst {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {s : set (α × β)} {p : α × β} : continuous_within_at prod.fst s p := continuous.continuous_within_at continuous_fst theorem continuous_on_snd {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {s : set (α × β)} : continuous_on prod.snd s := continuous.continuous_on continuous_snd theorem continuous_within_at_snd {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {s : set (α × β)} {p : α × β} : continuous_within_at prod.snd s p := continuous.continuous_within_at continuous_snd end Mathlib
6a4cd38ec1c937a5d2b58409f1736565f62b9be2
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/sheaves/forget.lean
a90ac66653eba658bef7e117662efec5a5db1357
[ "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
8,020
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.limits.preserves.shapes.products import topology.sheaves.sheaf /-! # Checking the sheaf condition on the underlying presheaf of types. If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in both `C` and `D`), then checking the sheaf condition for a presheaf `F : presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. ## References * https://stacks.math.columbia.edu/tag/0073 -/ noncomputable theory open category_theory open category_theory.limits open topological_space open opposite namespace Top namespace presheaf namespace sheaf_condition open sheaf_condition_equalizer_products universes v u₁ u₂ variables {C : Type u₁} [category.{v} C] [has_limits C] variables {D : Type u₂} [category.{v} D] [has_limits D] variables (G : C ⥤ D) [preserves_limits G] variables {X : Top.{v}} (F : presheaf C X) variables {ι : Type v} (U : ι → opens X) local attribute [reducible] diagram left_res right_res /-- When `G` preserves limits, the sheaf condition diagram for `F` composed with `G` is naturally isomorphic to the sheaf condition diagram for `F ⋙ G`. -/ def diagram_comp_preserves_limits : diagram F U ⋙ G ≅ diagram (F ⋙ G) U := begin fapply nat_iso.of_components, rintro ⟨j⟩, exact (preserves_product.iso _ _), exact (preserves_product.iso _ _), rintros ⟨⟩ ⟨⟩ ⟨⟩, { ext, simp, dsimp, simp, }, -- non-terminal `simp`, but `squeeze_simp` fails { ext, simp only [limit.lift_π, functor.comp_map, map_lift_pi_comparison, fan.mk_π_app, preserves_product.iso_hom, parallel_pair_map_left, functor.map_comp, category.assoc], dsimp, simp, }, { ext, simp only [limit.lift_π, functor.comp_map, parallel_pair_map_right, fan.mk_π_app, preserves_product.iso_hom, map_lift_pi_comparison, functor.map_comp, category.assoc], dsimp, simp, }, { ext, simp, dsimp, simp, }, end local attribute [reducible] res /-- When `G` preserves limits, the image under `G` of the sheaf condition fork for `F` is the sheaf condition fork for `F ⋙ G`, postcomposed with the inverse of the natural isomorphism `diagram_comp_preserves_limits`. -/ def map_cone_fork : G.map_cone (fork F U) ≅ (cones.postcompose (diagram_comp_preserves_limits G F U).inv).obj (fork (F ⋙ G) U) := cones.ext (iso.refl _) (λ j, begin dsimp, simp [diagram_comp_preserves_limits], cases j; dsimp, { rw iso.eq_comp_inv, ext, simp, dsimp, simp, }, { rw iso.eq_comp_inv, ext, simp, -- non-terminal `simp`, but `squeeze_simp` fails dsimp, simp only [limit.lift_π, fan.mk_π_app, ←G.map_comp, limit.lift_π_assoc, fan.mk_π_app] } end) end sheaf_condition universes v u₁ u₂ open sheaf_condition sheaf_condition_equalizer_products variables {C : Type u₁} [category.{v} C] {D : Type u₂} [category.{v} D] variables (G : C ⥤ D) variables [reflects_isomorphisms G] variables [has_limits C] [has_limits D] [preserves_limits G] variables {X : Top.{v}} (F : presheaf C X) /-- If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in both `C` and `D`), then checking the sheaf condition for a presheaf `F : presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. Another useful example is the forgetful functor `TopCommRing ⥤ Top`. See <https://stacks.math.columbia.edu/tag/0073>. In fact we prove a stronger version with arbitrary complete target category. -/ lemma is_sheaf_iff_is_sheaf_comp : presheaf.is_sheaf F ↔ presheaf.is_sheaf (F ⋙ G) := begin split, { intros S ι U, -- We have that the sheaf condition fork for `F` is a limit fork, obtain ⟨t₁⟩ := S U, -- and since `G` preserves limits, the image under `G` of this fork is a limit fork too. have t₂ := @preserves_limit.preserves _ _ _ _ _ _ _ G _ _ t₁, -- As we established above, that image is just the sheaf condition fork -- for `F ⋙ G` postcomposed with some natural isomorphism, have t₃ := is_limit.of_iso_limit t₂ (map_cone_fork G F U), -- and as postcomposing by a natural isomorphism preserves limit cones, have t₄ := is_limit.postcompose_inv_equiv _ _ t₃, -- we have our desired conclusion. exact ⟨t₄⟩, }, { intros S ι U, refine ⟨_⟩, -- Let `f` be the universal morphism from `F.obj U` to the equalizer -- of the sheaf condition fork, whatever it is. -- Our goal is to show that this is an isomorphism. let f := equalizer.lift _ (w F U), -- If we can do that, suffices : is_iso (G.map f), { resetI, -- we have that `f` itself is an isomorphism, since `G` reflects isomorphisms haveI : is_iso f := is_iso_of_reflects_iso f G, -- TODO package this up as a result elsewhere: apply is_limit.of_iso_limit (limit.is_limit _), apply iso.symm, fapply cones.ext, exact (as_iso f), rintro ⟨_|_⟩; { dsimp [f], simp, }, }, { -- Returning to the task of shwoing that `G.map f` is an isomorphism, -- we note that `G.map f` is almost but not quite (see below) a morphism -- from the sheaf condition cone for `F ⋙ G` to the -- image under `G` of the equalizer cone for the sheaf condition diagram. let c := fork (F ⋙ G) U, obtain ⟨hc⟩ := S U, let d := G.map_cone (equalizer.fork (left_res F U) (right_res F U)), have hd : is_limit d := preserves_limit.preserves (limit.is_limit _), -- Since both of these are limit cones -- (`c` by our hypothesis `S`, and `d` because `G` preserves limits), -- we hope to be able to conclude that `f` is an isomorphism. -- We say "not quite" above because `c` and `d` don't quite have the same shape: -- we need to postcompose by the natural isomorphism `diagram_comp_preserves_limits` -- introduced above. let d' := (cones.postcompose (diagram_comp_preserves_limits G F U).hom).obj d, have hd' : is_limit d' := (is_limit.postcompose_hom_equiv (diagram_comp_preserves_limits G F U : _) d).symm hd, -- Now everything works: we verify that `f` really is a morphism between these cones: let f' : c ⟶ d' := fork.mk_hom (G.map f) begin dsimp only [c, d, d', f, diagram_comp_preserves_limits, res], dunfold fork.ι, ext1 j, dsimp, simp only [category.assoc, ←functor.map_comp_assoc, equalizer.lift_ι, map_lift_pi_comparison_assoc], dsimp [res], simp, end, -- conclude that it is an isomorphism, -- just because it's a morphism between two limit cones. haveI : is_iso f' := is_limit.hom_is_iso hc hd' f', -- A cone morphism is an isomorphism exactly if the morphism between the cone points is, -- so we're done! exact is_iso.of_iso ((cones.forget _).map_iso (as_iso f')) }, }, end /-! As an example, we now have everything we need to check the sheaf condition for a presheaf of commutative rings, merely by checking the sheaf condition for the underlying sheaf of types. ``` import algebra.category.Ring.limits example (X : Top) (F : presheaf CommRing X) (h : presheaf.is_sheaf (F ⋙ (forget CommRing))) : F.is_sheaf := (is_sheaf_iff_is_sheaf_comp (forget CommRing) F).mpr h ``` -/ end presheaf end Top
546beb9845ee09a16ca431c739ddf6ffd91010d9
82e44445c70db0f03e30d7be725775f122d72f3e
/test/to_additive.lean
8985fbb652b0bd36d3ac184c5925f84725923c2d
[ "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
1,846
lean
import algebra.group.to_additive @[to_additive bar0] def foo0 {α} [has_mul α] [has_one α] (x y : α) : α := x * y * 1 class {u v} my_has_pow (α : Type u) (β : Type v) := (pow : α → β → α) class my_has_scalar (M : Type*) (α : Type*) := (smul : M → α → α) attribute [to_additive_reorder 1] my_has_pow attribute [to_additive_reorder 1 4] my_has_pow.pow attribute [to_additive my_has_scalar] my_has_pow attribute [to_additive my_has_scalar.smul] my_has_pow.pow -- set_option pp.universes true -- set_option pp.implicit true -- set_option pp.notation false @[priority 10000] local infix ` ^ `:80 := my_has_pow.pow @[to_additive bar1] def foo1 {α} [my_has_pow α ℕ] (x : α) (n : ℕ) : α := @my_has_pow.pow α ℕ _ x n instance dummy : my_has_pow ℕ $ plift ℤ := ⟨λ _ _, 0⟩ set_option pp.universes true @[to_additive bar2] def foo2 {α} [my_has_pow α ℕ] (x : α) (n : ℕ) (m : plift ℤ) : α := x ^ (n ^ m) @[to_additive bar3] def foo3 {α} [my_has_pow α ℕ] (x : α) : ℕ → α := @my_has_pow.pow α ℕ _ x @[to_additive bar4] def {a b} foo4 {α : Type a} : Type b → Type (max a b) := @my_has_pow α @[to_additive bar4_test] lemma foo4_test {α β : Type*} : @foo4 α β = @my_has_pow α β := rfl @[to_additive bar5] def foo5 {α} [my_has_pow α ℕ] [my_has_pow ℕ ℤ] : true := trivial @[to_additive bar6] def foo6 {α} [my_has_pow α ℕ] : α → ℕ → α := @my_has_pow.pow α ℕ _ @[to_additive bar7] def foo7 := @my_has_pow.pow open tactic /- test the eta-expansion applied on `foo6`. -/ run_cmd do env ← get_env, reorder ← to_additive.reorder_attr.get_cache, d ← get_decl `foo6, let e := d.value.eta_expand env reorder, let t := d.type.eta_expand env reorder, let decl := declaration.defn `barr6 d.univ_params t e d.reducibility_hints d.is_trusted, add_decl decl, skip
760b10e76c48a395204152345d6014fee966eb23
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/analysis/normed_space/inner_product.lean
d3c6141b1b8595c38e16cd0625be2281072d431f
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
74,232
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis -/ import linear_algebra.bilinear_form import linear_algebra.sesquilinear_form import analysis.special_functions.pow import topology.metric_space.pi_Lp import data.complex.is_R_or_C /-! # Inner Product Space This file defines inner product spaces and proves its basic properties. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. We define both the real and complex cases at the same time using the `is_R_or_C` typeclass. ## Main results - We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ` or `ℂ`, through the `is_R_or_C` typeclass. - We show that if `f i` is an inner product space for each `i`, then so is `Π i, f i` - We define `euclidean_space 𝕜 n` to be `n → 𝕜` for any `fintype n`, and show that this an inner product space. - Existence of orthogonal projection onto nonempty complete subspace: Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. The point `v` is usually called the orthogonal projection of `u` onto `K`. ## Notation We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively. We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`, which respectively introduce the plain notation `⟪·, ·⟫` for the the real and complex inner product. ## Implementation notes We choose the convention that inner products are conjugate linear in the first argument and linear in the second. ## TODO - Fix the section on the existence of minimizers and orthogonal projections to make sure that it also applies in the complex case. ## Tags inner product space, norm ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real open_locale big_operators classical variables {𝕜 E F : Type*} [is_R_or_C 𝕜] local notation `𝓚` := @is_R_or_C.of_real 𝕜 _ /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜) export has_inner (inner) notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y section notations localized "notation `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space localized "notation `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space end notations /-- An inner product space is a vector space with an additional operation called inner product. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that `∥x∥^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜] extends normed_group E, normed_space 𝕜 E, has_inner 𝕜 E := (norm_sq_eq_inner : ∀ (x : E), ∥x∥^2 = re (inner x x)) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_im : ∀ x, im (inner x x) = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- This instance generates the type-class problem `inner_product_space ?m E` when looking for `normed_group E`. However, since `?m` can only ever be `ℝ` or `ℂ`, this should not cause problems. -/ attribute [nolint dangerous_instance] inner_product_space.to_normed_group /-! ### Constructing a normed space structure from an inner product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_inhabited_instance] structure inner_product_space.core (𝕜 : Type*) (F : Type*) [is_R_or_C 𝕜] [add_comm_group F] [semimodule 𝕜 F] := (inner : F → F → 𝕜) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_im : ∀ x, im (inner x x) = 0) (nonneg_re : ∀ x, re (inner x x) ≥ 0) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [semimodule 𝕜 F] [c : inner_product_space.core 𝕜 F] include c local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y local notation `𝓚` := @is_R_or_C.of_real 𝕜 _ local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _ local notation `reK` := @is_R_or_C.re 𝕜 _ local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _ local postfix `†`:90 := @is_R_or_C.conj 𝕜 _ /-- Inner product defined by the `inner_product_space.core` structure. -/ def to_has_inner : has_inner 𝕜 F := { inner := c.inner } local attribute [instance] to_has_inner /-- The norm squared function for `inner_product_space.core` structure. -/ def norm_sq (x : F) := reK ⟪x, x⟫ local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _ lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _ lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 := c.nonneg_im _ lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 := c.nonneg_im _ lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := c.add_left _ _ _ lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by rw [←inner_conj_sym, inner_add_left, ring_hom.map_add]; simp only [inner_conj_sym] lemma inner_norm_sq_eq_inner_self (x : F) : 𝓚 (norm_sqF x) = ⟪x, x⟫ := begin rw ext_iff, exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩ end lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := c.smul_left _ _ _ lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_hom.map_mul] lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 := by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_hom.map_zero] lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_hom.map_zero] lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 := iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left }) lemma inner_self_re_to_K {x : F} : 𝓚 (re ⟪x, x⟫) = ⟪x, x⟫ := by norm_num [ext_iff, inner_self_nonneg_im] lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] } lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] } lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. We need this for the `core` structure to prove the triangle inequality below when showing the core is a normed group. -/ lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = 𝓚 (re ⟪y, y⟫) := by simp only [inner_self_re_to_K], have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw ext_iff, exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, inner_conj_sym, hT, conj_div, h₁, h₃] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / 𝓚 (re ⟪y, y⟫)) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (re ⟪x, x⟫) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (re ⟪x, x⟫) := rfl lemma inner_self_eq_norm_square (x : F) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ∥x∥ := rfl /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin have H : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = re ⟪y, y⟫ * re ⟪x, x⟫, { simp only [inner_self_eq_norm_square], ring, }, rw H, conv begin to_lhs, congr, rw[inner_abs_conj_sym], end, exact inner_mul_inner_self_le y x, end /-- Normed group structure constructed from an `inner_product_space.core` structure -/ def to_normed_group : normed_group F := normed_group.of_core F { norm_eq_zero_iff := assume x, begin split, { intro H, change sqrt (re ⟪x, x⟫) = 0 at H, rw [sqrt_eq_zero inner_self_nonneg] at H, apply (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).mp, rw ext_iff, exact ⟨by simp [H], by simp [inner_self_im_zero]⟩ }, { rintro rfl, change sqrt (re ⟪0, 0⟫) = 0, simp only [sqrt_zero, inner_zero_right, add_monoid_hom.map_zero] } end, triangle := assume x y, begin have h₁ : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := abs_inner_le_norm _ _, have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _, have h₃ : re ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := by linarith, have h₄ : re ⟪y, x⟫ ≤ ∥x∥ * ∥y∥ := by rwa [←inner_conj_sym, conj_re], have : ∥x + y∥ * ∥x + y∥ ≤ (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥), { simp [←inner_self_eq_norm_square, inner_add_add_self, add_mul, mul_add, mul_comm], linarith }, exact nonneg_le_nonneg_of_squares_le (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end, norm_neg := λ x, by simp only [norm, inner_neg_left, neg_neg, inner_neg_right] } local attribute [instance] to_normed_group /-- Normed space structure constructed from a `inner_product_space.core` structure -/ def to_normed_space : normed_space 𝕜 F := { norm_smul_le := assume r x, begin rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc], rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self, of_real_re], { simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] }, { exact norm_sq_nonneg r } end } end inner_product_space.of_core /-- Given a `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product -/ def inner_product_space.of_core [add_comm_group F] [semimodule 𝕜 F] (c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F := begin letI : normed_group F := @inner_product_space.of_core.to_normed_group 𝕜 F _ _ _ c, letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c, exact { norm_sq_eq_inner := λ x, begin have h₁ : ∥x∥^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl, have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg, simp [h₁, sqr_sqrt, h₂], end, ..c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y local notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y local notation `IK` := @is_R_or_C.I 𝕜 _ local notation `absR` := _root_.abs local postfix `†`:90 := @is_R_or_C.conj 𝕜 _ local postfix `⋆`:90 := complex.conj export inner_product_space (norm_sq_eq_inner) section basic_properties lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _ lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := inner_conj_sym x y lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := ⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩ lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 := inner_product_space.nonneg_im _ lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_product_space.nonneg_im _ lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := begin rw [←inner_conj_sym, inner_add_left, ring_hom.map_add], conv_rhs { rw ←inner_conj_sym, conv { congr, skip, rw ←inner_conj_sym } } end lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := inner_product_space.smul_left _ _ _ lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left, ring_hom.map_mul, conj_conj, inner_conj_sym] lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right /-- The inner product as a sesquilinear form. -/ def sesq_form_of_inner : sesq_form 𝕜 E conj_to_ring_equiv := { sesq := λ x y, ⟪y, x⟫, -- Note that sesquilinear forms are linear in the first argument sesq_add_left := λ x y z, inner_add_right, sesq_add_right := λ x y z, inner_add_left, sesq_smul_left := λ r x y, inner_smul_right, sesq_smul_right := λ r x y, inner_smul_left } /-- The real inner product as a bilinear form. -/ def bilin_form_of_real_inner : bilin_form ℝ F := { bilin := inner, bilin_add_left := λ x y z, inner_add_left, bilin_smul_left := λ a x y, inner_smul_left, bilin_add_right := λ x y z, inner_add_right, bilin_smul_right := λ a x y, inner_smul_right } /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ := sesq_form.map_sum_right (sesq_form_of_inner) _ _ _ /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ := sesq_form.map_sum_left (sesq_form_of_inner) _ _ _ @[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 := by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_hom.map_zero, zero_mul] lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 := by simp only [inner_zero_left, add_monoid_hom.map_zero] @[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left, ring_hom.map_zero] lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 := by simp only [inner_zero_right, add_monoid_hom.map_zero] lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ := by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2 lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x @[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := begin split, { intro h, have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp [h.1], rw [←norm_sq_eq_inner x] at h₁, rw [←norm_eq_zero], exact pow_eq_zero h₁ }, { rintro rfl, exact inner_zero_left } end @[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := begin split, { intro h, rw ←inner_self_eq_zero, have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg, have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁, rw is_R_or_C.ext_iff, exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ }, { rintro rfl, simp only [inner_zero_left, add_monoid_hom.map_zero] } end lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h } @[simp] lemma inner_self_re_to_K {x : E} : 𝓚 (re ⟪x, x⟫) = ⟪x, x⟫ := by rw is_R_or_C.ext_iff; exact ⟨by simp, by simp [inner_self_nonneg_im]⟩ lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ := begin have H : ⟪x, x⟫ = 𝓚 (re ⟪x, x⟫) + 𝓚 (im ⟪x, x⟫) * I, { rw re_add_im, }, rw [H, is_add_hom.map_add re (𝓚 (re ⟪x, x⟫)) ((𝓚 (im ⟪x, x⟫)) * I)], rw [mul_re, I_re, mul_zero, I_im, zero_sub, tactic.ring.add_neg_eq_sub], rw [of_real_re, of_real_im, sub_zero, inner_self_nonneg_im], simp only [abs_of_real, add_zero, of_real_zero, zero_mul], exact (_root_.abs_of_nonneg inner_self_nonneg).symm, end lemma inner_self_abs_to_K {x : E} : 𝓚 (abs ⟪x, x⟫) = ⟪x, x⟫ := by { rw[←inner_self_re_abs], exact inner_self_re_to_K } lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ := by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h } lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] @[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp @[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ := by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩ lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right] } lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `⟪x + y, x + y⟫` -/ lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /-- Expand `⟪x + y, x + y⟫_ℝ` -/ lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_add_add_self, this], ring, end /- Expand `⟪x - y, x - y⟫` -/ lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Expand `⟪x - y, x - y⟫_ℝ` -/ lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_sub_sub_self, this], ring, end /-- Parallelogram law -/ lemma parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/ lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = 𝓚 (re ⟪y, y⟫) := by simp, have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw is_R_or_C.ext_iff, exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, hT, conj_div, h₁, h₃, inner_conj_sym] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / 𝓚 (re ⟪y, y⟫)) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Cauchy–Schwarz inequality for real inner products. -/ lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := begin have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y, dsimp at h₂, have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ, rw [h₁] at h₂, simpa [h₃] using h₂, end /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j), { rw inner_sum, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_right }, { intros j hj hji, rw [inner_smul_right, ho i j hji.symm, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section norm lemma norm_eq_sqrt_inner (x : E) : ∥x∥ = sqrt (re ⟪x, x⟫) := begin have h₁ : ∥x∥^2 = re ⟪x, x⟫ := norm_sq_eq_inner x, have h₂ := congr_arg sqrt h₁, simpa using h₂, end lemma norm_eq_sqrt_real_inner (x : F) : ∥x∥ = sqrt ⟪x, x⟫_ℝ := by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h } lemma inner_self_eq_norm_square (x : E) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma real_inner_self_eq_norm_square (x : F) : ⟪x, x⟫_ℝ = ∥x∥ * ∥x∥ := by { have h := @inner_self_eq_norm_square ℝ F _ _ x, simpa using h } /-- Expand the square -/ lemma norm_add_pow_two {x y : E} : ∥x + y∥^2 = ∥x∥^2 + 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [pow_two, ←inner_self_eq_norm_square]}, rw[inner_add_add_self, two_mul], simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add], rw [←inner_conj_sym, conj_re], end /-- Expand the square -/ lemma norm_add_pow_two_real {x y : F} : ∥x + y∥^2 = ∥x∥^2 + 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := by { have h := @norm_add_pow_two ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_add_mul_self {x y : E} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * (re ⟪x, y⟫) + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_add_pow_two } /-- Expand the square -/ lemma norm_add_mul_self_real {x y : F} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_add_mul_self ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_pow_two {x y : E} : ∥x - y∥^2 = ∥x∥^2 - 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [pow_two, ←inner_self_eq_norm_square]}, rw[inner_sub_sub_self], calc re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫) = re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp ... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring ... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[inner_conj_sym] ... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[conj_re] ... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring end /-- Expand the square -/ lemma norm_sub_pow_two_real {x y : F} : ∥x - y∥^2 = ∥x∥^2 - 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := by { have h := @norm_sub_pow_two ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_mul_self {x y : E} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * re ⟪x, y⟫ + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_sub_pow_two } /-- Expand the square -/ lemma norm_sub_mul_self_real {x y : F} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = (re ⟪x, x⟫) * (re ⟪y, y⟫), simp only [inner_self_eq_norm_square], ring, rw this, conv_lhs { congr, skip, rw [inner_abs_conj_sym] }, exact inner_mul_inner_self_le _ _ end /-- Cauchy–Schwarz inequality with norm -/ lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h } include 𝕜 lemma parallelogram_law_with_norm {x y : E} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := begin simp only [(inner_self_eq_norm_square _).symm], rw[←add_monoid_hom.map_add, parallelogram_law, two_mul, two_mul], simp only [add_monoid_hom.map_add], end omit 𝕜 lemma parallelogram_law_with_norm_real {x y : F} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := by { have h := @parallelogram_law_with_norm ℝ F _ _ x y, simpa using h } /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := by rw norm_add_mul_self; ring /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := by rw norm_sub_mul_self; ring /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero (x y : F) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero (x y : F) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ∥x∥ = ∥y∥ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp only [←inner_self_eq_norm_square, inner_add_left, inner_sub_right, real_inner_comm y x, sub_eq_zero, re_to_real], split, { intro h, rw [add_comm] at h, linarith }, { intro h, linarith } end /-- The real inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) ≤ 1 := begin rw _root_.abs_div, by_cases h : 0 = absR (∥x∥ * ∥y∥), { rw [←h, div_zero], norm_num }, { change 0 ≠ absR (∥x∥ * ∥y∥) at h, rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (∥x∥ * ∥y∥))) h), convert abs_real_inner_le_norm x y using 1, rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [real_inner_smul_left, ←real_inner_self_eq_norm_square] /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [inner_smul_right, ←real_inner_self_eq_norm_square] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin simp [real_inner_smul_self_right, norm_smul, _root_.abs_mul, norm_eq_abs], conv_lhs { congr, rw [←mul_assoc, mul_comm] }, apply div_self, intro h, rcases (mul_eq_zero.mp h) with h₁|h₂, { exact hx (norm_eq_zero.mp h₁) }, { rcases (mul_eq_zero.mp h₂) with h₂'|h₂'', { rw [_root_.abs_eq_zero] at h₂', exact hr h₂' }, { exact hx (norm_eq_zero.mp h₂'') } } end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw [real_inner_smul_self_right, norm_smul, norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = -1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, abs_of_neg hr, ←neg_mul_eq_neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, exact h }, refine and.intro hx0 _, set r := inner x y / (∥x∥ * ∥x∥) with hr, use r, set t := y - r • x with ht, have ht0 : ⟪x, t⟫_ℝ = 0, { rw [ht, inner_sub_right, inner_smul_right, hr, ←real_inner_self_eq_norm_square, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, real_inner_self_eq_norm_square, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), _root_.abs_div, _root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg _), _root_.abs_of_nonneg (norm_nonneg _), ←real.norm_eq_abs, ←norm_smul] at h, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2, { rw [eq_of_div_eq_one h] }, rw [pow_two, pow_two, ←real_inner_self_eq_norm_square, ←real_inner_self_eq_norm_square, inner_add_add_self] at h2, conv_rhs at h2 { congr, congr, skip, rw [real_inner_smul_left, ht0, mul_zero] }, symmetry' at h2, have h₁ : ⟪t, r • x⟫_ℝ = 0 := by rw [inner_smul_right, real_inner_comm, ht0, mul_zero], rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, rw [_root_.abs_div, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 := by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] end norm /-! ### Inner product space structure on product spaces -/ /- If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space, then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm, we use instead `pi_Lp 2 one_le_two f` for the product space, which is endowed with the `L^2` norm. -/ instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*) [Π i, inner_product_space 𝕜 (f i)] : inner_product_space 𝕜 (pi_Lp 2 one_le_two f) := { inner := λ x y, ∑ i, inner (x i) (y i), norm_sq_eq_inner := begin intro x, have h₁ : ∑ (i : ι), ∥x i∥ ^ (2 : ℕ) = ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { apply finset.sum_congr rfl, intros j hj, simp [←rpow_nat_cast] }, have h₂ : 0 ≤ ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { rw [←h₁], exact finset.sum_nonneg (λ (j : ι) (hj : j ∈ finset.univ), pow_nonneg (norm_nonneg (x j)) 2) }, simp [norm, add_monoid_hom.map_sum, ←norm_sq_eq_inner], rw [←rpow_nat_cast ((∑ (i : ι), ∥x i∥ ^ (2 : ℝ)) ^ (2 : ℝ)⁻¹) 2], rw [←rpow_mul h₂], norm_num [h₁], end, conj_sym := begin intros x y, unfold inner, rw [←finset.sum_hom finset.univ conj], apply finset.sum_congr rfl, rintros z -, apply inner_conj_sym, apply_instance end, nonneg_im := begin intro x, unfold inner, rw[←finset.sum_hom finset.univ im], apply finset.sum_eq_zero, rintros z -, exact inner_self_nonneg_im, apply_instance end, add_left := λ x y z, show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i), by simp only [inner_add_left, finset.sum_add_distrib], smul_left := λ x y r, show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i), by simp only [finset.mul_sum, inner_smul_left] } /-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/ instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 := { inner := (λ x y, (conj x) * y), norm_sq_eq_inner := λ x, by unfold inner; rw [mul_comm, mul_conj, of_real_re, norm_sq, norm_sq_eq_def], conj_sym := λ x y, by simp [mul_comm], nonneg_im := λ x, by rw[mul_im, conj_re, conj_im]; ring, add_left := λ x y z, by simp [inner, add_mul], smul_left := λ x y z, by simp [inner, mul_assoc] } /-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional space use `euclidean_space 𝕜 (fin n)`. -/ @[reducible, nolint unused_arguments] def euclidean_space (𝕜 : Type*) [nondiscrete_normed_field 𝕜] [normed_algebra ℝ 𝕜] [is_R_or_C 𝕜] (n : Type*) [fintype n] : Type* := pi_Lp 2 one_le_two (λ (i : n), 𝕜) section is_R_or_C_to_real variables {G : Type*} variables (𝕜) include 𝕜 /-- A general inner product implies a real inner product. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`. -/ def has_inner.is_R_or_C_to_real : has_inner ℝ E := { inner := λ x y, re ⟪x, y⟫ } lemma real_inner_eq_re_inner (x y : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜) x y = re ⟪x, y⟫ := rfl /-- A general inner product space structure implies a real inner product structure. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a proof to obtain a real inner product space structure from a given `𝕜`-inner product space structure. -/ def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E := { norm_sq_eq_inner := norm_sq_eq_inner, conj_sym := λ x y, inner_re_symm, nonneg_im := λ x, rfl, add_left := λ x y z, by { change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫, simp [inner_add_left] }, smul_left := begin intros x y r, change re ⟪(algebra_map ℝ 𝕜 r) • x, y⟫ = r * re ⟪x, y⟫, have : algebra_map ℝ 𝕜 r = r • (1 : 𝕜) := by simp [algebra_map, algebra.smul_def'], simp [this, inner_smul_left, smul_coe_mul_ax], end, ..has_inner.is_R_or_C_to_real 𝕜, ..normed_space.restrict_scalars' ℝ 𝕜 E } omit 𝕜 /-- A complex inner product implies a real inner product -/ instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G := inner_product_space.is_R_or_C_to_real ℂ end is_R_or_C_to_real section pi_Lp local attribute [reducible] pi_Lp variables {ι : Type*} [fintype ι] instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance @[simp] lemma findim_euclidean_space : finite_dimensional.findim 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp lemma findim_euclidean_space_fin {n : ℕ} : finite_dimensional.findim 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp end pi_Lp /-! ### Orthogonal projection in inner product spaces -/ section orthogonal open filter /-- Existence of minimizers Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. -/ -- FIXME this monolithic proof causes a deterministic timeout with `-T50000` -- It should be broken in a sequence of more manageable pieces, -- perhaps with individual statements for the three steps below. theorem exists_norm_eq_infi_of_complete_convex {K : set F} (ne : K.nonempty) (h₁ : is_complete K) (h₂ : convex K) : ∀ u : F, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u, begin let δ := ⨅ w : K, ∥u - w∥, letI : nonempty K := ne.to_subtype, have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _), have δ_le : ∀ w : K, δ ≤ ∥u - w∥, from cinfi_le ⟨0, set.forall_range_iff.2 $ λ _, norm_nonneg _⟩, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1), { have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos (le_refl _) nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩ }, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (nhds δ), { have h : tendsto (λ n:ℕ, δ) at_top (nhds δ) := tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (nhds δ), { convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] }, exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (λ x, δ_le _) (λ x, le_of_lt (hw _)) }, -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):F)), { rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):F), let wq := ((w q):F), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) := calc 4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring ... = (absR ((2:ℝ)) * ∥u - half•(wq + wp)∥) * (absR ((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by { rw _root_.abs_of_nonneg, exact add_nonneg zero_le_one zero_le_one } ... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ : by simp [norm_smul] ... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ : begin rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0), ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b := calc wp - wq = (u - wq) - (u - wp) : by rw [sub_sub_assoc_swap, add_sub_assoc, sub_add_sub_cancel'] ... = a - b : rfl, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm, have eq : δ ≤ ∥u - half • (wq + wp)∥, { rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1 }, have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥, { mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ }, have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_squares_le, { exact sqrt_nonneg _ }, rw mul_self_sqrt, exact calc ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp } ... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) (le_of_lt nat.one_div_pos_of_nat)) (le_of_lt nat.one_div_pos_of_nat)), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert this.mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, convert eq₁.add eq₂, simp only [add_zero] }, -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ∥u - v∥) := continuous.comp continuous_norm (continuous.sub continuous_const continuous_id), have : tendsto (λ n, ∥u - w n∥) at_top (nhds ∥u - v∥), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers for the projection on a convex set in a real inner product space. -/ theorem norm_eq_infi_iff_real_inner_le_zero {K : set F} (h : convex K) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ∥u - w∥, let p := ⟪u - v, w - v⟫_ℝ, let q := ∥w - v∥^2, letI : nonempty K := ⟨⟨v, hv⟩⟩, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ*θ*∥w - v∥^2 := calc ∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 : begin simp only [pow_two], apply mul_self_le_mul_self (norm_nonneg _), rw [eq], apply δ_le', apply h hw hv, exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _], end ... = ∥(u - v) - θ • (w - v)∥^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), { rw [smul_sub, sub_smul, one_smul], simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] }, rw this end ... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 : begin rw [norm_sub_pow_two, inner_smul_right, norm_smul], simp only [pow_two], show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+absR (θ)*∥w-v∥*(absR (θ)*∥w-v∥)= ∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥), rw abs_of_pos hθ₁, ring end, have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_left this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact pow_two_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (pow_two_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, letI : nonempty K := ⟨⟨v, hv⟩⟩, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_squares_le (norm_nonneg _), have := h w w.2, exact calc ∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:F) - v) : by linarith ... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:F) - v) + ∥(w:F) - v∥^2 : by { rw pow_two, refine le_add_of_nonneg_right _, exact pow_two_nonneg _ } ... = ∥(u - v) - (w - v)∥^2 : norm_sub_pow_two.symm ... = ∥u - w∥ * ∥u - w∥ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, pow_two] } }, { show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end /-- Existence of projections on complete subspaces. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (K : subspace 𝕜 E) (h : is_complete (↑K : set E)) : ∀ u : E, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (K : set E), ∥u - w∥ := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜, let K' : subspace ℝ E := K.restrict_scalars ℝ, exact exists_norm_eq_infi_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex end /-- Characterization of minimizers in the projection on a subspace, in the real case. Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`). This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over any `is_R_or_C` field. -/ theorem norm_eq_infi_iff_real_inner_eq_zero (K : subspace ℝ F) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set F), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, { rwa [norm_eq_infi_iff_real_inner_le_zero] at h, exacts [K.convex, hv] }, assume w hw, have le : ⟪u - v, w⟫_ℝ ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : ⟪u - v, w⟫_ℝ ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_real_inner_le_zero, exacts [submodule.convex _, hv] end /-- Characterization of minimizers in the projection on a subspace. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero (K : subspace 𝕜 E) {u : E} {v : E} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set E), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜, let K' : subspace ℝ E := K.restrict_scalars ℝ, split, { assume H, have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infi_iff_real_inner_eq_zero K' hv).1 H, assume w hw, apply ext, { simp [A w hw] }, { symmetry, calc im (0 : 𝕜) = 0 : im.map_zero ... = re ⟪u - v, (-I) • w⟫ : (A _ (K.smul_mem (-I) hw)).symm ... = re ((-I) * ⟪u - v, w⟫) : by rw inner_smul_right ... = im ⟪u - v, w⟫ : by simp } }, { assume H, have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0, { assume w hw, rw [real_inner_eq_re_inner, H w hw], exact zero_re' }, exact (norm_eq_infi_iff_real_inner_eq_zero K' hv).2 this } end /-- The orthogonal projection onto a complete subspace, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn {K : subspace 𝕜 E} (h : is_complete (K : set E)) (v : E) := (exists_norm_eq_infi_of_complete_subspace K h v).some /-- The unbundled orthogonal projection is in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem {K : submodule 𝕜 E} (h : is_complete (K : set E)) (v : E) : orthogonal_projection_fn h v ∈ K := (exists_norm_eq_infi_of_complete_subspace K h v).some_spec.some /-- The characterization of the unbundled orthogonal projection. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_inner_eq_zero {K : submodule 𝕜 E} (h : is_complete (K : set E)) (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection_fn h v, w⟫ = 0 := begin rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem h v), exact (exists_norm_eq_infi_of_complete_subspace K h v).some_spec.some_spec end /-- The unbundled orthogonal projection is the unique point in `K` with the orthogonality property. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero {K : submodule 𝕜 E} (h : is_complete (K : set E)) {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : v = orthogonal_projection_fn h u := begin rw [←sub_eq_zero, ←inner_self_eq_zero], have hvs : v - orthogonal_projection_fn h u ∈ K := submodule.sub_mem K hvm (orthogonal_projection_fn_mem h u), have huo : ⟪u - orthogonal_projection_fn h u, v - orthogonal_projection_fn h u⟫ = 0 := orthogonal_projection_fn_inner_eq_zero h u _ hvs, have huv : ⟪u - v, v - orthogonal_projection_fn h u⟫ = 0 := hvo _ hvs, have houv : ⟪(u - orthogonal_projection_fn h u) - (u - v), v - orthogonal_projection_fn h u⟫ = 0, { rw [inner_sub_left, huo, huv, sub_zero] }, rwa sub_sub_sub_cancel_left at houv end /-- The orthogonal projection onto a complete subspace. For most purposes, `orthogonal_projection`, which removes the `is_complete` hypothesis and is the identity map when the subspace is not complete, should be used instead. -/ def orthogonal_projection_of_complete {K : submodule 𝕜 E} (h : is_complete (K : set E)) : linear_map 𝕜 E E := { to_fun := orthogonal_projection_fn h, map_add' := λ x y, begin have hm : orthogonal_projection_fn h x + orthogonal_projection_fn h y ∈ K := submodule.add_mem K (orthogonal_projection_fn_mem h x) (orthogonal_projection_fn_mem h y), have ho : ∀ w ∈ K, ⟪x + y - (orthogonal_projection_fn h x + orthogonal_projection_fn h y), w⟫ = 0, { intros w hw, rw [add_sub_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero h _ w hw, orthogonal_projection_fn_inner_eq_zero h _ w hw, add_zero] }, rw eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hm ho end, map_smul' := λ c x, begin have hm : c • orthogonal_projection_fn h x ∈ K := submodule.smul_mem K _ (orthogonal_projection_fn_mem h x), have ho : ∀ w ∈ K, ⟪c • x - c • orthogonal_projection_fn h x, w⟫ = 0, { intros w hw, rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero h _ w hw, mul_zero] }, rw eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hm ho end } /-- The orthogonal projection onto a subspace, which is expected to be complete. If the subspace is not complete, this uses the identity map instead. -/ def orthogonal_projection (K : submodule 𝕜 E) : linear_map 𝕜 E E := if h : is_complete (K : set E) then orthogonal_projection_of_complete h else linear_map.id /-- The definition of `orthogonal_projection` using `if`. -/ lemma orthogonal_projection_def (K : submodule 𝕜 E) : orthogonal_projection K = if h : is_complete (K : set E) then orthogonal_projection_of_complete h else linear_map.id := rfl @[simp] lemma orthogonal_projection_fn_eq {K : submodule 𝕜 E} (h : is_complete (K : set E)) (v : E) : orthogonal_projection_fn h v = orthogonal_projection K v := by { rw [orthogonal_projection_def, dif_pos h], refl } /-- The orthogonal projection is in the given subspace. -/ lemma orthogonal_projection_mem {K : submodule 𝕜 E} (h : is_complete (K : set E)) (v : E) : orthogonal_projection K v ∈ K := begin rw ←orthogonal_projection_fn_eq h, exact orthogonal_projection_fn_mem h v end /-- The characterization of the orthogonal projection. -/ @[simp] lemma orthogonal_projection_inner_eq_zero (K : submodule 𝕜 E) (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection K v, w⟫ = 0 := begin simp_rw orthogonal_projection_def, split_ifs, { exact orthogonal_projection_fn_inner_eq_zero h v }, { simp }, end /-- The orthogonal projection is the unique point in `K` with the orthogonality property. -/ lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero {K : submodule 𝕜 E} (h : is_complete (K : set E)) {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : v = orthogonal_projection K u := begin rw ←orthogonal_projection_fn_eq h, exact eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero h hvm hvo end /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal (K : submodule 𝕜 E) : submodule 𝕜 E := { carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } /-- When a vector is in `K.orthogonal`. -/ lemma submodule.mem_orthogonal (K : submodule 𝕜 E) (v : E) : v ∈ K.orthogonal ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl /-- When a vector is in `K.orthogonal`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (K : submodule 𝕜 E) (v : E) : v ∈ K.orthogonal ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 := by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym] /-- A vector in `K` is orthogonal to one in `K.orthogonal`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : E} {K : submodule 𝕜 E} (hu : u ∈ K) (hv : v ∈ K.orthogonal) : ⟪u, v⟫ = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `K.orthogonal` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : E} {K : submodule 𝕜 E} (hu : u ∈ K) (hv : v ∈ K.orthogonal) : ⟪v, u⟫ = 0 := by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv /-- `K` and `K.orthogonal` have trivial intersection. -/ lemma submodule.orthogonal_disjoint (K : submodule 𝕜 E) : disjoint K K.orthogonal := begin simp_rw [submodule.disjoint_def, submodule.mem_orthogonal], exact λ x hx ho, inner_self_eq_zero.1 (ho x hx) end variables (𝕜 E) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule 𝕜 E` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule 𝕜 E) (order_dual $ submodule 𝕜 E) _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {𝕜 E} /-- `submodule.orthogonal` reverses the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂.orthogonal ≤ K₁.orthogonal := (submodule.orthogonal_gc 𝕜 E).monotone_l h /-- `K` is contained in `K.orthogonal.orthogonal`. -/ lemma submodule.le_orthogonal_orthogonal (K : submodule 𝕜 E) : K ≤ K.orthogonal.orthogonal := (submodule.orthogonal_gc 𝕜 E).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁.orthogonal ⊓ K₂.orthogonal = (K₁ ⊔ K₂).orthogonal := (submodule.orthogonal_gc 𝕜 E).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i).orthogonal) = (supr K).orthogonal := (submodule.orthogonal_gc 𝕜 E).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, submodule.orthogonal K) = (Sup s).orthogonal := (submodule.orthogonal_gc 𝕜 E).l_Sup.symm /-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁.orthogonal ⊓ K₂` span `K₂`. -/ lemma submodule.sup_orthogonal_inf_of_is_complete {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) (hc : is_complete (K₁ : set E)) : K₁ ⊔ (K₁.orthogonal ⊓ K₂) = K₂ := begin ext x, rw submodule.mem_sup, rcases exists_norm_eq_infi_of_complete_subspace K₁ hc x with ⟨v, hv, hvm⟩, rw norm_eq_infi_iff_inner_eq_zero K₁ hv at hvm, split, { rintro ⟨y, hy, z, hz, rfl⟩, exact K₂.add_mem (h hy) hz.2 }, { exact λ hx, ⟨v, hv, x - v, ⟨(K₁.mem_orthogonal' _).2 hvm, K₂.sub_mem hx (h hv)⟩, add_sub_cancel'_right _ _⟩ } end /-- If `K` is complete, `K` and `K.orthogonal` span the whole space. -/ lemma submodule.sup_orthogonal_of_is_complete {K : submodule 𝕜 E} (h : is_complete (K : set E)) : K ⊔ K.orthogonal = ⊤ := begin convert submodule.sup_orthogonal_inf_of_is_complete (le_top : K ≤ ⊤) h, simp end /-- If `K` is complete, `K` and `K.orthogonal` are complements of each other. -/ lemma submodule.is_compl_orthogonal_of_is_complete_real {K : submodule 𝕜 E} (h : is_complete (K : set E)) : is_compl K K.orthogonal := ⟨K.orthogonal_disjoint, le_of_eq (submodule.sup_orthogonal_of_is_complete h).symm⟩ open finite_dimensional /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.findim_add_inf_findim_orthogonal {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) : findim 𝕜 K₁ + findim 𝕜 (K₁.orthogonal ⊓ K₂ : submodule 𝕜 E) = findim 𝕜 K₂ := begin haveI := submodule.finite_dimensional_of_le h, have hd := submodule.dim_sup_add_dim_inf_eq K₁ (K₁.orthogonal ⊓ K₂), rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, findim_bot, submodule.sup_orthogonal_inf_of_is_complete h (submodule.complete_of_finite_dimensional _)] at hd, rw add_zero at hd, exact hd.symm end end orthogonal
1ca4a2e8978367e00e49641ba4a4d45042253cea
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/hom/lattice.lean
2843cd4bbb8d8ba01b543c682bb67f285cc6259a
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
40,996
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.lattice import order.hom.bounded import order.symm_diff /-! # Lattice homomorphisms This file defines (bounded) lattice homomorphisms. We use the `fun_like` design, so each type of morphisms has a companion typeclass which is meant to be satisfied by itself and all stricter types. ## Types of morphisms * `sup_hom`: Maps which preserve `⊔`. * `inf_hom`: Maps which preserve `⊓`. * `sup_bot_hom`: Finitary supremum homomorphisms. Maps which preserve `⊔` and `⊥`. * `inf_top_hom`: Finitary infimum homomorphisms. Maps which preserve `⊓` and `⊤`. * `lattice_hom`: Lattice homomorphisms. Maps which preserve `⊔` and `⊓`. * `bounded_lattice_hom`: Bounded lattice homomorphisms. Maps which preserve `⊤`, `⊥`, `⊔` and `⊓`. ## Typeclasses * `sup_hom_class` * `inf_hom_class` * `sup_bot_hom_class` * `inf_top_hom_class` * `lattice_hom_class` * `bounded_lattice_hom_class` ## TODO Do we need more intersections between `bot_hom`, `top_hom` and lattice homomorphisms? -/ open function order_dual variables {F ι α β γ δ : Type*} /-- The type of `⊔`-preserving functions from `α` to `β`. -/ structure sup_hom (α β : Type*) [has_sup α] [has_sup β] := (to_fun : α → β) (map_sup' (a b : α) : to_fun (a ⊔ b) = to_fun a ⊔ to_fun b) /-- The type of `⊓`-preserving functions from `α` to `β`. -/ structure inf_hom (α β : Type*) [has_inf α] [has_inf β] := (to_fun : α → β) (map_inf' (a b : α) : to_fun (a ⊓ b) = to_fun a ⊓ to_fun b) /-- The type of finitary supremum-preserving homomorphisms from `α` to `β`. -/ structure sup_bot_hom (α β : Type*) [has_sup α] [has_sup β] [has_bot α] [has_bot β] extends sup_hom α β := (map_bot' : to_fun ⊥ = ⊥) /-- The type of finitary infimum-preserving homomorphisms from `α` to `β`. -/ structure inf_top_hom (α β : Type*) [has_inf α] [has_inf β] [has_top α] [has_top β] extends inf_hom α β := (map_top' : to_fun ⊤ = ⊤) /-- The type of lattice homomorphisms from `α` to `β`. -/ structure lattice_hom (α β : Type*) [lattice α] [lattice β] extends sup_hom α β := (map_inf' (a b : α) : to_fun (a ⊓ b) = to_fun a ⊓ to_fun b) /-- The type of bounded lattice homomorphisms from `α` to `β`. -/ structure bounded_lattice_hom (α β : Type*) [lattice α] [lattice β] [bounded_order α] [bounded_order β] extends lattice_hom α β := (map_top' : to_fun ⊤ = ⊤) (map_bot' : to_fun ⊥ = ⊥) /-- `sup_hom_class F α β` states that `F` is a type of `⊔`-preserving morphisms. You should extend this class when you extend `sup_hom`. -/ class sup_hom_class (F : Type*) (α β : out_param $ Type*) [has_sup α] [has_sup β] extends fun_like F α (λ _, β) := (map_sup (f : F) (a b : α) : f (a ⊔ b) = f a ⊔ f b) /-- `inf_hom_class F α β` states that `F` is a type of `⊓`-preserving morphisms. You should extend this class when you extend `inf_hom`. -/ class inf_hom_class (F : Type*) (α β : out_param $ Type*) [has_inf α] [has_inf β] extends fun_like F α (λ _, β) := (map_inf (f : F) (a b : α) : f (a ⊓ b) = f a ⊓ f b) /-- `sup_bot_hom_class F α β` states that `F` is a type of finitary supremum-preserving morphisms. You should extend this class when you extend `sup_bot_hom`. -/ class sup_bot_hom_class (F : Type*) (α β : out_param $ Type*) [has_sup α] [has_sup β] [has_bot α] [has_bot β] extends sup_hom_class F α β := (map_bot (f : F) : f ⊥ = ⊥) /-- `inf_top_hom_class F α β` states that `F` is a type of finitary infimum-preserving morphisms. You should extend this class when you extend `sup_bot_hom`. -/ class inf_top_hom_class (F : Type*) (α β : out_param $ Type*) [has_inf α] [has_inf β] [has_top α] [has_top β] extends inf_hom_class F α β := (map_top (f : F) : f ⊤ = ⊤) /-- `lattice_hom_class F α β` states that `F` is a type of lattice morphisms. You should extend this class when you extend `lattice_hom`. -/ class lattice_hom_class (F : Type*) (α β : out_param $ Type*) [lattice α] [lattice β] extends sup_hom_class F α β := (map_inf (f : F) (a b : α) : f (a ⊓ b) = f a ⊓ f b) /-- `bounded_lattice_hom_class F α β` states that `F` is a type of bounded lattice morphisms. You should extend this class when you extend `bounded_lattice_hom`. -/ class bounded_lattice_hom_class (F : Type*) (α β : out_param $ Type*) [lattice α] [lattice β] [bounded_order α] [bounded_order β] extends lattice_hom_class F α β := (map_top (f : F) : f ⊤ = ⊤) (map_bot (f : F) : f ⊥ = ⊥) export sup_hom_class (map_sup) export inf_hom_class (map_inf) attribute [simp] map_top map_bot map_sup map_inf @[priority 100] -- See note [lower instance priority] instance sup_hom_class.to_order_hom_class [semilattice_sup α] [semilattice_sup β] [sup_hom_class F α β] : order_hom_class F α β := ⟨λ f a b h, by rw [←sup_eq_right, ←map_sup, sup_eq_right.2 h]⟩ @[priority 100] -- See note [lower instance priority] instance inf_hom_class.to_order_hom_class [semilattice_inf α] [semilattice_inf β] [inf_hom_class F α β] : order_hom_class F α β := ⟨λ f a b h, by rw [←inf_eq_left, ←map_inf, inf_eq_left.2 h]⟩ @[priority 100] -- See note [lower instance priority] instance sup_bot_hom_class.to_bot_hom_class [has_sup α] [has_sup β] [has_bot α] [has_bot β] [sup_bot_hom_class F α β] : bot_hom_class F α β := { .. ‹sup_bot_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance inf_top_hom_class.to_top_hom_class [has_inf α] [has_inf β] [has_top α] [has_top β] [inf_top_hom_class F α β] : top_hom_class F α β := { .. ‹inf_top_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance lattice_hom_class.to_inf_hom_class [lattice α] [lattice β] [lattice_hom_class F α β] : inf_hom_class F α β := { .. ‹lattice_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance bounded_lattice_hom_class.to_sup_bot_hom_class [lattice α] [lattice β] [bounded_order α] [bounded_order β] [bounded_lattice_hom_class F α β] : sup_bot_hom_class F α β := { .. ‹bounded_lattice_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance bounded_lattice_hom_class.to_inf_top_hom_class [lattice α] [lattice β] [bounded_order α] [bounded_order β] [bounded_lattice_hom_class F α β] : inf_top_hom_class F α β := { .. ‹bounded_lattice_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance bounded_lattice_hom_class.to_bounded_order_hom_class [lattice α] [lattice β] [bounded_order α] [bounded_order β] [bounded_lattice_hom_class F α β] : bounded_order_hom_class F α β := { .. ‹bounded_lattice_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_sup_hom_class [semilattice_sup α] [semilattice_sup β] [order_iso_class F α β] : sup_hom_class F α β := ⟨λ f a b, eq_of_forall_ge_iff $ λ c, by simp only [←le_map_inv_iff, sup_le_iff]⟩ @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_inf_hom_class [semilattice_inf α] [semilattice_inf β] [order_iso_class F α β] : inf_hom_class F α β := ⟨λ f a b, eq_of_forall_le_iff $ λ c, by simp only [←map_inv_le_iff, le_inf_iff]⟩ @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_sup_bot_hom_class [semilattice_sup α] [order_bot α] [semilattice_sup β] [order_bot β] [order_iso_class F α β] : sup_bot_hom_class F α β := { ..order_iso_class.to_sup_hom_class, ..order_iso_class.to_bot_hom_class } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_inf_top_hom_class [semilattice_inf α] [order_top α] [semilattice_inf β] [order_top β] [order_iso_class F α β] : inf_top_hom_class F α β := { ..order_iso_class.to_inf_hom_class, ..order_iso_class.to_top_hom_class } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_lattice_hom_class [lattice α] [lattice β] [order_iso_class F α β] : lattice_hom_class F α β := { ..order_iso_class.to_sup_hom_class, ..order_iso_class.to_inf_hom_class } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_bounded_lattice_hom_class [lattice α] [lattice β] [bounded_order α] [bounded_order β] [order_iso_class F α β] : bounded_lattice_hom_class F α β := { ..order_iso_class.to_lattice_hom_class, ..order_iso_class.to_bounded_order_hom_class } @[simp] lemma map_finset_sup [semilattice_sup α] [order_bot α] [semilattice_sup β] [order_bot β] [sup_bot_hom_class F α β] (f : F) (s : finset ι) (g : ι → α) : f (s.sup g) = s.sup (f ∘ g) := finset.cons_induction_on s (map_bot f) $ λ i s _ h, by rw [finset.sup_cons, finset.sup_cons, map_sup, h] @[simp] lemma map_finset_inf [semilattice_inf α] [order_top α] [semilattice_inf β] [order_top β] [inf_top_hom_class F α β] (f : F) (s : finset ι) (g : ι → α) : f (s.inf g) = s.inf (f ∘ g) := finset.cons_induction_on s (map_top f) $ λ i s _ h, by rw [finset.inf_cons, finset.inf_cons, map_inf, h] section bounded_lattice variables [lattice α] [bounded_order α] [lattice β] [bounded_order β] [bounded_lattice_hom_class F α β] (f : F) {a b : α} include β lemma disjoint.map (h : disjoint a b) : disjoint (f a) (f b) := by rw [disjoint_iff, ←map_inf, h.eq_bot, map_bot] lemma codisjoint.map (h : codisjoint a b) : codisjoint (f a) (f b) := by rw [codisjoint_iff, ←map_sup, h.eq_top, map_top] lemma is_compl.map (h : is_compl a b) : is_compl (f a) (f b) := ⟨h.1.map _, h.2.map _⟩ end bounded_lattice section boolean_algebra variables [boolean_algebra α] [boolean_algebra β] [bounded_lattice_hom_class F α β] (f : F) include β lemma map_compl (a : α) : f aᶜ = (f a)ᶜ := (is_compl_compl.map _).compl_eq.symm lemma map_sdiff (a b : α) : f (a \ b) = f a \ f b := by rw [sdiff_eq, sdiff_eq, map_inf, map_compl] lemma map_symm_diff (a b : α) : f (a ∆ b) = f a ∆ f b := by rw [symm_diff, symm_diff, map_sup, map_sdiff, map_sdiff] end boolean_algebra instance [has_sup α] [has_sup β] [sup_hom_class F α β] : has_coe_t F (sup_hom α β) := ⟨λ f, ⟨f, map_sup f⟩⟩ instance [has_inf α] [has_inf β] [inf_hom_class F α β] : has_coe_t F (inf_hom α β) := ⟨λ f, ⟨f, map_inf f⟩⟩ instance [has_sup α] [has_sup β] [has_bot α] [has_bot β] [sup_bot_hom_class F α β] : has_coe_t F (sup_bot_hom α β) := ⟨λ f, ⟨f, map_bot f⟩⟩ instance [has_inf α] [has_inf β] [has_top α] [has_top β] [inf_top_hom_class F α β] : has_coe_t F (inf_top_hom α β) := ⟨λ f, ⟨f, map_top f⟩⟩ instance [lattice α] [lattice β] [lattice_hom_class F α β] : has_coe_t F (lattice_hom α β) := ⟨λ f, { to_fun := f, map_sup' := map_sup f, map_inf' := map_inf f }⟩ instance [lattice α] [lattice β] [bounded_order α] [bounded_order β] [bounded_lattice_hom_class F α β] : has_coe_t F (bounded_lattice_hom α β) := ⟨λ f, { to_fun := f, map_top' := map_top f, map_bot' := map_bot f, ..(f : lattice_hom α β) }⟩ /-! ### Supremum homomorphisms -/ namespace sup_hom variables [has_sup α] section has_sup variables [has_sup β] [has_sup γ] [has_sup δ] instance : sup_hom_class (sup_hom α β) α β := { coe := sup_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_sup := sup_hom.map_sup' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (sup_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : sup_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : sup_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `sup_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : sup_hom α β) (f' : α → β) (h : f' = f) : sup_hom α β := { to_fun := f', map_sup' := h.symm ▸ f.map_sup' } variables (α) /-- `id` as a `sup_hom`. -/ protected def id : sup_hom α α := ⟨id, λ a b, rfl⟩ instance : inhabited (sup_hom α α) := ⟨sup_hom.id α⟩ @[simp] lemma coe_id : ⇑(sup_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : sup_hom.id α a = a := rfl /-- Composition of `sup_hom`s as a `sup_hom`. -/ def comp (f : sup_hom β γ) (g : sup_hom α β) : sup_hom α γ := { to_fun := f ∘ g, map_sup' := λ a b, by rw [comp_apply, map_sup, map_sup] } @[simp] lemma coe_comp (f : sup_hom β γ) (g : sup_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : sup_hom β γ) (g : sup_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : sup_hom γ δ) (g : sup_hom β γ) (h : sup_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : sup_hom α β) : f.comp (sup_hom.id α) = f := sup_hom.ext $ λ a, rfl @[simp] lemma id_comp (f : sup_hom α β) : (sup_hom.id β).comp f = f := sup_hom.ext $ λ a, rfl lemma cancel_right {g₁ g₂ : sup_hom β γ} {f : sup_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, sup_hom.ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : sup_hom β γ} {f₁ f₂ : sup_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, sup_hom.ext $ λ a, hg $ by rw [←sup_hom.comp_apply, h, sup_hom.comp_apply], congr_arg _⟩ end has_sup variables (α) [semilattice_sup β] /-- The constant function as a `sup_hom`. -/ def const (b : β) : sup_hom α β := ⟨λ _, b, λ _ _, sup_idem.symm⟩ @[simp] lemma coe_const (b : β) : ⇑(const α b) = function.const α b := rfl @[simp] lemma const_apply (b : β) (a : α) : const α b a = b := rfl variables {α} instance : has_sup (sup_hom α β) := ⟨λ f g, ⟨f ⊔ g, λ a b, by { rw [pi.sup_apply, map_sup, map_sup], exact sup_sup_sup_comm _ _ _ _ }⟩⟩ instance : semilattice_sup (sup_hom α β) := fun_like.coe_injective.semilattice_sup _ $ λ f g, rfl instance [has_bot β] : has_bot (sup_hom α β) := ⟨sup_hom.const α ⊥⟩ instance [has_top β] : has_top (sup_hom α β) := ⟨sup_hom.const α ⊤⟩ instance [order_bot β] : order_bot (sup_hom α β) := order_bot.lift (coe_fn : _ → α → β) (λ _ _, id) rfl instance [order_top β] : order_top (sup_hom α β) := order_top.lift (coe_fn : _ → α → β) (λ _ _, id) rfl instance [bounded_order β] : bounded_order (sup_hom α β) := bounded_order.lift (coe_fn : _ → α → β) (λ _ _, id) rfl rfl @[simp] lemma coe_sup (f g : sup_hom α β) : ⇑(f ⊔ g) = f ⊔ g := rfl @[simp] lemma coe_bot [has_bot β] : ⇑(⊥ : sup_hom α β) = ⊥ := rfl @[simp] lemma coe_top [has_top β] : ⇑(⊤ : sup_hom α β) = ⊤ := rfl @[simp] lemma sup_apply (f g : sup_hom α β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma bot_apply [has_bot β] (a : α) : (⊥ : sup_hom α β) a = ⊥ := rfl @[simp] lemma top_apply [has_top β] (a : α) : (⊤ : sup_hom α β) a = ⊤ := rfl end sup_hom /-! ### Infimum homomorphisms -/ namespace inf_hom variables [has_inf α] section has_inf variables [has_inf β] [has_inf γ] [has_inf δ] instance : inf_hom_class (inf_hom α β) α β := { coe := inf_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_inf := inf_hom.map_inf' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (inf_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : inf_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : inf_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of an `inf_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : inf_hom α β) (f' : α → β) (h : f' = f) : inf_hom α β := { to_fun := f', map_inf' := h.symm ▸ f.map_inf' } variables (α) /-- `id` as an `inf_hom`. -/ protected def id : inf_hom α α := ⟨id, λ a b, rfl⟩ instance : inhabited (inf_hom α α) := ⟨inf_hom.id α⟩ @[simp] lemma coe_id : ⇑(inf_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : inf_hom.id α a = a := rfl /-- Composition of `inf_hom`s as an `inf_hom`. -/ def comp (f : inf_hom β γ) (g : inf_hom α β) : inf_hom α γ := { to_fun := f ∘ g, map_inf' := λ a b, by rw [comp_apply, map_inf, map_inf] } @[simp] lemma coe_comp (f : inf_hom β γ) (g : inf_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : inf_hom β γ) (g : inf_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : inf_hom γ δ) (g : inf_hom β γ) (h : inf_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : inf_hom α β) : f.comp (inf_hom.id α) = f := inf_hom.ext $ λ a, rfl @[simp] lemma id_comp (f : inf_hom α β) : (inf_hom.id β).comp f = f := inf_hom.ext $ λ a, rfl lemma cancel_right {g₁ g₂ : inf_hom β γ} {f : inf_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, inf_hom.ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : inf_hom β γ} {f₁ f₂ : inf_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, inf_hom.ext $ λ a, hg $ by rw [←inf_hom.comp_apply, h, inf_hom.comp_apply], congr_arg _⟩ end has_inf variables (α) [semilattice_inf β] /-- The constant function as an `inf_hom`. -/ def const (b : β) : inf_hom α β := ⟨λ _, b, λ _ _, inf_idem.symm⟩ @[simp] lemma coe_const (b : β) : ⇑(const α b) = function.const α b := rfl @[simp] lemma const_apply (b : β) (a : α) : const α b a = b := rfl variables {α} instance : has_inf (inf_hom α β) := ⟨λ f g, ⟨f ⊓ g, λ a b, by { rw [pi.inf_apply, map_inf, map_inf], exact inf_inf_inf_comm _ _ _ _ }⟩⟩ instance : semilattice_inf (inf_hom α β) := fun_like.coe_injective.semilattice_inf _ $ λ f g, rfl instance [has_bot β] : has_bot (inf_hom α β) := ⟨inf_hom.const α ⊥⟩ instance [has_top β] : has_top (inf_hom α β) := ⟨inf_hom.const α ⊤⟩ instance [order_bot β] : order_bot (inf_hom α β) := order_bot.lift (coe_fn : _ → α → β) (λ _ _, id) rfl instance [order_top β] : order_top (inf_hom α β) := order_top.lift (coe_fn : _ → α → β) (λ _ _, id) rfl instance [bounded_order β] : bounded_order (inf_hom α β) := bounded_order.lift (coe_fn : _ → α → β) (λ _ _, id) rfl rfl @[simp] lemma coe_inf (f g : inf_hom α β) : ⇑(f ⊓ g) = f ⊓ g := rfl @[simp] lemma coe_bot [has_bot β] : ⇑(⊥ : inf_hom α β) = ⊥ := rfl @[simp] lemma coe_top [has_top β] : ⇑(⊤ : inf_hom α β) = ⊤ := rfl @[simp] lemma inf_apply (f g : inf_hom α β) (a : α) : (f ⊓ g) a = f a ⊓ g a := rfl @[simp] lemma bot_apply [has_bot β] (a : α) : (⊥ : inf_hom α β) a = ⊥ := rfl @[simp] lemma top_apply [has_top β] (a : α) : (⊤ : inf_hom α β) a = ⊤ := rfl end inf_hom /-! ### Finitary supremum homomorphisms -/ namespace sup_bot_hom variables [has_sup α] [has_bot α] section has_sup variables [has_sup β] [has_bot β] [has_sup γ] [has_bot γ] [has_sup δ] [has_bot δ] /-- Reinterpret a `sup_bot_hom` as a `bot_hom`. -/ def to_bot_hom (f : sup_bot_hom α β) : bot_hom α β := { ..f } instance : sup_bot_hom_class (sup_bot_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_sup := λ f, f.map_sup', map_bot := λ f, f.map_bot' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (sup_bot_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : sup_bot_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : sup_bot_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `sup_bot_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : sup_bot_hom α β) (f' : α → β) (h : f' = f) : sup_bot_hom α β := { to_sup_hom := f.to_sup_hom.copy f' h, ..f.to_bot_hom.copy f' h } variables (α) /-- `id` as a `sup_bot_hom`. -/ @[simps] protected def id : sup_bot_hom α α := ⟨sup_hom.id α, rfl⟩ instance : inhabited (sup_bot_hom α α) := ⟨sup_bot_hom.id α⟩ @[simp] lemma coe_id : ⇑(sup_bot_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : sup_bot_hom.id α a = a := rfl /-- Composition of `sup_bot_hom`s as a `sup_bot_hom`. -/ def comp (f : sup_bot_hom β γ) (g : sup_bot_hom α β) : sup_bot_hom α γ := { ..f.to_sup_hom.comp g.to_sup_hom, ..f.to_bot_hom.comp g.to_bot_hom } @[simp] lemma coe_comp (f : sup_bot_hom β γ) (g : sup_bot_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : sup_bot_hom β γ) (g : sup_bot_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : sup_bot_hom γ δ) (g : sup_bot_hom β γ) (h : sup_bot_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : sup_bot_hom α β) : f.comp (sup_bot_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : sup_bot_hom α β) : (sup_bot_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : sup_bot_hom β γ} {f : sup_bot_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : sup_bot_hom β γ} {f₁ f₂ : sup_bot_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, sup_bot_hom.ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end has_sup variables [semilattice_sup β] [order_bot β] instance : has_sup (sup_bot_hom α β) := ⟨λ f g, { to_sup_hom := f.to_sup_hom ⊔ g.to_sup_hom, ..f.to_bot_hom ⊔ g.to_bot_hom }⟩ instance : semilattice_sup (sup_bot_hom α β) := fun_like.coe_injective.semilattice_sup _ $ λ f g, rfl instance : order_bot (sup_bot_hom α β) := { bot := ⟨⊥, rfl⟩, bot_le := λ f, bot_le } @[simp] lemma coe_sup (f g : sup_bot_hom α β) : ⇑(f ⊔ g) = f ⊔ g := rfl @[simp] lemma coe_bot : ⇑(⊥ : sup_bot_hom α β) = ⊥ := rfl @[simp] lemma sup_apply (f g : sup_bot_hom α β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma bot_apply (a : α) : (⊥ : sup_bot_hom α β) a = ⊥ := rfl end sup_bot_hom /-! ### Finitary infimum homomorphisms -/ namespace inf_top_hom variables [has_inf α] [has_top α] section has_inf variables [has_inf β] [has_top β] [has_inf γ] [has_top γ] [has_inf δ] [has_top δ] /-- Reinterpret an `inf_top_hom` as a `top_hom`. -/ def to_top_hom (f : inf_top_hom α β) : top_hom α β := { ..f } instance : inf_top_hom_class (inf_top_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_inf := λ f, f.map_inf', map_top := λ f, f.map_top' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (inf_top_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : inf_top_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : inf_top_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of an `inf_top_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : inf_top_hom α β) (f' : α → β) (h : f' = f) : inf_top_hom α β := { to_inf_hom := f.to_inf_hom.copy f' h, ..f.to_top_hom.copy f' h } variables (α) /-- `id` as an `inf_top_hom`. -/ @[simps] protected def id : inf_top_hom α α := ⟨inf_hom.id α, rfl⟩ instance : inhabited (inf_top_hom α α) := ⟨inf_top_hom.id α⟩ @[simp] lemma coe_id : ⇑(inf_top_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : inf_top_hom.id α a = a := rfl /-- Composition of `inf_top_hom`s as an `inf_top_hom`. -/ def comp (f : inf_top_hom β γ) (g : inf_top_hom α β) : inf_top_hom α γ := { ..f.to_inf_hom.comp g.to_inf_hom, ..f.to_top_hom.comp g.to_top_hom } @[simp] lemma coe_comp (f : inf_top_hom β γ) (g : inf_top_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : inf_top_hom β γ) (g : inf_top_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : inf_top_hom γ δ) (g : inf_top_hom β γ) (h : inf_top_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : inf_top_hom α β) : f.comp (inf_top_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : inf_top_hom α β) : (inf_top_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : inf_top_hom β γ} {f : inf_top_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : inf_top_hom β γ} {f₁ f₂ : inf_top_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, inf_top_hom.ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end has_inf variables [semilattice_inf β] [order_top β] instance : has_inf (inf_top_hom α β) := ⟨λ f g, { to_inf_hom := f.to_inf_hom ⊓ g.to_inf_hom, ..f.to_top_hom ⊓ g.to_top_hom }⟩ instance : semilattice_inf (inf_top_hom α β) := fun_like.coe_injective.semilattice_inf _ $ λ f g, rfl instance : order_top (inf_top_hom α β) := { top := ⟨⊤, rfl⟩, le_top := λ f, le_top } @[simp] lemma coe_inf (f g : inf_top_hom α β) : ⇑(f ⊓ g) = f ⊓ g := rfl @[simp] lemma coe_top : ⇑(⊤ : inf_top_hom α β) = ⊤ := rfl @[simp] lemma inf_apply (f g : inf_top_hom α β) (a : α) : (f ⊓ g) a = f a ⊓ g a := rfl @[simp] lemma top_apply (a : α) : (⊤ : inf_top_hom α β) a = ⊤ := rfl end inf_top_hom /-! ### Lattice homomorphisms -/ namespace lattice_hom variables [lattice α] [lattice β] [lattice γ] [lattice δ] /-- Reinterpret a `lattice_hom` as an `inf_hom`. -/ def to_inf_hom (f : lattice_hom α β) : inf_hom α β := { ..f } instance : lattice_hom_class (lattice_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by obtain ⟨⟨_, _⟩, _⟩ := f; obtain ⟨⟨_, _⟩, _⟩ := g; congr', map_sup := λ f, f.map_sup', map_inf := λ f, f.map_inf' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (lattice_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : lattice_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : lattice_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `lattice_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : lattice_hom α β) (f' : α → β) (h : f' = f) : lattice_hom α β := { .. f.to_sup_hom.copy f' h, .. f.to_inf_hom.copy f' h } variables (α) /-- `id` as a `lattice_hom`. -/ protected def id : lattice_hom α α := { to_fun := id, map_sup' := λ _ _, rfl, map_inf' := λ _ _, rfl } instance : inhabited (lattice_hom α α) := ⟨lattice_hom.id α⟩ @[simp] lemma coe_id : ⇑(lattice_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : lattice_hom.id α a = a := rfl /-- Composition of `lattice_hom`s as a `lattice_hom`. -/ def comp (f : lattice_hom β γ) (g : lattice_hom α β) : lattice_hom α γ := { ..f.to_sup_hom.comp g.to_sup_hom, ..f.to_inf_hom.comp g.to_inf_hom } @[simp] lemma coe_comp (f : lattice_hom β γ) (g : lattice_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : lattice_hom β γ) (g : lattice_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma coe_comp_sup_hom (f : lattice_hom β γ) (g : lattice_hom α β) : (f.comp g : sup_hom α γ) = (f : sup_hom β γ).comp g := rfl @[simp] lemma coe_comp_inf_hom (f : lattice_hom β γ) (g : lattice_hom α β) : (f.comp g : inf_hom α γ) = (f : inf_hom β γ).comp g := rfl @[simp] lemma comp_assoc (f : lattice_hom γ δ) (g : lattice_hom β γ) (h : lattice_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : lattice_hom α β) : f.comp (lattice_hom.id α) = f := lattice_hom.ext $ λ a, rfl @[simp] lemma id_comp (f : lattice_hom α β) : (lattice_hom.id β).comp f = f := lattice_hom.ext $ λ a, rfl lemma cancel_right {g₁ g₂ : lattice_hom β γ} {f : lattice_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, lattice_hom.ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : lattice_hom β γ} {f₁ f₂ : lattice_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, lattice_hom.ext $ λ a, hg $ by rw [←lattice_hom.comp_apply, h, lattice_hom.comp_apply], congr_arg _⟩ end lattice_hom namespace order_hom_class variables (α β) [linear_order α] [lattice β] [order_hom_class F α β] /-- An order homomorphism from a linear order is a lattice homomorphism. -/ @[reducible] def to_lattice_hom_class : lattice_hom_class F α β := { map_sup := λ f a b, begin obtain h | h := le_total a b, { rw [sup_eq_right.2 h, sup_eq_right.2 (order_hom_class.mono f h : f a ≤ f b)] }, { rw [sup_eq_left.2 h, sup_eq_left.2 (order_hom_class.mono f h : f b ≤ f a)] } end, map_inf := λ f a b, begin obtain h | h := le_total a b, { rw [inf_eq_left.2 h, inf_eq_left.2 (order_hom_class.mono f h : f a ≤ f b)] }, { rw [inf_eq_right.2 h, inf_eq_right.2 (order_hom_class.mono f h : f b ≤ f a)] } end, .. ‹order_hom_class F α β› } /-- Reinterpret an order homomorphism to a linear order as a `lattice_hom`. -/ def to_lattice_hom (f : F) : lattice_hom α β := by { haveI : lattice_hom_class F α β := order_hom_class.to_lattice_hom_class α β, exact f } @[simp] lemma coe_to_lattice_hom (f : F) : ⇑(to_lattice_hom α β f) = f := rfl @[simp] lemma to_lattice_hom_apply (f : F) (a : α) : to_lattice_hom α β f a = f a := rfl end order_hom_class /-! ### Bounded lattice homomorphisms -/ namespace bounded_lattice_hom variables [lattice α] [lattice β] [lattice γ] [lattice δ] [bounded_order α] [bounded_order β] [bounded_order γ] [bounded_order δ] /-- Reinterpret a `bounded_lattice_hom` as a `sup_bot_hom`. -/ def to_sup_bot_hom (f : bounded_lattice_hom α β) : sup_bot_hom α β := { ..f } /-- Reinterpret a `bounded_lattice_hom` as an `inf_top_hom`. -/ def to_inf_top_hom (f : bounded_lattice_hom α β) : inf_top_hom α β := { ..f } /-- Reinterpret a `bounded_lattice_hom` as a `bounded_order_hom`. -/ def to_bounded_order_hom (f : bounded_lattice_hom α β) : bounded_order_hom α β := { ..f, ..(f.to_lattice_hom : α →o β) } instance : bounded_lattice_hom_class (bounded_lattice_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := f; obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := g; congr', map_sup := λ f, f.map_sup', map_inf := λ f, f.map_inf', map_top := λ f, f.map_top', map_bot := λ f, f.map_bot' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (bounded_lattice_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : bounded_lattice_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : bounded_lattice_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `bounded_lattice_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : bounded_lattice_hom α β) (f' : α → β) (h : f' = f) : bounded_lattice_hom α β := { .. f.to_lattice_hom.copy f' h, .. f.to_bounded_order_hom.copy f' h } variables (α) /-- `id` as a `bounded_lattice_hom`. -/ protected def id : bounded_lattice_hom α α := { ..lattice_hom.id α, ..bounded_order_hom.id α } instance : inhabited (bounded_lattice_hom α α) := ⟨bounded_lattice_hom.id α⟩ @[simp] lemma coe_id : ⇑(bounded_lattice_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : bounded_lattice_hom.id α a = a := rfl /-- Composition of `bounded_lattice_hom`s as a `bounded_lattice_hom`. -/ def comp (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) : bounded_lattice_hom α γ := { ..f.to_lattice_hom.comp g.to_lattice_hom, ..f.to_bounded_order_hom.comp g.to_bounded_order_hom } @[simp] lemma coe_comp (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma coe_comp_lattice_hom (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) : (f.comp g : lattice_hom α γ) = (f : lattice_hom β γ).comp g := rfl @[simp] lemma coe_comp_sup_hom (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) : (f.comp g : sup_hom α γ) = (f : sup_hom β γ).comp g := rfl @[simp] lemma coe_comp_inf_hom (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) : (f.comp g : inf_hom α γ) = (f : inf_hom β γ).comp g := rfl @[simp] lemma comp_assoc (f : bounded_lattice_hom γ δ) (g : bounded_lattice_hom β γ) (h : bounded_lattice_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : bounded_lattice_hom α β) : f.comp (bounded_lattice_hom.id α) = f := bounded_lattice_hom.ext $ λ a, rfl @[simp] lemma id_comp (f : bounded_lattice_hom α β) : (bounded_lattice_hom.id β).comp f = f := bounded_lattice_hom.ext $ λ a, rfl lemma cancel_right {g₁ g₂ : bounded_lattice_hom β γ} {f : bounded_lattice_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, bounded_lattice_hom.ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : bounded_lattice_hom β γ} {f₁ f₂ : bounded_lattice_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end bounded_lattice_hom /-! ### Dual homs -/ namespace sup_hom variables [has_sup α] [has_sup β] [has_sup γ] /-- Reinterpret a supremum homomorphism as an infimum homomorphism between the dual lattices. -/ @[simps] protected def dual : sup_hom α β ≃ inf_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f, f.map_sup'⟩, inv_fun := λ f, ⟨f, f.map_inf'⟩, left_inv := λ f, sup_hom.ext $ λ _, rfl, right_inv := λ f, inf_hom.ext $ λ _, rfl } @[simp] lemma dual_id : (sup_hom.id α).dual = inf_hom.id _ := rfl @[simp] lemma dual_comp (g : sup_hom β γ) (f : sup_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : sup_hom.dual.symm (inf_hom.id _) = sup_hom.id α := rfl @[simp] lemma symm_dual_comp (g : inf_hom βᵒᵈ γᵒᵈ) (f : inf_hom αᵒᵈ βᵒᵈ) : sup_hom.dual.symm (g.comp f) = (sup_hom.dual.symm g).comp (sup_hom.dual.symm f) := rfl end sup_hom namespace inf_hom variables [has_inf α] [has_inf β] [has_inf γ] /-- Reinterpret an infimum homomorphism as a supremum homomorphism between the dual lattices. -/ @[simps] protected def dual : inf_hom α β ≃ sup_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f, f.map_inf'⟩, inv_fun := λ f, ⟨f, f.map_sup'⟩, left_inv := λ f, inf_hom.ext $ λ _, rfl, right_inv := λ f, sup_hom.ext $ λ _, rfl } @[simp] lemma dual_id : (inf_hom.id α).dual = sup_hom.id _ := rfl @[simp] lemma dual_comp (g : inf_hom β γ) (f : inf_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : inf_hom.dual.symm (sup_hom.id _) = inf_hom.id α := rfl @[simp] lemma symm_dual_comp (g : sup_hom βᵒᵈ γᵒᵈ) (f : sup_hom αᵒᵈ βᵒᵈ) : inf_hom.dual.symm (g.comp f) = (inf_hom.dual.symm g).comp (inf_hom.dual.symm f) := rfl end inf_hom namespace sup_bot_hom variables [has_sup α] [has_bot α] [has_sup β] [has_bot β] [has_sup γ] [has_bot γ] /-- Reinterpret a finitary supremum homomorphism as a finitary infimum homomorphism between the dual lattices. -/ def dual : sup_bot_hom α β ≃ inf_top_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f.to_sup_hom.dual, f.map_bot'⟩, inv_fun := λ f, ⟨sup_hom.dual.symm f.to_inf_hom, f.map_top'⟩, left_inv := λ f, sup_bot_hom.ext $ λ _, rfl, right_inv := λ f, inf_top_hom.ext $ λ _, rfl } @[simp] lemma dual_id : (sup_bot_hom.id α).dual = inf_top_hom.id _ := rfl @[simp] lemma dual_comp (g : sup_bot_hom β γ) (f : sup_bot_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : sup_bot_hom.dual.symm (inf_top_hom.id _) = sup_bot_hom.id α := rfl @[simp] lemma symm_dual_comp (g : inf_top_hom βᵒᵈ γᵒᵈ) (f : inf_top_hom αᵒᵈ βᵒᵈ) : sup_bot_hom.dual.symm (g.comp f) = (sup_bot_hom.dual.symm g).comp (sup_bot_hom.dual.symm f) := rfl end sup_bot_hom namespace inf_top_hom variables [has_inf α] [has_top α] [has_inf β] [has_top β] [has_inf γ] [has_top γ] /-- Reinterpret a finitary infimum homomorphism as a finitary supremum homomorphism between the dual lattices. -/ @[simps] protected def dual : inf_top_hom α β ≃ sup_bot_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f.to_inf_hom.dual, f.map_top'⟩, inv_fun := λ f, ⟨inf_hom.dual.symm f.to_sup_hom, f.map_bot'⟩, left_inv := λ f, inf_top_hom.ext $ λ _, rfl, right_inv := λ f, sup_bot_hom.ext $ λ _, rfl } @[simp] lemma dual_id : (inf_top_hom.id α).dual = sup_bot_hom.id _ := rfl @[simp] lemma dual_comp (g : inf_top_hom β γ) (f : inf_top_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : inf_top_hom.dual.symm (sup_bot_hom.id _) = inf_top_hom.id α := rfl @[simp] lemma symm_dual_comp (g : sup_bot_hom βᵒᵈ γᵒᵈ) (f : sup_bot_hom αᵒᵈ βᵒᵈ) : inf_top_hom.dual.symm (g.comp f) = (inf_top_hom.dual.symm g).comp (inf_top_hom.dual.symm f) := rfl end inf_top_hom namespace lattice_hom variables [lattice α] [lattice β] [lattice γ] /-- Reinterpret a lattice homomorphism as a lattice homomorphism between the dual lattices. -/ @[simps] protected def dual : lattice_hom α β ≃ lattice_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f.to_inf_hom.dual, f.map_sup'⟩, inv_fun := λ f, ⟨f.to_inf_hom.dual, f.map_sup'⟩, left_inv := λ f, ext $ λ a, rfl, right_inv := λ f, ext $ λ a, rfl } @[simp] lemma dual_id : (lattice_hom.id α).dual = lattice_hom.id _ := rfl @[simp] lemma dual_comp (g : lattice_hom β γ) (f : lattice_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : lattice_hom.dual.symm (lattice_hom.id _) = lattice_hom.id α := rfl @[simp] lemma symm_dual_comp (g : lattice_hom βᵒᵈ γᵒᵈ) (f : lattice_hom αᵒᵈ βᵒᵈ) : lattice_hom.dual.symm (g.comp f) = (lattice_hom.dual.symm g).comp (lattice_hom.dual.symm f) := rfl end lattice_hom namespace bounded_lattice_hom variables [lattice α] [bounded_order α] [lattice β] [bounded_order β] [lattice γ] [bounded_order γ] /-- Reinterpret a bounded lattice homomorphism as a bounded lattice homomorphism between the dual bounded lattices. -/ @[simps] protected def dual : bounded_lattice_hom α β ≃ bounded_lattice_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f.to_lattice_hom.dual, f.map_bot', f.map_top'⟩, inv_fun := λ f, ⟨lattice_hom.dual.symm f.to_lattice_hom, f.map_bot', f.map_top'⟩, left_inv := λ f, ext $ λ a, rfl, right_inv := λ f, ext $ λ a, rfl } @[simp] lemma dual_id : (bounded_lattice_hom.id α).dual = bounded_lattice_hom.id _ := rfl @[simp] lemma dual_comp (g : bounded_lattice_hom β γ) (f : bounded_lattice_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : bounded_lattice_hom.dual.symm (bounded_lattice_hom.id _) = bounded_lattice_hom.id α := rfl @[simp] lemma symm_dual_comp (g : bounded_lattice_hom βᵒᵈ γᵒᵈ) (f : bounded_lattice_hom αᵒᵈ βᵒᵈ) : bounded_lattice_hom.dual.symm (g.comp f) = (bounded_lattice_hom.dual.symm g).comp (bounded_lattice_hom.dual.symm f) := rfl end bounded_lattice_hom
217ec67e99cf6bc92141c65633733354e22b5259
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/algebra/char_zero.lean
eb1c6fc93203688cf668799a30e83b3948185fce
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
3,158
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import data.nat.cast algebra.group algebra.field local attribute [instance, priority 0] nat.cast_coe /-- Typeclass for monoids with characteristic zero. (This is usually stated on fields but it makes sense for any additive monoid with 1.) -/ class char_zero (α : Type*) [add_monoid α] [has_one α] : Prop := (cast_inj : ∀ {m n : ℕ}, (m : α) = n ↔ m = n) theorem char_zero_of_inj_zero {α : Type*} [add_monoid α] [has_one α] (add_left_cancel : ∀ a b c : α, a + b = a + c → b = c) (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := ⟨λ m n, ⟨suffices ∀ {m n : ℕ}, (m:α) = n → m ≤ n, from λ h, le_antisymm (this h) (this h.symm), λ m n h, (le_total m n).elim id $ λ h2, le_of_eq $ begin cases nat.le.dest h2 with k e, suffices : k = 0, {rw [← e, this, add_zero]}, apply H, apply add_left_cancel n, rw [← nat.cast_add, e, add_zero, h] end, congr_arg _⟩⟩ theorem add_group.char_zero_of_inj_zero {α : Type*} [add_group α] [has_one α] (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := char_zero_of_inj_zero (@add_left_cancel _ _) H theorem ordered_cancel_comm_monoid.char_zero_of_inj_zero {α : Type*} [ordered_cancel_comm_monoid α] [has_one α] (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := char_zero_of_inj_zero (@add_left_cancel _ _) H instance linear_ordered_semiring.to_char_zero {α : Type*} [linear_ordered_semiring α] : char_zero α := ordered_cancel_comm_monoid.char_zero_of_inj_zero $ λ n h, nat.eq_zero_of_le_zero $ (@nat.cast_le α _ _ _).1 (le_of_eq h) namespace nat variables {α : Type*} [add_monoid α] [has_one α] [char_zero α] @[simp] theorem cast_inj {m n : ℕ} : (m : α) = n ↔ m = n := char_zero.cast_inj _ theorem cast_injective : function.injective (coe : ℕ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero {n : ℕ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] @[simp] theorem cast_ne_zero {n : ℕ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero end nat lemma two_ne_zero' {α : Type*} [add_monoid α] [has_one α] [char_zero α] : (2:α) ≠ 0 := have ((2:ℕ):α) ≠ 0, from nat.cast_ne_zero.2 dec_trivial, by rwa [nat.cast_succ, nat.cast_one] at this section variables {α : Type*} [domain α] [char_zero α] lemma add_self_eq_zero {a : α} : a + a = 0 ↔ a = 0 := by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or] lemma bit0_eq_zero {a : α} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero end section variables {α : Type*} [division_ring α] [char_zero α] @[simp] lemma half_add_self (a : α) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero'] @[simp] lemma add_halves' (a : α) : a / 2 + a / 2 = a := by rw [← add_div, half_add_self] lemma sub_half (a : α) : a - a / 2 = a / 2 := by rw [sub_eq_iff_eq_add, add_halves'] lemma half_sub (a : α) : a / 2 - a = - (a / 2) := by rw [← neg_sub, sub_half] end
5dd6ded7c4b04d0ad824f21630ed42e469e0229d
94e33a31faa76775069b071adea97e86e218a8ee
/src/measure_theory/constructions/polish.lean
03147e5777603ffcb40b57ac0760ea07101fa7e3
[ "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
33,204
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.polish import measure_theory.constructions.borel_space /-! # The Borel sigma-algebra on Polish spaces We discuss several results pertaining to the relationship between the topology and the Borel structure on Polish spaces. ## Main definitions and results First, we define the class of analytic sets and establish its basic properties. * `measure_theory.analytic_set s`: a set in a topological space is analytic if it is the continuous image of a Polish space. Equivalently, it is empty, or the image of `ℕ → ℕ`. * `measure_theory.analytic_set.image_of_continuous`: a continuous image of an analytic set is analytic. * `measurable_set.analytic_set`: in a Polish space, any Borel-measurable set is analytic. Then, we show Lusin's theorem that two disjoint analytic sets can be separated by Borel sets. * `measurably_separable s t` states that there exists a measurable set containing `s` and disjoint from `t`. * `analytic_set.measurably_separable` shows that two disjoint analytic sets are separated by a Borel set. Finally, we prove the Lusin-Souslin theorem that a continuous injective image of a Borel subset of a Polish space is Borel. The proof of this nontrivial result relies on the above results on analytic sets. * `measurable_set.image_of_continuous_on_inj_on` asserts that, if `s` is a Borel measurable set in a Polish space, then the image of `s` under a continuous injective map is still Borel measurable. * `continuous.measurable_embedding` states that a continuous injective map on a Polish space is a measurable embedding for the Borel sigma-algebra. * `continuous_on.measurable_embedding` is the same result for a map restricted to a measurable set on which it is continuous. * `measurable.measurable_embedding` states that a measurable injective map from a Polish space to a second-countable topological space is a measurable embedding. * `is_clopenable_iff_measurable_set`: in a Polish space, a set is clopenable (i.e., it can be made open and closed by using a finer Polish topology) if and only if it is Borel-measurable. -/ open set function polish_space pi_nat topological_space metric filter open_locale topological_space measure_theory variables {α : Type*} [topological_space α] {ι : Type*} namespace measure_theory /-! ### Analytic sets -/ /-- An analytic set is a set which is the continuous image of some Polish space. There are several equivalent characterizations of this definition. For the definition, we pick one that avoids universe issues: a set is analytic if and only if it is a continuous image of `ℕ → ℕ` (or if it is empty). The above more usual characterization is given in `analytic_set_iff_exists_polish_space_range`. Warning: these are analytic sets in the context of descriptive set theory (which is why they are registered in the namespace `measure_theory`). They have nothing to do with analytic sets in the context of complex analysis. -/ @[irreducible] def analytic_set (s : set α) : Prop := s = ∅ ∨ ∃ (f : (ℕ → ℕ) → α), continuous f ∧ range f = s lemma analytic_set_empty : analytic_set (∅ : set α) := begin rw analytic_set, exact or.inl rfl end lemma analytic_set_range_of_polish_space {β : Type*} [topological_space β] [polish_space β] {f : β → α} (f_cont : continuous f) : analytic_set (range f) := begin casesI is_empty_or_nonempty β, { rw range_eq_empty, exact analytic_set_empty }, { rw analytic_set, obtain ⟨g, g_cont, hg⟩ : ∃ (g : (ℕ → ℕ) → β), continuous g ∧ surjective g := exists_nat_nat_continuous_surjective β, refine or.inr ⟨f ∘ g, f_cont.comp g_cont, _⟩, rwa hg.range_comp } end /-- The image of an open set under a continuous map is analytic. -/ lemma _root_.is_open.analytic_set_image {β : Type*} [topological_space β] [polish_space β] {s : set β} (hs : is_open s) {f : β → α} (f_cont : continuous f) : analytic_set (f '' s) := begin rw image_eq_range, haveI : polish_space s := hs.polish_space, exact analytic_set_range_of_polish_space (f_cont.comp continuous_subtype_coe), end /-- A set is analytic if and only if it is the continuous image of some Polish space. -/ theorem analytic_set_iff_exists_polish_space_range {s : set α} : analytic_set s ↔ ∃ (β : Type) (h : topological_space β) (h' : @polish_space β h) (f : β → α), @continuous _ _ h _ f ∧ range f = s := begin split, { assume h, rw analytic_set at h, cases h, { refine ⟨empty, by apply_instance, by apply_instance, empty.elim, continuous_bot, _⟩, rw h, exact range_eq_empty _ }, { exact ⟨ℕ → ℕ, by apply_instance, by apply_instance, h⟩ } }, { rintros ⟨β, h, h', f, f_cont, f_range⟩, resetI, rw ← f_range, exact analytic_set_range_of_polish_space f_cont } end /-- The continuous image of an analytic set is analytic -/ lemma analytic_set.image_of_continuous_on {β : Type*} [topological_space β] {s : set α} (hs : analytic_set s) {f : α → β} (hf : continuous_on f s) : analytic_set (f '' s) := begin rcases analytic_set_iff_exists_polish_space_range.1 hs with ⟨γ, γtop, γpolish, g, g_cont, gs⟩, resetI, have : f '' s = range (f ∘ g), by rw [range_comp, gs], rw this, apply analytic_set_range_of_polish_space, apply hf.comp_continuous g_cont (λ x, _), rw ← gs, exact mem_range_self _ end lemma analytic_set.image_of_continuous {β : Type*} [topological_space β] {s : set α} (hs : analytic_set s) {f : α → β} (hf : continuous f) : analytic_set (f '' s) := hs.image_of_continuous_on hf.continuous_on /-- A countable intersection of analytic sets is analytic. -/ theorem analytic_set.Inter [hι : nonempty ι] [encodable ι] [t2_space α] {s : ι → set α} (hs : ∀ n, analytic_set (s n)) : analytic_set (⋂ n, s n) := begin unfreezingI { rcases hι with ⟨i₀⟩ }, /- For the proof, write each `s n` as the continuous image under a map `f n` of a Polish space `β n`. The product space `γ = Π n, β n` is also Polish, and so is the subset `t` of sequences `x n` for which `f n (x n)` is independent of `n`. The set `t` is Polish, and the range of `x ↦ f 0 (x 0)` on `t` is exactly `⋂ n, s n`, so this set is analytic. -/ choose β hβ h'β f f_cont f_range using λ n, analytic_set_iff_exists_polish_space_range.1 (hs n), resetI, let γ := Π n, β n, let t : set γ := ⋂ n, {x | f n (x n) = f i₀ (x i₀)}, have t_closed : is_closed t, { apply is_closed_Inter, assume n, exact is_closed_eq ((f_cont n).comp (continuous_apply n)) ((f_cont i₀).comp (continuous_apply i₀)) }, haveI : polish_space t := t_closed.polish_space, let F : t → α := λ x, f i₀ ((x : γ) i₀), have F_cont : continuous F := (f_cont i₀).comp ((continuous_apply i₀).comp continuous_subtype_coe), have F_range : range F = ⋂ (n : ι), s n, { apply subset.antisymm, { rintros y ⟨x, rfl⟩, apply mem_Inter.2 (λ n, _), have : f n ((x : γ) n) = F x := (mem_Inter.1 x.2 n : _), rw [← this, ← f_range n], exact mem_range_self _ }, { assume y hy, have A : ∀ n, ∃ (x : β n), f n x = y, { assume n, rw [← mem_range, f_range n], exact mem_Inter.1 hy n }, choose x hx using A, have xt : x ∈ t, { apply mem_Inter.2 (λ n, _), simp [hx] }, refine ⟨⟨x, xt⟩, _⟩, exact hx i₀ } }, rw ← F_range, exact analytic_set_range_of_polish_space F_cont, end /-- A countable union of analytic sets is analytic. -/ theorem analytic_set.Union [encodable ι] {s : ι → set α} (hs : ∀ n, analytic_set (s n)) : analytic_set (⋃ n, s n) := begin /- For the proof, write each `s n` as the continuous image under a map `f n` of a Polish space `β n`. The union space `γ = Σ n, β n` is also Polish, and the map `F : γ → α` which coincides with `f n` on `β n` sends it to `⋃ n, s n`. -/ choose β hβ h'β f f_cont f_range using λ n, analytic_set_iff_exists_polish_space_range.1 (hs n), resetI, let γ := Σ n, β n, let F : γ → α := by { rintros ⟨n, x⟩, exact f n x }, have F_cont : continuous F := continuous_sigma f_cont, have F_range : range F = ⋃ n, s n, { rw [range_sigma_eq_Union_range], congr, ext1 n, rw ← f_range n }, rw ← F_range, exact analytic_set_range_of_polish_space F_cont, end theorem _root_.is_closed.analytic_set [polish_space α] {s : set α} (hs : is_closed s) : analytic_set s := begin haveI : polish_space s := hs.polish_space, rw ← @subtype.range_val α s, exact analytic_set_range_of_polish_space continuous_subtype_coe, end /-- Given a Borel-measurable set in a Polish space, there exists a finer Polish topology making it clopen. This is in fact an equivalence, see `is_clopenable_iff_measurable_set`. -/ lemma _root_.measurable_set.is_clopenable [polish_space α] [measurable_space α] [borel_space α] {s : set α} (hs : measurable_set s) : is_clopenable s := begin revert s, apply measurable_set.induction_on_open, { exact λ u hu, hu.is_clopenable }, { exact λ u hu h'u, h'u.compl }, { exact λ f f_disj f_meas hf, is_clopenable.Union hf } end theorem _root_.measurable_set.analytic_set {α : Type*} [t : topological_space α] [polish_space α] [measurable_space α] [borel_space α] {s : set α} (hs : measurable_set s) : analytic_set s := begin /- For a short proof (avoiding measurable induction), one sees `s` as a closed set for a finer topology `t'`. It is analytic for this topology. As the identity from `t'` to `t` is continuous and the image of an analytic set is analytic, it follows that `s` is also analytic for `t`. -/ obtain ⟨t', t't, t'_polish, s_closed, s_open⟩ : ∃ (t' : topological_space α), t' ≤ t ∧ @polish_space α t' ∧ @is_closed α t' s ∧ @is_open α t' s := hs.is_clopenable, have A := @is_closed.analytic_set α t' t'_polish s s_closed, convert @analytic_set.image_of_continuous α t' α t s A id (continuous_id_of_le t't), simp only [id.def, image_id'], end /-- Given a Borel-measurable function from a Polish space to a second-countable space, there exists a finer Polish topology on the source space for which the function is continuous. -/ lemma _root_.measurable.exists_continuous {α β : Type*} [t : topological_space α] [polish_space α] [measurable_space α] [borel_space α] [tβ : topological_space β] [second_countable_topology β] [measurable_space β] [borel_space β] {f : α → β} (hf : measurable f) : ∃ (t' : topological_space α), t' ≤ t ∧ @continuous α β t' tβ f ∧ @polish_space α t' := begin obtain ⟨b, b_count, -, hb⟩ : ∃b : set (set β), b.countable ∧ ∅ ∉ b ∧ is_topological_basis b := exists_countable_basis β, haveI : encodable b := b_count.to_encodable, have : ∀ (s : b), is_clopenable (f ⁻¹' s), { assume s, apply measurable_set.is_clopenable, exact hf (hb.is_open s.2).measurable_set }, choose T Tt Tpolish Tclosed Topen using this, obtain ⟨t', t'T, t't, t'_polish⟩ : ∃ (t' : topological_space α), (∀ i, t' ≤ T i) ∧ (t' ≤ t) ∧ @polish_space α t' := exists_polish_space_forall_le T Tt Tpolish, refine ⟨t', t't, _, t'_polish⟩, apply hb.continuous _ (λ s hs, _), exact t'T ⟨s, hs⟩ _ (Topen ⟨s, hs⟩), end /-! ### Separating sets with measurable sets -/ /-- Two sets `u` and `v` in a measurable space are measurably separable if there exists a measurable set containing `u` and disjoint from `v`. This is mostly interesting for Borel-separable sets. -/ def measurably_separable {α : Type*} [measurable_space α] (s t : set α) : Prop := ∃ u, s ⊆ u ∧ disjoint t u ∧ measurable_set u lemma measurably_separable.Union [encodable ι] {α : Type*} [measurable_space α] {s t : ι → set α} (h : ∀ m n, measurably_separable (s m) (t n)) : measurably_separable (⋃ n, s n) (⋃ m, t m) := begin choose u hsu htu hu using h, refine ⟨⋃ m, (⋂ n, u m n), _, _, _⟩, { refine Union_subset (λ m, subset_Union_of_subset m _), exact subset_Inter (λ n, hsu m n) }, { simp_rw [disjoint_Union_left, disjoint_Union_right], assume n m, apply disjoint.mono_right _ (htu m n), apply Inter_subset }, { refine measurable_set.Union (λ m, _), exact measurable_set.Inter (λ n, hu m n) } end /-- The hard part of the Lusin separation theorem saying that two disjoint analytic sets are contained in disjoint Borel sets (see the full statement in `analytic_set.measurably_separable`). Here, we prove this when our analytic sets are the ranges of functions from `ℕ → ℕ`. -/ lemma measurably_separable_range_of_disjoint [t2_space α] [measurable_space α] [borel_space α] {f g : (ℕ → ℕ) → α} (hf : continuous f) (hg : continuous g) (h : disjoint (range f) (range g)) : measurably_separable (range f) (range g) := begin /- We follow [Kechris, *Classical Descriptive Set Theory* (Theorem 14.7)][kechris1995]. If the ranges are not Borel-separated, then one can find two cylinders of length one whose images are not Borel-separated, and then two smaller cylinders of length two whose images are not Borel-separated, and so on. One thus gets two sequences of cylinders, that decrease to two points `x` and `y`. Their images are different by the disjointness assumption, hence contained in two disjoint open sets by the T2 property. By continuity, long enough cylinders around `x` and `y` have images which are separated by these two disjoint open sets, a contradiction. -/ by_contra hfg, have I : ∀ n x y, (¬(measurably_separable (f '' (cylinder x n)) (g '' (cylinder y n)))) → ∃ x' y', x' ∈ cylinder x n ∧ y' ∈ cylinder y n ∧ ¬(measurably_separable (f '' (cylinder x' (n+1))) (g '' (cylinder y' (n+1)))), { assume n x y, contrapose!, assume H, rw [← Union_cylinder_update x n, ← Union_cylinder_update y n, image_Union, image_Union], refine measurably_separable.Union (λ i j, _), exact H _ _ (update_mem_cylinder _ _ _) (update_mem_cylinder _ _ _) }, -- consider the set of pairs of cylinders of some length whose images are not Borel-separated let A := {p : ℕ × (ℕ → ℕ) × (ℕ → ℕ) // ¬(measurably_separable (f '' (cylinder p.2.1 p.1)) (g '' (cylinder p.2.2 p.1)))}, -- for each such pair, one can find longer cylinders whose images are not Borel-separated either have : ∀ (p : A), ∃ (q : A), q.1.1 = p.1.1 + 1 ∧ q.1.2.1 ∈ cylinder p.1.2.1 p.1.1 ∧ q.1.2.2 ∈ cylinder p.1.2.2 p.1.1, { rintros ⟨⟨n, x, y⟩, hp⟩, rcases I n x y hp with ⟨x', y', hx', hy', h'⟩, exact ⟨⟨⟨n+1, x', y'⟩, h'⟩, rfl, hx', hy'⟩ }, choose F hFn hFx hFy using this, let p0 : A := ⟨⟨0, λ n, 0, λ n, 0⟩, by simp [hfg]⟩, -- construct inductively decreasing sequences of cylinders whose images are not separated let p : ℕ → A := λ n, F^[n] p0, have prec : ∀ n, p (n+1) = F (p n) := λ n, by simp only [p, iterate_succ'], -- check that at the `n`-th step we deal with cylinders of length `n` have pn_fst : ∀ n, (p n).1.1 = n, { assume n, induction n with n IH, { refl }, { simp only [prec, hFn, IH] } }, -- check that the cylinders we construct are indeed decreasing, by checking that the coordinates -- are stationary. have Ix : ∀ m n, m + 1 ≤ n → (p n).1.2.1 m = (p (m+1)).1.2.1 m, { assume m, apply nat.le_induction, { refl }, assume n hmn IH, have I : (F (p n)).val.snd.fst m = (p n).val.snd.fst m, { apply hFx (p n) m, rw pn_fst, exact hmn }, rw [prec, I, IH] }, have Iy : ∀ m n, m + 1 ≤ n → (p n).1.2.2 m = (p (m+1)).1.2.2 m, { assume m, apply nat.le_induction, { refl }, assume n hmn IH, have I : (F (p n)).val.snd.snd m = (p n).val.snd.snd m, { apply hFy (p n) m, rw pn_fst, exact hmn }, rw [prec, I, IH] }, -- denote by `x` and `y` the limit points of these two sequences of cylinders. set x : ℕ → ℕ := λ n, (p (n+1)).1.2.1 n with hx, set y : ℕ → ℕ := λ n, (p (n+1)).1.2.2 n with hy, -- by design, the cylinders around these points have images which are not Borel-separable. have M : ∀ n, ¬(measurably_separable (f '' (cylinder x n)) (g '' (cylinder y n))), { assume n, convert (p n).2 using 3, { rw [pn_fst, ← mem_cylinder_iff_eq, mem_cylinder_iff], assume i hi, rw hx, exact (Ix i n hi).symm }, { rw [pn_fst, ← mem_cylinder_iff_eq, mem_cylinder_iff], assume i hi, rw hy, exact (Iy i n hi).symm } }, -- consider two open sets separating `f x` and `g y`. obtain ⟨u, v, u_open, v_open, xu, yv, huv⟩ : ∃ u v : set α, is_open u ∧ is_open v ∧ f x ∈ u ∧ g y ∈ v ∧ disjoint u v, { apply t2_separation, exact disjoint_iff_forall_ne.1 h _ (mem_range_self _) _ (mem_range_self _) }, letI : metric_space (ℕ → ℕ) := metric_space_nat_nat, obtain ⟨εx, εxpos, hεx⟩ : ∃ (εx : ℝ) (H : εx > 0), metric.ball x εx ⊆ f ⁻¹' u, { apply metric.mem_nhds_iff.1, exact hf.continuous_at.preimage_mem_nhds (u_open.mem_nhds xu) }, obtain ⟨εy, εypos, hεy⟩ : ∃ (εy : ℝ) (H : εy > 0), metric.ball y εy ⊆ g ⁻¹' v, { apply metric.mem_nhds_iff.1, exact hg.continuous_at.preimage_mem_nhds (v_open.mem_nhds yv) }, obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1/2 : ℝ)^n < min εx εy := exists_pow_lt_of_lt_one (lt_min εxpos εypos) (by norm_num), -- for large enough `n`, these open sets separate the images of long cylinders around `x` and `y` have B : measurably_separable (f '' (cylinder x n)) (g '' (cylinder y n)), { refine ⟨u, _, _, u_open.measurable_set⟩, { rw image_subset_iff, apply subset.trans _ hεx, assume z hz, rw mem_cylinder_iff_dist_le at hz, exact hz.trans_lt (hn.trans_le (min_le_left _ _)) }, { refine disjoint.mono_left _ huv.symm, change g '' cylinder y n ⊆ v, rw image_subset_iff, apply subset.trans _ hεy, assume z hz, rw mem_cylinder_iff_dist_le at hz, exact hz.trans_lt (hn.trans_le (min_le_right _ _)) } }, -- this is a contradiction. exact M n B end /-- The Lusin separation theorem: if two analytic sets are disjoint, then they are contained in disjoint Borel sets. -/ theorem analytic_set.measurably_separable [t2_space α] [measurable_space α] [borel_space α] {s t : set α} (hs : analytic_set s) (ht : analytic_set t) (h : disjoint s t) : measurably_separable s t := begin rw analytic_set at hs ht, rcases hs with rfl|⟨f, f_cont, rfl⟩, { refine ⟨∅, subset.refl _, by simp, measurable_set.empty⟩ }, rcases ht with rfl|⟨g, g_cont, rfl⟩, { exact ⟨univ, subset_univ _, by simp, measurable_set.univ⟩ }, exact measurably_separable_range_of_disjoint f_cont g_cont h, end /-! ### Injective images of Borel sets -/ variables {γ : Type*} [tγ : topological_space γ] [polish_space γ] include tγ /-- The Lusin-Souslin theorem: the range of a continuous injective function defined on a Polish space is Borel-measurable. -/ theorem measurable_set_range_of_continuous_injective {β : Type*} [topological_space β] [t2_space β] [measurable_space β] [borel_space β] {f : γ → β} (f_cont : continuous f) (f_inj : injective f) : measurable_set (range f) := begin /- We follow [Fremlin, *Measure Theory* (volume 4, 423I)][fremlin_vol4]. Let `b = {s i}` be a countable basis for `α`. When `s i` and `s j` are disjoint, their images are disjoint analytic sets, hence by the separation theorem one can find a Borel-measurable set `q i j` separating them. Let `E i = closure (f '' s i) ∩ ⋂ j, q i j \ q j i`. It contains `f '' (s i)` and it is measurable. Let `F n = ⋃ E i`, where the union is taken over those `i` for which `diam (s i)` is bounded by some number `u n` tending to `0` with `n`. We claim that `range f = ⋂ F n`, from which the measurability is obvious. The inclusion `⊆` is straightforward. To show `⊇`, consider a point `x` in the intersection. For each `n`, it belongs to some `E i` with `diam (s i) ≤ u n`. Pick a point `y i ∈ s i`. We claim that for such `i` and `j`, the intersection `s i ∩ s j` is nonempty: if it were empty, then thanks to the separating set `q i j` in the definition of `E i` one could not have `x ∈ E i ∩ E j`. Since these two sets have small diameter, it follows that `y i` and `y j` are close. Thus, `y` is a Cauchy sequence, converging to a limit `z`. We claim that `f z = x`, completing the proof. Otherwise, one could find open sets `v` and `w` separating `f z` from `x`. Then, for large `n`, the image `f '' (s i)` would be included in `v` by continuity of `f`, so its closure would be contained in the closure of `v`, and therefore it would be disjoint from `w`. This is a contradiction since `x` belongs both to this closure and to `w`. -/ letI := upgrade_polish_space γ, obtain ⟨b, b_count, b_nonempty, hb⟩ : ∃ b : set (set γ), b.countable ∧ ∅ ∉ b ∧ is_topological_basis b := exists_countable_basis γ, haveI : encodable b := b_count.to_encodable, let A := {p : b × b // disjoint (p.1 : set γ) p.2}, -- for each pair of disjoint sets in the topological basis `b`, consider Borel sets separating -- their images, by injectivity of `f` and the Lusin separation theorem. have : ∀ (p : A), ∃ (q : set β), f '' (p.1.1 : set γ) ⊆ q ∧ disjoint (f '' (p.1.2 : set γ)) q ∧ measurable_set q, { assume p, apply analytic_set.measurably_separable ((hb.is_open p.1.1.2).analytic_set_image f_cont) ((hb.is_open p.1.2.2).analytic_set_image f_cont), exact disjoint.image p.2 (f_inj.inj_on univ) (subset_univ _) (subset_univ _) }, choose q hq1 hq2 q_meas using this, -- define sets `E i` and `F n` as in the proof sketch above let E : b → set β := λ s, closure (f '' s) ∩ (⋂ (t : b) (ht : disjoint s.1 t.1), q ⟨(s, t), ht⟩ \ q ⟨(t, s), ht.symm⟩), obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), let F : ℕ → set β := λ n, ⋃ (s : b) (hs : bounded s.1 ∧ diam s.1 ≤ u n), E s, -- it is enough to show that `range f = ⋂ F n`, as the latter set is obviously measurable. suffices : range f = ⋂ n, F n, { have E_meas : ∀ (s : b), measurable_set (E s), { assume b, refine is_closed_closure.measurable_set.inter _, refine measurable_set.Inter (λ s, _), exact measurable_set.Inter_Prop (λ hs, (q_meas _).diff (q_meas _)) }, have F_meas : ∀ n, measurable_set (F n), { assume n, refine measurable_set.Union (λ s, _), exact measurable_set.Union_Prop (λ hs, E_meas _) }, rw this, exact measurable_set.Inter (λ n, F_meas n) }, -- we check both inclusions. apply subset.antisymm, -- we start with the easy inclusion `range f ⊆ ⋂ F n`. One just needs to unfold the definitions. { rintros x ⟨y, rfl⟩, apply mem_Inter.2 (λ n, _), obtain ⟨s, sb, ys, hs⟩ : ∃ (s : set γ) (H : s ∈ b), y ∈ s ∧ s ⊆ ball y (u n / 2), { apply hb.mem_nhds_iff.1, exact ball_mem_nhds _ (half_pos (u_pos n)) }, have diam_s : diam s ≤ u n, { apply (diam_mono hs bounded_ball).trans, convert diam_ball (half_pos (u_pos n)).le, ring }, refine mem_Union.2 ⟨⟨s, sb⟩, _⟩, refine mem_Union.2 ⟨⟨metric.bounded.mono hs bounded_ball, diam_s⟩, _⟩, apply mem_inter (subset_closure (mem_image_of_mem _ ys)), refine mem_Inter.2 (λ t, mem_Inter.2 (λ ht, ⟨_, _⟩)), { apply hq1, exact mem_image_of_mem _ ys }, { apply disjoint_left.1 (hq2 ⟨(t, ⟨s, sb⟩), ht.symm⟩), exact mem_image_of_mem _ ys } }, -- Now, let us prove the harder inclusion `⋂ F n ⊆ range f`. { assume x hx, -- pick for each `n` a good set `s n` of small diameter for which `x ∈ E (s n)`. have C1 : ∀ n, ∃ (s : b) (hs : bounded s.1 ∧ diam s.1 ≤ u n), x ∈ E s := λ n, by simpa only [mem_Union] using mem_Inter.1 hx n, choose s hs hxs using C1, have C2 : ∀ n, (s n).1.nonempty, { assume n, rw ← ne_empty_iff_nonempty, assume hn, have := (s n).2, rw hn at this, exact b_nonempty this }, -- choose a point `y n ∈ s n`. choose y hy using C2, have I : ∀ m n, ((s m).1 ∩ (s n).1).nonempty, { assume m n, rw ← not_disjoint_iff_nonempty_inter, by_contra' h, have A : x ∈ q ⟨(s m, s n), h⟩ \ q ⟨(s n, s m), h.symm⟩, { have := mem_Inter.1 (hxs m).2 (s n), exact (mem_Inter.1 this h : _) }, have B : x ∈ q ⟨(s n, s m), h.symm⟩ \ q ⟨(s m, s n), h⟩, { have := mem_Inter.1 (hxs n).2 (s m), exact (mem_Inter.1 this h.symm : _) }, exact A.2 B.1 }, -- the points `y n` are nearby, and therefore they form a Cauchy sequence. have cauchy_y : cauchy_seq y, { have : tendsto (λ n, 2 * u n) at_top (𝓝 0), by simpa only [mul_zero] using u_lim.const_mul 2, apply cauchy_seq_of_le_tendsto_0' (λ n, 2 * u n) (λ m n hmn, _) this, rcases I m n with ⟨z, zsm, zsn⟩, calc dist (y m) (y n) ≤ dist (y m) z + dist z (y n) : dist_triangle _ _ _ ... ≤ u m + u n : add_le_add ((dist_le_diam_of_mem (hs m).1 (hy m) zsm).trans (hs m).2) ((dist_le_diam_of_mem (hs n).1 zsn (hy n)).trans (hs n).2) ... ≤ 2 * u m : by linarith [u_anti.antitone hmn] }, haveI : nonempty γ := ⟨y 0⟩, -- let `z` be its limit. let z := lim at_top y, have y_lim : tendsto y at_top (𝓝 z) := cauchy_y.tendsto_lim, suffices : f z = x, by { rw ← this, exact mem_range_self _ }, -- assume for a contradiction that `f z ≠ x`. by_contra' hne, -- introduce disjoint open sets `v` and `w` separating `f z` from `x`. obtain ⟨v, w, v_open, w_open, fzv, xw, hvw⟩ := t2_separation hne, obtain ⟨δ, δpos, hδ⟩ : ∃ δ > (0 : ℝ), ball z δ ⊆ f ⁻¹' v, { apply metric.mem_nhds_iff.1, exact f_cont.continuous_at.preimage_mem_nhds (v_open.mem_nhds fzv) }, obtain ⟨n, hn⟩ : ∃ n, u n + dist (y n) z < δ, { have : tendsto (λ n, u n + dist (y n) z) at_top (𝓝 0), by simpa only [add_zero] using u_lim.add (tendsto_iff_dist_tendsto_zero.1 y_lim), exact ((tendsto_order.1 this).2 _ δpos).exists }, -- for large enough `n`, the image of `s n` is contained in `v`, by continuity of `f`. have fsnv : f '' (s n) ⊆ v, { rw image_subset_iff, apply subset.trans _ hδ, assume a ha, calc dist a z ≤ dist a (y n) + dist (y n) z : dist_triangle _ _ _ ... ≤ u n + dist (y n) z : add_le_add_right ((dist_le_diam_of_mem (hs n).1 ha (hy n)).trans (hs n).2) _ ... < δ : hn }, -- as `x` belongs to the closure of `f '' (s n)`, it belongs to the closure of `v`. have : x ∈ closure v := closure_mono fsnv (hxs n).1, -- this is a contradiction, as `x` is supposed to belong to `w`, which is disjoint from -- the closure of `v`. exact disjoint_left.1 (hvw.closure_left w_open) this xw } end theorem _root_.is_closed.measurable_set_image_of_continuous_on_inj_on {β : Type*} [topological_space β] [t2_space β] [measurable_space β] [borel_space β] {s : set γ} (hs : is_closed s) {f : γ → β} (f_cont : continuous_on f s) (f_inj : inj_on f s) : measurable_set (f '' s) := begin rw image_eq_range, haveI : polish_space s := is_closed.polish_space hs, apply measurable_set_range_of_continuous_injective, { rwa continuous_on_iff_continuous_restrict at f_cont }, { rwa inj_on_iff_injective at f_inj } end variables [measurable_space γ] [borel_space γ] {β : Type*} [tβ : topological_space β] [t2_space β] [measurable_space β] [borel_space β] {s : set γ} {f : γ → β} include tβ /-- The Lusin-Souslin theorem: if `s` is Borel-measurable in a Polish space, then its image under a continuous injective map is also Borel-measurable. -/ theorem _root_.measurable_set.image_of_continuous_on_inj_on (hs : measurable_set s) (f_cont : continuous_on f s) (f_inj : inj_on f s) : measurable_set (f '' s) := begin obtain ⟨t', t't, t'_polish, s_closed, s_open⟩ : ∃ (t' : topological_space γ), t' ≤ tγ ∧ @polish_space γ t' ∧ @is_closed γ t' s ∧ @is_open γ t' s := hs.is_clopenable, exact @is_closed.measurable_set_image_of_continuous_on_inj_on γ t' t'_polish β _ _ _ _ s s_closed f (f_cont.mono_dom t't) f_inj, end /-- The Lusin-Souslin theorem: if `s` is Borel-measurable in a Polish space, then its image under a measurable injective map taking values in a second-countable topological space is also Borel-measurable. -/ theorem _root_.measurable_set.image_of_measurable_inj_on [second_countable_topology β] (hs : measurable_set s) (f_meas : measurable f) (f_inj : inj_on f s) : measurable_set (f '' s) := begin -- for a finer Polish topology, `f` is continuous. Therefore, one may apply the corresponding -- result for continuous maps. obtain ⟨t', t't, f_cont, t'_polish⟩ : ∃ (t' : topological_space γ), t' ≤ tγ ∧ @continuous γ β t' tβ f ∧ @polish_space γ t' := f_meas.exists_continuous, have M : measurable_set[@borel γ t'] s := @continuous.measurable γ γ t' (@borel γ t') (@borel_space.opens_measurable γ t' (@borel γ t') (by { constructor, refl })) tγ _ _ _ (continuous_id_of_le t't) s hs, exact @measurable_set.image_of_continuous_on_inj_on γ t' t'_polish (@borel γ t') (by { constructor, refl }) β _ _ _ _ s f M (@continuous.continuous_on γ β t' tβ f s f_cont) f_inj, end /-- An injective continuous function on a Polish space is a measurable embedding. -/ theorem _root_.continuous.measurable_embedding (f_cont : continuous f) (f_inj : injective f) : measurable_embedding f := { injective := f_inj, measurable := f_cont.measurable, measurable_set_image' := λ u hu, hu.image_of_continuous_on_inj_on f_cont.continuous_on (f_inj.inj_on _) } /-- If `s` is Borel-measurable in a Polish space and `f` is continuous injective on `s`, then the restriction of `f` to `s` is a measurable embedding. -/ theorem _root_.continuous_on.measurable_embedding (hs : measurable_set s) (f_cont : continuous_on f s) (f_inj : inj_on f s) : measurable_embedding (s.restrict f) := { injective := inj_on_iff_injective.1 f_inj, measurable := (continuous_on_iff_continuous_restrict.1 f_cont).measurable, measurable_set_image' := begin assume u hu, have A : measurable_set ((coe : s → γ) '' u) := (measurable_embedding.subtype_coe hs).measurable_set_image.2 hu, have B : measurable_set (f '' ((coe : s → γ) '' u)) := A.image_of_continuous_on_inj_on (f_cont.mono (subtype.coe_image_subset s u)) (f_inj.mono ((subtype.coe_image_subset s u))), rwa ← image_comp at B, end } /-- An injective measurable function from a Polish space to a second-countable topological space is a measurable embedding. -/ theorem _root_.measurable.measurable_embedding [second_countable_topology β] (f_meas : measurable f) (f_inj : injective f) : measurable_embedding f := { injective := f_inj, measurable := f_meas, measurable_set_image' := λ u hu, hu.image_of_measurable_inj_on f_meas (f_inj.inj_on _) } omit tβ /-- In a Polish space, a set is clopenable if and only if it is Borel-measurable. -/ lemma is_clopenable_iff_measurable_set : is_clopenable s ↔ measurable_set s := begin -- we already know that a measurable set is clopenable. Conversely, assume that `s` is clopenable. refine ⟨λ hs, _, λ hs, hs.is_clopenable⟩, -- consider a finer topology `t'` in which `s` is open and closed. obtain ⟨t', t't, t'_polish, s_closed, s_open⟩ : ∃ (t' : topological_space γ), t' ≤ tγ ∧ @polish_space γ t' ∧ @is_closed γ t' s ∧ @is_open γ t' s := hs, -- the identity is continuous from `t'` to `tγ`. have C : @continuous γ γ t' tγ id := continuous_id_of_le t't, -- therefore, it is also a measurable embedding, by the Lusin-Souslin theorem have E := @continuous.measurable_embedding γ t' t'_polish (@borel γ t') (by { constructor, refl }) γ tγ (polish_space.t2_space γ) _ _ id C injective_id, -- the set `s` is measurable for `t'` as it is closed. have M : @measurable_set γ (@borel γ t') s := @is_closed.measurable_set γ s t' (@borel γ t') (@borel_space.opens_measurable γ t' (@borel γ t') (by { constructor, refl })) s_closed, -- therefore, its image under the measurable embedding `id` is also measurable for `tγ`. convert E.measurable_set_image.2 M, simp only [id.def, image_id'], end end measure_theory
51574e5d2599496517a4216890e159676580fe40
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/data/nat/cast.lean
a3fae9f3d9921c7e5da37a836c8a384c5f96d88b
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
8,696
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import algebra.ordered_field import data.nat.basic namespace nat variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] /-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/ protected def cast : ℕ → α | 0 := 0 | (n+1) := cast n + 1 /-- Coercions such as `nat.cast_coe` that go from a concrete structure such as `ℕ` to an arbitrary ring `α` should be set up as follows: ```lean @[priority 900] instance : has_coe_t ℕ α := ⟨...⟩ ``` It needs to be `has_coe_t` instead of `has_coe` because otherwise type-class inference would loop when constructing the transitive coercion `ℕ → ℕ → ℕ → ...`. The reduced priority is necessary so that it doesn't conflict with instances such as `has_coe_t α (option α)`. For this to work, we reduce the priority of the `coe_base` and `coe_trans` instances because we want the instances for `has_coe_t` to be tried in the following order: 1. `has_coe_t` instances declared in mathlib (such as `has_coe_t α (with_top α)`, etc.) 2. `coe_base`, which contains instances such as `has_coe (fin n) n` 3. `nat.cast_coe : has_coe_t ℕ α` etc. 4. `coe_trans` If `coe_trans` is tried first, then `nat.cast_coe` doesn't get a chance to apply. -/ library_note "coercion into rings" attribute [instance, priority 950] coe_base attribute [instance, priority 500] coe_trans -- see note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℕ α := ⟨nat.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl @[simp, norm_cast, priority 500] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl @[simp, norm_cast] theorem cast_ite (P : Prop) [decidable P] (m n : ℕ) : (((ite P m n) : ℕ) : α) = ite P (m : α) (n : α) := by { split_ifs; refl, } end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _ @[simp, norm_cast] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc] /-- `coe : ℕ → α` as an `add_monoid_hom`. -/ def cast_add_monoid_hom (α : Type*) [add_monoid α] [has_one α] : ℕ →+ α := { to_fun := coe, map_add' := cast_add, map_zero' := cast_zero } @[simp] lemma coe_cast_add_monoid_hom [add_monoid α] [has_one α] : (cast_add_monoid_hom α : ℕ → α) = coe := rfl @[simp, norm_cast] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) : ((bit0 n : ℕ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) : ((bit1 n : ℕ) : α) = bit1 n := by rw [bit1, cast_add_one, cast_bit0]; refl lemma cast_two {α : Type*} [semiring α] : ((2 : ℕ) : α) = 2 := by simp @[simp, norm_cast] theorem cast_pred [add_group α] [has_one α] : ∀ {n}, 0 < n → ((n - 1 : ℕ) : α) = n - 1 | (n+1) h := (add_sub_cancel (n:α) 1).symm @[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m := eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h] @[simp, norm_cast] theorem cast_mul [semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n | 0 := (mul_zero _).symm | (n+1) := (cast_add _ _).trans $ show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one] /-- `coe : ℕ → α` as a `ring_hom` -/ def cast_ring_hom (α : Type*) [semiring α] : ℕ →+* α := { to_fun := coe, map_one' := cast_one, map_mul' := cast_mul, .. cast_add_monoid_hom α } @[simp] lemma coe_cast_ring_hom [semiring α] : (cast_ring_hom α : ℕ → α) = coe := rfl lemma cast_commute [semiring α] (n : ℕ) (x : α) : commute ↑n x := nat.rec_on n (commute.zero_left x) $ λ n ihn, ihn.add_left $ commute.one_left x lemma commute_cast [semiring α] (x : α) (n : ℕ) : commute x n := (n.cast_commute x).symm @[simp] theorem cast_nonneg [linear_ordered_semiring α] : ∀ n : ℕ, 0 ≤ (n : α) | 0 := le_refl _ | (n+1) := add_nonneg (cast_nonneg n) zero_le_one @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] : ∀ {m n : ℕ}, (m : α) ≤ n ↔ m ≤ n | 0 n := by simp [zero_le] | (m+1) 0 := by simpa [not_succ_le_zero] using lt_add_of_nonneg_of_lt (@cast_nonneg α _ m) zero_lt_one | (m+1) (n+1) := (add_le_add_iff_right 1).trans $ (@cast_le m n).trans $ (add_le_add_iff_right 1).symm @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : ℕ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_pos [linear_ordered_semiring α] {n : ℕ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] lemma cast_add_one_pos [linear_ordered_semiring α] (n : ℕ) : 0 < (n : α) + 1 := add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one @[simp, norm_cast] theorem cast_min [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, norm_cast] theorem abs_cast [decidable_linear_ordered_comm_ring α] (a : ℕ) : abs (a : α) = a := abs_of_nonneg (cast_nonneg a) section linear_ordered_field variables [linear_ordered_field α] lemma inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ := inv_pos.2 $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one lemma one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) := by { rw one_div_eq_inv, exact inv_pos_of_nat } lemma one_div_le_one_div {n m : ℕ} (h : n ≤ m) : 1 / ((m : α) + 1) ≤ 1 / ((n : α) + 1) := by { refine one_div_le_one_div_of_le _ _, exact nat.cast_add_one_pos _, simpa } lemma one_div_lt_one_div {n m : ℕ} (h : n < m) : 1 / ((m : α) + 1) < 1 / ((n : α) + 1) := by { refine one_div_lt_one_div_of_lt _ _, exact nat.cast_add_one_pos _, simpa } end linear_ordered_field end nat namespace add_monoid_hom variables {A : Type*} [add_monoid A] @[ext] lemma ext_nat {f g : ℕ →+ A} (h : f 1 = g 1) : f = g := ext $ λ n, nat.rec_on n (f.map_zero.trans g.map_zero.symm) $ λ n ihn, by simp only [nat.succ_eq_add_one, *, map_add] lemma eq_nat_cast {A} [add_monoid A] [has_one A] (f : ℕ →+ A) (h1 : f 1 = 1) : ∀ n : ℕ, f n = n := ext_iff.1 $ show f = nat.cast_add_monoid_hom A, from ext_nat (h1.trans nat.cast_one.symm) end add_monoid_hom namespace ring_hom variables {R : Type*} {S : Type*} [semiring R] [semiring S] @[simp] lemma eq_nat_cast (f : ℕ →+* R) (n : ℕ) : f n = n := f.to_add_monoid_hom.eq_nat_cast f.map_one n @[simp] lemma map_nat_cast (f : R →+* S) (n : ℕ) : f n = n := (f.comp (nat.cast_ring_hom R)).eq_nat_cast n lemma ext_nat (f g : ℕ →+* R) : f = g := coe_add_monoid_hom_injective $ add_monoid_hom.ext_nat $ f.map_one.trans g.map_one.symm end ring_hom @[simp, norm_cast] theorem nat.cast_id (n : ℕ) : ↑n = n := ((ring_hom.id ℕ).eq_nat_cast n).symm @[simp] theorem nat.cast_with_bot : ∀ (n : ℕ), @coe ℕ (with_bot ℕ) (@coe_to_lift _ _ nat.cast_coe) n = n | 0 := rfl | (n+1) := by rw [with_bot.coe_add, nat.cast_add, nat.cast_with_bot n]; refl instance nat.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℕ →+* R) := ⟨ring_hom.ext_nat⟩ namespace with_top variables {α : Type*} variables [has_zero α] [has_one α] [has_add α] @[simp, norm_cast] lemma coe_nat : ∀(n : nat), ((n : α) : with_top α) = n | 0 := rfl | (n+1) := by { push_cast, rw [coe_nat n] } @[simp] lemma nat_ne_top (n : nat) : (n : with_top α) ≠ ⊤ := by { rw [←coe_nat n], apply coe_ne_top } @[simp] lemma top_ne_nat (n : nat) : (⊤ : with_top α) ≠ n := by { rw [←coe_nat n], apply top_ne_coe } lemma add_one_le_of_lt {i n : with_top ℕ} (h : i < n) : i + 1 ≤ n := begin cases n, { exact le_top }, cases i, { exact (not_le_of_lt h le_top).elim }, exact with_top.coe_le_coe.2 (with_top.coe_lt_coe.1 h) end @[elab_as_eliminator] lemma nat_induction {P : with_top ℕ → Prop} (a : with_top ℕ) (h0 : P 0) (hsuc : ∀n:ℕ, P n → P n.succ) (htop : (∀n : ℕ, P n) → P ⊤) : P a := begin have A : ∀n:ℕ, P n := λ n, nat.rec_on n h0 hsuc, cases a, { exact htop A }, { exact A a } end end with_top
5816d447d22ffab1aafd8f10e7539826f9b2149e
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/data/nat/sqrt.lean
eef7c019cac2f62073870f2eb14328d0af69809d
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,089
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Johannes Hölzl, Mario Carneiro An efficient binary implementation of a (sqrt n) function that returns s s.t. s*s ≤ n ≤ s*s + s + s -/ import data.nat.basic algebra.ordered_group algebra.ring tactic namespace nat theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b := begin simp [shiftr_eq_div_pow], apply (nat.div_lt_iff_lt_mul _ _ (dec_trivial : 4 > 0)).2, have := nat.mul_lt_mul_of_pos_left (dec_trivial : 1 < 4) (nat.pos_of_ne_zero h), rwa mul_one at this end def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r := by rw sqrt_aux; simp local attribute [simp] sqrt_aux_0 theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' := by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false]; rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1] theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n := begin rw sqrt_aux; simp only [h, h₂, if_false], cases int.eq_neg_succ_of_lt_zero (sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e, rw [e, sqrt_aux._match_1] end private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1) private lemma sqrt_aux_is_sqrt_lemma (m r n) (h₁ : r*r ≤ n) (m') (hm : shiftr (2^m * 2^m) 2 = m') (H1 : n < (r + 2^m) * (r + 2^m) → is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r))) (H2 : (r + 2^m) * (r + 2^m) ≤ n → is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) : is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) := begin have b0 := have b0:_, from ne_of_gt (@pos_pow_of_pos 2 m dec_trivial), nat.mul_ne_zero b0 b0, have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔ n < (r+2^m)*(r+2^m), { rw [nat.sub_lt_right_iff_lt_add h₁], simp [left_distrib, right_distrib, two_mul] }, have re : div2 (2 * r * 2^m) = r * 2^m, { rw [div2_val, mul_assoc, nat.mul_div_cancel_left _ (dec_trivial:2>0)] }, cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl, { rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl }, { cases le.dest hl with n' e, rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)), hm, re, ← right_distrib], { apply H2 hl }, apply eq.symm, apply nat.sub_eq_of_eq_add, rw [← add_assoc, (_ : r*r + _ = _)], exact (nat.add_sub_cancel' hl).symm, simp [left_distrib, right_distrib, two_mul] }, end private lemma sqrt_aux_is_sqrt (n) : ∀ m r, r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) → is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r)) | 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl; intros; simp; [exact ⟨h₁, a⟩, exact ⟨a, h₂⟩] | (m+1) r h₁ h₂ := begin apply sqrt_aux_is_sqrt_lemma (m+1) r n h₁ (2^m * 2^m) (by simp [shiftr, pow_succ, div2_val]; repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial}); intros, { have := sqrt_aux_is_sqrt m r h₁ a, simpa [pow_succ] }, { rw [pow_succ, mul_two, ← add_assoc] at h₂, have := sqrt_aux_is_sqrt m (r + 2^(m+1)) a h₂, rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m, by simp [pow_succ] } end private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) := begin generalize e : size n = s, cases s with s; simp [e, sqrt], { rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial }, { have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _), simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by { generalize: div2 s = x, change bit0 x with x+x, rw [one_shiftl, pow_add] }] at this, apply this, rw [← pow_add, ← mul_two], apply size_le.1, rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1, rw [div2_val], apply lt_succ_self } end theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n := (sqrt_is_sqrt n).left theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) := (sqrt_is_sqrt n).right theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n := by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n) theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n := ⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n), λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $ lt_of_le_of_lt h (lt_succ_sqrt n)⟩ theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n := le_iff_le_iff_lt_iff_lt.1 le_sqrt theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n := le_trans (le_mul_self _) (sqrt_le n) theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n := le_sqrt.2 (le_trans (sqrt_le _) h) theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 := ⟨λ h, eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $ by rw [h]; exact dec_trivial, λ e, e.symm ▸ rfl⟩ theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 := le_of_lt_succ $ (@sqrt_lt n 2).1 $ by rw [h]; exact dec_trivial theorem sqrt_lt_self {n : ℕ} (h : n > 1) : sqrt n < n := sqrt_lt.2 $ by have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h); rwa [mul_one] at this theorem sqrt_pos {n : ℕ} : sqrt n > 0 ↔ n > 0 := le_sqrt theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n := le_antisymm (le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc]; exact lt_succ_of_le (nat.add_le_add_left h _)) (le_sqrt.2 $ nat.le_add_right _ _) theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n := sqrt_add_eq n (zero_le _) end nat
e86de3e94dc8ca557cc79e0e0dec72663aad6a2d
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/mixed_tmp_non_tmp_universe_bug.lean
6b9da801540f39d6e6f8100314c2ded709110d8c
[ "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
85
lean
#reduce default (bool × unit × nat) #reduce default (bool × bool × bool × bool)
26e17949343e136e2d461e03cbce02c49604d8af
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Util/Recognizers.lean
e1e8aa3605ccbd3eb51a3024491f24221a00812f
[ "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,341
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.Environment namespace Lean namespace Expr @[inline] def app1? (e : Expr) (fName : Name) : Option Expr := if e.isAppOfArity fName 1 then some $ e.appArg! else none @[inline] def app2? (e : Expr) (fName : Name) : Option (Expr × Expr) := if e.isAppOfArity fName 2 then some $ (e.appFn!.appArg!, e.appArg!) else none @[inline] def app3? (e : Expr) (fName : Name) : Option (Expr × Expr × Expr) := if e.isAppOfArity fName 3 then some $ (e.appFn!.appFn!.appArg!, e.appFn!.appArg!, e.appArg!) else none @[inline] def app4? (e : Expr) (fName : Name) : Option (Expr × Expr × Expr × Expr) := if e.isAppOfArity fName 4 then some $ (e.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appArg!, e.appFn!.appArg!, e.appArg!) else none @[inline] def eq? (p : Expr) : Option (Expr × Expr × Expr) := p.app3? `Eq @[inline] def iff? (p : Expr) : Option (Expr × Expr) := p.app2? `Iff @[inline] def heq? (p : Expr) : Option (Expr × Expr × Expr × Expr) := p.app4? `HEq @[inline] def arrow? : Expr → Option (Expr × Expr) | Expr.forallE _ α β _ => if β.hasLooseBVars then none else some (α, β) | _ => none def isEq (e : Expr) := e.isAppOfArity `Eq 3 def isHEq (e : Expr) := e.isAppOfArity `HEq 4 partial def listLit? (e : Expr) : Option (Expr × List Expr) := let rec loop (e : Expr) (acc : List Expr) := if e.isAppOfArity `List.nil 1 then some (e.appArg!, acc.reverse) else if e.isAppOfArity `List.cons 3 then loop e.appArg! (e.appFn!.appArg! :: acc) else none loop e [] def arrayLit? (e : Expr) : Option (Expr × List Expr) := match e.app2? `List.toArray with | some (_, e) => e.listLit? | none => none /-- Recognize `α × β` -/ def prod? (e : Expr) : Option (Expr × Expr) := e.app2? `Prod private def getConstructorVal? (env : Environment) (ctorName : Name) : Option ConstructorVal := do match env.find? ctorName with | some (ConstantInfo.ctorInfo v) => v | _ => none def isConstructorApp? (env : Environment) (e : Expr) : Option ConstructorVal := match e with | Expr.lit (Literal.natVal n) _ => if n == 0 then getConstructorVal? env `Nat.zero else getConstructorVal? env `Nat.succ | _ => match e.getAppFn with | Expr.const n _ _ => match getConstructorVal? env n with | some v => if v.nparams + v.nfields == e.getAppNumArgs then some v else none | none => none | _ => none def isConstructorApp (env : Environment) (e : Expr) : Bool := e.isConstructorApp? env $.isSome def constructorApp? (env : Environment) (e : Expr) : Option (ConstructorVal × Array Expr) := match e with | Expr.lit (Literal.natVal n) _ => if n == 0 then do let v ← getConstructorVal? env `Nat.zero pure (v, #[]) else do let v ← getConstructorVal? env `Nat.succ pure (v, #[mkNatLit (n-1)]) | _ => match e.getAppFn with | Expr.const n _ _ => do let v ← getConstructorVal? env n if v.nparams + v.nfields == e.getAppNumArgs then pure (v, e.getAppArgs) else none | _ => none end Expr end Lean
1f186dff9c4d338bab54630d64c8530d2c1fd23b
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Util/SCC.lean
164235fd97f6fee995b231dd578ce8c6d085f1b8
[ "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
3,182
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 Std.Data.HashMap namespace Lean.SCC /- Very simple implementation of Tarjan's SCC algorithm. Performance is not a goal here since we use this module to compiler mutually recursive definitions, where each function (and nested let-rec) in the mutual block is a vertex. So, the graphs are small. -/ open Std section variables (α : Type) [BEq α] [Hashable α] structure Data where index? : Option Nat := none lowlink? : Option Nat := none onStack : Bool := false structure State where stack : List α := [] nextIndex : Nat := 0 data : Std.HashMap α Data := {} sccs : List (List α) := [] abbrev M := StateM (State α) end variables {α : Type} [BEq α] [Hashable α] private def getDataOf (a : α) : M α Data := do let s ← get match s.data.find? a with | some d => pure d | none => pure {} private def push (a : α) : M α Unit := modify fun s => { s with stack := a :: s.stack, nextIndex := s.nextIndex + 1, data := s.data.insert a { index? := s.nextIndex, lowlink? := s.nextIndex, onStack := true } } private def modifyDataOf (a : α) (f : Data → Data) : M α Unit := modify fun s => { s with data := match s.data.find? a with | none => s.data | some d => s.data.insert a (f d) } private def resetOnStack (a : α) : M α Unit := modifyDataOf a fun d => { d with onStack := false } private def updateLowLinkOf (a : α) (v : Option Nat) : M α Unit := modifyDataOf a fun d => { d with lowlink? := match d.lowlink?, v with | i, none => i | none, i => i | some i, some j => if i < j then i else j } private def addSCC (a : α) : M α Unit := do let rec add | [], newSCC => modify fun s => { s with stack := [], sccs := newSCC :: s.sccs } | b::bs, newSCC => do resetOnStack b; let newSCC := b::newSCC; if a != b then add bs newSCC else modify fun s => { s with stack := bs, sccs := newSCC :: s.sccs } add (← get).stack [] @[specialize] private partial def sccAux (successorsOf : α → List α) (a : α) : M α Unit := do push a (successorsOf a).forM fun b => do let bData ← getDataOf b; if bData.index?.isNone then -- `b` has not been visited yet sccAux successorsOf b; let bData ← getDataOf b; updateLowLinkOf a bData.lowlink? else if bData.onStack then do -- `b` is on the stack. So, it must be in the current SCC -- The edge `(a, b)` is pointing to an SCC already found and must be ignored updateLowLinkOf a bData.index? else pure () let aData ← getDataOf a; if aData.lowlink? == aData.index? then addSCC a @[specialize] def scc (vertices : List α) (successorsOf : α → List α) : List (List α) := let main : M α Unit := vertices.forM fun a => do let aData ← getDataOf a if aData.index?.isNone then sccAux successorsOf a let (_, s) := main.run {} s.sccs.reverse end Lean.SCC
631ff9dab35ee5330a32f483a8704f5f6ac1ebe9
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/arity.hlean
d6856eeb9c515d23590bfb39b3e4e42c6f4df0f6
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
11,201
hlean
/- 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 Theorems about functions with multiple arguments -/ variables {A U V W X Y Z : Type} {B : A → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {E : Πa b c, D a b c → Type} {F : Πa b c d, E a b c d → Type} {G : Πa b c d e, F a b c d e → Type} {H : Πa b c d e f, G a b c d e f → Type} variables {a a' : A} {u u' : U} {v v' : V} {w w' : W} {x x' x'' : X} {y y' : Y} {z z' : Z} {b : B a} {b' : B a'} {c : C a b} {c' : C a' b'} {d : D a b c} {d' : D a' b' c'} {e : E a b c d} {e' : E a' b' c' d'} {ff : F a b c d e} {f' : F a' b' c' d' e'} {g : G a b c d e ff} {g' : G a' b' c' d' e' f'} {h : H a b c d e ff g} {h' : H a' b' c' d' e' f' g'} namespace eq /- Naming convention: The theorem which states how to construct an path between two function applications is api₀i₁...iₙ. Here i₀, ... iₙ are digits, n is the arity of the function(s), and iⱼ specifies the dimension of the path between the jᵗʰ argument (i₀ specifies the dimension of the path between the functions). A value iⱼ ≡ 0 means that the jᵗʰ arguments are definitionally equal The functions are non-dependent, except when the theorem name contains trailing zeroes (where the function is dependent only in the arguments where it doesn't result in any transports in the theorem statement). For the fully-dependent versions (except that the conclusion doesn't contain a transport) we write apdi₀i₁...iₙ. For versions where only some arguments depend on some other arguments, or for versions with transport in the conclusion (like apd), we don't have a consistent naming scheme (yet). We don't prove each theorem systematically, but prove only the ones which we actually need. -/ definition homotopy2 [reducible] (f g : Πa b, C a b) : Type := Πa b, f a b = g a b definition homotopy3 [reducible] (f g : Πa b c, D a b c) : Type := Πa b c, f a b c = g a b c definition homotopy4 [reducible] (f g : Πa b c d, E a b c d) : Type := Πa b c d, f a b c d = g a b c d infix ` ~2 `:50 := homotopy2 infix ` ~3 `:50 := homotopy3 definition ap011 (f : U → V → W) (Hu : u = u') (Hv : v = v') : f u v = f u' v' := by cases Hu; congruence; repeat assumption definition ap0111 (f : U → V → W → X) (Hu : u = u') (Hv : v = v') (Hw : w = w') : f u v w = f u' v' w' := by cases Hu; congruence; repeat assumption definition ap01111 (f : U → V → W → X → Y) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') : f u v w x = f u' v' w' x' := by cases Hu; congruence; repeat assumption definition ap011111 (f : U → V → W → X → Y → Z) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y') : f u v w x y = f u' v' w' x' y' := by cases Hu; congruence; repeat assumption definition ap0111111 (f : U → V → W → X → Y → Z → A) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y') (Hz : z = z') : f u v w x y z = f u' v' w' x' y' z' := by cases Hu; congruence; repeat assumption definition ap010 (f : X → Πa, B a) (Hx : x = x') : f x ~ f x' := by intros; cases Hx; reflexivity definition ap0100 (f : X → Πa b, C a b) (Hx : x = x') : f x ~2 f x' := by intros; cases Hx; reflexivity definition ap01000 (f : X → Πa b c, D a b c) (Hx : x = x') : f x ~3 f x' := by intros; cases Hx; reflexivity definition apd011 (f : Πa, B a → Z) (Ha : a = a') (Hb : transport B Ha b = b') : f a b = f a' b' := by cases Ha; cases Hb; reflexivity definition apd0111 (f : Πa b, C a b → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apd011 C Ha Hb) c = c') : f a b c = f a' b' c' := by cases Ha; cases Hb; cases Hc; reflexivity definition apd01111 (f : Πa b c, D a b c → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') : f a b c d = f a' b' c' d' := by cases Ha; cases Hb; cases Hc; cases Hd; reflexivity definition apd011111 (f : Πa b c d, E a b c d → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') (He : cast (apd01111 E Ha Hb Hc Hd) e = e') : f a b c d e = f a' b' c' d' e' := by cases Ha; cases Hb; cases Hc; cases Hd; cases He; reflexivity definition apd0111111 (f : Πa b c d e, F a b c d e → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f') : f a b c d e ff = f a' b' c' d' e' f' := begin cases Ha, cases Hb, cases Hc, cases Hd, cases He, cases Hf, reflexivity end -- definition apd0111111 (f : Πa b c d e ff, G a b c d e ff → Z) (Ha : a = a') (Hb : transport B Ha b = b') -- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') -- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f') -- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g') -- : f a b c d e ff g = f a' b' c' d' e' f' g' := -- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; reflexivity -- definition apd01111111 (f : Πa b c d e ff g, G a b c d e ff g → Z) (Ha : a = a') (Hb : transport B Ha b = b') -- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') -- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f') -- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g') (Hh : cast (apd01111111 H Ha Hb Hc Hd He Hf Hg) h = h') -- : f a b c d e ff g h = f a' b' c' d' e' f' g' h' := -- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; cases Hh; reflexivity definition apd100 [unfold 6] {f g : Πa b, C a b} (p : f = g) : f ~2 g := λa b, apd10 (apd10 p a) b definition apd1000 [unfold 7] {f g : Πa b c, D a b c} (p : f = g) : f ~3 g := λa b c, apd100 (apd10 p a) b c /- some properties of these variants of ap -/ -- we only prove what we currently need definition ap010_con (f : X → Πa, B a) (p : x = x') (q : x' = x'') : ap010 f (p ⬝ q) a = ap010 f p a ⬝ ap010 f q a := eq.rec_on q (eq.rec_on p idp) definition ap010_ap (f : X → Πa, B a) (g : Y → X) (p : y = y') : ap010 f (ap g p) a = ap010 (λy, f (g y)) p a := eq.rec_on p idp /- the following theorems are function extentionality for functions with multiple arguments -/ definition eq_of_homotopy2 {f g : Πa b, C a b} (H : f ~2 g) : f = g := eq_of_homotopy (λa, eq_of_homotopy (H a)) definition eq_of_homotopy3 {f g : Πa b c, D a b c} (H : f ~3 g) : f = g := eq_of_homotopy (λa, eq_of_homotopy2 (H a)) definition eq_of_homotopy2_id (f : Πa b, C a b) : eq_of_homotopy2 (λa b, idpath (f a b)) = idpath f := begin transitivity eq_of_homotopy (λ a, idpath (f a)), {apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy_idp}, apply eq_of_homotopy_idp end definition eq_of_homotopy3_id (f : Πa b c, D a b c) : eq_of_homotopy3 (λa b c, idpath (f a b c)) = idpath f := begin transitivity _, {apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy2_id}, apply eq_of_homotopy_idp end definition eq_of_homotopy2_inv {f g : Πa b, C a b} (H : f ~2 g) : eq_of_homotopy2 (λa b, (H a b)⁻¹) = (eq_of_homotopy2 H)⁻¹ := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_inv)) ⬝ !eq_of_homotopy_inv definition eq_of_homotopy3_inv {f g : Πa b c, D a b c} (H : f ~3 g) : eq_of_homotopy3 (λa b c, (H a b c)⁻¹) = (eq_of_homotopy3 H)⁻¹ := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_inv)) ⬝ !eq_of_homotopy_inv definition eq_of_homotopy2_con {f g h : Πa b, C a b} (H1 : f ~2 g) (H2 : g ~2 h) : eq_of_homotopy2 (λa b, H1 a b ⬝ H2 a b) = eq_of_homotopy2 H1 ⬝ eq_of_homotopy2 H2 := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_con)) ⬝ !eq_of_homotopy_con definition eq_of_homotopy3_con {f g h : Πa b c, D a b c} (H1 : f ~3 g) (H2 : g ~3 h) : eq_of_homotopy3 (λa b c, H1 a b c ⬝ H2 a b c) = eq_of_homotopy3 H1 ⬝ eq_of_homotopy3 H2 := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_con)) ⬝ !eq_of_homotopy_con end eq open eq equiv is_equiv namespace funext definition is_equiv_apd100 [instance] (f g : Πa b, C a b) : is_equiv (@apd100 A B C f g) := adjointify _ eq_of_homotopy2 begin intro H, esimp [apd100, eq_of_homotopy2], apply eq_of_homotopy, intro a, apply concat, apply (ap (λx, apd10 (x a))), apply (right_inv apd10), apply (right_inv apd10) end begin intro p, cases p, apply eq_of_homotopy2_id end definition is_equiv_apd1000 [instance] (f g : Πa b c, D a b c) : is_equiv (@apd1000 A B C D f g) := adjointify _ eq_of_homotopy3 begin intro H, esimp, apply eq_of_homotopy, intro a, transitivity apd100 (eq_of_homotopy2 (H a)), {apply ap (λx, apd100 (x a)), apply right_inv apd10}, apply right_inv apd100 end begin intro p, cases p, apply eq_of_homotopy3_id end end funext attribute funext.is_equiv_apd100 funext.is_equiv_apd1000 [constructor] namespace eq open funext local attribute funext.is_equiv_apd100 [instance] protected definition homotopy2.rec_on {f g : Πa b, C a b} {P : (f ~2 g) → Type} (p : f ~2 g) (H : Π(q : f = g), P (apd100 q)) : P p := right_inv apd100 p ▸ H (eq_of_homotopy2 p) protected definition homotopy3.rec_on {f g : Πa b c, D a b c} {P : (f ~3 g) → Type} (p : f ~3 g) (H : Π(q : f = g), P (apd1000 q)) : P p := right_inv apd1000 p ▸ H (eq_of_homotopy3 p) definition eq_equiv_homotopy2 [constructor] (f g : Πa b, C a b) : (f = g) ≃ (f ~2 g) := equiv.mk apd100 _ definition eq_equiv_homotopy3 [constructor] (f g : Πa b c, D a b c) : (f = g) ≃ (f ~3 g) := equiv.mk apd1000 _ definition apd10_ap (f : X → Πa, B a) (p : x = x') : apd10 (ap f p) = ap010 f p := eq.rec_on p idp definition eq_of_homotopy_ap010 (f : X → Πa, B a) (p : x = x') : eq_of_homotopy (ap010 f p) = ap f p := inv_eq_of_eq !apd10_ap⁻¹ definition ap_eq_ap_of_homotopy {f : X → Πa, B a} {p q : x = x'} (H : ap010 f p ~ ap010 f q) : ap f p = ap f q := calc ap f p = eq_of_homotopy (ap010 f p) : eq_of_homotopy_ap010 ... = eq_of_homotopy (ap010 f q) : eq_of_homotopy H ... = ap f q : eq_of_homotopy_ap010 end eq
2f88d8206e42bcb73095a70651b721e9a094fb5c
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/degree/lemmas.lean
020dcbdd03bffb1962c0b9c040868ad3655309cd
[ "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,589
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.eval import tactic.interval_cases /-! # Theory of degrees of polynomials Some of the main results include - `nat_degree_comp_le` : The degree of the composition is at most the product of degrees -/ noncomputable theory open_locale classical polynomial open finsupp finset namespace polynomial universes u v w variables {R : Type u} {S : Type v} { ι : Type w} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : R[X]} section degree lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... = _ : congr_arg degree comp_eq_sum_left ... ≤ _ : degree_sum_le _ _ ... ≤ _ : sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + n • (degree q) : add_le_add degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + n • (nat_degree q) : add_le_add_left (nsmul_le_nsmul_of_le_right (@degree_le_nat_degree _ _ q) n) _ ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_nsmul, nsmul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_pos_of_root {p : R[X]} (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, simp only [h, ring_hom.map_zero] at this, exact hp this, end lemma nat_degree_le_iff_coeff_eq_zero : p.nat_degree ≤ n ↔ ∀ N : ℕ, n < N → p.coeff N = 0 := by simp_rw [nat_degree_le_iff_degree_le, degree_le_iff_coeff_zero, with_bot.coe_lt_coe] lemma nat_degree_C_mul_le (a : R) (f : R[X]) : (C a * f).nat_degree ≤ f.nat_degree := calc (C a * f).nat_degree ≤ (C a).nat_degree + f.nat_degree : nat_degree_mul_le ... = 0 + f.nat_degree : by rw nat_degree_C a ... = f.nat_degree : zero_add _ lemma nat_degree_mul_C_le (f : R[X]) (a : R) : (f * C a).nat_degree ≤ f.nat_degree := calc (f * C a).nat_degree ≤ f.nat_degree + (C a).nat_degree : nat_degree_mul_le ... = f.nat_degree + 0 : by rw nat_degree_C a ... = f.nat_degree : add_zero _ lemma eq_nat_degree_of_le_mem_support (pn : p.nat_degree ≤ n) (ns : n ∈ p.support) : p.nat_degree = n := le_antisymm pn (le_nat_degree_of_mem_supp _ ns) lemma nat_degree_C_mul_eq_of_mul_eq_one {ai : R} (au : ai * a = 1) : (C a * p).nat_degree = p.nat_degree := le_antisymm (nat_degree_C_mul_le a p) (calc p.nat_degree = (1 * p).nat_degree : by nth_rewrite 0 [← one_mul p] ... = (C ai * (C a * p)).nat_degree : by rw [← C_1, ← au, ring_hom.map_mul, ← mul_assoc] ... ≤ (C a * p).nat_degree : nat_degree_C_mul_le ai (C a * p)) lemma nat_degree_mul_C_eq_of_mul_eq_one {ai : R} (au : a * ai = 1) : (p * C a).nat_degree = p.nat_degree := le_antisymm (nat_degree_mul_C_le p a) (calc p.nat_degree = (p * 1).nat_degree : by nth_rewrite 0 [← mul_one p] ... = ((p * C a) * C ai).nat_degree : by rw [← C_1, ← au, ring_hom.map_mul, ← mul_assoc] ... ≤ (p * C a).nat_degree : nat_degree_mul_C_le (p * C a) ai) /-- Although not explicitly stated, the assumptions of lemma `nat_degree_mul_C_eq_of_mul_ne_zero` force the polynomial `p` to be non-zero, via `p.leading_coeff ≠ 0`. -/ lemma nat_degree_mul_C_eq_of_mul_ne_zero (h : p.leading_coeff * a ≠ 0) : (p * C a).nat_degree = p.nat_degree := begin refine eq_nat_degree_of_le_mem_support (nat_degree_mul_C_le p a) _, refine mem_support_iff.mpr _, rwa coeff_mul_C, end /-- Although not explicitly stated, the assumptions of lemma `nat_degree_C_mul_eq_of_mul_ne_zero` force the polynomial `p` to be non-zero, via `p.leading_coeff ≠ 0`. -/ lemma nat_degree_C_mul_eq_of_mul_ne_zero (h : a * p.leading_coeff ≠ 0) : (C a * p).nat_degree = p.nat_degree := begin refine eq_nat_degree_of_le_mem_support (nat_degree_C_mul_le a p) _, refine mem_support_iff.mpr _, rwa coeff_C_mul, end lemma nat_degree_add_coeff_mul (f g : R[X]) : (f * g).coeff (f.nat_degree + g.nat_degree) = f.coeff f.nat_degree * g.coeff g.nat_degree := by simp only [coeff_nat_degree, coeff_mul_degree_add_degree] lemma nat_degree_lt_coeff_mul (h : p.nat_degree + q.nat_degree < m + n) : (p * q).coeff (m + n) = 0 := coeff_eq_zero_of_nat_degree_lt (nat_degree_mul_le.trans_lt h) lemma degree_sum_eq_of_disjoint (f : S → R[X]) (s : finset S) (h : set.pairwise { i | i ∈ s ∧ f i ≠ 0 } (ne on (degree ∘ f))) : degree (s.sum f) = s.sup (λ i, degree (f i)) := begin induction s using finset.induction_on with x s hx IH, { simp }, { simp only [hx, finset.sum_insert, not_false_iff, finset.sup_insert], specialize IH (h.mono (λ _, by simp {contextual := tt})), rcases lt_trichotomy (degree (f x)) (degree (s.sum f)) with H|H|H, { rw [←IH, sup_eq_right.mpr H.le, degree_add_eq_right_of_degree_lt H] }, { rcases s.eq_empty_or_nonempty with rfl|hs, { simp }, obtain ⟨y, hy, hy'⟩ := finset.exists_mem_eq_sup s hs (λ i, degree (f i)), rw [IH, hy'] at H, by_cases hx0 : f x = 0, { simp [hx0, IH] }, have hy0 : f y ≠ 0, { contrapose! H, simpa [H, degree_eq_bot] using hx0 }, refine absurd H (h _ _ (λ H, hx _)), { simp [hx0] }, { simp [hy, hy0] }, { exact H.symm ▸ hy } }, { rw [←IH, sup_eq_left.mpr H.le, degree_add_eq_left_of_degree_lt H] } } end lemma nat_degree_sum_eq_of_disjoint (f : S → R[X]) (s : finset S) (h : set.pairwise { i | i ∈ s ∧ f i ≠ 0 } (ne on (nat_degree ∘ f))) : nat_degree (s.sum f) = s.sup (λ i, nat_degree (f i)) := begin by_cases H : ∃ x ∈ s, f x ≠ 0, { obtain ⟨x, hx, hx'⟩ := H, have hs : s.nonempty := ⟨x, hx⟩, refine nat_degree_eq_of_degree_eq_some _, rw degree_sum_eq_of_disjoint, { rw [←finset.sup'_eq_sup hs, ←finset.sup'_eq_sup hs, finset.coe_sup', ←finset.sup'_eq_sup hs], refine le_antisymm _ _, { rw finset.sup'_le_iff, intros b hb, by_cases hb' : f b = 0, { simpa [hb'] using hs }, rw degree_eq_nat_degree hb', exact finset.le_sup' _ hb }, { rw finset.sup'_le_iff, intros b hb, simp only [finset.le_sup'_iff, exists_prop, function.comp_app], by_cases hb' : f b = 0, { refine ⟨x, hx, _⟩, contrapose! hx', simpa [hb', degree_eq_bot] using hx' }, exact ⟨b, hb, (degree_eq_nat_degree hb').ge⟩ } }, { exact h.imp (λ x y hxy hxy', hxy (nat_degree_eq_of_degree_eq hxy')) } }, { push_neg at H, rw [finset.sum_eq_zero H, nat_degree_zero, eq_comm, show 0 = ⊥, from rfl, finset.sup_eq_bot_iff], intros x hx, simp [H x hx] } end variables [semiring S] lemma nat_degree_pos_of_eval₂_root {p : R[X]} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < nat_degree p := lt_of_not_ge $ λ hlt, begin have A : p = C (p.coeff 0) := eq_C_of_nat_degree_le_zero hlt, rw [A, eval₂_C] at hz, simp only [inj (p.coeff 0) hz, ring_hom.map_zero] at A, exact hp A end lemma degree_pos_of_eval₂_root {p : R[X]} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < degree p := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_eval₂_root hp f hz inj) @[simp] lemma coe_lt_degree {p : R[X]} {n : ℕ} : ((n : with_bot ℕ) < degree p) ↔ n < nat_degree p := begin by_cases h : p = 0, { simp [h] }, rw [degree_eq_nat_degree h, with_bot.coe_lt_coe], end end degree end semiring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} lemma degree_mul_C (a0 : a ≠ 0) : (p * C a).degree = p.degree := by rw [degree_mul, degree_C a0, add_zero] lemma degree_C_mul (a0 : a ≠ 0) : (C a * p).degree = p.degree := by rw [degree_mul, degree_C a0, zero_add] lemma nat_degree_mul_C (a0 : a ≠ 0) : (p * C a).nat_degree = p.nat_degree := by simp only [nat_degree, degree_mul_C a0] lemma nat_degree_C_mul (a0 : a ≠ 0) : (C a * p).nat_degree = p.nat_degree := by simp only [nat_degree, degree_C_mul a0] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := begin by_cases q0 : q.nat_degree = 0, { rw [degree_le_zero_iff.mp (nat_degree_eq_zero_iff_degree_le_zero.mp q0), comp_C, nat_degree_C, nat_degree_C, mul_zero] }, { by_cases p0 : p = 0, { simp only [p0, zero_comp, nat_degree_zero, zero_mul] }, refine le_antisymm nat_degree_comp_le (le_nat_degree_of_ne_zero _), simp only [coeff_comp_degree_mul_degree q0, p0, mul_eq_zero, leading_coeff_eq_zero, or_self, ne_zero_of_nat_degree_gt (nat.pos_of_ne_zero q0), pow_ne_zero, ne.def, not_false_iff] } end lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp, coeff_nat_degree] end no_zero_divisors end polynomial
cf025bff75e3494edb6668c1b543b6a62c788236
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/impLambdaTac.lean
aaced1164123e7bc62cb9a5b2853b44d04649bba
[ "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
667
lean
example (P : Prop) : ∀ {p : P}, P := by exact fun {p} => p example (P : Prop) : ∀ {p : P}, P := by intro h; exact h example (P : Prop) : ∀ {p : P}, P := by exact @id _ example (P : Prop) : ∀ {p : P}, P := by exact noImplicitLambda% id macro "exact'" x:term : tactic => `(exact noImplicitLambda% $x) example (P : Prop) : ∀ {p : P}, P := by exact' id example (P : Prop) : ∀ {p : P}, P := by apply id example (P : Prop) : ∀ p : P, P := by have : _ := 1 apply id example (P : Prop) : ∀ {p : P}, P := by refine noImplicitLambda% (have : _ := 1; ?_) apply id example (P : Prop) : ∀ {p : P}, P := by have : _ := 1 apply id
3c903619ffecd3c385adfd3cd6dc7c25a8b6af98
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/category_theory/equivalence.lean
10e1870cfa7bd4c454f250c775bb0bbe572df501
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,609
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.fully_faithful import category_theory.whiskering import tactic.slice /-! # Equivalence of categories An equivalence of categories `C` and `D` is a pair of functors `F : C ⥤ D` and `G : D ⥤ C` such that `η : 𝟭 C ≅ F ⋙ G` and `ε : G ⋙ F ≅ 𝟭 D`. In many situations, equivalences are a better notion of "sameness" of categories than the stricter isomorphims of categories. Recall that one way to express that two functors `F : C ⥤ D` and `G : D ⥤ C` are adjoint is using two natural transformations `η : 𝟭 C ⟶ F ⋙ G` and `ε : G ⋙ F ⟶ 𝟭 D`, called the unit and the counit, such that the compositions `F ⟶ FGF ⟶ F` and `G ⟶ GFG ⟶ G` are the identity. Unfortunately, it is not the case that the natural isomorphisms `η` and `ε` in the definition of an equivalence automatically give an adjunction. However, it is true that * if one of the two compositions is the identity, then so is the other, and * given an equivalence of categories, it is always possible to refine `η` in such a way that the identities are satisfied. For this reason, in mathlib we define an equivalence to be a "half-adjoint equivalence", which is a tuple `(F, G, η, ε)` as in the first paragraph such that the composite `F ⟶ FGF ⟶ F` is the identity. By the remark above, this already implies that the tuple is an "adjoint equivalence", i.e., that the composite `G ⟶ GFG ⟶ G` is also the identity. We also define essentially surjective functors and show that a functor is an equivalence if and only if it is full, faithful and essentially surjective. ## Main definitions * `equivalence`: bundled (half-)adjoint equivalences of categories * `is_equivalence`: type class on a functor `F` containing the data of the inverse `G` as well as the natural isomorphisms `η` and `ε`. * `ess_surj`: type class on a functor `F` containing the data of the preimages and the isomorphisms `F.obj (preimage d) ≅ d`. ## Main results * `equivalence.mk`: upgrade an equivalence to a (half-)adjoint equivalence * `equivalence_of_fully_faithfully_ess_surj`: a fully faithful essentially surjective functor is an equivalence. ## Notations We write `C ≌ D` (`\backcong`, not to be confused with `≅`/`\cong`) for a bundled equivalence. -/ namespace category_theory open category_theory.functor nat_iso category universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- We define an equivalence as a (half)-adjoint equivalence, a pair of functors with a unit and counit which are natural isomorphisms and the triangle law `Fη ≫ εF = 1`, or in other words the composite `F ⟶ FGF ⟶ F` is the identity. In `unit_inverse_comp`, we show that this is actually an adjoint equivalence, i.e., that the composite `G ⟶ GFG ⟶ G` is also the identity. The triangle equation is written as a family of equalities between morphisms, it is more complicated if we write it as an equality of natural transformations, because then we would have to insert natural transformations like `F ⟶ F1`. See https://stacks.math.columbia.edu/tag/001J -/ structure equivalence (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] := mk' :: (functor : C ⥤ D) (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ functor ⋙ inverse) (counit_iso : inverse ⋙ functor ≅ 𝟭 D) (functor_unit_iso_comp' : ∀(X : C), functor.map ((unit_iso.hom : 𝟭 C ⟶ functor ⋙ inverse).app X) ≫ counit_iso.hom.app (functor.obj X) = 𝟙 (functor.obj X) . obviously) restate_axiom equivalence.functor_unit_iso_comp' infixr ` ≌ `:10 := equivalence variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] namespace equivalence /-- The unit of an equivalence of categories. -/ abbreviation unit (e : C ≌ D) : 𝟭 C ⟶ e.functor ⋙ e.inverse := e.unit_iso.hom /-- The counit of an equivalence of categories. -/ abbreviation counit (e : C ≌ D) : e.inverse ⋙ e.functor ⟶ 𝟭 D := e.counit_iso.hom /-- The inverse of the unit of an equivalence of categories. -/ abbreviation unit_inv (e : C ≌ D) : e.functor ⋙ e.inverse ⟶ 𝟭 C := e.unit_iso.inv /-- The inverse of the counit of an equivalence of categories. -/ abbreviation counit_inv (e : C ≌ D) : 𝟭 D ⟶ e.inverse ⋙ e.functor := e.counit_iso.inv /- While these abbreviations are convenient, they also cause some trouble, preventing structure projections from unfolding. -/ @[simp] lemma equivalence_mk'_unit (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit = unit_iso.hom := rfl @[simp] lemma equivalence_mk'_counit (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit = counit_iso.hom := rfl @[simp] lemma equivalence_mk'_unit_inv (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit_inv = unit_iso.inv := rfl @[simp] lemma equivalence_mk'_counit_inv (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit_inv = counit_iso.inv := rfl @[simp] lemma functor_unit_comp (e : C ≌ D) (X : C) : e.functor.map (e.unit.app X) ≫ e.counit.app (e.functor.obj X) = 𝟙 (e.functor.obj X) := e.functor_unit_iso_comp X @[simp] lemma counit_inv_functor_comp (e : C ≌ D) (X : C) : e.counit_inv.app (e.functor.obj X) ≫ e.functor.map (e.unit_inv.app X) = 𝟙 (e.functor.obj X) := begin erw [iso.inv_eq_inv (e.functor.map_iso (e.unit_iso.app X) ≪≫ e.counit_iso.app (e.functor.obj X)) (iso.refl _)], exact e.functor_unit_comp X end lemma counit_inv_app_functor (e : C ≌ D) (X : C) : e.counit_inv.app (e.functor.obj X) = e.functor.map (e.unit.app X) := by { symmetry, erw [←iso.comp_hom_eq_id (e.counit_iso.app _), functor_unit_comp], refl } lemma counit_app_functor (e : C ≌ D) (X : C) : e.counit.app (e.functor.obj X) = e.functor.map (e.unit_inv.app X) := by { erw [←iso.hom_comp_eq_id (e.functor.map_iso (e.unit_iso.app X)), functor_unit_comp], refl } /-- The other triangle equality. The proof follows the following proof in Globular: http://globular.science/1905.001 -/ @[simp] lemma unit_inverse_comp (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) ≫ e.inverse.map (e.counit.app Y) = 𝟙 (e.inverse.obj Y) := begin rw [←id_comp (e.inverse.map _), ←map_id e.inverse, ←counit_inv_functor_comp, map_comp, ←iso.hom_inv_id_assoc (e.unit_iso.app _) (e.inverse.map (e.functor.map _)), app_hom, app_inv], slice_lhs 2 3 { erw [e.unit.naturality] }, slice_lhs 1 2 { erw [e.unit.naturality] }, slice_lhs 4 4 { rw [←iso.hom_inv_id_assoc (e.inverse.map_iso (e.counit_iso.app _)) (e.unit_inv.app _)] }, slice_lhs 3 4 { erw [←map_comp e.inverse, e.counit.naturality], erw [(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 2 3 { erw [←map_comp e.inverse, e.counit_iso.inv.naturality, map_comp] }, slice_lhs 3 4 { erw [e.unit_inv.naturality] }, slice_lhs 4 5 { erw [←map_comp (e.functor ⋙ e.inverse), (e.unit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 3 4 { erw [←e.unit_inv.naturality] }, slice_lhs 2 3 { erw [←map_comp e.inverse, ←e.counit_iso.inv.naturality, (e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp, (e.unit_iso.app _).hom_inv_id], refl end @[simp] lemma inverse_counit_inv_comp (e : C ≌ D) (Y : D) : e.inverse.map (e.counit_inv.app Y) ≫ e.unit_inv.app (e.inverse.obj Y) = 𝟙 (e.inverse.obj Y) := begin erw [iso.inv_eq_inv (e.unit_iso.app (e.inverse.obj Y) ≪≫ e.inverse.map_iso (e.counit_iso.app Y)) (iso.refl _)], exact e.unit_inverse_comp Y end lemma unit_app_inverse (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) = e.inverse.map (e.counit_inv.app Y) := by { erw [←iso.comp_hom_eq_id (e.inverse.map_iso (e.counit_iso.app Y)), unit_inverse_comp], refl } lemma unit_inv_app_inverse (e : C ≌ D) (Y : D) : e.unit_inv.app (e.inverse.obj Y) = e.inverse.map (e.counit.app Y) := by { symmetry, erw [←iso.hom_comp_eq_id (e.unit_iso.app _), unit_inverse_comp], refl } @[simp] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) : e.functor.map (e.inverse.map f) = e.counit.app X ≫ f ≫ e.counit_inv.app Y := (nat_iso.naturality_2 (e.counit_iso) f).symm @[simp] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) : e.inverse.map (e.functor.map f) = e.unit_inv.app X ≫ f ≫ e.unit.app Y := (nat_iso.naturality_1 (e.unit_iso) f).symm section -- In this section we convert an arbitrary equivalence to a half-adjoint equivalence. variables {F : C ⥤ D} {G : D ⥤ C} (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) /-- If `η : 𝟭 C ≅ F ⋙ G` is part of a (not necessarily half-adjoint) equivalence, we can upgrade it to a refined natural isomorphism `adjointify_η η : 𝟭 C ≅ F ⋙ G` which exhibits the properties required for a half-adjoint equivalence. See `equivalence.mk`. -/ def adjointify_η : 𝟭 C ≅ F ⋙ G := calc 𝟭 C ≅ F ⋙ G : η ... ≅ F ⋙ (𝟭 D ⋙ G) : iso_whisker_left F (left_unitor G).symm ... ≅ F ⋙ ((G ⋙ F) ⋙ G) : iso_whisker_left F (iso_whisker_right ε.symm G) ... ≅ F ⋙ (G ⋙ (F ⋙ G)) : iso_whisker_left F (associator G F G) ... ≅ (F ⋙ G) ⋙ (F ⋙ G) : (associator F G (F ⋙ G)).symm ... ≅ 𝟭 C ⋙ (F ⋙ G) : iso_whisker_right η.symm (F ⋙ G) ... ≅ F ⋙ G : left_unitor (F ⋙ G) lemma adjointify_η_ε (X : C) : F.map ((adjointify_η η ε).hom.app X) ≫ ε.hom.app (F.obj X) = 𝟙 (F.obj X) := begin dsimp [adjointify_η], simp, have := ε.hom.naturality (F.map (η.inv.app X)), dsimp at this, rw [this], clear this, rw [←assoc _ _ (F.map _)], have := ε.hom.naturality (ε.inv.app $ F.obj X), dsimp at this, rw [this], clear this, have := (ε.app $ F.obj X).hom_inv_id, dsimp at this, rw [this], clear this, rw [id_comp], have := (F.map_iso $ η.app X).hom_inv_id, dsimp at this, rw [this] end end /-- Every equivalence of categories consisting of functors `F` and `G` such that `F ⋙ G` and `G ⋙ F` are naturally isomorphic to identity functors can be transformed into a half-adjoint equivalence without changing `F` or `G`. -/ protected definition mk (F : C ⥤ D) (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : C ≌ D := ⟨F, G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ /-- Equivalence of categories is reflexive. -/ @[refl, simps] def refl : C ≌ C := ⟨𝟭 C, 𝟭 C, iso.refl _, iso.refl _, λ X, category.id_comp _⟩ instance : inhabited (C ≌ C) := ⟨refl⟩ /-- Equivalence of categories is symmetric. -/ @[symm, simps] def symm (e : C ≌ D) : D ≌ C := ⟨e.inverse, e.functor, e.counit_iso.symm, e.unit_iso.symm, e.inverse_counit_inv_comp⟩ variables {E : Type u₃} [category.{v₃} E] /-- Equivalence of categories is transitive. -/ @[trans, simps] def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E := { functor := e.functor ⋙ f.functor, inverse := f.inverse ⋙ e.inverse, unit_iso := begin refine iso.trans e.unit_iso _, exact iso_whisker_left e.functor (iso_whisker_right f.unit_iso e.inverse) , end, counit_iso := begin refine iso.trans _ f.counit_iso, exact iso_whisker_left f.inverse (iso_whisker_right e.counit_iso f.functor) end, -- We wouldn't have needed to give this proof if we'd used `equivalence.mk`, -- but we choose to avoid using that here, for the sake of good structure projection `simp` lemmas. functor_unit_iso_comp' := λ X, begin dsimp, rw [← f.functor.map_comp_assoc, e.functor.map_comp, ←counit_inv_app_functor, fun_inv_map, iso.inv_hom_id_app_assoc, assoc, iso.inv_hom_id_app, counit_app_functor, ← functor.map_comp], erw [comp_id, iso.hom_inv_id_app, functor.map_id], end } /-- Composing a functor with both functors of an equivalence yields a naturally isomorphic functor. -/ def fun_inv_id_assoc (e : C ≌ D) (F : C ⥤ E) : e.functor ⋙ e.inverse ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.unit_iso.symm F ≪≫ F.left_unitor @[simp] lemma fun_inv_id_assoc_hom_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).hom.app X = F.map (e.unit_inv.app X) := by { dsimp [fun_inv_id_assoc], tidy } @[simp] lemma fun_inv_id_assoc_inv_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).inv.app X = F.map (e.unit.app X) := by { dsimp [fun_inv_id_assoc], tidy } /-- Composing a functor with both functors of an equivalence yields a naturally isomorphic functor. -/ def inv_fun_id_assoc (e : C ≌ D) (F : D ⥤ E) : e.inverse ⋙ e.functor ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.counit_iso F ≪≫ F.left_unitor @[simp] lemma inv_fun_id_assoc_hom_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).hom.app X = F.map (e.counit.app X) := by { dsimp [inv_fun_id_assoc], tidy } @[simp] lemma inv_fun_id_assoc_inv_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).inv.app X = F.map (e.counit_inv.app X) := by { dsimp [inv_fun_id_assoc], tidy } /-- If `C` is equivalent to `D`, then `C ⥤ E` is equivalent to `D ⥤ E`. -/ @[simps functor inverse unit_iso counit_iso {rhs_md:=semireducible}] def congr_left (e : C ≌ D) : (C ⥤ E) ≌ (D ⥤ E) := equivalence.mk ((whiskering_left _ _ _).obj e.inverse) ((whiskering_left _ _ _).obj e.functor) (nat_iso.of_components (λ F, (e.fun_inv_id_assoc F).symm) (by tidy)) (nat_iso.of_components (λ F, e.inv_fun_id_assoc F) (by tidy)) /-- If `C` is equivalent to `D`, then `E ⥤ C` is equivalent to `E ⥤ D`. -/ @[simps functor inverse unit_iso counit_iso {rhs_md:=semireducible}] def congr_right (e : C ≌ D) : (E ⥤ C) ≌ (E ⥤ D) := equivalence.mk ((whiskering_right _ _ _).obj e.functor) ((whiskering_right _ _ _).obj e.inverse) (nat_iso.of_components (λ F, F.right_unitor.symm ≪≫ iso_whisker_left F e.unit_iso ≪≫ functor.associator _ _ _) (by tidy)) (nat_iso.of_components (λ F, functor.associator _ _ _ ≪≫ iso_whisker_left F e.counit_iso ≪≫ F.right_unitor) (by tidy)) section cancellation_lemmas variables (e : C ≌ D) -- We need special forms of `cancel_nat_iso_hom_right(_assoc)` and `cancel_nat_iso_inv_right(_assoc)` -- for units and counits, because neither `simp` or `rw` will apply those lemmas in this -- setting without providing `e.unit_iso` (or similar) as an explicit argument. -- We also provide the lemmas for length four compositions, since they're occasionally useful. -- (e.g. in proving that equivalences take monos to monos) @[simp] lemma cancel_unit_right {X Y : C} (f f' : X ⟶ Y) : f ≫ e.unit.app Y = f' ≫ e.unit.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_unit_inv_right {X Y : C} (f f' : X ⟶ e.inverse.obj (e.functor.obj Y)) : f ≫ e.unit_inv.app Y = f' ≫ e.unit_inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_counit_right {X Y : D} (f f' : X ⟶ e.functor.obj (e.inverse.obj Y)) : f ≫ e.counit.app Y = f' ≫ e.counit.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_counit_inv_right {X Y : D} (f f' : X ⟶ Y) : f ≫ e.counit_inv.app Y = f' ≫ e.counit_inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_unit_right_assoc {W X X' Y : C} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) : f ≫ g ≫ e.unit.app Y = f' ≫ g' ≫ e.unit.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_counit_inv_right_assoc {W X X' Y : D} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) : f ≫ g ≫ e.counit_inv.app Y = f' ≫ g' ≫ e.counit_inv.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_unit_right_assoc' {W X X' Y Y' Z : C} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) : f ≫ g ≫ h ≫ e.unit.app Z = f' ≫ g' ≫ h' ≫ e.unit.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_counit_inv_right_assoc' {W X X' Y Y' Z : D} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) : f ≫ g ≫ h ≫ e.counit_inv.app Z = f' ≫ g' ≫ h' ≫ e.counit_inv.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' := by simp only [←category.assoc, cancel_mono] end cancellation_lemmas section -- There's of course a monoid structure on `C ≌ C`, -- but let's not encourage using it. -- The power structure is nevertheless useful. /-- Powers of an auto-equivalence. -/ def pow (e : C ≌ C) : ℤ → (C ≌ C) | (int.of_nat 0) := equivalence.refl | (int.of_nat 1) := e | (int.of_nat (n+2)) := e.trans (pow (int.of_nat (n+1))) | (int.neg_succ_of_nat 0) := e.symm | (int.neg_succ_of_nat (n+1)) := e.symm.trans (pow (int.neg_succ_of_nat n)) instance : has_pow (C ≌ C) ℤ := ⟨pow⟩ @[simp] lemma pow_zero (e : C ≌ C) : e^(0 : ℤ) = equivalence.refl := rfl @[simp] lemma pow_one (e : C ≌ C) : e^(1 : ℤ) = e := rfl @[simp] lemma pow_minus_one (e : C ≌ C) : e^(-1 : ℤ) = e.symm := rfl -- TODO as necessary, add the natural isomorphisms `(e^a).trans e^b ≅ e^(a+b)`. -- At this point, we haven't even defined the category of equivalences. end end equivalence /-- A functor that is part of a (half) adjoint equivalence -/ class is_equivalence (F : C ⥤ D) := mk' :: (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ F ⋙ inverse) (counit_iso : inverse ⋙ F ≅ 𝟭 D) (functor_unit_iso_comp' : ∀ (X : C), F.map ((unit_iso.hom : 𝟭 C ⟶ F ⋙ inverse).app X) ≫ counit_iso.hom.app (F.obj X) = 𝟙 (F.obj X) . obviously) restate_axiom is_equivalence.functor_unit_iso_comp' namespace is_equivalence instance of_equivalence (F : C ≌ D) : is_equivalence F.functor := { ..F } instance of_equivalence_inverse (F : C ≌ D) : is_equivalence F.inverse := is_equivalence.of_equivalence F.symm open equivalence /-- To see that a functor is an equivalence, it suffices to provide an inverse functor `G` such that `F ⋙ G` and `G ⋙ F` are naturally isomorphic to identity functors. -/ protected definition mk {F : C ⥤ D} (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : is_equivalence F := ⟨G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ end is_equivalence namespace functor /-- Interpret a functor that is an equivalence as an equivalence. -/ def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D := ⟨F, is_equivalence.inverse F, is_equivalence.unit_iso, is_equivalence.counit_iso, is_equivalence.functor_unit_iso_comp⟩ instance is_equivalence_refl : is_equivalence (𝟭 C) := is_equivalence.of_equivalence equivalence.refl /-- The inverse functor of a functor that is an equivalence. -/ def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C := is_equivalence.inverse F instance is_equivalence_inv (F : C ⥤ D) [is_equivalence F] : is_equivalence F.inv := is_equivalence.of_equivalence F.as_equivalence.symm @[simp] lemma as_equivalence_functor (F : C ⥤ D) [is_equivalence F] : F.as_equivalence.functor = F := rfl @[simp] lemma as_equivalence_inverse (F : C ⥤ D) [is_equivalence F] : F.as_equivalence.inverse = inv F := rfl @[simp] lemma inv_inv (F : C ⥤ D) [is_equivalence F] : inv (inv F) = F := rfl /-- The composition of functor that is an equivalence with its inverse is naturally isomorphic to the identity functor. -/ def fun_inv_id (F : C ⥤ D) [is_equivalence F] : F ⋙ F.inv ≅ 𝟭 C := is_equivalence.unit_iso.symm /-- The composition of functor that is an equivalence with its inverse is naturally isomorphic to the identity functor. -/ def inv_fun_id (F : C ⥤ D) [is_equivalence F] : F.inv ⋙ F ≅ 𝟭 D := is_equivalence.counit_iso variables {E : Type u₃} [category.{v₃} E] instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] : is_equivalence (F ⋙ G) := is_equivalence.of_equivalence (equivalence.trans (as_equivalence F) (as_equivalence G)) end functor namespace equivalence @[simp] lemma functor_inv (E : C ≌ D) : E.functor.inv = E.inverse := rfl @[simp] lemma inverse_inv (E : C ≌ D) : E.inverse.inv = E.functor := rfl @[simp] lemma functor_as_equivalence (E : C ≌ D) : E.functor.as_equivalence = E := by { cases E, congr, } @[simp] lemma inverse_as_equivalence (E : C ≌ D) : E.inverse.as_equivalence = E.symm := by { cases E, congr, } end equivalence namespace is_equivalence @[simp] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) : F.map (F.inv.map f) = F.inv_fun_id.hom.app X ≫ f ≫ F.inv_fun_id.inv.app Y := begin erw [nat_iso.naturality_2], refl end @[simp] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) : F.inv.map (F.map f) = F.fun_inv_id.hom.app X ≫ f ≫ F.fun_inv_id.inv.app Y := begin erw [nat_iso.naturality_2], refl end -- We should probably restate many of the lemmas about `equivalence` for `is_equivalence`, -- but these are the only ones I need for now. @[simp] lemma functor_unit_comp (E : C ⥤ D) [is_equivalence E] (Y) : E.map (E.fun_inv_id.inv.app Y) ≫ E.inv_fun_id.hom.app (E.obj Y) = 𝟙 _ := equivalence.functor_unit_comp E.as_equivalence Y @[simp] lemma inv_fun_id_inv_comp (E : C ⥤ D) [is_equivalence E] (Y) : E.inv_fun_id.inv.app (E.obj Y) ≫ E.map (E.fun_inv_id.hom.app Y) = 𝟙 _ := eq_of_inv_eq_inv (functor_unit_comp _ _) end is_equivalence /-- A functor `F : C ⥤ D` is essentially surjective if for every `d : D`, there is some `c : C` so `F.obj c ≅ D`. See https://stacks.math.columbia.edu/tag/001C. -/ -- TODO should we make this a `Prop` that merely asserts the existence of a preimage, -- rather than choosing one? class ess_surj (F : C ⥤ D) := (obj_preimage (d : D) : C) (iso' (d : D) : F.obj (obj_preimage d) ≅ d . obviously) restate_axiom ess_surj.iso' /-- Applying an essentially surjective functor to a preimage of `d` yields an object that is isomorphic to `d`. -/ add_decl_doc ess_surj.iso namespace functor /-- Given an essentially surjective functor, we can find a preimage for every object `d` in the codomain. Applying the functor to this preimage will yield an object isomorphic to `d`, see `fun_obj_preimage_iso`. -/ def obj_preimage (F : C ⥤ D) [ess_surj F] (d : D) : C := ess_surj.obj_preimage.{v₁ v₂} F d /-- Applying an essentially surjective functor to a preimage of `d` yields an object that is isomorphic to `d`. -/ def fun_obj_preimage_iso (F : C ⥤ D) [ess_surj F] (d : D) : F.obj (F.obj_preimage d) ≅ d := ess_surj.iso d end functor namespace equivalence /-- An equivalence is essentially surjective. See https://stacks.math.columbia.edu/tag/02C3. -/ def ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F := ⟨ λ Y : D, F.inv.obj Y, λ Y : D, (F.inv_fun_id.app Y) ⟩ /-- An equivalence is faithful. See https://stacks.math.columbia.edu/tag/02C3. -/ @[priority 100] -- see Note [lower instance priority] instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F := { map_injective' := λ X Y f g w, begin have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w, simpa only [cancel_epi, cancel_mono, is_equivalence.inv_fun_map] using p end }. /-- An equivalence is full. See https://stacks.math.columbia.edu/tag/02C3. -/ @[priority 100] -- see Note [lower instance priority] instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F := { preimage := λ X Y f, F.fun_inv_id.inv.app X ≫ F.inv.map f ≫ F.fun_inv_id.hom.app Y, witness' := λ X Y f, F.inv.map_injective (by simpa only [is_equivalence.inv_fun_map, assoc, iso.hom_inv_id_app_assoc, iso.hom_inv_id_app] using comp_id _) } @[simp] private def equivalence_inverse (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : D ⥤ C := { obj := λ X, F.obj_preimage X, map := λ X Y f, F.preimage ((F.fun_obj_preimage_iso X).hom ≫ f ≫ (F.fun_obj_preimage_iso Y).inv), map_id' := λ X, begin apply F.map_injective, tidy end, map_comp' := λ X Y Z f g, by apply F.map_injective; simp } /-- A functor which is full, faithful, and essentially surjective is an equivalence. See https://stacks.math.columbia.edu/tag/02C3. -/ def equivalence_of_fully_faithfully_ess_surj (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : is_equivalence F := is_equivalence.mk (equivalence_inverse F) (nat_iso.of_components (λ X, (preimage_iso $ F.fun_obj_preimage_iso $ F.obj X).symm) (λ X Y f, by { apply F.map_injective, obviously })) (nat_iso.of_components (λ Y, F.fun_obj_preimage_iso Y) (by obviously)) @[simp] lemma functor_map_inj_iff (e : C ≌ D) {X Y : C} (f g : X ⟶ Y) : e.functor.map f = e.functor.map g ↔ f = g := begin split, { intro w, apply e.functor.map_injective, exact w, }, { rintro ⟨rfl⟩, refl, } end @[simp] lemma inverse_map_inj_iff (e : C ≌ D) {X Y : D} (f g : X ⟶ Y) : e.inverse.map f = e.inverse.map g ↔ f = g := begin split, { intro w, apply e.inverse.map_injective, exact w, }, { rintro ⟨rfl⟩, refl, } end end equivalence end category_theory
bad10d7fd59109724ea63c53c5f678f5a9ab9260
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/hom/freiman.lean
8a68912793ea7e17945a7ee05e2a6c96067958ab
[ "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
17,323
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.big_operators.multiset import data.fun_like.basic /-! # Freiman homomorphisms In this file, we define Freiman homomorphisms. A `n`-Freiman homomorphism on `A` is a function `f : α → β` such that `f (x₁) * ... * f (xₙ) = f (y₁) * ... * f (yₙ)` for all `x₁, ..., xₙ, y₁, ..., yₙ ∈ A` such that `x₁ * ... * xₙ = y₁ * ... * yₙ`. In particular, any `mul_hom` is a Freiman homomorphism. They are of interest in additive combinatorics. ## Main declaration * `freiman_hom`: Freiman homomorphism. * `add_freiman_hom`: Additive Freiman homomorphism. ## Notation * `A →*[n] β`: Multiplicative `n`-Freiman homomorphism on `A` * `A →+[n] β`: Additive `n`-Freiman homomorphism on `A` ## Implementation notes In the context of combinatorics, we are interested in Freiman homomorphisms over sets which are not necessarily closed under addition/multiplication. This means we must parametrize them with a set in an `add_monoid`/`monoid` instead of the `add_monoid`/`monoid` itself. ## References [Yufei Zhao, *18.225: Graph Theory and Additive Combinatorics*](https://yufeizhao.com/gtac/) ## TODO `monoid_hom.to_freiman_hom` could be relaxed to `mul_hom.to_freiman_hom` by proving `(s.map f).prod = (t.map f).prod` directly by induction instead of going through `f s.prod`. Define `n`-Freiman isomorphisms. Affine maps induce Freiman homs. Concretely, provide the `add_freiman_hom_class (α →ₐ[𝕜] β) A β n` instance. -/ open multiset variables {F α β γ δ G : Type*} /-- An additive `n`-Freiman homomorphism is a map which preserves sums of `n` elements. -/ structure add_freiman_hom (A : set α) (β : Type*) [add_comm_monoid α] [add_comm_monoid β] (n : ℕ) := (to_fun : α → β) (map_sum_eq_map_sum' {s t : multiset α} (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A) (hs : s.card = n) (ht : t.card = n) (h : s.sum = t.sum) : (s.map to_fun).sum = (t.map to_fun).sum) /-- A `n`-Freiman homomorphism on a set `A` is a map which preserves products of `n` elements. -/ @[to_additive add_freiman_hom] structure freiman_hom (A : set α) (β : Type*) [comm_monoid α] [comm_monoid β] (n : ℕ) := (to_fun : α → β) (map_prod_eq_map_prod' {s t : multiset α} (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A) (hs : s.card = n) (ht : t.card = n) (h : s.prod = t.prod) : (s.map to_fun).prod = (t.map to_fun).prod) notation A ` →+[`:25 n:25 `] `:0 β:0 := add_freiman_hom A β n notation A ` →*[`:25 n:25 `] `:0 β:0 := freiman_hom A β n /-- `add_freiman_hom_class F s β n` states that `F` is a type of `n`-ary sums-preserving morphisms. You should extend this class when you extend `add_freiman_hom`. -/ class add_freiman_hom_class (F : Type*) (A : out_param $ set α) (β : out_param $ Type*) [add_comm_monoid α] [add_comm_monoid β] (n : ℕ) [fun_like F α (λ _, β)] := (map_sum_eq_map_sum' (f : F) {s t : multiset α} (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A) (hs : s.card = n) (ht : t.card = n) (h : s.sum = t.sum) : (s.map f).sum = (t.map f).sum) /-- `freiman_hom_class F A β n` states that `F` is a type of `n`-ary products-preserving morphisms. You should extend this class when you extend `freiman_hom`. -/ @[to_additive add_freiman_hom_class "`add_freiman_hom_class F A β n` states that `F` is a type of `n`-ary sums-preserving morphisms. You should extend this class when you extend `add_freiman_hom`."] class freiman_hom_class (F : Type*) (A : out_param $ set α) (β : out_param $ Type*) [comm_monoid α] [comm_monoid β] (n : ℕ) [fun_like F α (λ _, β)] := (map_prod_eq_map_prod' (f : F) {s t : multiset α} (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A) (hs : s.card = n) (ht : t.card = n) (h : s.prod = t.prod) : (s.map f).prod = (t.map f).prod) variables [fun_like F α (λ _, β)] section comm_monoid variables [comm_monoid α] [comm_monoid β] [comm_monoid γ] [comm_monoid δ] [comm_group G] {A : set α} {B : set β} {C : set γ} {n : ℕ} {a b c d : α} @[to_additive] lemma map_prod_eq_map_prod [freiman_hom_class F A β n] (f : F) {s t : multiset α} (hsA : ∀ ⦃x⦄, x ∈ s → x ∈ A) (htA : ∀ ⦃x⦄, x ∈ t → x ∈ A) (hs : s.card = n) (ht : t.card = n) (h : s.prod = t.prod) : (s.map f).prod = (t.map f).prod := freiman_hom_class.map_prod_eq_map_prod' f hsA htA hs ht h @[to_additive] lemma map_mul_map_eq_map_mul_map [freiman_hom_class F A β 2] (f : F) (ha : a ∈ A) (hb : b ∈ A) (hc : c ∈ A) (hd : d ∈ A) (h : a * b = c * d) : f a * f b = f c * f d := begin simp_rw ←prod_pair at ⊢ h, refine map_prod_eq_map_prod f _ _ (card_pair _ _) (card_pair _ _) h; simp [ha, hb, hc, hd], end namespace freiman_hom @[to_additive] instance fun_like : fun_like (A →*[n] β) α (λ _, β) := { coe := to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' } @[to_additive] instance freiman_hom_class : freiman_hom_class (A →*[n] β) A β n := { map_prod_eq_map_prod' := map_prod_eq_map_prod' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ @[to_additive] instance : has_coe_to_fun (A →*[n] β) (λ _, α → β) := ⟨to_fun⟩ initialize_simps_projections freiman_hom (to_fun → apply) @[simp, to_additive] lemma to_fun_eq_coe (f : A →*[n] β) : f.to_fun = f := rfl @[ext, to_additive] lemma ext ⦃f g : A →*[n] β⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h @[simp, to_additive] lemma coe_mk (f : α → β) (h : ∀ s t : multiset α, (∀ ⦃x⦄, x ∈ s → x ∈ A) → (∀ ⦃x⦄, x ∈ t → x ∈ A) → s.card = n → t.card = n → s.prod = t.prod → (s.map f).prod = (t.map f).prod) : ⇑(mk f h) = f := rfl @[simp, to_additive] lemma mk_coe (f : A →*[n] β) (h) : mk f h = f := ext $ λ _, rfl /-- The identity map from a commutative monoid to itself. -/ @[to_additive "The identity map from an additive commutative monoid to itself.", simps] protected def id (A : set α) (n : ℕ) : A →*[n] α := { to_fun := λ x, x, map_prod_eq_map_prod' := λ s t _ _ _ _ h, by rw [map_id', map_id', h] } /-- Composition of Freiman homomorphisms as a Freiman homomorphism. -/ @[to_additive "Composition of additive Freiman homomorphisms as an additive Freiman homomorphism."] protected def comp (f : B →*[n] γ) (g : A →*[n] β) (hAB : A.maps_to g B) : A →*[n] γ := { to_fun := f ∘ g, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, begin rw [←map_map, map_prod_eq_map_prod f _ _ ((s.card_map _).trans hs) ((t.card_map _).trans ht) (map_prod_eq_map_prod g hsA htA hs ht h), map_map], { simpa using (λ a h, hAB (hsA h)) }, { simpa using (λ a h, hAB (htA h)) } end } @[simp, to_additive] lemma coe_comp (f : B →*[n] γ) (g : A →*[n] β) {hfg} : ⇑(f.comp g hfg) = f ∘ g := rfl @[to_additive] lemma comp_apply (f : B →*[n] γ) (g : A →*[n] β) {hfg} (x : α) : f.comp g hfg x = f (g x) := rfl @[to_additive] lemma comp_assoc (f : A →*[n] β) (g : B →*[n] γ) (h : C →*[n] δ) {hf hhg hgf} {hh : A.maps_to (g.comp f hgf) C} : (h.comp g hhg).comp f hf = h.comp (g.comp f hgf) hh := rfl @[to_additive] lemma cancel_right {g₁ g₂ : B →*[n] γ} {f : A →*[n] β} (hf : function.surjective f) {hg₁ hg₂} : g₁.comp f hg₁ = g₂.comp f hg₂ ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, λ h, h ▸ rfl⟩ @[to_additive] lemma cancel_right_on {g₁ g₂ : B →*[n] γ} {f : A →*[n] β} (hf : A.surj_on f B) {hf'} : A.eq_on (g₁.comp f hf') (g₂.comp f hf') ↔ B.eq_on g₁ g₂ := hf.cancel_right hf' @[to_additive] lemma cancel_left_on {g : B →*[n] γ} {f₁ f₂ : A →*[n] β} (hg : B.inj_on g) {hf₁ hf₂} : A.eq_on (g.comp f₁ hf₁) (g.comp f₂ hf₂) ↔ A.eq_on f₁ f₂ := hg.cancel_left hf₁ hf₂ @[simp, to_additive] lemma comp_id (f : A →*[n] β) {hf} : f.comp (freiman_hom.id A n) hf = f := ext $ λ x, rfl @[simp, to_additive] lemma id_comp (f : A →*[n] β) {hf} : (freiman_hom.id B n).comp f hf = f := ext $ λ x, rfl /-- `freiman_hom.const A n b` is the Freiman homomorphism sending everything to `b`. -/ @[to_additive "`add_freiman_hom.const n b` is the Freiman homomorphism sending everything to `b`."] def const (A : set α) (n : ℕ) (b : β) : A →*[n] β := { to_fun := λ _, b, map_prod_eq_map_prod' := λ s t _ _ hs ht _, by rw [multiset.map_const, multiset.map_const, prod_repeat, prod_repeat, hs, ht] } @[simp, to_additive] lemma const_apply (n : ℕ) (b : β) (x : α) : const A n b x = b := rfl @[simp, to_additive] lemma const_comp (n : ℕ) (c : γ) (f : A →*[n] β) {hf} : (const B n c).comp f hf = const A n c := rfl /-- `1` is the Freiman homomorphism sending everything to `1`. -/ @[to_additive "`0` is the Freiman homomorphism sending everything to `0`."] instance : has_one (A →*[n] β) := ⟨const A n 1⟩ @[simp, to_additive] lemma one_apply (x : α) : (1 : A →*[n] β) x = 1 := rfl @[simp, to_additive] lemma one_comp (f : A →*[n] β) {hf} : (1 : B →*[n] γ).comp f hf = 1 := rfl @[to_additive] instance : inhabited (A →*[n] β) := ⟨1⟩ /-- `f * g` is the Freiman homomorphism sends `x` to `f x * g x`. -/ @[to_additive "`f + g` is the Freiman homomorphism sending `x` to `f x + g x`."] instance : has_mul (A →*[n] β) := ⟨λ f g, { to_fun := λ x, f x * g x, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, by rw [prod_map_mul, prod_map_mul, map_prod_eq_map_prod f hsA htA hs ht h, map_prod_eq_map_prod g hsA htA hs ht h] }⟩ @[simp, to_additive] lemma mul_apply (f g : A →*[n] β) (x : α) : (f * g) x = f x * g x := rfl @[to_additive] lemma mul_comp (g₁ g₂ : B →*[n] γ) (f : A →*[n] β) {hg hg₁ hg₂} : (g₁ * g₂).comp f hg = g₁.comp f hg₁ * g₂.comp f hg₂ := rfl /-- If `f` is a Freiman homomorphism to a commutative group, then `f⁻¹` is the Freiman homomorphism sending `x` to `(f x)⁻¹`. -/ @[to_additive "If `f` is a Freiman homomorphism to an additive commutative group, then `-f` is the Freiman homomorphism sending `x` to `-f x`."] instance : has_inv (A →*[n] G) := ⟨λ f, { to_fun := λ x, (f x)⁻¹, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, by rw [prod_map_inv', prod_map_inv', map_prod_eq_map_prod f hsA htA hs ht h] }⟩ @[simp, to_additive] lemma inv_apply (f : A →*[n] G) (x : α) : f⁻¹ x = (f x)⁻¹ := rfl @[simp, to_additive] lemma inv_comp (f : B →*[n] G) (g : A →*[n] β) {hf hf'} : f⁻¹.comp g hf = (f.comp g hf')⁻¹ := ext $ λ x, rfl /-- If `f` and `g` are Freiman homomorphisms to a commutative group, then `f / g` is the Freiman homomorphism sending `x` to `f x / g x`. -/ @[to_additive "If `f` and `g` are additive Freiman homomorphisms to an additive commutative group, then `f - g` is the additive Freiman homomorphism sending `x` to `f x - g x`"] instance : has_div (A →*[n] G) := ⟨λ f g, { to_fun := λ x, f x / g x, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, by rw [prod_map_div, prod_map_div, map_prod_eq_map_prod f hsA htA hs ht h, map_prod_eq_map_prod g hsA htA hs ht h] }⟩ @[simp, to_additive] lemma div_apply (f g : A →*[n] G) (x : α) : (f / g) x = f x / g x := rfl @[simp, to_additive] lemma div_comp (f₁ f₂ : B →*[n] G) (g : A →*[n] β) {hf hf₁ hf₂} : (f₁ / f₂).comp g hf = f₁.comp g hf₁ / f₂.comp g hf₂ := ext $ λ x, rfl /-! ### Instances -/ /-- `A →*[n] β` is a `comm_monoid`. -/ @[to_additive "`α →+[n] β` is an `add_comm_monoid`."] instance : comm_monoid (A →*[n] β) := { mul := (*), mul_assoc := λ a b c, by { ext, apply mul_assoc }, one := 1, one_mul := λ a, by { ext, apply one_mul }, mul_one := λ a, by { ext, apply mul_one }, mul_comm := λ a b, by { ext, apply mul_comm }, npow := λ m f, { to_fun := λ x, f x ^ m, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, by rw [prod_map_pow, prod_map_pow, map_prod_eq_map_prod f hsA htA hs ht h] }, npow_zero' := λ f, by { ext x, exact pow_zero _ }, npow_succ' := λ n f, by { ext x, exact pow_succ _ _ } } /-- If `β` is a commutative group, then `A →*[n] β` is a commutative group too. -/ @[to_additive "If `β` is an additive commutative group, then `A →*[n] β` is an additive commutative group too."] instance {β} [comm_group β] : comm_group (A →*[n] β) := { inv := has_inv.inv, div := has_div.div, div_eq_mul_inv := by { intros, ext, apply div_eq_mul_inv }, mul_left_inv := by { intros, ext, apply mul_left_inv }, zpow := λ n f, { to_fun := λ x, (f x) ^ n, map_prod_eq_map_prod' := λ s t hsA htA hs ht h, by rw [prod_map_zpow, prod_map_zpow, map_prod_eq_map_prod f hsA htA hs ht h] }, zpow_zero' := λ f, by { ext x, exact zpow_zero _ }, zpow_succ' := λ n f, by { ext x, simp_rw [zpow_of_nat, pow_succ, mul_apply, coe_mk] }, zpow_neg' := λ n f, by { ext x, simp_rw [zpow_neg_succ_of_nat, zpow_coe_nat], refl }, ..freiman_hom.comm_monoid } end freiman_hom /-! ### Hom hierarchy -/ --TODO: change to `monoid_hom_class F A β → freiman_hom_class F A β n` once `map_multiset_prod` is -- generalized /-- A monoid homomorphism is naturally a `freiman_hom` on its entire domain. We can't leave the domain `A : set α` of the `freiman_hom` a free variable, since it wouldn't be inferrable. -/ @[to_additive " An additive monoid homomorphism is naturally an `add_freiman_hom` on its entire domain. We can't leave the domain `A : set α` of the `freiman_hom` a free variable, since it wouldn't be inferrable."] instance monoid_hom.freiman_hom_class : freiman_hom_class (α →* β) set.univ β n := { map_prod_eq_map_prod' := λ f s t _ _ _ _ h, by rw [←f.map_multiset_prod, h, f.map_multiset_prod] } /-- A `monoid_hom` is naturally a `freiman_hom`. -/ @[to_additive add_monoid_hom.to_add_freiman_hom "An `add_monoid_hom` is naturally an `add_freiman_hom`"] def monoid_hom.to_freiman_hom (A : set α) (n : ℕ) (f : α →* β) : A →*[n] β := { to_fun := f, map_prod_eq_map_prod' := λ s t hsA htA, map_prod_eq_map_prod f (λ _ _, set.mem_univ _) (λ _ _, set.mem_univ _) } @[simp, to_additive] lemma monoid_hom.to_freiman_hom_coe (f : α →* β) : (f.to_freiman_hom A n : α → β) = f := rfl @[to_additive] lemma monoid_hom.to_freiman_hom_injective : function.injective (monoid_hom.to_freiman_hom A n : (α →* β) → A →*[n] β) := λ f g h, monoid_hom.ext $ show _, from fun_like.ext_iff.mp h end comm_monoid section cancel_comm_monoid variables [comm_monoid α] [cancel_comm_monoid β] {A : set α} {m n : ℕ} @[to_additive] lemma map_prod_eq_map_prod_of_le [freiman_hom_class F A β n] (f : F) {s t : multiset α} (hsA : ∀ x ∈ s, x ∈ A) (htA : ∀ x ∈ t, x ∈ A) (hs : s.card = m) (ht : t.card = m) (hst : s.prod = t.prod) (h : m ≤ n) : (s.map f).prod = (t.map f).prod := begin obtain rfl | hm := m.eq_zero_or_pos, { rw card_eq_zero at hs ht, rw [hs, ht] }, rw [←hs, card_pos_iff_exists_mem] at hm, obtain ⟨a, ha⟩ := hm, suffices : ((s + repeat a (n - m)).map f).prod = ((t + repeat a (n - m)).map f).prod, { simp_rw [multiset.map_add, prod_add] at this, exact mul_right_cancel this }, replace ha := hsA _ ha, refine map_prod_eq_map_prod f (λ x hx, _) (λ x hx, _) _ _ _, rotate 2, assumption, -- Can't infer `A` and `n` from the context, so do it manually. { rw mem_add at hx, refine hx.elim (hsA _) (λ h, _), rwa eq_of_mem_repeat h }, { rw mem_add at hx, refine hx.elim (htA _) (λ h, _), rwa eq_of_mem_repeat h }, { rw [card_add, hs, card_repeat, add_tsub_cancel_of_le h] }, { rw [card_add, ht, card_repeat, add_tsub_cancel_of_le h] }, { rw [prod_add, prod_add, hst] } end /-- `α →*[n] β` is naturally included in `A →*[m] β` for any `m ≤ n`. -/ @[to_additive add_freiman_hom.to_add_freiman_hom "`α →+[n] β` is naturally included in `α →+[m] β` for any `m ≤ n`"] def freiman_hom.to_freiman_hom (h : m ≤ n) (f : A →*[n] β) : A →*[m] β := { to_fun := f, map_prod_eq_map_prod' := λ s t hsA htA hs ht hst, map_prod_eq_map_prod_of_le f hsA htA hs ht hst h } /-- A `n`-Freiman homomorphism is also a `m`-Freiman homomorphism for any `m ≤ n`. -/ @[to_additive add_freiman_hom.add_freiman_hom_class_of_le "An additive `n`-Freiman homomorphism is also an additive `m`-Freiman homomorphism for any `m ≤ n`."] def freiman_hom.freiman_hom_class_of_le [freiman_hom_class F A β n] (h : m ≤ n) : freiman_hom_class F A β m := { map_prod_eq_map_prod' := λ f s t hsA htA hs ht hst, map_prod_eq_map_prod_of_le f hsA htA hs ht hst h } @[simp, to_additive add_freiman_hom.to_add_freiman_hom_coe] lemma freiman_hom.to_freiman_hom_coe (h : m ≤ n) (f : A →*[n] β) : (f.to_freiman_hom h : α → β) = f := rfl @[to_additive] lemma freiman_hom.to_freiman_hom_injective (h : m ≤ n) : function.injective (freiman_hom.to_freiman_hom h : (A →*[n] β) → A →*[m] β) := λ f g hfg, freiman_hom.ext $ by convert fun_like.ext_iff.1 hfg end cancel_comm_monoid
485f923fdaa516a56f931ff0297ba7d04d8d8e3e
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/topology/uniform_space/pi.lean
bbb72266fef1501bf351cb4e72c49c0027612975
[ "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
1,975
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot Indexed product of uniform spaces -/ import topology.uniform_space.cauchy import topology.uniform_space.separation noncomputable theory local notation `𝓤` := uniformity section open filter lattice uniform_space universe u variables {ι : Type*} (α : ι → Type u) [U : Πi, uniform_space (α i)] include U instance Pi.uniform_space : uniform_space (Πi, α i) := uniform_space.of_core_eq (⨆i, uniform_space.comap (λ a : Πi, α i, a i) (U i)).to_core Pi.topological_space $ eq.symm to_topological_space_supr lemma Pi.uniformity : 𝓤 (Π i, α i) = ⨅ i : ι, filter.comap (λ a, (a.1 i, a.2 i)) $ 𝓤 (α i) := supr_uniformity lemma Pi.uniform_continuous_proj (i : ι) : uniform_continuous (λ (a : Π (i : ι), α i), a i) := begin rw uniform_continuous_iff, apply le_supr (λ j, uniform_space.comap (λ (a : Π (i : ι), α i), a j) (U j)) end lemma Pi.uniform_space_topology : (Pi.uniform_space α).to_topological_space = Pi.topological_space := rfl instance Pi.complete [∀ i, complete_space (α i)] : complete_space (Π i, α i) := ⟨begin intros f hf, have : ∀ i, ∃ x : α i, filter.map (λ a : Πi, α i, a i) f ≤ nhds x, { intro i, have key : cauchy (map (λ (a : Π (i : ι), α i), a i) f), from cauchy_map (Pi.uniform_continuous_proj α i) hf, exact (cauchy_iff_exists_le_nhds $ map_ne_bot hf.1).1 key }, choose x hx using this, use x, rw [show nhds x = (⨅i, comap (λa, a i) (nhds (x i))), by rw Pi.uniform_space_topology ; exact nhds_pi, le_infi_iff], exact λ i, map_le_iff_le_comap.mp (hx i), end⟩ instance Pi.separated [∀ i, separated (α i)] : separated (Π i, α i) := separated_def.2 $ assume x y H, begin ext i, apply eq_of_separated_of_uniform_continuous (Pi.uniform_continuous_proj α i), apply H, end end
4c130d5590791b3b8c41da3fe8d0cac0db0286be
690889011852559ee5ac4dfea77092de8c832e7e
/src/order/conditionally_complete_lattice.lean
356fbf4894ca733cbdad5b66d69a42dfbf7aa195
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
34,739
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel Adapted from the corresponding theory for complete lattices. Theory of conditionally complete lattices. A conditionally complete lattice is a lattice in which every non-empty bounded subset s has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s. Typical examples are real, nat, int with their usual orders. The theory is very comparable to the theory of complete lattices, except that suitable boundedness and non-emptyness assumptions have to be added to most statements. We introduce two predicates bdd_above and bdd_below to express this boundedness, prove their basic properties, and then go on to prove most useful properties of Sup and Inf in conditionally complete lattices. To differentiate the statements between complete lattices and conditionally complete lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance, Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same statement in conditionally complete lattices with an additional assumption that s is bounded below. -/ import order.lattice order.complete_lattice order.bounds tactic.finish data.set.finite set_option old_structure_cmd true open preorder set lattice universes u v w variables {α : Type u} {β : Type v} {ι : Type w} section preorder variables [preorder α] [preorder β] {s t : set α} {a b : α} /-Sets bounded above and bounded below.-/ def bdd_above (s : set α) := ∃x, ∀y∈s, y ≤ x def bdd_below (s : set α) := ∃x, ∀y∈s, x ≤ y /-Introduction rules for boundedness above and below. Most of the time, it is more efficient to use ⟨w, P⟩ where P is a proof that all elements of the set are bounded by w. However, they are sometimes handy.-/ lemma bdd_above.mk (a : α) (H : ∀y∈s, y≤a) : bdd_above s := ⟨a, H⟩ lemma bdd_below.mk (a : α) (H : ∀y∈s, a≤y) : bdd_below s := ⟨a, H⟩ /-Empty sets and singletons are trivially bounded. For finite sets, we need a notion of maximum and minimum, i.e., a lattice structure, see later on.-/ @[simp] lemma bdd_above_empty : ∀ [nonempty α], bdd_above (∅ : set α) | ⟨x⟩ := ⟨x, by simp⟩ @[simp] lemma bdd_below_empty : ∀ [nonempty α], bdd_below (∅ : set α) | ⟨x⟩ := ⟨x, by simp⟩ @[simp] lemma bdd_above_singleton : bdd_above ({a} : set α) := ⟨a, by simp only [set.mem_singleton_iff, forall_eq]⟩ @[simp] lemma bdd_below_singleton : bdd_below ({a} : set α) := ⟨a, by simp only [set.mem_singleton_iff, forall_eq]⟩ /-If a set is included in another one, boundedness of the second implies boundedness of the first-/ lemma bdd_above_subset (st : s ⊆ t) : bdd_above t → bdd_above s | ⟨w, hw⟩ := ⟨w, λ y ys, hw _ (st ys)⟩ lemma bdd_below_subset (st : s ⊆ t) : bdd_below t → bdd_below s | ⟨w, hw⟩ := ⟨w, λ y ys, hw _ (st ys)⟩ /- Boundedness of intersections of sets, in different guises, deduced from the monotonicity of boundedness.-/ lemma bdd_above_inter_left : bdd_above s → bdd_above (s ∩ t) := bdd_above_subset (set.inter_subset_left _ _) lemma bdd_above_inter_right : bdd_above t → bdd_above (s ∩ t) := bdd_above_subset (set.inter_subset_right _ _) lemma bdd_below_inter_left : bdd_below s → bdd_below (s ∩ t) := bdd_below_subset (set.inter_subset_left _ _) lemma bdd_below_inter_right : bdd_below t → bdd_below (s ∩ t) := bdd_below_subset (set.inter_subset_right _ _) /--The image under a monotone function of a set which is bounded above is bounded above-/ lemma bdd_above_of_bdd_above_of_monotone {f : α → β} (hf : monotone f) : bdd_above s → bdd_above (f '' s) | ⟨C, hC⟩ := ⟨f C, by rintro y ⟨x, x_bnd, rfl⟩; exact hf (hC x x_bnd)⟩ /--The image under a monotone function of a set which is bounded below is bounded below-/ lemma bdd_below_of_bdd_below_of_monotone {f : α → β} (hf : monotone f) : bdd_below s → bdd_below (f '' s) | ⟨C, hC⟩ := ⟨f C, by rintro y ⟨x, x_bnd, rfl⟩; exact hf (hC x x_bnd)⟩ end preorder /--When there is a global maximum, every set is bounded above.-/ @[simp] lemma bdd_above_top [order_top α] (s : set α) : bdd_above s := ⟨⊤, by intros; apply order_top.le_top⟩ /--When there is a global minimum, every set is bounded below.-/ @[simp] lemma bdd_below_bot [order_bot α] (s : set α) : bdd_below s := ⟨⊥, by intros; apply order_bot.bot_le⟩ /-When there is a max (i.e., in the class semilattice_sup), then the union of two bounded sets is bounded, by the maximum of the bounds for the two sets. With this, we deduce that finite sets are bounded by induction, and that a finite union of bounded sets is bounded.-/ section semilattice_sup variables [semilattice_sup α] {s t : set α} {a b : α} /--The union of two sets is bounded above if and only if each of the sets is.-/ @[simp] lemma bdd_above_union : bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t := ⟨show bdd_above (s ∪ t) → (bdd_above s ∧ bdd_above t), from assume : bdd_above (s ∪ t), have S : bdd_above s, by apply bdd_above_subset _ ‹bdd_above (s ∪ t)›; simp only [set.subset_union_left], have T : bdd_above t, by apply bdd_above_subset _ ‹bdd_above (s ∪ t)›; simp only [set.subset_union_right], and.intro S T, show (bdd_above s ∧ bdd_above t) → bdd_above (s ∪ t), from assume H : bdd_above s ∧ bdd_above t, let ⟨⟨ws, hs⟩, ⟨wt, ht⟩⟩ := H in /-hs : ∀ (y : α), y ∈ s → y ≤ ws ht : ∀ (y : α), y ∈ s → y ≤ wt-/ have Bs : ∀b∈s, b ≤ ws ⊔ wt, by intros; apply le_trans (hs b ‹b ∈ s›) _; simp only [lattice.le_sup_left], have Bt : ∀b∈t, b ≤ ws ⊔ wt, by intros; apply le_trans (ht b ‹b ∈ t›) _; simp only [lattice.le_sup_right], show bdd_above (s ∪ t), begin apply bdd_above.mk (ws ⊔ wt), intros b H_1, cases H_1, apply Bs _ ‹b ∈ s›, apply Bt _ ‹b ∈ t›, end⟩ /--Adding a point to a set preserves its boundedness above.-/ @[simp] lemma bdd_above_insert : bdd_above (insert a s) ↔ bdd_above s := ⟨bdd_above_subset (by simp only [set.subset_insert]), λ h, by rw [insert_eq, bdd_above_union]; exact ⟨bdd_above_singleton, h⟩⟩ /--A finite set is bounded above.-/ lemma bdd_above_finite [nonempty α] (hs : finite s) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _, bdd_above_insert.2 /--A finite union of sets which are all bounded above is still bounded above.-/ lemma bdd_above_finite_union [nonempty α] {β : Type v} {I : set β} {S : β → set α} (H : finite I) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := ⟨λ (bdd : bdd_above (⋃i∈I, S i)) i (hi : i ∈ I), bdd_above_subset (subset_bUnion_of_mem hi) bdd, show (∀i ∈ I, bdd_above (S i)) → (bdd_above (⋃i∈I, S i)), from finite.induction_on H (λ _, by rw bUnion_empty; exact bdd_above_empty) (λ x s hn hf IH h, by simp only [ set.mem_insert_iff, or_imp_distrib, forall_and_distrib, forall_eq] at h; rw [set.bUnion_insert, bdd_above_union]; exact ⟨h.1, IH h.2⟩)⟩ end semilattice_sup /-When there is a min (i.e., in the class semilattice_inf), then the union of two sets which are bounded from below is bounded from below, by the minimum of the bounds for the two sets. With this, we deduce that finite sets are bounded below by induction, and that a finite union of sets which are bounded below is still bounded below.-/ section semilattice_inf variables [semilattice_inf α] {s t : set α} {a b : α} /--The union of two sets is bounded below if and only if each of the sets is.-/ @[simp] lemma bdd_below_union : bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t := ⟨show bdd_below (s ∪ t) → (bdd_below s ∧ bdd_below t), from assume : bdd_below (s ∪ t), have S : bdd_below s, by apply bdd_below_subset _ ‹bdd_below (s ∪ t)›; simp only [set.subset_union_left], have T : bdd_below t, by apply bdd_below_subset _ ‹bdd_below (s ∪ t)›; simp only [set.subset_union_right], and.intro S T, show (bdd_below s ∧ bdd_below t) → bdd_below (s ∪ t), from assume H : bdd_below s ∧ bdd_below t, let ⟨⟨ws, hs⟩, ⟨wt, ht⟩⟩ := H in /-hs : ∀ (y : α), y ∈ s → ws ≤ y ht : ∀ (y : α), y ∈ s → wt ≤ y-/ have Bs : ∀b∈s, ws ⊓ wt ≤ b, by intros; apply le_trans _ (hs b ‹b ∈ s›); simp only [lattice.inf_le_left], have Bt : ∀b∈t, ws ⊓ wt ≤ b, by intros; apply le_trans _ (ht b ‹b ∈ t›); simp only [lattice.inf_le_right], show bdd_below (s ∪ t), begin apply bdd_below.mk (ws ⊓ wt), intros b H_1, cases H_1, apply Bs _ ‹b ∈ s›, apply Bt _ ‹b ∈ t›, end⟩ /--Adding a point to a set preserves its boundedness below.-/ @[simp] lemma bdd_below_insert : bdd_below (insert a s) ↔ bdd_below s := ⟨show bdd_below (insert a s) → bdd_below s, from bdd_below_subset (by simp only [set.subset_insert]), show bdd_below s → bdd_below (insert a s), by rw[insert_eq]; simp only [bdd_below_singleton, bdd_below_union, and_self, forall_true_iff] {contextual := tt}⟩ /--A finite set is bounded below.-/ lemma bdd_below_finite [nonempty α] (hs : finite s) : bdd_below s := finite.induction_on hs bdd_below_empty $ λ a s _ _, bdd_below_insert.2 /--A finite union of sets which are all bounded below is still bounded below.-/ lemma bdd_below_finite_union [nonempty α] {β : Type v} {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := ⟨λ (bdd : bdd_below (⋃i∈I, S i)) i (hi : i ∈ I), bdd_below_subset (subset_bUnion_of_mem hi) bdd, show (∀i ∈ I, bdd_below (S i)) → (bdd_below (⋃i∈I, S i)), from finite.induction_on H (λ _, by rw bUnion_empty; exact bdd_below_empty) (λ x s hn hf IH h, by simp only [ set.mem_insert_iff, or_imp_distrib, forall_and_distrib, forall_eq] at h; rw [set.bUnion_insert, bdd_below_union]; exact ⟨h.1, IH h.2⟩)⟩ end semilattice_inf namespace lattice /-- A conditionally complete lattice is a lattice in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of non-emptyness or boundedness.-/ class conditionally_complete_lattice (α : Type u) extends lattice α, has_Sup α, has_Inf α := (le_cSup : ∀s a, bdd_above s → a ∈ s → a ≤ Sup s) (cSup_le : ∀s a, s ≠ ∅ → (∀b∈s, b ≤ a) → Sup s ≤ a) (cInf_le : ∀s a, bdd_below s → a ∈ s → Inf s ≤ a) (le_cInf : ∀s a, s ≠ ∅ → (∀b∈s, a ≤ b) → a ≤ Inf s) class conditionally_complete_linear_order (α : Type u) extends conditionally_complete_lattice α, decidable_linear_order α class conditionally_complete_linear_order_bot (α : Type u) extends conditionally_complete_lattice α, decidable_linear_order α, order_bot α := (cSup_empty : Sup ∅ = ⊥) /- A complete lattice is a conditionally complete lattice, as there are no restrictions on the properties of Inf and Sup in a complete lattice.-/ instance conditionally_complete_lattice_of_complete_lattice [complete_lattice α]: conditionally_complete_lattice α := { le_cSup := by intros; apply le_Sup; assumption, cSup_le := by intros; apply Sup_le; assumption, cInf_le := by intros; apply Inf_le; assumption, le_cInf := by intros; apply le_Inf; assumption, ..‹complete_lattice α›} instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order α]: conditionally_complete_linear_order α := { ..lattice.conditionally_complete_lattice_of_complete_lattice, .. ‹complete_linear_order α› } section conditionally_complete_lattice variables [conditionally_complete_lattice α] {s t : set α} {a b : α} theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s := conditionally_complete_lattice.le_cSup s a h₁ h₂ theorem cSup_le (h₁ : s ≠ ∅) (h₂ : ∀b∈s, b ≤ a) : Sup s ≤ a := conditionally_complete_lattice.cSup_le s a h₁ h₂ theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a := conditionally_complete_lattice.cInf_le s a h₁ h₂ theorem le_cInf (h₁ : s ≠ ∅) (h₂ : ∀b∈s, a ≤ b) : a ≤ Inf s := conditionally_complete_lattice.le_cInf s a h₁ h₂ theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_cSup ‹bdd_above s› hb) theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (cInf_le ‹bdd_below s› hb) h theorem cSup_le_cSup (_ : bdd_above t) (_ : s ≠ ∅) (h : s ⊆ t) : Sup s ≤ Sup t := cSup_le ‹s ≠ ∅› (assume (a) (ha : a ∈ s), le_cSup ‹bdd_above t› (h ha)) theorem cInf_le_cInf (_ : bdd_below t) (_ :s ≠ ∅) (h : s ⊆ t) : Inf t ≤ Inf s := le_cInf ‹s ≠ ∅› (assume (a) (ha : a ∈ s), cInf_le ‹bdd_below t› (h ha)) theorem cSup_le_iff (_ : bdd_above s) (_ : s ≠ ∅) : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := ⟨assume (_ : Sup s ≤ a) (b) (_ : b ∈ s), le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) ‹Sup s ≤ a›, cSup_le ‹s ≠ ∅›⟩ theorem le_cInf_iff (_ : bdd_below s) (_ : s ≠ ∅) : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := ⟨assume (_ : a ≤ Inf s) (b) (_ : b ∈ s), le_trans ‹a ≤ Inf s› (cInf_le ‹bdd_below s› ‹b ∈ s›), le_cInf ‹s ≠ ∅›⟩ lemma cSup_upper_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s ≠ ∅) : Sup {a | ∀x∈s, a ≤ x} = Inf s := let ⟨b, hb⟩ := h, ⟨a, ha⟩ := ne_empty_iff_exists_mem.1 hs in le_antisymm (cSup_le (ne_empty_iff_exists_mem.2 ⟨b, hb⟩) $ assume a ha, le_cInf hs ha) (le_cSup ⟨a, assume y hy, hy a ha⟩ $ assume x hx, cInf_le h hx) lemma cInf_lower_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s ≠ ∅) : Inf {a | ∀x∈s, x ≤ a} = Sup s := let ⟨b, hb⟩ := h, ⟨a, ha⟩ := ne_empty_iff_exists_mem.1 hs in le_antisymm (cInf_le ⟨a, assume y hy, hy a ha⟩ $ assume x hx, le_cSup h hx) (le_cInf (ne_empty_iff_exists_mem.2 ⟨b, hb⟩) $ assume a ha, cSup_le hs ha) /--Introduction rule to prove that b is the supremum of s: it suffices to check that b is larger than all elements of s, and that this is not the case of any w<b.-/ theorem cSup_intro (_ : s ≠ ∅) (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b := have bdd_above s := ⟨b, by assumption⟩, have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le ‹s ≠ ∅› ‹∀a∈s, a ≤ b›), have ¬(Sup s < b) := assume: Sup s < b, let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_cSup ‹bdd_above s› ‹a ∈ s›), show false, by finish [lt_irrefl (Sup s)], show Sup s = b, by finish /--Introduction rule to prove that b is the infimum of s: it suffices to check that b is smaller than all elements of s, and that this is not the case of any w>b.-/ theorem cInf_intro (_ : s ≠ ∅) (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b := have bdd_below s := ⟨b, by assumption⟩, have (b < Inf s) ∨ (b = Inf s) := lt_or_eq_of_le (le_cInf ‹s ≠ ∅› ‹∀a∈s, b ≤ a›), have ¬(b < Inf s) := assume: b < Inf s, let ⟨a, _, _⟩ := (H (Inf s) ‹b < Inf s›) in /- a ∈ s, a < Inf s-/ have Inf s < Inf s := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < Inf s› , show false, by finish [lt_irrefl (Inf s)], show Inf s = b, by finish /--When an element a of a set s is larger than all elements of the set, it is Sup s-/ theorem cSup_of_mem_of_le (_ : a ∈ s) (_ : ∀w∈s, w ≤ a) : Sup s = a := have bdd_above s := ⟨a, by assumption⟩, have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›, have A : a ≤ Sup s := le_cSup ‹bdd_above s› ‹a ∈ s›, have B : Sup s ≤ a := cSup_le ‹s ≠ ∅› ‹∀w∈s, w ≤ a›, le_antisymm B A /--When an element a of a set s is smaller than all elements of the set, it is Inf s-/ theorem cInf_of_mem_of_le (_ : a ∈ s) (_ : ∀w∈s, a ≤ w) : Inf s = a := have bdd_below s := ⟨a, by assumption⟩, have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›, have A : Inf s ≤ a := cInf_le ‹bdd_below s› ‹a ∈ s›, have B : a ≤ Inf s := le_cInf ‹s ≠ ∅› ‹∀w∈s, a ≤ w›, le_antisymm A B /--b < Sup s when there is an element a in s with b < a, when s is bounded above. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness above for one direction, nonemptyness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s := lt_of_lt_of_le ‹b < a› (le_cSup ‹bdd_above s› ‹a ∈ s›) /--Inf s < b s when there is an element a in s with a < b, when s is bounded below. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness below for one direction, nonemptyness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < b› /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : α) : Sup {a} = a := have A : a ≤ Sup {a} := by apply le_cSup _ _; simp only [set.mem_singleton,bdd_above_singleton], have B : Sup {a} ≤ a := by apply cSup_le _ _; simp only [set.mem_singleton_iff, forall_eq,ne.def, not_false_iff, set.singleton_ne_empty], le_antisymm B A /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : α) : Inf {a} = a := have A : Inf {a} ≤ a := by apply cInf_le _ _; simp only [set.mem_singleton,bdd_below_singleton], have B : a ≤ Inf {a} := by apply le_cInf _ _; simp only [set.mem_singleton_iff, forall_eq,ne.def, not_false_iff, set.singleton_ne_empty], le_antisymm A B /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (_ : bdd_below s) (_ : bdd_above s) (_ : s ≠ ∅) : Inf s ≤ Sup s := let ⟨w, hw⟩ := exists_mem_of_ne_empty ‹s ≠ ∅› in /-hw : w ∈ s-/ have Inf s ≤ w := cInf_le ‹bdd_below s› ‹w ∈ s›, have w ≤ Sup s := le_cSup ‹bdd_above s› ‹w ∈ s›, le_trans ‹Inf s ≤ w› ‹w ≤ Sup s› /--The sup of a union of sets is the max of the suprema of each subset, under the assumptions that all sets are bounded above and nonempty.-/ theorem cSup_union (_ : bdd_above s) (_ : s ≠ ∅) (_ : bdd_above t) (_ : t ≠ ∅) : Sup (s ∪ t) = Sup s ⊔ Sup t := have A : Sup (s ∪ t) ≤ Sup s ⊔ Sup t := have s ∪ t ≠ ∅ := by simp only [not_and, set.union_empty_iff, ne.def] at *; finish, have F : ∀b∈ s∪t, b ≤ Sup s ⊔ Sup t := begin intros, cases H, apply le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) _, simp only [lattice.le_sup_left], apply le_trans (le_cSup ‹bdd_above t› ‹b ∈ t›) _, simp only [lattice.le_sup_right] end, cSup_le this F, have B : Sup s ⊔ Sup t ≤ Sup (s ∪ t) := have Sup s ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹s ≠ ∅›; simp only [bdd_above_union,set.subset_union_left]; finish, have Sup t ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹t ≠ ∅›; simp only [bdd_above_union,set.subset_union_right]; finish, by simp only [lattice.sup_le_iff]; split; assumption; assumption, le_antisymm A B /--The inf of a union of sets is the min of the infima of each subset, under the assumptions that all sets are bounded below and nonempty.-/ theorem cInf_union (_ : bdd_below s) (_ : s ≠ ∅) (_ : bdd_below t) (_ : t ≠ ∅) : Inf (s ∪ t) = Inf s ⊓ Inf t := have A : Inf s ⊓ Inf t ≤ Inf (s ∪ t) := have s ∪ t ≠ ∅ := by simp only [not_and, set.union_empty_iff, ne.def] at *; finish, have F : ∀b∈ s∪t, Inf s ⊓ Inf t ≤ b := begin intros, cases H, apply le_trans _ (cInf_le ‹bdd_below s› ‹b ∈ s›), simp only [lattice.inf_le_left], apply le_trans _ (cInf_le ‹bdd_below t› ‹b ∈ t›), simp only [lattice.inf_le_right] end, le_cInf this F, have B : Inf (s ∪ t) ≤ Inf s ⊓ Inf t := have Inf (s ∪ t) ≤ Inf s := by apply cInf_le_cInf _ ‹s ≠ ∅›; simp only [bdd_below_union,set.subset_union_left]; finish, have Inf (s ∪ t) ≤ Inf t := by apply cInf_le_cInf _ ‹t ≠ ∅›; simp only [bdd_below_union,set.subset_union_right]; finish, by simp only [lattice.le_inf_iff]; split; assumption; assumption, le_antisymm B A /--The supremum of an intersection of sets is bounded by the minimum of the suprema of each set, if all sets are bounded above and nonempty.-/ theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (_ : s ∩ t ≠ ∅) : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := begin apply cSup_le ‹s ∩ t ≠ ∅› _, simp only [lattice.le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split, apply le_cSup ‹bdd_above s› ‹b ∈ s›, apply le_cSup ‹bdd_above t› ‹b ∈ t› end /--The infimum of an intersection of sets is bounded below by the maximum of the infima of each set, if all sets are bounded below and nonempty.-/ theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (_ : s ∩ t ≠ ∅) : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := begin apply le_cInf ‹s ∩ t ≠ ∅› _, simp only [and_imp, set.mem_inter_eq, lattice.sup_le_iff], intros b _ _, split, apply cInf_le ‹bdd_below s› ‹b ∈ s›, apply cInf_le ‹bdd_below t› ‹b ∈ t› end /-- The supremum of insert a s is the maximum of a and the supremum of s, if s is nonempty and bounded above.-/ theorem cSup_insert (_ : bdd_above s) (_ : s ≠ ∅) : Sup (insert a s) = a ⊔ Sup s := calc Sup (insert a s) = Sup ({a} ∪ s) : by rw [insert_eq] ... = Sup {a} ⊔ Sup s : by apply cSup_union _ _ ‹bdd_above s› ‹s ≠ ∅›; simp only [ne.def, not_false_iff, set.singleton_ne_empty,bdd_above_singleton] ... = a ⊔ Sup s : by simp only [eq_self_iff_true, lattice.cSup_singleton] /-- The infimum of insert a s is the minimum of a and the infimum of s, if s is nonempty and bounded below.-/ theorem cInf_insert (_ : bdd_below s) (_ : s ≠ ∅) : Inf (insert a s) = a ⊓ Inf s := calc Inf (insert a s) = Inf ({a} ∪ s) : by rw [insert_eq] ... = Inf {a} ⊓ Inf s : by apply cInf_union _ _ ‹bdd_below s› ‹s ≠ ∅›; simp only [ne.def, not_false_iff, set.singleton_ne_empty,bdd_below_singleton] ... = a ⊓ Inf s : by simp only [eq_self_iff_true, lattice.cInf_singleton] @[simp] lemma cInf_interval : Inf {b | a ≤ b} = a := cInf_of_mem_of_le (by simp only [set.mem_set_of_eq]) (λw Hw, by simp only [set.mem_set_of_eq] at Hw; apply Hw) @[simp] lemma cSup_interval : Sup {b | b ≤ a} = a := cSup_of_mem_of_le (by simp only [set.mem_set_of_eq]) (λw Hw, by simp only [set.mem_set_of_eq] at Hw; apply Hw) /--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/ lemma csupr_le_csupr {f g : β → α} (B : bdd_above (range g)) (H : ∀x, f x ≤ g x) : supr f ≤ supr g := begin classical, by_cases nonempty β, { have Rf : range f ≠ ∅, {simpa}, apply cSup_le Rf, rintros y ⟨x, rfl⟩, have : g x ∈ range g := ⟨x, rfl⟩, exact le_cSup_of_le B this (H x) }, { have Rf : range f = ∅, {simpa}, have Rg : range g = ∅, {simpa}, unfold supr, rw [Rf, Rg] } end /--The indexed supremum of a function is bounded above by a uniform bound-/ lemma csupr_le [ne : nonempty β] {f : β → α} {c : α} (H : ∀x, f x ≤ c) : supr f ≤ c := cSup_le (by simp [not_not_intro ne]) (by rwa forall_range_iff) /--The indexed supremum of a function is bounded below by the value taken at one point-/ lemma le_csupr {f : β → α} (H : bdd_above (range f)) {c : β} : f c ≤ supr f := le_cSup H (mem_range_self _) /--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/ lemma cinfi_le_cinfi {f g : β → α} (B : bdd_below (range f)) (H : ∀x, f x ≤ g x) : infi f ≤ infi g := begin classical, by_cases nonempty β, { have Rg : range g ≠ ∅, {simpa}, apply le_cInf Rg, rintros y ⟨x, rfl⟩, have : f x ∈ range f := ⟨x, rfl⟩, exact cInf_le_of_le B this (H x) }, { have Rf : range f = ∅, {simpa}, have Rg : range g = ∅, {simpa}, unfold infi, rw [Rf, Rg] } end /--The indexed minimum of a function is bounded below by a uniform lower bound-/ lemma le_cinfi [ne : nonempty β] {f : β → α} {c : α} (H : ∀x, c ≤ f x) : c ≤ infi f := le_cInf (by simp [not_not_intro ne]) (by rwa forall_range_iff) /--The indexed infimum of a function is bounded above by the value taken at one point-/ lemma cinfi_le {f : β → α} (H : bdd_below (range f)) {c : β} : infi f ≤ f c := cInf_le H (mem_range_self _) lemma is_lub_cSup {s : set α} (ne : s ≠ ∅) (H : bdd_above s) : is_lub s (Sup s) := ⟨assume x, le_cSup H, assume x, cSup_le ne⟩ lemma is_glb_cInf {s : set α} (ne : s ≠ ∅) (H : bdd_below s) : is_glb s (Inf s) := ⟨assume x, cInf_le H, assume x, le_cInf ne⟩ @[simp] theorem cinfi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a := begin rcases exists_mem_of_nonempty ι with ⟨x, _⟩, refine le_antisymm (@cinfi_le _ _ _ _ _ x) (le_cinfi (λi, _root_.le_refl _)), rw range_const, exact bdd_below_singleton end @[simp] theorem csupr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a := begin rcases exists_mem_of_nonempty ι with ⟨x, _⟩, refine le_antisymm (csupr_le (λi, _root_.le_refl _)) (@le_csupr _ _ _ (λ b:ι, a) _ x), rw range_const, exact bdd_above_singleton end end conditionally_complete_lattice section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} /-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is a linear order. -/ lemma exists_lt_of_lt_cSup (_ : s ≠ ∅) (_ : b < Sup s) : ∃a∈s, b < a := begin classical, by_contra h, have : Sup s ≤ b := by apply cSup_le ‹s ≠ ∅› _; finish, apply lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›) end /-- Indexed version of the above lemma `exists_lt_of_lt_cSup`. When `b < supr f`, there is an element `i` such that `b < f i`. -/ lemma exists_lt_of_lt_csupr {ι : Sort*} (ne : nonempty ι) {f : ι → α} (h : b < supr f) : ∃i, b < f i := have h' : range f ≠ ∅ := nonempty.elim ne (λ i, ne_empty_of_mem (mem_range_self i)), let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup h' h in ⟨i, h⟩ /--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_cInf_lt (_ : s ≠ ∅) (_ : Inf s < b) : ∃a∈s, a < b := begin classical, by_contra h, have : b ≤ Inf s := by apply le_cInf ‹s ≠ ∅› _; finish, apply lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›) end /-- Indexed version of the above lemma `exists_lt_of_cInf_lt` When `infi f < a`, there is an element `i` such that `f i < a`. -/ lemma exists_lt_of_cinfi_lt {ι : Sort*} (ne : nonempty ι) {f : ι → α} (h : infi f < a) : (∃i, f i < a) := have h' : range f ≠ ∅ := nonempty.elim ne (λ i, ne_empty_of_mem (mem_range_self i)), let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_cInf_lt h' h in ⟨i, h⟩ /--Introduction rule to prove that b is the supremum of s: it suffices to check that 1) b is an upper bound 2) every other upper bound b' satisfies b ≤ b'.-/ theorem cSup_intro' (_ : s ≠ ∅) (h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b := le_antisymm (show Sup s ≤ b, from cSup_le ‹s ≠ ∅› h_is_ub) (show b ≤ Sup s, from h_b_le_ub _ $ assume a, le_cSup ⟨b, h_is_ub⟩) end conditionally_complete_linear_order section conditionally_complete_linear_order_bot lemma cSup_empty [conditionally_complete_linear_order_bot α] : (Sup ∅ : α) = ⊥ := conditionally_complete_linear_order_bot.cSup_empty α end conditionally_complete_linear_order_bot section open_locale classical noncomputable instance : has_Inf ℕ := ⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩ noncomputable instance : has_Sup ℕ := ⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩ lemma Inf_nat_def {s : set ℕ} (h : ∃n, n ∈ s) : Inf s = @nat.find (λn, n ∈ s) _ h := dif_pos _ lemma Sup_nat_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) : Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h := dif_pos _ /-- This instance is necessary, otherwise the lattice operations would be derived via conditionally_complete_linear_order_bot and marked as noncomputable. -/ instance : lattice ℕ := infer_instance noncomputable instance : conditionally_complete_linear_order_bot ℕ := { Sup := Sup, Inf := Inf, le_cSup := assume s a hb ha, by rw [Sup_nat_def hb]; revert a ha; exact @nat.find_spec _ _ hb, cSup_le := assume s a hs ha, by rw [Sup_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, le_cInf := assume s a hs hb, by rw [Inf_nat_def (ne_empty_iff_exists_mem.1 hs)]; exact hb _ (@nat.find_spec (λn, n ∈ s) _ _), cInf_le := assume s a hb ha, by rw [Inf_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, cSup_empty := begin simp only [Sup_nat_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const], apply bot_unique (nat.find_min' _ _), trivial end, .. (infer_instance : order_bot ℕ), .. (infer_instance : lattice ℕ), .. (infer_instance : decidable_linear_order ℕ) } end end lattice /-end of namespace lattice-/ namespace with_top open lattice open_locale classical variables [conditionally_complete_linear_order_bot α] lemma has_lub (s : set (with_top α)) : ∃a, is_lub s a := begin by_cases hs : s = ∅, { subst hs, exact ⟨⊥, is_lub_empty⟩, }, rcases ne_empty_iff_exists_mem.1 hs with ⟨x, hxs⟩, by_cases bnd : ∃b:α, ↑b ∈ upper_bounds s, { rcases bnd with ⟨b, hb⟩, have bdd : bdd_above {a : α | ↑a ∈ s}, from ⟨b, assume y hy, coe_le_coe.1 $ hb _ hy⟩, refine ⟨(Sup {a : α | ↑a ∈ s} : α), _, _⟩, { assume a has, rcases (le_coe_iff _ _).1 (hb _ has) with ⟨a, rfl, h⟩, exact (coe_le_coe.2 $ le_cSup bdd has) }, { assume a hs, rcases (le_coe_iff _ _).1 (hb _ hxs) with ⟨x, rfl, h⟩, refine (coe_le_iff _ _).2 (assume c hc, _), subst hc, exact (cSup_le (ne_empty_of_mem hxs) $ assume b (hbs : ↑b ∈ s), coe_le_coe.1 $ hs _ hbs), } }, exact ⟨⊤, assume a _, le_top, assume a, match a with | some a, ha := (bnd ⟨a, ha⟩).elim | none, ha := _root_.le_refl ⊤ end⟩ end lemma has_glb (s : set (with_top α)) : ∃a, is_glb s a := begin by_cases hs : ∃x:α, ↑x ∈ s, { rcases hs with ⟨x, hxs⟩, refine ⟨(Inf {a : α | ↑a ∈ s} : α), _, _⟩, exact (assume a has, (coe_le_iff _ _).2 $ assume x hx, cInf_le (bdd_below_bot _) $ show ↑x ∈ s, from hx ▸ has), { assume a has, rcases (le_coe_iff _ _).1 (has _ hxs) with ⟨x, rfl, h⟩, exact (coe_le_coe.2 $ le_cInf (ne_empty_of_mem hxs) $ assume b hbs, coe_le_coe.1 $ has _ hbs) } }, exact ⟨⊤, assume a, match a with | some a, ha := (hs ⟨a, ha⟩).elim | none, ha := _root_.le_refl _ end, assume a _, le_top⟩ end noncomputable instance : has_Sup (with_top α) := ⟨λs, classical.some $ has_lub s⟩ noncomputable instance : has_Inf (with_top α) := ⟨λs, classical.some $ has_glb s⟩ lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) := classical.some_spec _ lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) := classical.some_spec _ noncomputable instance : complete_linear_order (with_top α) := { Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2, Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1, decidable_le := classical.dec_rel _, .. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma coe_Sup {s : set α} (hb : bdd_above s) : (↑(Sup s) : with_top α) = (⨆a∈s, ↑a) := begin by_cases hs : s = ∅, { rw [hs, cSup_empty], simp only [set.mem_empty_eq, lattice.supr_bot, lattice.supr_false], refl }, apply le_antisymm, { refine ((coe_le_iff _ _).2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb ▸ _), exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) }, { exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) } end lemma coe_Inf {s : set α} (hs : s ≠ ∅) : (↑(Inf s) : with_top α) = (⨅a∈s, ↑a) := let ⟨x, hx⟩ := ne_empty_iff_exists_mem.1 hs in have (⨅a∈s, ↑a : with_top α) ≤ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _, let ⟨r, r_eq, hr⟩ := (le_coe_iff _ _).1 this in le_antisymm (le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (bdd_below_bot s) ha) begin refine (r_eq.symm ▸ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _), refine (r_eq ▸ infi_le_of_le a _), exact (infi_le_of_le has $ _root_.le_refl _), end end with_top section order_dual open lattice instance (α : Type*) [conditionally_complete_lattice α] : conditionally_complete_lattice (order_dual α) := { le_cSup := @cInf_le α _, cSup_le := @le_cInf α _, le_cInf := @cSup_le α _, cInf_le := @le_cSup α _, ..order_dual.lattice.has_Inf α, ..order_dual.lattice.has_Sup α, ..order_dual.lattice.lattice α } instance (α : Type*) [conditionally_complete_linear_order α] : conditionally_complete_linear_order (order_dual α) := { ..order_dual.lattice.conditionally_complete_lattice α, ..order_dual.decidable_linear_order α } end order_dual
9d8b26cac4c711301f55845ce26f016ce30f6b6c
ea11767c9c6a467c4b7710ec6f371c95cfc023fd
/src/monoidal_categories/monoidal_structure_from_products.lean
57a07c505ea480c244a0a8de730a779e69a3c6b5
[]
no_license
RitaAhmadi/lean-monoidal-categories
68a23f513e902038e44681336b87f659bbc281e0
81f43e1e0d623a96695aa8938951d7422d6d7ba6
refs/heads/master
1,651,458,686,519
1,529,824,613,000
1,529,824,613,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,129
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .braided_monoidal_category import categories.universal.instances import categories.types import categories.universal.types open categories open categories.functor open categories.products open categories.natural_transformation open categories.monoidal_category open categories.universal namespace categories.monoidal_category universes u v variables {C : Type u} [category.{u v} C] [has_BinaryProducts.{u v} C] {W X Y Z : C} @[reducible,applicable] definition left_associated_triple_Product_projection_1 : (binary_product (binary_product.{u v} X Y).product Z).product ⟶ X := (BinaryProduct.left_projection _) ≫ (BinaryProduct.left_projection _) @[reducible,applicable] definition left_associated_triple_Product_projection_2 : (binary_product (binary_product.{u v} X Y).product Z).product ⟶ Y := (BinaryProduct.left_projection _) ≫ (BinaryProduct.right_projection _) @[reducible,applicable] definition right_associated_triple_Product_projection_2 : (binary_product X (binary_product.{u v} Y Z).product).product ⟶ Y := (BinaryProduct.right_projection _) ≫ (BinaryProduct.left_projection _) @[reducible,applicable] definition right_associated_triple_Product_projection_3 : (binary_product X (binary_product.{u v} Y Z).product).product ⟶ Z := (BinaryProduct.right_projection _) ≫ (BinaryProduct.right_projection _) @[simp] lemma left_factorisation_associated_1 (h : W ⟶ Z) (f : Z ⟶ X ) (g : Z ⟶ Y) : (h ≫ ((binary_product.{u v} X Y).map f g)) ≫ (binary_product X Y).left_projection = h ≫ f := by obviously @[simp] lemma left_factorisation_associated_2 (h : X ⟶ W) (f : Z ⟶ X ) (g : Z ⟶ Y) : ((binary_product.{u v} X Y).map f g) ≫ ((binary_product X Y).left_projection ≫ h) = f ≫ h := by obviously @[simp] lemma right_factorisation_associated_1 (h : W ⟶ Z) (f : Z ⟶ X ) (g : Z ⟶ Y) : (h ≫ ((binary_product.{u v} X Y).map f g)) ≫ (binary_product X Y).right_projection = h ≫ g := by obviously @[simp] lemma right_factorisation_associated_2 (h : Y ⟶ W) (f : Z ⟶ X ) (g : Z ⟶ Y) : ((binary_product.{u v} X Y).map f g) ≫ ((binary_product X Y).right_projection ≫ h) = g ≫ h := by obviously definition TensorProduct_from_Products (C : Type u) [category.{u v} C] [has_BinaryProducts.{u v} C] : TensorProduct C := { onObjects := λ p, (binary_product.{u v} p.1 p.2).product, onMorphisms := λ X Y f, ((binary_product Y.1 Y.2).map ((binary_product X.1 X.2).left_projection ≫ (f.1)) ((binary_product X.1 X.2).right_projection ≫ (f.2))) } local attribute [simp] category.associativity definition Associator_for_Products : Associator (TensorProduct_from_Products C) := by tidy definition LeftUnitor_for_Products [has_TerminalObject C] : LeftUnitor terminal_object (TensorProduct_from_Products C) := by tidy definition RightUnitor_for_Products [has_TerminalObject C] : RightUnitor terminal_object (TensorProduct_from_Products C) := by tidy instance MonoidalStructure_from_Products (C : Type u) [category.{u v} C] [has_TerminalObject C] [has_BinaryProducts.{u v} C] : monoidal_category.{u v} C := { tensor := TensorProduct_from_Products C, tensor_unit := terminal_object, associator_transformation := Associator_for_Products C, left_unitor_transformation := LeftUnitor_for_Products C, right_unitor_transformation := RightUnitor_for_Products C, pentagon := by obviously, triangle := by obviously } open categories.braided_monoidal_category definition Symmetry_on_MonoidalStructure_from_Products (C : Type u) [category.{u v} C] [has_TerminalObject C] [has_BinaryProducts.{u v} C] : Symmetry (MonoidalStructure_from_Products C) := by tidy open categories.types private definition symmetry_on_types := (Symmetry_on_MonoidalStructure_from_Products CategoryOfTypes).braiding.morphism.components private example : symmetry_on_types (ℕ, bool) (3, ff) == (ff, 3) := by obviously end categories.monoidal_category
e9d6af25dc167ba260685cd790e290224e72626a
08a8ee10652ba4f8592710ceb654b37e951d9082
/src/hott/types/W.lean
a4d495a1fa175ed5d185a9f03826080d01bb5603
[ "Apache-2.0" ]
permissive
felixwellen/hott3
e9f299c84d30a782a741c40d38741ec024d391fb
8ac87a2699ab94c23ea7984b4a5fbd5a7052575c
refs/heads/master
1,619,972,899,098
1,509,047,351,000
1,518,040,986,000
120,676,559
0
0
null
1,518,040,503,000
1,518,040,503,000
null
UTF-8
Lean
false
false
5,910
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 Theorems about W-types (well-founded trees) -/ import .sigma .pi universes u v w hott_theory namespace hott open decidable open hott.eq hott.equiv hott.is_equiv sigma inductive Wtype {A : Type u} (B : A → Type v) : Type (max u v) | sup : Π (a : A), (B a → Wtype) → Wtype namespace Wtype notation `W` binders `, ` r:(scoped B, Wtype B) := r variables {A A' : Type u} {B B' : A → Type v} {C : Π(a : A), B a → Type _} {a a' : A} {f : B a → W a, B a} {f' : B a' → W a, B a} {w w' : W(a : A), B a} @[hott] protected def fst (w : W(a : A), B a) : A := by induction w with a f; exact a @[hott] protected def snd (w : W(a : A), B a) : B w.fst → W(a : A), B a := by induction w with a f; exact f @[hott] protected def eta (w : W a, B a) : sup w.fst w.snd = w := by induction w; exact idp @[hott] def sup_eq_sup (p : a = a') (q : f =[p; λa, B a → W a, B a] f') : sup a f = sup a' f' := by induction q; exact idp @[hott] def Wtype_eq (p : Wtype.fst w = Wtype.fst w') (q : Wtype.snd w =[p;λ a, B a → W(a : A), B a] Wtype.snd w') : w = w' := by induction w; induction w';exact (sup_eq_sup p q) @[hott] def Wtype_eq_fst (p : w = w') : w.fst = w'.fst := by induction p;exact idp @[hott] def Wtype_eq_snd (p : w = w') : w.snd =[Wtype_eq_fst p; λ a, B a → W(a : A), B a] w'.snd := by induction p;exact idpo namespace ops postfix `..fst`:(max+1) := Wtype_eq_fst postfix `..snd`:(max+1) := Wtype_eq_snd end ops open ops open sigma @[hott] def sup_path_W (p : w.fst = w'.fst) (q : w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : @dpair (w.fst=w'.fst) (λp, w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) (Wtype_eq p q)..fst (Wtype_eq p q)..snd = ⟨p, q⟩ := begin induction w with a f, induction w' with a' f', dsimp [Wtype.fst] at p, dsimp [Wtype.snd] at q, hinduction q using pathover.rec, refl end @[hott] def fst_path_W (p : w.fst = w'.fst) (q : w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : (Wtype_eq p q)..fst = p := (sup_path_W _ _)..1 @[hott] def snd_path_W (p : w.fst = w'.fst) (q : w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : (Wtype_eq p q)..snd =[fst_path_W p q; λp, w.snd =[p; λ a, B a → W(a : A), B a] w'.snd] q := (sup_path_W _ _)..2 @[hott] def eta_path_W (p : w = w') : Wtype_eq (p..fst) (p..snd) = p := by induction p; induction w; exact idp @[hott] def transport_fst_path_W {B' : A → Type _} (p : w.fst = w'.fst) (q : w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : transport (λ(x:W a, B a), B' x.fst) (Wtype_eq p q) = transport B' p := begin induction w with a f, induction w' with a f', dsimp [Wtype.fst] at p, dsimp [Wtype.snd] at q, hinduction q using pathover.rec, refl end @[hott] def path_W_uncurried (pq : Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : w = w' := by induction pq with p q; exact (Wtype_eq p q) @[hott] def sup_path_W_uncurried (pq : Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : @dpair (w.fst = w'.fst) (λp, w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) (path_W_uncurried pq)..fst (path_W_uncurried pq)..snd = pq := by induction pq with p q; exact (sup_path_W p q) @[hott] def fst_path_W_uncurried (pq : Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : (path_W_uncurried pq)..fst = pq.fst := (sup_path_W_uncurried _)..1 @[hott] def snd_path_W_uncurried (pq : Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : (path_W_uncurried pq)..snd =[fst_path_W_uncurried pq; λ p, w.snd =[p; λ a, B a → W(a : A), B a] w'.snd] pq.snd := (sup_path_W_uncurried _)..2 @[hott] def eta_path_W_uncurried (p : w = w') : path_W_uncurried ⟨p..fst, p..snd⟩ = p := eta_path_W _ @[hott] def transport_fst_path_W_uncurried {B' : A → Type _} (pq : Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : transport (λ(x:W a, B a), B' x.fst) (@path_W_uncurried A B w w' pq) = transport B' pq.fst := by induction pq with p q; exact (transport_fst_path_W p q) @[hott] def isequiv_path_W /-[instance]-/ (w w' : W a, B a) : is_equiv (path_W_uncurried : (Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) → w = w') := adjointify path_W_uncurried (λp, ⟨p..fst, p..snd⟩) eta_path_W_uncurried sup_path_W_uncurried @[hott] def equiv_path_W (w w' : W a, B a) : (Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) ≃ (w = w') := equiv.mk path_W_uncurried (isequiv_path_W _ _) @[hott] def double_induction_on {P : (W a, B a) → (W a, B a) → Type _} (w w' : W a, B a) (H : ∀ (a a' : A) (f : B a → W a, B a) (f' : B a' → W a, B a), (∀ (b : B a) (b' : B a'), P (f b) (f' b')) → P (sup a f) (sup a' f')) : P w w' := begin revert w', induction w with a f IH, intro w', induction w' with a' f', apply H, intros b b', apply IH end /- truncatedness -/ open is_trunc pi hott.sigma hott.pi local attribute [instance] is_trunc_pi_eq @[hott, instance] def is_trunc_W (n : trunc_index) [HA : is_trunc (n.+1) A] : is_trunc (n.+1) (W a, B a) := begin fapply is_trunc_succ_intro, intros w w', eapply (double_induction_on w w'), intros a a' f f' IH, apply is_trunc_equiv_closed, apply equiv_path_W, dsimp [Wtype.fst,Wtype.snd], let HD : Π (p : a = a'), is_trunc n (f =[p; λ (a : A), B a → Wtype B] f'), intro p, induction p, apply is_trunc_equiv_closed_rev, apply pathover_idp, apply_instance, apply is_trunc_sigma, end end Wtype end hott
a250d0497bd3aad7bb6bc1b7a40197e323f781fc
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/padics/padic_integers.lean
7a176cef434318a3a24c261bed0b08d569c32664
[ "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
19,916
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Mario Carneiro, Johan Commelin -/ import data.int.modeq import data.zmod.basic import linear_algebra.adic_completion import data.padics.padic_numbers import ring_theory.discrete_valuation_ring import topology.metric_space.cau_seq_filter /-! # p-adic integers This file defines the p-adic integers `ℤ_p` as the subtype of `ℚ_p` with norm `≤ 1`. We show that `ℤ_p` * is complete * is nonarchimedean * is a normed ring * is a local ring * is a discrete valuation ring The relation between `ℤ_[p]` and `zmod p` is established in another file. ## Important definitions * `padic_int` : the type of p-adic numbers ## Notation We introduce the notation `ℤ_[p]` for the p-adic integers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (nat.prime p)] as a type class argument. Coercions into `ℤ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, p-adic integer -/ open nat padic metric local_ring noncomputable theory open_locale classical /-- The p-adic integers ℤ_p are the p-adic numbers with norm ≤ 1. -/ def padic_int (p : ℕ) [fact p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1} notation `ℤ_[`p`]` := padic_int p namespace padic_int /-! ### Ring structure and coercion to `ℚ_[p]` -/ variables {p : ℕ} [fact p.prime] instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩ lemma ext {x y : ℤ_[p]} : (x : ℚ_[p]) = y → x = y := subtype.ext_iff_val.2 /-- Addition on ℤ_p is inherited from ℚ_p. -/ instance : has_add ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x+y, le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩⟩ /-- Multiplication on ℤ_p is inherited from ℚ_p. -/ instance : has_mul ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x*y, begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩⟩ /-- Negation on ℤ_p is inherited from ℚ_p. -/ instance : has_neg ℤ_[p] := ⟨λ ⟨x, hx⟩, ⟨-x, by simpa⟩⟩ /-- Zero on ℤ_p is inherited from ℚ_p. -/ instance : has_zero ℤ_[p] := ⟨⟨0, by norm_num⟩⟩ instance : inhabited ℤ_[p] := ⟨0⟩ /-- One on ℤ_p is inherited from ℚ_p. -/ instance : has_one ℤ_[p] := ⟨⟨1, by norm_num⟩⟩ @[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl @[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = z := rfl @[simp, norm_cast] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), ((z1 + z2 : ℤ_[p]) : ℚ_[p]) = z1 + z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), ((z1 * z2 : ℤ_[p]) : ℚ_[p]) = z1 * z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_neg : ∀ (z1 : ℤ_[p]), ((-z1 : ℤ_[p]) : ℚ_[p]) = -z1 | ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_one : ((1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl @[simp, norm_cast] lemma coe_coe : ∀ n : ℕ, ((n : ℤ_[p]) : ℚ_[p]) = n | 0 := rfl | (k+1) := by simp [coe_coe] @[simp, norm_cast] lemma coe_coe_int : ∀ (z : ℤ), ((z : ℤ_[p]) : ℚ_[p]) = z | (int.of_nat n) := by simp | -[1+n] := by simp @[simp, norm_cast] lemma coe_zero : ((0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl instance : ring ℤ_[p] := begin refine { add := (+), mul := (*), neg := has_neg.neg, zero := 0, one := 1, .. }; intros; ext; simp; ring end /-- The coercion from ℤ[p] to ℚ[p] as a ring homomorphism. -/ def coe.ring_hom : ℤ_[p] →+* ℚ_[p] := { to_fun := (coe : ℤ_[p] → ℚ_[p]), map_zero' := rfl, map_one' := rfl, map_mul' := coe_mul, map_add' := coe_add } @[simp, norm_cast] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), (↑(z1 - z2) : ℚ_[p]) = ↑z1 - ↑z2 := coe.ring_hom.map_sub @[simp, norm_cast] lemma cast_pow (x : ℤ_[p]) : ∀ (n : ℕ), (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n | 0 := by simp | (k+1) := by simp [monoid.pow, pow]; congr; apply cast_pow @[simp] lemma mk_coe : ∀ (k : ℤ_[p]), (⟨k, k.2⟩ : ℤ_[p]) = k | ⟨_, _⟩ := rfl /-- The inverse of a p-adic integer with norm equal to 1 is also a p-adic integer. Otherwise, the inverse is defined to be 0. -/ def inv : ℤ_[p] → ℤ_[p] | ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0 instance : char_zero ℤ_[p] := { cast_injective := λ m n h, cast_injective $ show (m:ℚ_[p]) = n, by { rw subtype.ext_iff at h, norm_cast at h, exact h } } @[simp, norm_cast] lemma coe_int_eq (z1 z2 : ℤ) : (z1 : ℤ_[p]) = z2 ↔ z1 = z2 := suffices (z1 : ℚ_[p]) = z2 ↔ z1 = z2, from iff.trans (by norm_cast) this, by norm_cast /-- A sequence of integers that is Cauchy with respect to the `p`-adic norm converges to a `p`-adic integer. -/ def of_int_seq (seq : ℕ → ℤ) (h : is_cau_seq (padic_norm p) (λ n, seq n)) : ℤ_[p] := ⟨⟦⟨_, h⟩⟧, show ↑(padic_seq.norm _) ≤ (1 : ℝ), begin rw padic_seq.norm, split_ifs with hne; norm_cast, { exact zero_le_one }, { apply padic_norm.of_int } end ⟩ end padic_int namespace padic_int /-! ### Instances We now show that `ℤ_[p]` is a * complete metric space * normed ring * integral domain -/ variables (p : ℕ) [fact p.prime] instance : metric_space ℤ_[p] := subtype.metric_space instance complete_space : complete_space ℤ_[p] := begin delta padic_int, rw [complete_space_iff_is_complete_range uniform_embedding_subtype_coe, subtype.range_coe_subtype], have : is_complete (closed_ball (0 : ℚ_[p]) 1) := is_closed_ball.is_complete, simpa [closed_ball], end instance : has_norm ℤ_[p] := ⟨λ z, ∥(z : ℚ_[p])∥⟩ variables {p} lemma norm_def {z : ℤ_[p]} : ∥z∥ = ∥(z : ℚ_[p])∥ := rfl variables (p) instance : normed_ring ℤ_[p] := { dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl, norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul_le _ _ } instance : is_absolute_value (λ z : ℤ_[p], ∥z∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero], abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_add_le _ _, abv_mul := λ _ _, by simp only [norm_def, padic_norm_e.mul, padic_int.coe_mul]} variables {p} protected lemma mul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1 | ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [_root_.mul_comm] protected lemma zero_ne_one : (0 : ℤ_[p]) ≠ 1 := show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext_iff_val.1 zero_ne_one protected lemma eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0 | ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩, have a * b = 0, from subtype.ext_iff_val.1 h, (mul_eq_zero.1 this).elim (λ h1, or.inl (by simp [h1]; refl)) (λ h2, or.inr (by simp [h2]; refl)) instance : comm_ring ℤ_[p] := { mul_comm := padic_int.mul_comm, ..padic_int.ring } instance : integral_domain ℤ_[p] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y, padic_int.eq_zero_or_eq_zero_of_mul_eq_zero x y, exists_pair_ne := ⟨0, 1, padic_int.zero_ne_one⟩, ..padic_int.comm_ring } end padic_int namespace padic_int /-! ### Norm -/ variables {p : ℕ} [fact p.prime] lemma norm_le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1 | ⟨_, h⟩ := h @[simp] lemma norm_one : ∥(1 : ℤ_[p])∥ = 1 := normed_field.norm_one @[simp] lemma norm_mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ := by simp [norm_def] @[simp] lemma norm_pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n | 0 := by simp | (k+1) := show ∥z*z^k∥ = ∥z∥*∥z∥^k, by {rw norm_mul, congr, apply norm_pow} theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _ theorem norm_add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne lemma norm_eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_right) h lemma norm_eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_left) h @[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ := by simp [norm_def] lemma norm_int_cast_eq_padic_norm (z : ℤ) : ∥(z : ℤ_[p])∥ = ∥(z : ℚ_[p])∥ := by simp [norm_def] @[simp] lemma norm_eq_padic_norm {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) : @norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl @[simp] lemma norm_p : ∥(p : ℤ_[p])∥ = p⁻¹ := show ∥((p : ℤ_[p]) : ℚ_[p])∥ = p⁻¹, by exact_mod_cast padic_norm_e.norm_p @[simp] lemma norm_p_pow (n : ℕ) : ∥(p : ℤ_[p])^n∥ = p^(-n:ℤ) := show ∥((p^n : ℤ_[p]) : ℚ_[p])∥ = p^(-n:ℤ), by { convert padic_norm_e.norm_p_pow n, simp, } private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) : cau_seq ℚ_[p] (λ a, ∥a∥) := ⟨ λ n, f n, λ _ hε, by simpa [norm, norm_def] using f.cauchy hε ⟩ variables (p) instance complete : cau_seq.is_complete ℤ_[p] norm := ⟨ λ f, have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1, from padic_norm_e_lim_le zero_lt_one (λ _, norm_le_one _), ⟨ ⟨_, hqn⟩, λ ε, by simpa [norm, norm_def] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩ end padic_int namespace padic_int variables (p : ℕ) [hp_prime : fact p.prime] include hp_prime lemma exists_pow_neg_lt {ε : ℝ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := exists_nat_gt ε⁻¹, use k, rw ← inv_lt_inv hε (_root_.fpow_pos_of_pos _ _), { rw [fpow_neg, inv_inv', fpow_coe_nat], apply lt_of_lt_of_le hk, norm_cast, apply le_of_lt, convert nat.lt_pow_self _ _ using 1, exact hp_prime.one_lt }, { exact_mod_cast hp_prime.pos } end lemma exists_pow_neg_lt_rat {ε : ℚ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := @exists_pow_neg_lt p _ ε (by exact_mod_cast hε), use k, rw (show (p : ℝ) = (p : ℚ), by simp) at hk, exact_mod_cast hk end variable {p} lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℤ_[p])∥ < 1 ↔ ↑p ∣ k := suffices ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k, by rwa norm_int_cast_eq_padic_norm, padic_norm_e.norm_int_lt_one_iff_dvd k lemma norm_int_le_pow_iff_dvd {k : ℤ} {n : ℕ} : ∥(k : ℤ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑p^n ∣ k := suffices ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k, by simpa [norm_int_cast_eq_padic_norm], padic_norm_e.norm_int_le_pow_iff_dvd _ _ /-! ### Valuation on `ℤ_[p]` -/ /-- `padic_int.valuation` lifts the p-adic valuation on `ℚ` to `ℤ_[p]`. -/ def valuation (x : ℤ_[p]) := padic.valuation (x : ℚ_[p]) lemma norm_eq_pow_val {x : ℤ_[p]} (hx : x ≠ 0) : ∥x∥ = p^(-x.valuation) := begin convert padic.norm_eq_pow_val _, contrapose! hx, exact subtype.val_injective hx end @[simp] lemma valuation_zero : valuation (0 : ℤ_[p]) = 0 := padic.valuation_zero @[simp] lemma valuation_one : valuation (1 : ℤ_[p]) = 0 := padic.valuation_one @[simp] lemma valuation_p : valuation (p : ℤ_[p]) = 1 := by simp [valuation, -cast_eq_of_rat_of_nat] lemma valuation_nonneg (x : ℤ_[p]) : 0 ≤ x.valuation := begin by_cases hx : x = 0, { simp [hx] }, have h : (1 : ℝ) < p := by exact_mod_cast hp_prime.one_lt, rw [← neg_nonpos, ← (fpow_strict_mono h).le_iff_le], show (p : ℝ) ^ -valuation x ≤ p ^ 0, rw [← norm_eq_pow_val hx], simpa using x.property, end @[simp] lemma valuation_p_pow_mul (n : ℕ) (c : ℤ_[p]) (hc : c ≠ 0) : (↑p ^ n * c).valuation = n + c.valuation := begin have : ∥↑p ^ n * c∥ = ∥(p ^ n : ℤ_[p])∥ * ∥c∥, { exact norm_mul _ _ }, have aux : ↑p ^ n * c ≠ 0, { contrapose! hc, rw mul_eq_zero at hc, cases hc, { refine (hp_prime.ne_zero _).elim, exact_mod_cast (pow_eq_zero hc) }, { exact hc } }, rwa [norm_eq_pow_val aux, norm_p_pow, norm_eq_pow_val hc, ← fpow_add, ← neg_add, fpow_inj, neg_inj] at this, { exact_mod_cast hp_prime.pos }, { exact_mod_cast hp_prime.ne_one }, { exact_mod_cast hp_prime.ne_zero }, end section units /-! ### Units of `ℤ_[p]` -/ local attribute [reducible] padic_int lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1 | ⟨k, _⟩ h := begin have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ _ (by simpa [h'] using h), unfold padic_int.inv, split_ifs, { change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1, simp [hk], refl }, { apply subtype.ext_iff_val.2, simp [mul_inv_cancel hk] } end lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 := by rw [mul_comm, mul_inv hz] lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 := ⟨λ h, begin rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩, refine le_antisymm (norm_le_one _) _, have := mul_le_mul_of_nonneg_left (norm_le_one w) (norm_nonneg z), rwa [mul_one, ← norm_mul, ← eq, norm_one] at this end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩ lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 := lt_of_le_of_lt (nonarchimedean _ _) (max_lt hz1 hz2) lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 := calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp ... < 1 : mul_lt_one_of_nonneg_of_lt_one_right (norm_le_one _) (norm_nonneg _) hz2 @[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 := by rw lt_iff_le_and_ne; simp [norm_le_one z, nonunits, is_unit_iff] /-- A `p`-adic number `u` with `∥u∥ = 1` is a unit of `ℤ_[p]`. -/ def mk_units {u : ℚ_[p]} (h : ∥u∥ = 1) : units ℤ_[p] := let z : ℤ_[p] := ⟨u, le_of_eq h⟩ in ⟨z, z.inv, mul_inv h, inv_mul h⟩ @[simp] lemma mk_units_eq {u : ℚ_[p]} (h : ∥u∥ = 1) : ((mk_units h : ℤ_[p]) : ℚ_[p]) = u := rfl @[simp] lemma norm_units (u : units ℤ_[p]) : ∥(u : ℤ_[p])∥ = 1 := is_unit_iff.mp $ by simp /-- `unit_coeff hx` is the unit `u` in the unique representation `x = u * p ^ n`. See `unit_coeff_spec`. -/ def unit_coeff {x : ℤ_[p]} (hx : x ≠ 0) : units ℤ_[p] := let u : ℚ_[p] := x*p^(-x.valuation) in have hu : ∥u∥ = 1, by simp [hx, nat.fpow_ne_zero_of_pos (by exact_mod_cast hp_prime.pos) x.valuation, norm_eq_pow_val, fpow_neg, inv_mul_cancel, -cast_eq_of_rat_of_nat], mk_units hu @[simp] lemma unit_coeff_coe {x : ℤ_[p]} (hx : x ≠ 0) : (unit_coeff hx : ℚ_[p]) = x * p ^ (-x.valuation) := rfl lemma unit_coeff_spec {x : ℤ_[p]} (hx : x ≠ 0) : x = (unit_coeff hx : ℤ_[p]) * p ^ int.nat_abs (valuation x) := begin apply subtype.coe_injective, push_cast, have repr : (x : ℚ_[p]) = (unit_coeff hx) * p ^ x.valuation, { rw [unit_coeff_coe, mul_assoc, ← fpow_add], { simp }, { exact_mod_cast hp_prime.ne_zero } }, convert repr using 2, rw [← fpow_coe_nat, int.nat_abs_of_nonneg (valuation_nonneg x)], end end units section norm_le_iff /-! ### Various characterizations of open unit balls -/ lemma norm_le_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ ↑n ≤ x.valuation := begin rw norm_eq_pow_val hx, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.coe_nat_le, fpow_neg, fpow_coe_nat], have aux : ∀ n : ℕ, 0 < (p ^ n : ℝ), { apply pow_pos, exact_mod_cast nat.prime.pos ‹_› }, rw [inv_le_inv (aux _) (aux _)], have : p ^ n ≤ p ^ k ↔ n ≤ k := (pow_right_strict_mono (nat.prime.two_le ‹_›)).le_iff_le, rw [← this], norm_cast, end lemma mem_span_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) ↔ ↑n ≤ x.valuation := begin rw [ideal.mem_span_singleton], split, { rintro ⟨c, rfl⟩, suffices : c ≠ 0, { rw [valuation_p_pow_mul _ _ this, le_add_iff_nonneg_right], apply valuation_nonneg, }, contrapose! hx, rw [hx, mul_zero], }, { rw [unit_coeff_spec hx] { occs := occurrences.pos [2] }, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.nat_abs_of_nat, is_unit_unit, is_unit.dvd_mul_left, int.coe_nat_le], intro H, obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le H, simp only [pow_add, dvd_mul_right], } end lemma norm_le_pow_iff_mem_span_pow (x : ℤ_[p]) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) := begin by_cases hx : x = 0, { subst hx, simp only [norm_zero, fpow_neg, fpow_coe_nat, inv_nonneg, iff_true, submodule.zero_mem], exact_mod_cast nat.zero_le _ }, rw [norm_le_pow_iff_le_valuation x hx, mem_span_pow_iff_le_valuation x hx], end lemma norm_le_pow_iff_norm_lt_pow_add_one (x : ℤ_[p]) (n : ℤ) : ∥x∥ ≤ p ^ n ↔ ∥x∥ < p ^ (n + 1) := begin have aux : ∀ n : ℤ, 0 < (p ^ n : ℝ), { apply nat.fpow_pos_of_pos, exact nat.prime.pos ‹_› }, by_cases hx0 : x = 0, { simp [hx0, norm_zero, aux, le_of_lt (aux _)], }, rw norm_eq_pow_val hx0, have h1p : 1 < (p : ℝ), { exact_mod_cast nat.prime.one_lt ‹_› }, have H := fpow_strict_mono h1p, rw [H.le_iff_le, H.lt_iff_lt, int.lt_add_one_iff], end lemma norm_lt_pow_iff_norm_le_pow_sub_one (x : ℤ_[p]) (n : ℤ) : ∥x∥ < p ^ n ↔ ∥x∥ ≤ p ^ (n - 1) := by rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel] lemma norm_lt_one_iff_dvd (x : ℤ_[p]) : ∥x∥ < 1 ↔ ↑p ∣ x := begin have := norm_le_pow_iff_mem_span_pow x 1, rw [ideal.mem_span_singleton, pow_one] at this, rw [← this, norm_le_pow_iff_norm_lt_pow_add_one], simp only [fpow_zero, int.coe_nat_zero, int.coe_nat_succ, add_left_neg, zero_add], end @[simp] lemma pow_p_dvd_int_iff (n : ℕ) (a : ℤ) : (p ^ n : ℤ_[p]) ∣ a ↔ ↑p ^ n ∣ a := by rw [← norm_int_le_pow_iff_dvd, norm_le_pow_iff_mem_span_pow, ideal.mem_span_singleton] end norm_le_iff section dvr /-! ### Discrete valuation ring -/ instance : local_ring ℤ_[p] := local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add lemma p_nonnunit : (p : ℤ_[p]) ∈ nonunits ℤ_[p] := have (p : ℝ)⁻¹ < 1, from inv_lt_one $ by exact_mod_cast hp_prime.one_lt, by simp [this] lemma maximal_ideal_eq_span_p : maximal_ideal ℤ_[p] = ideal.span {p} := begin apply le_antisymm, { intros x hx, rw ideal.mem_span_singleton, simp only [local_ring.mem_maximal_ideal, mem_nonunits] at hx, rwa ← norm_lt_one_iff_dvd, }, { rw [ideal.span_le, set.singleton_subset_iff], exact p_nonnunit } end lemma prime_p : prime (p : ℤ_[p]) := begin rw [← ideal.span_singleton_prime, ← maximal_ideal_eq_span_p], { apply_instance }, { exact_mod_cast hp_prime.ne_zero } end lemma irreducible_p : irreducible (p : ℤ_[p]) := irreducible_of_prime prime_p instance : discrete_valuation_ring ℤ_[p] := discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization ⟨p, irreducible_p, λ x hx, ⟨x.valuation.nat_abs, unit_coeff hx, by rw [mul_comm, ← unit_coeff_spec hx]⟩⟩ lemma ideal_eq_span_pow_p {s : ideal ℤ_[p]} (hs : s ≠ ⊥) : ∃ n : ℕ, s = ideal.span {p ^ n} := discrete_valuation_ring.ideal_eq_span_pow_irreducible hs irreducible_p end dvr end padic_int
44bca3e7b96aacdb8e8ebd583f5eae49640093c5
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/linear_algebra/dimension.lean
ca8536a55bad480e4baefd744fe7fbee4d6331d9
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
47,674
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Sander Dahmen, Scott Morrison -/ import linear_algebra.basis import linear_algebra.std_basis import set_theory.cofinality import linear_algebra.invariant_basis_number /-! # Dimension of modules and vector spaces ## Main definitions * The rank of a module is defined as `module.rank : cardinal`. This is defined as the supremum of the cardinalities of linearly independent subsets. * The rank of a linear map is defined as the rank of its range. ## Main statements * `linear_map.dim_le_of_injective`: the source of an injective linear map has dimension at most that of the target. * `linear_map.dim_le_of_surjective`: the target of a surjective linear map has dimension at most that of that source. * `basis_fintype_of_finite_spans`: the existence of a finite spanning set implies that any basis is finite. * `infinite_basis_le_maximal_linear_independent`: if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. For modules over rings satisfying the rank condition * `basis.le_span`: the cardinality of a basis is bounded by the cardinality of any spanning set For modules over rings satisfying the strong rank condition * `linear_independent_le_span`: For any linearly independent family `v : ι → M` and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. * `linear_independent_le_basis`: If `b` is a basis for a module `M`, and `s` is a linearly independent set, then the cardinality of `s` is bounded by the cardinality of `b`. For modules over rings with invariant basis number (including all commutative rings and all noetherian rings) * `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same cardinality. For vector spaces (i.e. modules over a field), we have * `dim_quotient_add_dim`: if `V₁` is a submodule of `V`, then `module.rank (V/V₁) + module.rank V₁ = module.rank V`. * `dim_range_add_dim_ker`: the rank-nullity theorem. ## Implementation notes There is a naming discrepancy: most of the theorem names refer to `dim`, even though the definition is of `module.rank`. This reflects that `module.rank` was originally called `dim`, and only defined for vector spaces. Many theorems in this file are not universe-generic when they relate dimensions in different universes. They should be as general as they can be without inserting `lift`s. The types `V`, `V'`, ... all live in different universes, and `V₁`, `V₂`, ... all live in the same universe. -/ noncomputable theory universes u v v' v'' u₁' w w' variables {K : Type u} {V V₁ V₂ V₃ : Type v} {V' V'₁ : Type v'} {V'' : Type v''} variables {ι : Type w} {ι' : Type w'} {η : Type u₁'} {φ : η → Type*} open_locale classical big_operators open basis submodule function set section module section variables [semiring K] [add_comm_monoid V] [module K V] include K variables (K V) /-- The rank of a module, defined as a term of type `cardinal`. We define this as the supremum of the cardinalities of linearly independent subsets. For a free module over any ring satisfying the strong rank condition (e.g. left-noetherian rings, commutative rings, and in particular division rings and fields), this is the same as the dimension of the space (i.e. the cardinality of any basis). In particular this agrees with the usual notion of the dimension of a vector space. The definition is marked as protected to avoid conflicts with `_root_.rank`, the rank of a linear map. -/ protected def module.rank : cardinal := cardinal.sup.{v v} (λ ι : {s : set V // linear_independent K (coe : s → V)}, cardinal.mk ι.1) end section variables {R : Type u} [ring R] variables {M : Type v} [add_comm_group M] [module R M] variables {M' : Type v'} [add_comm_group M'] [module R M'] variables {M₁ : Type v} [add_comm_group M₁] [module R M₁] theorem linear_map.lift_dim_le_of_injective (f : M →ₗ[R] M') (i : injective f) : cardinal.lift.{v v'} (module.rank R M) ≤ cardinal.lift.{v' v} (module.rank R M') := begin dsimp [module.rank], fapply cardinal.lift_sup_le_lift_sup', { rintro ⟨s, li⟩, use f '' s, convert (li.map' f (linear_map.ker_eq_bot.mpr i)).comp (equiv.set.image ⇑f s i).symm (equiv.injective _), ext ⟨-, ⟨x, ⟨h, rfl⟩⟩⟩, simp, }, { rintro ⟨s, li⟩, exact cardinal.lift_mk_le'.mpr ⟨(equiv.set.image f s i).to_embedding⟩, } end theorem linear_map.dim_le_of_injective (f : M →ₗ[R] M₁) (i : injective f) : module.rank R M ≤ module.rank R M₁ := cardinal.lift_le.1 (f.lift_dim_le_of_injective i) theorem dim_le {n : ℕ} (H : ∀ s : finset M, linear_independent R (λ i : s, (i : M)) → s.card ≤ n) : module.rank R M ≤ n := begin apply cardinal.sup_le.mpr, rintro ⟨s, li⟩, exact linear_independent_bounded_of_finset_linear_independent_bounded H _ li, end lemma dim_range_le (f : M →ₗ[R] M₁) : module.rank R f.range ≤ module.rank R M := begin dsimp [module.rank], apply cardinal.sup_le.mpr, rintro ⟨s, li⟩, refine le_trans _ (cardinal.le_sup _ ⟨range_splitting f '' s, _⟩), { apply linear_independent.of_comp f.range_restrict, convert li.comp (equiv.set.range_splitting_image_equiv f s) (equiv.injective _) using 1, }, { exact (cardinal.eq_congr (equiv.set.range_splitting_image_equiv f s)).ge, }, end lemma dim_map_le (f : M →ₗ[R] M₁) (p : submodule R M) : module.rank R (p.map f) ≤ module.rank R p := begin have h := dim_range_le (f.comp (submodule.subtype p)), rwa [linear_map.range_comp, range_subtype] at h, end lemma dim_le_of_submodule (s t : submodule R M) (h : s ≤ t) : module.rank R s ≤ module.rank R t := (of_le h).dim_le_of_injective $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq, subtype.eq $ show x = y, from subtype.ext_iff_val.1 eq /-- Two linearly equivalent vector spaces have the same dimension, a version with different universes. -/ theorem linear_equiv.lift_dim_eq (f : M ≃ₗ[R] M') : cardinal.lift.{v v'} (module.rank R M) = cardinal.lift.{v' v} (module.rank R M') := begin apply le_antisymm, { exact f.to_linear_map.lift_dim_le_of_injective f.injective, }, { exact f.symm.to_linear_map.lift_dim_le_of_injective f.symm.injective, }, end /-- Two linearly equivalent vector spaces have the same dimension. -/ theorem linear_equiv.dim_eq (f : M ≃ₗ[R] M₁) : module.rank R M = module.rank R M₁ := cardinal.lift_inj.1 f.lift_dim_eq lemma dim_eq_of_injective (f : M →ₗ[R] M₁) (h : injective f) : module.rank R M = module.rank R f.range := (linear_equiv.of_injective f (linear_map.ker_eq_bot.mpr h)).dim_eq variables (R M) @[simp] lemma dim_top : module.rank R (⊤ : submodule R M) = module.rank R M := begin have : (⊤ : submodule R M) ≃ₗ[R] M := linear_equiv.of_top ⊤ rfl, rw this.dim_eq, end variables {R M} lemma dim_range_of_surjective (f : M →ₗ[R] M') (h : surjective f) : module.rank R f.range = module.rank R M' := by rw [linear_map.range_eq_top.2 h, dim_top] lemma dim_submodule_le (s : submodule R M) : module.rank R s ≤ module.rank R M := begin rw ←dim_top R M, exact dim_le_of_submodule _ _ le_top, end lemma linear_map.dim_le_of_surjective (f : M →ₗ[R] M₁) (h : surjective f) : module.rank R M₁ ≤ module.rank R M := begin rw ←dim_range_of_surjective f h, apply dim_range_le, end variables [nontrivial R] lemma {m} cardinal_lift_le_dim_of_linear_independent {ι : Type w} {v : ι → M} (hv : linear_independent R v) : cardinal.lift.{w (max v m)} (cardinal.mk ι) ≤ cardinal.lift.{v (max w m)} (module.rank R M) := begin apply le_trans, { exact cardinal.lift_mk_le.mpr ⟨(equiv.of_injective _ hv.injective).to_embedding⟩, }, { simp only [cardinal.lift_le], apply le_trans, swap, exact cardinal.le_sup _ ⟨range v, hv.coe_range⟩, exact le_refl _, }, end lemma cardinal_le_dim_of_linear_independent {ι : Type v} {v : ι → M} (hv : linear_independent R v) : cardinal.mk ι ≤ module.rank R M := by simpa using cardinal_lift_le_dim_of_linear_independent hv lemma cardinal_le_dim_of_linear_independent' {s : set M} (hs : linear_independent R (λ x, x : s → M)) : cardinal.mk s ≤ module.rank R M := cardinal_le_dim_of_linear_independent hs variables (R M) @[simp] lemma dim_punit : module.rank R punit = 0 := begin apply le_bot_iff.mp, apply cardinal.sup_le.mpr, rintro ⟨s, li⟩, apply le_bot_iff.mpr, apply cardinal.mk_emptyc_iff.mpr, simp only [subtype.coe_mk], by_contradiction h, have ne : s.nonempty := ne_empty_iff_nonempty.mp h, simpa using linear_independent.ne_zero (⟨_, ne.some_mem⟩ : s) li, end @[simp] lemma dim_bot : module.rank R (⊥ : submodule R M) = 0 := begin have : (⊥ : submodule R M) ≃ₗ[R] punit := bot_equiv_punit, rw [this.dim_eq, dim_punit], end variables {R M} /-- Over any nontrivial ring, the existence of a finite spanning set implies that any basis is finite. -/ -- One might hope that a finite spanning set implies that any linearly independent set is finite. -- While this is true over a division ring -- (simply because any linearly independent set can be extended to a basis), -- I'm not certain what more general statements are possible. def basis_fintype_of_finite_spans (w : set M) [fintype w] (s : span R w = ⊤) {ι : Type w} (b : basis ι R M) : fintype ι := begin -- We'll work by contradiction, assuming `ι` is infinite. apply fintype_of_not_infinite _, introI i, -- Let `S` be the union of the supports of `x ∈ w` expressed as linear combinations of `b`. -- This is a finite set since `w` is finite. let S : finset ι := finset.univ.sup (λ x : w, (b.repr x).support), let bS : set M := b '' S, have h : ∀ x ∈ w, x ∈ span R bS, { intros x m, rw [←b.total_repr x, finsupp.span_image_eq_map_total, submodule.mem_map], use b.repr x, simp only [and_true, eq_self_iff_true, finsupp.mem_supported], change (b.repr x).support ≤ S, convert (finset.le_sup (by simp : (⟨x, m⟩ : w) ∈ finset.univ)), refl, }, -- Thus this finite subset of the basis elements spans the entire module. have k : span R bS = ⊤ := eq_top_iff.2 (le_trans s.ge (span_le.2 h)), -- Now there is some `x : ι` not in `S`, since `ι` is infinite. obtain ⟨x, nm⟩ := infinite.exists_not_mem_finset S, -- However it must be in the span of the finite subset, have k' : b x ∈ span R bS, { rw k, exact mem_top, }, -- giving the desire contradiction. refine b.linear_independent.not_mem_span_image _ k', exact nm, end /-- Over any ring `R`, if `b` is a basis for a module `M`, and `s` is a maximal linearly independent set, then the union of the supports of `x ∈ s` (when written out in the basis `b`) is all of `b`. -/ -- From [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973] lemma union_support_maximal_linear_independent_eq_range_basis {ι : Type w} (b : basis ι R M) {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : (⋃ k, ((b.repr (v k)).support : set ι)) = univ := begin -- If that's not the case, by_contradiction h, simp only [←ne.def, ne_univ_iff_exists_not_mem, mem_Union, not_exists_not, finsupp.mem_support_iff, finset.mem_coe] at h, -- We have some basis element `b b'` which is not in the support of any of the `v i`. obtain ⟨b', w⟩ := h, -- Using this, we'll construct a linearly independent family strictly larger than `v`, -- by also using this `b b'`. let v' : option κ → M := λ o, o.elim (b b') v, have r : range v ⊆ range v', { rintro - ⟨k, rfl⟩, use some k, refl, }, have r' : b b' ∉ range v, { rintro ⟨k, p⟩, simpa [w] using congr_arg (λ m, (b.repr m) b') p, }, have r'' : range v ≠ range v', { intro e, have p : b b' ∈ range v', { use none, refl, }, rw ←e at p, exact r' p, }, have inj' : injective v', { rintros (_|k) (_|k) z, { refl, }, { exfalso, exact r' ⟨k, z.symm⟩, }, { exfalso, exact r' ⟨k, z⟩, }, { congr, exact i.injective z, }, }, -- The key step in the proof is checking that this strictly larger family is linearly independent. have i' : linear_independent R (coe : range v' → M), { rw [linear_independent_subtype_range inj', linear_independent_iff], intros l z, rw [finsupp.total_option] at z, simp only [v', option.elim] at z, change _ + finsupp.total κ M R v l.some = 0 at z, -- We have some linear combination of `b b'` and the `v i`, which we want to show is trivial. -- We'll first show the coefficient of `b b'` is zero, -- by expressing the `v i` in the basis `b`, and using that the `v i` have no `b b'` term. have l₀ : l none = 0, { rw ←eq_neg_iff_add_eq_zero at z, replace z := eq_neg_of_eq_neg z, apply_fun (λ x, b.repr x b') at z, simp only [repr_self, linear_equiv.map_smul, mul_one, finsupp.single_eq_same, pi.neg_apply, finsupp.smul_single', linear_equiv.map_neg, finsupp.coe_neg] at z, erw finsupp.congr_fun (finsupp.apply_total R (b.repr : M →ₗ[R] ι →₀ R) v l.some) b' at z, simpa [finsupp.total_apply, w] using z, }, -- Then all the other coefficients are zero, because `v` is linear independent. have l₁ : l.some = 0, { rw [l₀, zero_smul, zero_add] at z, exact linear_independent_iff.mp i _ z, }, -- Finally we put those facts together to show the linear combination is trivial. ext (_|a), { simp only [l₀, finsupp.coe_zero, pi.zero_apply], }, { erw finsupp.congr_fun l₁ a, simp only [finsupp.coe_zero, pi.zero_apply], }, }, dsimp [linear_independent.maximal] at m, specialize m (range v') i' r, exact r'' m, end /-- Over any ring `R`, if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. -/ lemma infinite_basis_le_maximal_linear_independent' {ι : Type w} (b : basis ι R M) [infinite ι] {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : cardinal.lift.{w w'} (cardinal.mk ι) ≤ cardinal.lift.{w' w} (cardinal.mk κ) := begin let Φ := λ k : κ, (b.repr (v k)).support, have w₁ : cardinal.mk ι ≤ cardinal.mk (set.range Φ), { apply cardinal.le_range_of_union_finset_eq_top, exact union_support_maximal_linear_independent_eq_range_basis b v i m, }, have w₂ : cardinal.lift.{w w'} (cardinal.mk (set.range Φ)) ≤ cardinal.lift.{w' w} (cardinal.mk κ) := cardinal.mk_range_le_lift, exact (cardinal.lift_le.mpr w₁).trans w₂, end /-- Over any ring `R`, if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. -/ -- (See `infinite_basis_le_maximal_linear_independent'` for the more general version -- where the index types can live in different universes.) lemma infinite_basis_le_maximal_linear_independent {ι : Type w} (b : basis ι R M) [infinite ι] {κ : Type w} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : cardinal.mk ι ≤ cardinal.mk κ := cardinal.lift_le.mp (infinite_basis_le_maximal_linear_independent' b v i m) end section invariant_basis_number variables {R : Type u} [ring R] [nontrivial R] [invariant_basis_number R] variables {M : Type v} [add_comm_group M] [module R M] /-- The dimension theorem: if `v` and `v'` are two bases, their index types have the same cardinalities. -/ theorem mk_eq_mk_of_basis (v : basis ι R M) (v' : basis ι' R M) : cardinal.lift.{w w'} (cardinal.mk ι) = cardinal.lift.{w' w} (cardinal.mk ι') := begin by_cases h : cardinal.mk ι < cardinal.omega, { -- `v` is a finite basis, so by `basis_fintype_of_finite_spans` so is `v'`. haveI : fintype ι := (cardinal.lt_omega_iff_fintype.mp h).some, haveI : fintype (range v) := set.fintype_range ⇑v, haveI := basis_fintype_of_finite_spans _ v.span_eq v', -- We clean up a little: rw [cardinal.fintype_card, cardinal.fintype_card], simp only [cardinal.lift_nat_cast, cardinal.nat_cast_inj], -- Now we can use invariant basis number to show they have the same cardinality. apply card_eq_of_lequiv R, exact (((finsupp.linear_equiv_fun_on_fintype R R ι).symm.trans v.repr.symm).trans v'.repr).trans (finsupp.linear_equiv_fun_on_fintype R R ι'), }, { -- `v` is an infinite basis, -- so by `infinite_basis_le_maximal_linear_independent`, `v'` is at least as big, -- and then applying `infinite_basis_le_maximal_linear_independent` again -- we see they have the same cardinality. simp only [not_lt] at h, haveI : infinite ι := cardinal.infinite_iff.mpr h, have w₁ := infinite_basis_le_maximal_linear_independent' v _ v'.linear_independent v'.maximal, haveI : infinite ι' := cardinal.infinite_iff.mpr (begin apply cardinal.lift_le.{w' w}.mp, have p := (cardinal.lift_le.mpr h).trans w₁, rw cardinal.lift_omega at ⊢ p, exact p, end), have w₂ := infinite_basis_le_maximal_linear_independent' v' _ v.linear_independent v.maximal, exact le_antisymm w₁ w₂, } end theorem mk_eq_mk_of_basis' {ι' : Type w} (v : basis ι R M) (v' : basis ι' R M) : cardinal.mk ι = cardinal.mk ι' := cardinal.lift_inj.1 $ mk_eq_mk_of_basis v v' end invariant_basis_number section rank_condition variables {R : Type u} [ring R] [rank_condition R] variables {M : Type v} [add_comm_group M] [module R M] /-- An auxiliary lemma for `basis.le_span`. If `R` satisfies the rank condition, then for any finite basis `b : basis ι R M`, and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma basis.le_span'' {ι : Type*} [fintype ι] (b : basis ι R M) {w : set M} [fintype w] (s : span R w = ⊤) : fintype.card ι ≤ fintype.card w := begin -- We construct an surjective linear map `(w → R) →ₗ[R] (ι → R)`, -- by expressing a linear combination in `w` as a linear combination in `ι`. fapply card_le_of_surjective' R, { exact b.repr.to_linear_map.comp (finsupp.total w M R coe), }, { apply surjective.comp, apply linear_equiv.surjective, rw [←linear_map.range_eq_top, finsupp.range_total], simpa using s, }, end variables [nontrivial R] /-- Another auxiliary lemma for `basis.le_span`, which does not require assuming the basis is finite, but still assumes we have a finite spanning set. -/ lemma basis_le_span' {ι : Type*} (b : basis ι R M) {w : set M} [fintype w] (s : span R w = ⊤) : cardinal.mk ι ≤ fintype.card w := begin haveI := basis_fintype_of_finite_spans w s b, rw cardinal.fintype_card ι, simp only [cardinal.nat_cast_le], exact basis.le_span'' b s, end /-- If `R` satisfies the rank condition, then the cardinality of any basis is bounded by the cardinality of any spanning set. -/ -- Note that if `R` satisfies the strong rank condition, -- this also follows from `linear_independent_le_span` below. theorem basis.le_span {J : set M} (v : basis ι R M) (hJ : span R J = ⊤) : cardinal.mk (range v) ≤ cardinal.mk J := begin cases le_or_lt cardinal.omega (cardinal.mk J) with oJ oJ, { have := cardinal.mk_range_eq_of_injective v.injective, let S : J → set ι := λ j, ↑(v.repr j).support, let S' : J → set M := λ j, v '' S j, have hs : range v ⊆ ⋃ j, S' j, { intros b hb, rcases mem_range.1 hb with ⟨i, hi⟩, have : span R J ≤ comap v.repr.to_linear_map (finsupp.supported R R (⋃ j, S j)) := span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩), rw hJ at this, replace : v.repr (v i) ∈ (finsupp.supported R R (⋃ j, S j)) := this trivial, rw [v.repr_self, finsupp.mem_supported, finsupp.support_single_ne_zero one_ne_zero] at this, { subst b, rcases mem_Union.1 (this (finset.mem_singleton_self _)) with ⟨j, hj⟩, exact mem_Union.2 ⟨j, (mem_image _ _ _).2 ⟨i, hj, rfl⟩⟩ }, { apply_instance } }, refine le_of_not_lt (λ IJ, _), suffices : cardinal.mk (⋃ j, S' j) < cardinal.mk (range v), { exact not_le_of_lt this ⟨set.embedding_of_subset _ _ hs⟩ }, refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk (cardinal.sum_le_sum _ (λ _, cardinal.omega) _)) _, { exact λ j, le_of_lt (cardinal.lt_omega_iff_finite.2 $ (finset.finite_to_set _).image _) }, { rwa [cardinal.sum_const, cardinal.mul_eq_max oJ (le_refl _), max_eq_left oJ] } }, { haveI : fintype J := (cardinal.lt_omega_iff_fintype.mp oJ).some, rw [←cardinal.lift_le, cardinal.mk_range_eq_of_injective v.injective, cardinal.fintype_card J], convert cardinal.lift_le.{w v}.2 (basis_le_span' v hJ), simp, }, end end rank_condition section strong_rank_condition variables {R : Type u} [ring R] [strong_rank_condition R] variables {M : Type v} [add_comm_group M] [module R M] open submodule -- An auxiliary lemma for `linear_independent_le_span'`, -- with the additional assumption that the linearly independent family is finite. lemma linear_independent_le_span_aux' {ι : Type*} [fintype ι] (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : fintype.card ι ≤ fintype.card w := begin -- We construct an injective linear map `(ι → R) →ₗ[R] (w → R)`, -- by thinking of `f : ι → R` as a linear combination of the finite family `v`, -- and expressing that (using the axiom of choice) as a linear combination over `w`. -- We can do this linearly by constructing the map on a basis. fapply card_le_of_injective' R, { apply finsupp.total, exact λ i, span.repr R w ⟨v i, s (mem_range_self i)⟩, }, { intros f g h, apply_fun finsupp.total w M R coe at h, simp only [finsupp.total_total, submodule.coe_mk, span.finsupp_total_repr] at h, rw [←sub_eq_zero, ←linear_map.map_sub] at h, exact sub_eq_zero.mp (linear_independent_iff.mp i _ h), }, end /-- If `R` satisfies the strong rank condition, then any linearly independent family `v : ι → M` contained in the span of some finite `w : set M`, is itself finite. -/ def linear_independent_fintype_of_le_span_fintype {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : fintype ι := fintype_of_finset_card_le (fintype.card w) (λ t, begin let v' := λ x : (t : set ι), v x, have i' : linear_independent R v' := i.comp _ subtype.val_injective, have s' : range v' ≤ span R w := (range_comp_subset_range _ _).trans s, simpa using linear_independent_le_span_aux' v' i' w s', end) /-- If `R` satisfies the strong rank condition, then for any linearly independent family `v : ι → M` contained in the span of some finite `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma linear_independent_le_span' {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : cardinal.mk ι ≤ fintype.card w := begin haveI : fintype ι := linear_independent_fintype_of_le_span_fintype v i w s, rw cardinal.fintype_card, simp only [cardinal.nat_cast_le], exact linear_independent_le_span_aux' v i w s, end /-- If `R` satisfies the strong rank condition, then for any linearly independent family `v : ι → M` and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma linear_independent_le_span {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : span R w = ⊤) : cardinal.mk ι ≤ fintype.card w := begin apply linear_independent_le_span' v i w, rw s, exact le_top, end /-- An auxiliary lemma for `linear_independent_le_basis`: we handle the case where the basis `b` is infinite. -/ lemma linear_independent_le_infinite_basis {ι : Type*} (b : basis ι R M) [infinite ι] {κ : Type*} (v : κ → M) (i : linear_independent R v) : cardinal.mk κ ≤ cardinal.mk ι := begin by_contradiction, simp only [not_le] at h, have w : cardinal.mk (finset ι) = cardinal.mk ι := cardinal.mk_finset_eq_mk (cardinal.infinite_iff.mp ‹infinite ι›), rw ←w at h, let Φ := λ k : κ, (b.repr (v k)).support, obtain ⟨s, w : infinite ↥(Φ ⁻¹' {s})⟩ := cardinal.exists_infinite_fiber Φ h (by { rw [cardinal.infinite_iff, w], exact (cardinal.infinite_iff.mp ‹infinite ι›), }), let v' := λ k : Φ ⁻¹' {s}, v k, have i' : linear_independent R v' := i.comp _ subtype.val_injective, have w' : fintype (Φ ⁻¹' {s}), { apply linear_independent_fintype_of_le_span_fintype v' i' (s.image b), rintros m ⟨⟨p,⟨rfl⟩⟩,rfl⟩, simp only [set_like.mem_coe, subtype.coe_mk, finset.coe_image], apply basis.mem_span_repr_support, }, exactI w.false, end /-- Over any ring `R` satisfying the strong rank condition, if `b` is a basis for a module `M`, and `s` is a linearly independent set, then the cardinality of `s` is bounded by the cardinality of `b`. -/ lemma linear_independent_le_basis {ι : Type*} (b : basis ι R M) {κ : Type*} (v : κ → M) (i : linear_independent R v) : cardinal.mk κ ≤ cardinal.mk ι := begin -- We split into cases depending on whether `ι` is infinite. cases fintype_or_infinite ι; resetI, { -- When `ι` is finite, we have `linear_independent_le_span`, rw cardinal.fintype_card ι, haveI : nontrivial R := nontrivial_of_invariant_basis_number R, rw fintype.card_congr (equiv.of_injective b b.injective), exact linear_independent_le_span v i (range b) b.span_eq, }, { -- and otherwise we have `linear_indepedent_le_infinite_basis`. exact linear_independent_le_infinite_basis b v i, }, end /-- Over any ring `R` satisfying the strong rank condition, if `b` is an infinite basis for a module `M`, then every maximal linearly independent set has the same cardinality as `b`. This proof (along with some of the lemmas above) comes from [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973] -/ -- When the basis is not infinite this need not be true! lemma maximal_linear_independent_eq_infinite_basis {ι : Type*} (b : basis ι R M) [infinite ι] {κ : Type*} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : cardinal.mk κ = cardinal.mk ι := begin apply le_antisymm, { exact linear_independent_le_basis b v i, }, { haveI : nontrivial R := nontrivial_of_invariant_basis_number R, exact infinite_basis_le_maximal_linear_independent b v i m, } end variables [nontrivial R] theorem basis.mk_eq_dim'' {ι : Type v} (v : basis ι R M) : cardinal.mk ι = module.rank R M := begin apply le_antisymm, { transitivity, swap, apply cardinal.le_sup, exact ⟨set.range v, by { convert v.reindex_range.linear_independent, ext, simp }⟩, exact (cardinal.eq_congr (equiv.of_injective v v.injective)).le, }, { apply cardinal.sup_le.mpr, rintro ⟨s, li⟩, apply linear_independent_le_basis v _ li, }, end -- By this stage we want to have a complete API for `module.rank`, -- so we set it `irreducible` here, to keep ourselves honest. attribute [irreducible] module.rank theorem basis.mk_range_eq_dim (v : basis ι R M) : cardinal.mk (range v) = module.rank R M := v.reindex_range.mk_eq_dim'' theorem basis.mk_eq_dim (v : basis ι R M) : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (module.rank R M) := by rw [←v.mk_range_eq_dim, cardinal.mk_range_eq_of_injective v.injective] theorem {m} basis.mk_eq_dim' (v : basis ι R M) : cardinal.lift.{w (max v m)} (cardinal.mk ι) = cardinal.lift.{v (max w m)} (module.rank R M) := by simpa using v.mk_eq_dim /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ lemma basis.nonempty_fintype_index_of_dim_lt_omega {ι : Type*} (b : basis ι R M) (h : module.rank R M < cardinal.omega) : nonempty (fintype ι) := by rwa [← cardinal.lift_lt, ← b.mk_eq_dim, -- ensure `omega` has the correct universe cardinal.lift_omega, ← cardinal.lift_omega.{u_1 v}, cardinal.lift_lt, cardinal.lt_omega_iff_fintype] at h /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ noncomputable def basis.fintype_index_of_dim_lt_omega {ι : Type*} (b : basis ι R M) (h : module.rank R M < cardinal.omega) : fintype ι := classical.choice (b.nonempty_fintype_index_of_dim_lt_omega h) /-- If a module has a finite dimension, all bases are indexed by a finite set. -/ lemma basis.finite_index_of_dim_lt_omega {ι : Type*} {s : set ι} (b : basis s R M) (h : module.rank R M < cardinal.omega) : s.finite := b.nonempty_fintype_index_of_dim_lt_omega h lemma dim_span {v : ι → M} (hv : linear_independent R v) : module.rank R ↥(span R (range v)) = cardinal.mk (range v) := by rw [←cardinal.lift_inj, ← (basis.span hv).mk_eq_dim, cardinal.mk_range_eq_of_injective (@linear_independent.injective ι R M v _ _ _ _ hv)] lemma dim_span_set {s : set M} (hs : linear_independent R (λ x, x : s → M)) : module.rank R ↥(span R s) = cardinal.mk s := by { rw [← @set_of_mem_eq _ s, ← subtype.range_coe_subtype], exact dim_span hs } variables (R) lemma dim_of_ring : module.rank R R = 1 := by rw [←cardinal.lift_inj, ← (basis.singleton punit R).mk_eq_dim, cardinal.mk_punit] end strong_rank_condition section division_ring variables [division_ring K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables {K V} /-- If a vector space has a finite dimension, the index set of `basis.of_vector_space` is finite. -/ lemma basis.finite_of_vector_space_index_of_dim_lt_omega (h : module.rank K V < cardinal.omega) : (basis.of_vector_space_index K V).finite := (basis.of_vector_space K V).nonempty_fintype_index_of_dim_lt_omega h variables [add_comm_group V'] [module K V'] /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_lift_dim_eq (cond : cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V')) : nonempty (V ≃ₗ[K] V') := begin let B := basis.of_vector_space K V, let B' := basis.of_vector_space K V', have : cardinal.lift.{v v'} (cardinal.mk _) = cardinal.lift.{v' v} (cardinal.mk _), by rw [B.mk_eq_dim'', cond, B'.mk_eq_dim''], exact (cardinal.lift_mk_eq.{v v' 0}.1 this).map (B.equiv B') end /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_dim_eq (cond : module.rank K V = module.rank K V₁) : nonempty (V ≃ₗ[K] V₁) := nonempty_linear_equiv_of_lift_dim_eq $ congr_arg _ cond section variables (V V' V₁) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_lift_dim_eq (cond : cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V')) : V ≃ₗ[K] V' := classical.choice (nonempty_linear_equiv_of_lift_dim_eq cond) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_dim_eq (cond : module.rank K V = module.rank K V₁) : V ≃ₗ[K] V₁ := classical.choice (nonempty_linear_equiv_of_dim_eq cond) end /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_lift_dim_eq : nonempty (V ≃ₗ[K] V') ↔ cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V') := ⟨λ ⟨h⟩, linear_equiv.lift_dim_eq h, λ h, nonempty_linear_equiv_of_lift_dim_eq h⟩ /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_dim_eq : nonempty (V ≃ₗ[K] V₁) ↔ module.rank K V = module.rank K V₁ := ⟨λ ⟨h⟩, linear_equiv.dim_eq h, λ h, nonempty_linear_equiv_of_dim_eq h⟩ -- TODO how far can we generalise this? -- When `s` is finite, we could prove this for any ring satisfying the strong rank condition -- using `linear_independent_le_span'` lemma dim_span_le (s : set V) : module.rank K (span K s) ≤ cardinal.mk s := begin classical, rcases exists_linear_independent (linear_independent_empty K V) (set.empty_subset s) with ⟨b, hb, _, hsb, hlib⟩, have hsab : span K s = span K b, from span_eq_of_le _ hsb (span_le.2 (λ x hx, subset_span (hb hx))), convert cardinal.mk_le_mk_of_subset hb, rw [hsab, dim_span_set hlib] end lemma dim_span_of_finset (s : finset V) : module.rank K (span K (↑s : set V)) < cardinal.omega := calc module.rank K (span K (↑s : set V)) ≤ cardinal.mk (↑s : set V) : dim_span_le ↑s ... = s.card : by rw [cardinal.finset_card, finset.coe_sort_coe] ... < cardinal.omega : cardinal.nat_lt_omega _ theorem dim_prod : module.rank K (V × V₁) = module.rank K V + module.rank K V₁ := begin let b := basis.of_vector_space K V, let c := basis.of_vector_space K V₁, rw [← cardinal.lift_inj, ← (basis.prod b c).mk_eq_dim, cardinal.lift_add, cardinal.lift_mk, ← b.mk_eq_dim, ← c.mk_eq_dim, cardinal.lift_mk, cardinal.lift_mk, cardinal.add_def (ulift _)], exact cardinal.lift_inj.1 (cardinal.lift_mk_eq.2 ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm ⟩), end end division_ring section field variables [field K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables [add_comm_group V'] [module K V'] variables {K V} theorem dim_quotient_add_dim (p : submodule K V) : module.rank K p.quotient + module.rank K p = module.rank K V := by classical; exact let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq theorem dim_quotient_le (p : submodule K V) : module.rank K p.quotient ≤ module.rank K V := by { rw ← dim_quotient_add_dim p, exact self_le_add_right _ _ } /-- rank-nullity theorem -/ theorem dim_range_add_dim_ker (f : V →ₗ[K] V₁) : module.rank K f.range + module.rank K f.ker = module.rank K V := begin haveI := λ (p : submodule K V), classical.dec_eq p.quotient, rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient_add_dim] end lemma dim_eq_of_surjective (f : V →ₗ[K] V₁) (h : surjective f) : module.rank K V = module.rank K V₁ + module.rank K f.ker := by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h] section variables [add_comm_group V₂] [module K V₂] variables [add_comm_group V₃] [module K V₃] open linear_map /-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/ lemma dim_add_dim_split (db : V₂ →ₗ[K] V) (eb : V₃ →ₗ[K] V) (cd : V₁ →ₗ[K] V₂) (ce : V₁ →ₗ[K] V₃) (hde : ⊤ ≤ db.range ⊔ eb.range) (hgd : ker cd = ⊥) (eq : db.comp cd = eb.comp ce) (eq₂ : ∀d e, db d = eb e → (∃c, cd c = d ∧ ce c = e)) : module.rank K V + module.rank K V₁ = module.rank K V₂ + module.rank K V₃ := have hf : surjective (coprod db eb), begin refine (range_eq_top.1 $ top_unique $ _), rwa [← map_top, ← prod_top, map_coprod_prod, ←range_eq_map, ←range_eq_map] end, begin conv {to_rhs, rw [← dim_prod, dim_eq_of_surjective _ hf] }, congr' 1, apply linear_equiv.dim_eq, refine linear_equiv.of_bijective _ _ _, { refine cod_restrict _ (prod cd (- ce)) _, { assume c, simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, coprod_apply, neg_neg, map_neg, neg_apply], exact linear_map.ext_iff.1 eq c } }, { rw [ker_cod_restrict, ker_prod, hgd, bot_inf_eq] }, { rw [eq_top_iff, range_cod_restrict, ← map_le_iff_le_comap, map_top, range_subtype], rintros ⟨d, e⟩, have h := eq₂ d (-e), simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, set_like.mem_coe, prod.mk.inj_iff, coprod_apply, map_neg, neg_apply, linear_map.mem_range] at ⊢ h, assume hde, rcases h hde with ⟨c, h₁, h₂⟩, refine ⟨c, h₁, _⟩, rw [h₂, _root_.neg_neg] } end lemma dim_sup_add_dim_inf_eq (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) + module.rank K (s ⊓ t : submodule K V) = module.rank K s + module.rank K t := dim_add_dim_split (of_le le_sup_left) (of_le le_sup_right) (of_le inf_le_left) (of_le inf_le_right) begin rw [← map_le_map_iff' (ker_subtype $ s ⊔ t), map_sup, map_top, ← linear_map.range_comp, ← linear_map.range_comp, subtype_comp_of_le, subtype_comp_of_le, range_subtype, range_subtype, range_subtype], exact le_refl _ end (ker_of_le _ _ _) begin ext ⟨x, hx⟩, refl end begin rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq, have : b₁ = b₂ := congr_arg subtype.val eq, subst this, exact ⟨⟨b₁, hb₁, hb₂⟩, rfl, rfl⟩ end lemma dim_add_le_dim_add_dim (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) ≤ module.rank K s + module.rank K t := by { rw [← dim_sup_add_dim_inf_eq], exact self_le_add_right _ _ } end section fintype variable [fintype η] variables [∀i, add_comm_group (φ i)] [∀i, module K (φ i)] open linear_map lemma dim_pi : module.rank K (Πi, φ i) = cardinal.sum (λi, module.rank K (φ i)) := begin let b := assume i, basis.of_vector_space K (φ i), let this : basis (Σ j, _) K (Π j, φ j) := pi.basis b, rw [←cardinal.lift_inj, ← this.mk_eq_dim], simp [λ i, (b i).mk_range_eq_dim.symm, cardinal.sum_mk] end lemma dim_fun {V η : Type u} [fintype η] [add_comm_group V] [module K V] : module.rank K (η → V) = fintype.card η * module.rank K V := by rw [dim_pi, cardinal.sum_const, cardinal.fintype_card] lemma dim_fun_eq_lift_mul : module.rank K (η → V) = (fintype.card η : cardinal.{max u₁' v}) * cardinal.lift.{v u₁'} (module.rank K V) := by rw [dim_pi, cardinal.sum_const_eq_lift_mul, cardinal.fintype_card, cardinal.lift_nat_cast] lemma dim_fun' : module.rank K (η → K) = fintype.card η := by rw [dim_fun_eq_lift_mul, dim_of_ring, cardinal.lift_one, mul_one, cardinal.nat_cast_inj] lemma dim_fin_fun (n : ℕ) : module.rank K (fin n → K) = n := by simp [dim_fun'] end fintype lemma exists_mem_ne_zero_of_ne_bot {s : submodule K V} (h : s ≠ ⊥) : ∃ b : V, b ∈ s ∧ b ≠ 0 := begin classical, by_contradiction hex, have : ∀x∈s, (x:V) = 0, { simpa only [not_exists, not_and, not_not, ne.def] using hex }, exact (h $ bot_unique $ assume s hs, (submodule.mem_bot K).2 $ this s hs) end lemma exists_mem_ne_zero_of_dim_pos {s : submodule K V} (h : 0 < module.rank K s) : ∃ b : V, b ∈ s ∧ b ≠ 0 := exists_mem_ne_zero_of_ne_bot $ assume eq, by rw [eq, dim_bot] at h; exact lt_irrefl _ h section rank -- TODO This definition, and some of the results about it, could be generalized to arbitrary rings. /-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/ def rank (f : V →ₗ[K] V') : cardinal := module.rank K f.range lemma rank_le_domain (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V := by { rw [← dim_range_add_dim_ker f], exact self_le_add_right _ _ } lemma rank_le_range (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V₁ := dim_submodule_le _ lemma rank_add_le (f g : V →ₗ[K] V') : rank (f + g) ≤ rank f + rank g := calc rank (f + g) ≤ module.rank K (f.range ⊔ g.range : submodule K V') : begin refine dim_le_of_submodule _ _ _, exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $ assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule K V'), from mem_sup.2 ⟨_, ⟨x, rfl⟩, _, ⟨x, rfl⟩, rfl⟩) end ... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _ @[simp] lemma rank_zero : rank (0 : V →ₗ[K] V') = 0 := by rw [rank, linear_map.range_zero, dim_bot] lemma rank_finset_sum_le {η} (s : finset η) (f : η → V →ₗ[K] V') : rank (∑ d in s, f d) ≤ ∑ d in s, rank (f d) := @finset.sum_hom_rel _ _ _ _ _ (λa b, rank a ≤ b) f (λ d, rank (f d)) s (le_of_eq rank_zero) (λ i g c h, le_trans (rank_add_le _ _) (add_le_add_left h _)) variables [add_comm_group V''] [module K V''] lemma rank_comp_le1 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'') : rank (f.comp g) ≤ rank f := begin refine dim_le_of_submodule _ _ _, rw [linear_map.range_comp], exact linear_map.map_le_range, end variables [add_comm_group V'₁] [module K V'₁] lemma rank_comp_le2 (g : V →ₗ[K] V') (f : V' →ₗ V'₁) : rank (f.comp g) ≤ rank g := by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _ end rank -- TODO The remainder of this file could be generalized to arbitrary rings. lemma dim_zero_iff_forall_zero : module.rank K V = 0 ↔ ∀ x : V, x = 0 := begin split, { intros h x, have card_mk_range := (basis.of_vector_space K V).mk_range_eq_dim, rw [h, cardinal.mk_emptyc_iff, coe_of_vector_space, subtype.range_coe] at card_mk_range, simpa [card_mk_range] using (of_vector_space K V).mem_span x }, { intro h, have : (⊤ : submodule K V) = ⊥, { ext x, simp [h x] }, rw [←dim_top, this, dim_bot] } end lemma dim_zero_iff : module.rank K V = 0 ↔ subsingleton V := dim_zero_iff_forall_zero.trans (subsingleton_iff_forall_eq 0).symm /-- The `ι` indexed basis on `V`, where `ι` is an empty type and `V` is zero-dimensional. See also `finite_dimensional.fin_basis`. -/ def basis.of_dim_eq_zero {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) : basis ι K V := begin haveI : subsingleton V := dim_zero_iff.1 hV, exact basis.empty _ end @[simp] lemma basis.of_dim_eq_zero_apply {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) (i : ι) : basis.of_dim_eq_zero hV i = 0 := rfl lemma dim_pos_iff_exists_ne_zero : 0 < module.rank K V ↔ ∃ x : V, x ≠ 0 := begin rw ←not_iff_not, simpa using dim_zero_iff_forall_zero end lemma dim_pos_iff_nontrivial : 0 < module.rank K V ↔ nontrivial V := dim_pos_iff_exists_ne_zero.trans (nontrivial_iff_exists_ne 0).symm lemma dim_pos [h : nontrivial V] : 0 < module.rank K V := dim_pos_iff_nontrivial.2 h lemma le_dim_iff_exists_linear_independent {c : cardinal} : c ≤ module.rank K V ↔ ∃ s : set V, cardinal.mk s = c ∧ linear_independent K (coe : s → V) := begin split, { intro h, let t := basis.of_vector_space K V, rw [← t.mk_eq_dim'', cardinal.le_mk_iff_exists_subset] at h, rcases h with ⟨s, hst, hsc⟩, exact ⟨s, hsc, (of_vector_space_index.linear_independent K V).mono hst⟩ }, { rintro ⟨s, rfl, si⟩, exact cardinal_le_dim_of_linear_independent si } end lemma le_dim_iff_exists_linear_independent_finset {n : ℕ} : ↑n ≤ module.rank K V ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (coe : (s : set V) → V) := begin simp only [le_dim_iff_exists_linear_independent, cardinal.mk_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end lemma le_rank_iff_exists_linear_independent {c : cardinal} {f : V →ₗ[K] V'} : c ≤ rank f ↔ ∃ s : set V, cardinal.lift.{v v'} (cardinal.mk s) = cardinal.lift.{v' v} c ∧ linear_independent K (λ x : s, f x) := begin rcases f.range_restrict.exists_right_inverse_of_surjective f.range_range_restrict with ⟨g, hg⟩, have fg : left_inverse f.range_restrict g, from linear_map.congr_fun hg, refine ⟨λ h, _, _⟩, { rcases le_dim_iff_exists_linear_independent.1 h with ⟨s, rfl, si⟩, refine ⟨g '' s, cardinal.mk_image_eq_lift _ _ fg.injective, _⟩, replace fg : ∀ x, f (g x) = x, by { intro x, convert congr_arg subtype.val (fg x) }, replace si : linear_independent K (λ x : s, f (g x)), by simpa only [fg] using si.map' _ (ker_subtype _), exact si.image_of_comp s g f }, { rintro ⟨s, hsc, si⟩, have : linear_independent K (λ x : s, f.range_restrict x), from linear_independent.of_comp (f.range.subtype) (by convert si), convert cardinal_le_dim_of_linear_independent this.image, rw [← cardinal.lift_inj, ← hsc, cardinal.mk_image_eq_of_inj_on_lift], exact inj_on_iff_injective.2 this.injective } end lemma le_rank_iff_exists_linear_independent_finset {n : ℕ} {f : V →ₗ[K] V'} : ↑n ≤ rank f ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (λ x : (s : set V), f x) := begin simp only [le_rank_iff_exists_linear_independent, cardinal.lift_nat_cast, cardinal.lift_eq_nat_iff, cardinal.mk_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end /-- A vector space has dimension at most `1` if and only if there is a single vector of which all vectors are multiples. -/ lemma dim_le_one_iff : module.rank K V ≤ 1 ↔ ∃ v₀ : V, ∀ v, ∃ r : K, r • v₀ = v := begin let b := basis.of_vector_space K V, split, { intro hd, rw [← b.mk_eq_dim'', cardinal.le_one_iff_subsingleton, subsingleton_coe] at hd, rcases eq_empty_or_nonempty (of_vector_space_index K V) with hb | ⟨⟨v₀, hv₀⟩⟩, { use 0, have h' : ∀ v : V, v = 0, { simpa [hb, submodule.eq_bot_iff] using b.span_eq.symm }, intro v, simp [h' v] }, { use v₀, have h' : (K ∙ v₀) = ⊤, { simpa [hd.eq_singleton_of_mem hv₀] using b.span_eq }, intro v, have hv : v ∈ (⊤ : submodule K V) := mem_top, rwa [←h', mem_span_singleton] at hv } }, { rintros ⟨v₀, hv₀⟩, have h : (K ∙ v₀) = ⊤, { ext, simp [mem_span_singleton, hv₀] }, rw [←dim_top, ←h], convert dim_span_le _, simp } end /-- A submodule has dimension at most `1` if and only if there is a single vector in the submodule such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀ ∈ s, s ≤ K ∙ v₀ := begin simp_rw [dim_le_one_iff, le_span_singleton_iff], split, { rintro ⟨⟨v₀, hv₀⟩, h⟩, use [v₀, hv₀], intros v hv, obtain ⟨r, hr⟩ := h ⟨v, hv⟩, use r, simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk] at hr, exact hr }, { rintro ⟨v₀, hv₀, h⟩, use ⟨v₀, hv₀⟩, rintro ⟨v, hv⟩, obtain ⟨r, hr⟩ := h v hv, use r, simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk], exact hr } end /-- A submodule has dimension at most `1` if and only if there is a single vector, not necessarily in the submodule, such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff' (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀, s ≤ K ∙ v₀ := begin rw dim_submodule_le_one_iff, split, { rintros ⟨v₀, hv₀, h⟩, exact ⟨v₀, h⟩ }, { rintros ⟨v₀, h⟩, by_cases hw : ∃ w : V, w ∈ s ∧ w ≠ 0, { rcases hw with ⟨w, hw, hw0⟩, use [w, hw], rcases mem_span_singleton.1 (h hw) with ⟨r', rfl⟩, have h0 : r' ≠ 0, { rintro rfl, simpa using hw0 }, rwa span_singleton_smul_eq _ h0 }, { push_neg at hw, rw ←submodule.eq_bot_iff at hw, simp [hw] } } end end field end module
f42862e8623b73bacc8281be5eba8fd021b29bc1
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/topology/instances/real.lean
128650d0bda5b63e3d3f5e5e919fb6982147d9b2
[ "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
18,874
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro The real numbers ℝ. They are constructed as the topological completion of ℚ. With the following steps: (1) prove that ℚ forms a uniform space. (2) subtraction and addition are uniform continuous functions in this space (3) for multiplication and inverse this only holds on bounded subsets (4) ℝ is defined as separated Cauchy filters over ℚ (the separation requires a quotient construction) (5) extend the uniform continuous functions along the completion (6) proof field properties using the principle of extension of identities TODO generalizations: * topological groups & rings * order topologies * Archimedean fields -/ import topology.metric_space.basic topology.algebra.uniform_group topology.algebra.ring tactic.linarith noncomputable theory open classical set lattice filter topological_space metric local attribute [instance] prop_decidable universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), simpa using (@int.cast_le ℝ _ _ 0).2 (int.lt_add_one_iff.1 $ (@int.cast_lt ℝ _ (abs (a - b)) 1).1 $ by simpa using h) end theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ne_empty_iff_exists_mem.2 ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.uniform_continuous_iff.2 $ by simp [(∘)]; exact ((uniform_continuous_fst.comp uniform_continuous_of_rat).prod_mk (uniform_continuous_snd.comp uniform_continuous_of_rat)).comp real.uniform_continuous_add theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : orderable_topology ℚ := induced_orderable_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, hl, hu, h⟩ := (mem_nhds_unbounded (no_top _) (no_bot _)).mp (mem_nhds_sets hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by simp; exact ⟨q, p, rat.cast_lt.1 $ lt_trans hqa hap, rfl⟩, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h _ (lt_trans hlq hqa') (lt_trans ha'p hpu)⟩) instance : second_countable_topology ℝ := ⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}), by simp [countable_Union, countable_Union_Prop], real.is_topological_basis_Ioo_rat.2.2⟩⟩ /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma real.continuous_abs : continuous (abs : ℝ → ℝ) := real.uniform_continuous_abs.continuous lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) := rat.uniform_continuous_abs.continuous lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (nhds r) (nhds r⁻¹) := by rw ← abs_pos_iff at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets (real.continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0)) lemma real.continuous_inv' : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, (continuous_iff_continuous_at.mp continuous_subtype_val _).comp (real.tendsto_inv hr) lemma real.continuous_inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from (continuous_subtype_mk _ hf).comp real.continuous_inv' lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (r₁0 : 0 < r₁) (r₂0 : 0 < r₂) (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 r₁0 r₂0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (lt_of_le_of_lt (abs_nonneg _) (lt_add_one _)) (lt_of_le_of_lt (abs_nonneg _) (lt_add_one _)) (λ x, id)) (mem_nhds_sets (is_open_prod (real.continuous_abs _ $ is_open_gt' (abs a₁ + 1)) (real.continuous_abs _ $ is_open_gt' (abs a₂ + 1))) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact ((continuous_fst.comp continuous_of_rat).prod_mk (continuous_snd.comp continuous_of_rat)).comp real.continuous_mul instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) := metric.totally_bounded_iff.2 $ λ ε ε0, begin rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩, rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba, let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n}, refine ⟨s, finite_image _ ⟨set.fintype_lt_nat _⟩, λ x h, _⟩, rcases h with ⟨ax, xb⟩, let i : ℕ := ⌊(x - a) / ε⌋.to_nat, have : (i : ℤ) = ⌊(x - a) / ε⌋ := int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)), simp, refine ⟨_, ⟨i, _, rfl⟩, _⟩, { rw [← int.coe_nat_lt, this], refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _), rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'], exact lt_trans xb ba }, { rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg, ← sub_sub, sub_lt_iff_lt_add'], { have := lt_floor_add_one ((x - a) / ε), rwa [div_lt_iff' ε0, mul_add, mul_one] at this }, { have := floor_le ((x - a) / ε), rwa [ge, sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } } end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) := let ⟨c, ac⟩ := no_bot a in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩) (real.totally_bounded_Ioo c b) lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) := let ⟨c, bc⟩ := no_top b in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩) (real.totally_bounded_Ico a c) lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end -- TODO(Mario): Generalize to first-countable uniform spaces? instance : complete_space ℝ := ⟨λ f cf, begin let g : ℕ → {ε:ℝ//ε>0} := λ n, ⟨n.to_pnat'⁻¹, inv_pos (nat.cast_pos.2 n.to_pnat'.pos)⟩, choose S hS hS_dist using show ∀n:ℕ, ∃t ∈ f.sets, ∀ x y ∈ t, dist x y < g n, from assume n, let ⟨t, tf, h⟩ := (metric.cauchy_iff.1 cf).2 (g n).1 (g n).2 in ⟨t, tf, h⟩, let F : ℕ → set ℝ := λn, ⋂i≤n, S i, have hF : ∀n, F n ∈ f.sets := assume n, Inter_mem_sets (finite_le_nat n) (λ i _, hS i), have hF_dist : ∀n, ∀ x y ∈ F n, dist x y < g n := assume n x y hx hy, have F n ⊆ S n := bInter_subset_of_mem (le_refl n), (hS_dist n) _ _ (this hx) (this hy), choose G hG using assume n:ℕ, inhabited_of_mem_sets cf.1 (hF n), have hg : ∀ ε > 0, ∃ n, ∀ j ≥ n, (g j : ℝ) < ε, { intros ε ε0, cases exists_nat_gt ε⁻¹ with n hn, refine ⟨n, λ j nj, _⟩, have hj := lt_of_lt_of_le hn (nat.cast_le.2 nj), have j0 := lt_trans (inv_pos ε0) hj, have jε := (inv_lt j0 ε0).2 hj, rwa ← pnat.to_pnat'_coe (nat.cast_pos.1 j0) at jε }, let c : cau_seq ℝ abs, { refine ⟨λ n, G n, λ ε ε0, _⟩, cases hg _ ε0 with n hn, refine ⟨n, λ j jn, _⟩, have : F j ⊆ F n := bInter_subset_bInter_left (λ i h, @le_trans _ _ i n j h jn), exact lt_trans (hF_dist n _ _ (this (hG j)) (hG n)) (hn _ $ le_refl _) }, refine ⟨cau_seq.lim c, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, cases exists_forall_ge_and (hg _ $ half_pos ε0) (cau_seq.equiv_lim c _ $ half_pos ε0) with n hn, cases hn _ (le_refl _) with h₁ h₂, refine sets_of_superset _ (hF n) (subset.trans _ $ subset.trans (ball_half_subset (G n) h₂) hε), exact λ x h, lt_trans ((hF_dist n) x (G n) h (hG n)) h₁ end⟩ lemma tendsto_coe_nat_real_at_top_iff {f : α → ℕ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, nat.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨n, le_of_lt hn⟩ lemma tendsto_coe_nat_real_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top := tendsto_coe_nat_real_at_top_iff.2 tendsto_id lemma tendsto_coe_int_real_at_top_iff {f : α → ℤ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, int.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨(n:ℤ), le_of_lt $ by rwa [int.cast_coe_nat]⟩ lemma tendsto_coe_int_real_at_top_at_top : tendsto (coe : ℤ → ℝ) at_top at_top := tendsto_coe_int_real_at_top_iff.2 tendsto_id section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((closure_subset_iff_subset_of_is_closed (is_closed_ge' _)).2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ne_empty_iff_exists_mem.2 ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma compact_Icc {a b : ℝ} : compact (Icc a b) := compact_of_totally_bounded_is_closed (real.totally_bounded_Icc a b) (is_closed_inter (is_closed_ge' a) (is_closed_le' b)) instance : proper_space ℝ := { compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc } open real lemma real.intermediate_value {f : ℝ → ℝ} {a b t : ℝ} (hf : ∀ x, a ≤ x → x ≤ b → tendsto f (nhds x) (nhds (f x))) (ha : f a ≤ t) (hb : t ≤ f b) (hab : a ≤ b) : ∃ x : ℝ, a ≤ x ∧ x ≤ b ∧ f x = t := let x := real.Sup {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} in have hx₁ : ∃ y, ∀ g ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b}, g ≤ y := ⟨b, λ _ h, h.2.2⟩, have hx₂ : ∃ y, y ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} := ⟨a, ha, le_refl _, hab⟩, have hax : a ≤ x, from le_Sup _ hx₁ ⟨ha, le_refl _, hab⟩, have hxb : x ≤ b, from (Sup_le _ hx₂ hx₁).2 (λ _ h, h.2.2), ⟨x, hax, hxb, eq_of_forall_dist_le $ λ ε ε0, let ⟨δ, hδ0, hδ⟩ := metric.tendsto_nhds_nhds.1 (hf _ hax hxb) ε ε0 in (le_total t (f x)).elim (λ h, le_of_not_gt $ λ hfε, begin rw [dist_eq, abs_of_nonneg (sub_nonneg.2 h)] at hfε, refine mt (Sup_le {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} hx₂ hx₁).2 (not_le_of_gt (sub_lt_self x (half_pos hδ0))) (λ g hg, le_of_not_gt (λ hgδ, not_lt_of_ge hg.1 (lt_trans (lt_sub.1 hfε) (sub_lt_of_sub_lt (lt_of_le_of_lt (le_abs_self _) _))))), rw abs_sub, exact hδ (abs_sub_lt_iff.2 ⟨lt_of_le_of_lt (sub_nonpos.2 (le_Sup _ hx₁ hg)) hδ0, by simp only [x] at *; linarith⟩) end) (λ h, le_of_not_gt $ λ hfε, begin rw [dist_eq, abs_of_nonpos (sub_nonpos.2 h)] at hfε, exact mt (le_Sup {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b}) (λ h : ∀ k, k ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} → k ≤ x, not_le_of_gt ((lt_add_iff_pos_left x).2 (half_pos hδ0)) (h _ ⟨le_trans (le_sub_iff_add_le.2 (le_trans (le_abs_self _) (le_of_lt (hδ $ by rw [dist_eq, add_sub_cancel, abs_of_nonneg (le_of_lt (half_pos hδ0))]; exact half_lt_self hδ0)))) (by linarith), le_trans hax (le_of_lt ((lt_add_iff_pos_left _).2 (half_pos hδ0))), le_of_not_gt (λ hδy, not_lt_of_ge hb (lt_of_le_of_lt (show f b ≤ f b - f x - ε + t, by linarith) (add_lt_of_neg_of_le (sub_neg_of_lt (lt_of_le_of_lt (le_abs_self _) (@hδ b (abs_sub_lt_iff.2 ⟨by simp only [x] at *; linarith, by linarith⟩)))) (le_refl _))))⟩)) hx₁ end)⟩ lemma real.intermediate_value' {f : ℝ → ℝ} {a b t : ℝ} (hf : ∀ x, a ≤ x → x ≤ b → tendsto f (nhds x) (nhds (f x))) (ha : t ≤ f a) (hb : f b ≤ t) (hab : a ≤ b) : ∃ x : ℝ, a ≤ x ∧ x ≤ b ∧ f x = t := let ⟨x, hx₁, hx₂, hx₃⟩ := @real.intermediate_value (λ x, - f x) a b (-t) (λ x hax hxb, tendsto_neg (hf x hax hxb)) (neg_le_neg ha) (neg_le_neg hb) hab in ⟨x, hx₁, hx₂, neg_inj hx₃⟩ lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm x hx, hM x hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ end
82eada1ab9b5dd6059a4ed87da5c75de0653f747
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/special_functions/non_integrable.lean
fcb9d043b72076f7a020e831890b2ca71e47103a
[ "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
9,589
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.special_functions.integrals import analysis.calculus.fderiv_measurable /-! # Non integrable functions In this file we prove that the derivative of a function that tends to infinity is not interval integrable, see `interval_integral.not_integrable_has_deriv_at_of_tendsto_norm_at_top_filter` and `interval_integral.not_integrable_has_deriv_at_of_tendsto_norm_at_top_punctured`. Then we apply the latter lemma to prove that the function `λ x, x⁻¹` is integrable on `a..b` if and only if `a = b` or `0 ∉ [a, b]`. ## Main results * `not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_punctured`: if `f` tends to infinity along `𝓝[≠] c` and `f' = O(g)` along the same filter, then `g` is not interval integrable on any nontrivial integral `a..b`, `c ∈ [a, b]`. * `not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_filter`: a version of `not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_punctured` that works for one-sided neighborhoods; * `not_interval_integrable_of_sub_inv_is_O_punctured`: if `1 / (x - c) = O(f)` as `x → c`, `x ≠ c`, then `f` is not interval integrable on any nontrivial interval `a..b`, `c ∈ [a, b]`; * `interval_integrable_sub_inv_iff`, `interval_integrable_inv_iff`: integrability conditions for `(x - c)⁻¹` and `x⁻¹`. ## Tags integrable function -/ open_locale measure_theory topological_space interval nnreal ennreal open measure_theory topological_space set filter asymptotics interval_integral variables {E F : Type*} [normed_add_comm_group E] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [normed_add_comm_group F] /-- If `f` is eventually differentiable along a nontrivial filter `l : filter ℝ` that is generated by convex sets, the norm of `f` tends to infinity along `l`, and `f' = O(g)` along `l`, where `f'` is the derivative of `f`, then `g` is not integrable on any interval `a..b` such that `[a, b] ∈ l`. -/ lemma not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_filter {f : ℝ → E} {g : ℝ → F} {a b : ℝ} (l : filter ℝ) [ne_bot l] [tendsto_Ixx_class Icc l l] (hl : [a, b] ∈ l) (hd : ∀ᶠ x in l, differentiable_at ℝ f x) (hf : tendsto (λ x, ‖f x‖) l at_top) (hfg : deriv f =O[l] g) : ¬interval_integrable g volume a b := begin intro hgi, obtain ⟨C, hC₀, s, hsl, hsub, hfd, hg⟩ : ∃ (C : ℝ) (hC₀ : 0 ≤ C) (s ∈ l), (∀ (x ∈ s) (y ∈ s), [x, y] ⊆ [a, b]) ∧ (∀ (x ∈ s) (y ∈ s) (z ∈ [x, y]), differentiable_at ℝ f z) ∧ (∀ (x ∈ s) (y ∈ s) (z ∈ [x, y]), ‖deriv f z‖ ≤ C * ‖g z‖), { rcases hfg.exists_nonneg with ⟨C, C₀, hC⟩, have h : ∀ᶠ x : ℝ × ℝ in l.prod l, ∀ y ∈ [x.1, x.2], (differentiable_at ℝ f y ∧ ‖deriv f y‖ ≤ C * ‖g y‖) ∧ y ∈ [a, b], from (tendsto_fst.uIcc tendsto_snd).eventually ((hd.and hC.bound).and hl).small_sets, rcases mem_prod_self_iff.1 h with ⟨s, hsl, hs⟩, simp only [prod_subset_iff, mem_set_of_eq] at hs, exact ⟨C, C₀, s, hsl, λ x hx y hy z hz, (hs x hx y hy z hz).2, λ x hx y hy z hz, (hs x hx y hy z hz).1.1, λ x hx y hy z hz, (hs x hx y hy z hz).1.2⟩ }, replace hgi : interval_integrable (λ x, C * ‖g x‖) volume a b, by convert hgi.norm.smul C, obtain ⟨c, hc, d, hd, hlt⟩ : ∃ (c ∈ s) (d ∈ s), ‖f c‖ + ∫ y in Ι a b, C * ‖g y‖ < ‖f d‖, { rcases filter.nonempty_of_mem hsl with ⟨c, hc⟩, have : ∀ᶠ x in l, ‖f c‖ + ∫ y in Ι a b, C * ‖g y‖ < ‖f x‖, from hf.eventually (eventually_gt_at_top _), exact ⟨c, hc, (this.and hsl).exists.imp (λ d hd, ⟨hd.2, hd.1⟩)⟩ }, specialize hsub c hc d hd, specialize hfd c hc d hd, replace hg : ∀ x ∈ Ι c d, ‖deriv f x‖ ≤ C * ‖g x‖, from λ z hz, hg c hc d hd z ⟨hz.1.le, hz.2⟩, have hg_ae : ∀ᵐ x ∂(volume.restrict (Ι c d)), ‖deriv f x‖ ≤ C * ‖g x‖, from (ae_restrict_mem measurable_set_uIoc).mono hg, have hsub' : Ι c d ⊆ Ι a b, from uIoc_subset_uIoc_of_uIcc_subset_uIcc hsub, have hfi : interval_integrable (deriv f) volume c d, from (hgi.mono_set hsub).mono_fun' (ae_strongly_measurable_deriv _ _) hg_ae, refine hlt.not_le (sub_le_iff_le_add'.1 _), calc ‖f d‖ - ‖f c‖ ≤ ‖f d - f c‖ : norm_sub_norm_le _ _ ... = ‖∫ x in c..d, deriv f x‖ : congr_arg _ (integral_deriv_eq_sub hfd hfi).symm ... = ‖∫ x in Ι c d, deriv f x‖ : norm_integral_eq_norm_integral_Ioc _ ... ≤ ∫ x in Ι c d, ‖deriv f x‖ : norm_integral_le_integral_norm _ ... ≤ ∫ x in Ι c d, C * ‖g x‖ : set_integral_mono_on hfi.norm.def (hgi.def.mono_set hsub') measurable_set_uIoc hg ... ≤ ∫ x in Ι a b, C * ‖g x‖ : set_integral_mono_set hgi.def (ae_of_all _ $ λ x, mul_nonneg hC₀ (norm_nonneg _)) hsub'.eventually_le end /-- If `a ≠ b`, `c ∈ [a, b]`, `f` is differentiable in the neighborhood of `c` within `[a, b] \ {c}`, `‖f x‖ → ∞` as `x → c` within `[a, b] \ {c}`, and `f' = O(g)` along `𝓝[[a, b] \ {c}] c`, where `f'` is the derivative of `f`, then `g` is not interval integrable on `a..b`. -/ lemma not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_within_diff_singleton {f : ℝ → E} {g : ℝ → F} {a b c : ℝ} (hne : a ≠ b) (hc : c ∈ [a, b]) (h_deriv : ∀ᶠ x in 𝓝[[a, b] \ {c}] c, differentiable_at ℝ f x) (h_infty : tendsto (λ x, ‖f x‖) (𝓝[[a, b] \ {c}] c) at_top) (hg : deriv f =O[𝓝[[a, b] \ {c}] c] g) : ¬interval_integrable g volume a b := begin obtain ⟨l, hl, hl', hle, hmem⟩ : ∃ l : filter ℝ, tendsto_Ixx_class Icc l l ∧ l.ne_bot ∧ l ≤ 𝓝 c ∧ [a, b] \ {c} ∈ l, { cases (min_lt_max.2 hne).lt_or_lt c with hlt hlt, { refine ⟨𝓝[<] c, infer_instance, infer_instance, inf_le_left, _⟩, rw ← Iic_diff_right, exact diff_mem_nhds_within_diff (Icc_mem_nhds_within_Iic ⟨hlt, hc.2⟩) _ }, { refine ⟨𝓝[>] c, infer_instance, infer_instance, inf_le_left, _⟩, rw ← Ici_diff_left, exact diff_mem_nhds_within_diff (Icc_mem_nhds_within_Ici ⟨hc.1, hlt⟩) _ } }, resetI, have : l ≤ 𝓝[[a, b] \ {c}] c, from le_inf hle (le_principal_iff.2 hmem), exact not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_filter l (mem_of_superset hmem (diff_subset _ _)) (h_deriv.filter_mono this) (h_infty.mono_left this) (hg.mono this), end /-- If `f` is differentiable in a punctured neighborhood of `c`, `‖f x‖ → ∞` as `x → c` (more formally, along the filter `𝓝[≠] c`), and `f' = O(g)` along `𝓝[≠] c`, where `f'` is the derivative of `f`, then `g` is not interval integrable on any nontrivial interval `a..b` such that `c ∈ [a, b]`. -/ lemma not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_punctured {f : ℝ → E} {g : ℝ → F} {a b c : ℝ} (h_deriv : ∀ᶠ x in 𝓝[≠] c, differentiable_at ℝ f x) (h_infty : tendsto (λ x, ‖f x‖) (𝓝[≠] c) at_top) (hg : deriv f =O[𝓝[≠] c] g) (hne : a ≠ b) (hc : c ∈ [a, b]) : ¬interval_integrable g volume a b := have 𝓝[[a, b] \ {c}] c ≤ 𝓝[≠] c, from nhds_within_mono _ (inter_subset_right _ _), not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_within_diff_singleton hne hc (h_deriv.filter_mono this) (h_infty.mono_left this) (hg.mono this) /-- If `f` grows in the punctured neighborhood of `c : ℝ` at least as fast as `1 / (x - c)`, then it is not interval integrable on any nontrivial interval `a..b`, `c ∈ [a, b]`. -/ lemma not_interval_integrable_of_sub_inv_is_O_punctured {f : ℝ → F} {a b c : ℝ} (hf : (λ x, (x - c)⁻¹) =O[𝓝[≠] c] f) (hne : a ≠ b) (hc : c ∈ [a, b]) : ¬interval_integrable f volume a b := begin have A : ∀ᶠ x in 𝓝[≠] c, has_deriv_at (λ x, real.log (x - c)) (x - c)⁻¹ x, { filter_upwards [self_mem_nhds_within] with x hx, simpa using ((has_deriv_at_id x).sub_const c).log (sub_ne_zero.2 hx) }, have B : tendsto (λ x, ‖real.log (x - c)‖) (𝓝[≠] c) at_top, { refine tendsto_abs_at_bot_at_top.comp (real.tendsto_log_nhds_within_zero.comp _), rw ← sub_self c, exact ((has_deriv_at_id c).sub_const c).tendsto_punctured_nhds one_ne_zero }, exact not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_punctured (A.mono (λ x hx, hx.differentiable_at)) B (hf.congr' (A.mono $ λ x hx, hx.deriv.symm) eventually_eq.rfl) hne hc end /-- The function `λ x, (x - c)⁻¹` is integrable on `a..b` if and only if `a = b` or `c ∉ [a, b]`. -/ @[simp] lemma interval_integrable_sub_inv_iff {a b c : ℝ} : interval_integrable (λ x, (x - c)⁻¹) volume a b ↔ a = b ∨ c ∉ [a, b] := begin split, { refine λ h, or_iff_not_imp_left.2 (λ hne hc, _), exact not_interval_integrable_of_sub_inv_is_O_punctured (is_O_refl _ _) hne hc h }, { rintro (rfl|h₀), exacts [interval_integrable.refl, interval_integrable_inv (λ x hx, sub_ne_zero.2 $ ne_of_mem_of_not_mem hx h₀) (continuous_on_id.sub continuous_on_const)] } end /-- The function `λ x, x⁻¹` is integrable on `a..b` if and only if `a = b` or `0 ∉ [a, b]`. -/ @[simp] lemma interval_integrable_inv_iff {a b : ℝ} : interval_integrable (λ x, x⁻¹) volume a b ↔ a = b ∨ (0 : ℝ) ∉ [a, b] := by simp only [← interval_integrable_sub_inv_iff, sub_zero]
f9856f9bea2eee426f018adb96197bfe6f4edccc
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/targets/src/a.lean
c0ca18a5397ea37b0a55f3662882cc0c1835490d
[ "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
61
lean
import Foo def main : IO PUnit := IO.println s!"a: {foo}"
0994b73be5e1f8f19e75dd91408441ab07254c9c
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/data/zmod/quadratic_reciprocity.lean
3fed224c6409d82c182ad1426fb4bc00ee908adb
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
23,106
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 data.zmod.basic 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_pow_two_eq_prime_iff_of_mod_four_eq_one`, and `exists_pow_two_eq_prime_iff_of_mod_four_eq_three`. Also proven are conditions for `-1` and `2` to be a square modulo a prime, `exists_pow_two_eq_neg_one_iff_mod_four_ne_three` and `exists_pow_two_eq_two_iff` ## Implementation notes The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma -/ open function finset nat finite_field zmodp namespace zmodp variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q) @[simp] lemma card_units_zmodp : fintype.card (units (zmodp p hp)) = p - 1 := by rw [card_units, card_zmodp] theorem fermat_little {p : ℕ} (hp : nat.prime p) {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p - 1) = 1 := by rw [← units.mk0_val ha, ← @units.coe_one (zmodp p hp), ← units.coe_pow, ← units.ext_iff, ← card_units_zmodp hp, pow_card_eq_one] lemma euler_criterion_units {x : units (zmodp p hp)} : (∃ y : units (zmodp p hp), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := hp.eq_two_or_odd.elim (λ h, by resetI; subst h; revert x; exact dec_trivial) (λ hp1, let ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmodp p hp)) in let ⟨n, hn⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in ⟨λ ⟨y, hy⟩, by rw [← hy, ← pow_mul, two_mul_odd_div_two hp1, ← card_units_zmodp hp, pow_card_eq_one], λ hx, have 2 * (p / 2) ∣ n * (p / 2), by rw [two_mul_odd_div_two hp1, ← card_units_zmodp hp, ← order_of_eq_card_of_forall_mem_gpowers hg]; exact order_of_dvd_of_pow_eq_one (by rwa [pow_mul, hn]), let ⟨m, hm⟩ := dvd_of_mul_dvd_mul_right (nat.div_pos hp.two_le dec_trivial) this in ⟨g ^ m, by rwa [← pow_mul, mul_comm, ← hm]⟩⟩) lemma euler_criterion {a : zmodp p hp} (ha : a ≠ 0) : (∃ y : zmodp p hp, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := ⟨λ ⟨y, hy⟩, have hy0 : y ≠ 0, from λ h, by simp [h, _root_.zero_pow (succ_pos 1)] at hy; cc, by simpa using (units.ext_iff.1 $ (euler_criterion_units hp).1 ⟨units.mk0 _ hy0, show _ = units.mk0 _ ha, by rw [units.ext_iff]; simpa⟩), λ h, let ⟨y, hy⟩ := (euler_criterion_units hp).2 (show units.mk0 _ ha ^ (p / 2) = 1, by simpa [units.ext_iff]) in ⟨y, by simpa [units.ext_iff] using hy⟩⟩ lemma exists_pow_two_eq_neg_one_iff_mod_four_ne_three : (∃ y : zmodp p hp, y ^ 2 = -1) ↔ p % 4 ≠ 3 := have (-1 : zmodp p hp) ≠ 0, from mt neg_eq_zero.1 one_ne_zero, hp.eq_two_or_odd.elim (λ hp, by resetI; subst hp; exact dec_trivial) (λ hp1, (mod_two_eq_zero_or_one (p / 2)).elim (λ hp2, begin rw [euler_criterion hp this, neg_one_pow_eq_pow_mod_two, hp2, _root_.pow_zero, eq_self_iff_true, true_iff], assume h, rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, h] at hp2, exact absurd hp2 dec_trivial, end) (λ hp2, begin rw [euler_criterion hp this, neg_one_pow_eq_pow_mod_two, hp2, _root_.pow_one, iff_false_intro (zmodp.ne_neg_self hp hp1 one_ne_zero).symm, false_iff, not_not], rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at hp2, rw [← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp1, have hp4 : p % 4 < 4, from nat.mod_lt _ dec_trivial, revert hp1 hp2, revert hp4, generalize : p % 4 = k, revert k, exact dec_trivial end)) lemma pow_div_two_eq_neg_one_or_one {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := hp.eq_two_or_odd.elim (λ h, by revert a ha; resetI; subst h; exact dec_trivial) (λ hp1, by rw [← mul_self_eq_one_iff, ← _root_.pow_add, ← two_mul, two_mul_odd_div_two hp1]; exact fermat_little hp ha) @[simp] lemma wilsons_lemma {p : ℕ} (hp : nat.prime p) : (fact (p - 1) : zmodp p hp) = -1 := begin rw [← finset.prod_Ico_id_eq_fact, ← @units.coe_one (zmodp p hp), ← units.coe_neg, ← @prod_univ_units_id_eq_neg_one (zmodp p hp), ← prod_hom (coe : units (zmodp p hp) → zmodp p hp), ← prod_hom (coe : ℕ → zmodp p hp)], exact eq.symm (prod_bij (λ a _, (a : zmodp p hp).1) (λ a ha, Ico.mem.2 ⟨nat.pos_of_ne_zero (λ h, units.coe_ne_zero a (fin.eq_of_veq h)), by rw [← succ_sub hp.pos, succ_sub_one]; exact (a : zmodp p hp).2⟩) (λ a _, by simp) (λ _ _ _ _, units.ext_iff.2 ∘ fin.eq_of_veq) (λ b hb, have b ≠ 0 ∧ b < p, by rwa [Ico.mem, nat.succ_le_iff, ← succ_sub hp.pos, succ_sub_one, nat.pos_iff_ne_zero] at hb, ⟨units.mk0 _ (show (b : zmodp p hp) ≠ 0, from fin.ne_of_vne $ by rw [zmod.val_cast_nat, ← @nat.cast_zero (zmodp p hp), zmod.val_cast_nat]; simp [mod_eq_of_lt this.2, this.1]), mem_univ _, by simp [val_cast_of_lt hp this.2]⟩)) end @[simp] lemma prod_Ico_one_prime {p : ℕ} (hp : nat.prime p) : (Ico 1 p).prod (λ x, (x : zmodp p hp)) = -1 := by conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub hp.pos] }; rw [prod_hom (coe : ℕ → zmodp p hp), finset.prod_Ico_id_eq_fact, wilsons_lemma] end zmodp /-- 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 : p.prime) (a : zmodp p hp) (hpa : 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) := have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2, by simp [nat.lt_succ_iff, nat.succ_le_iff, nat.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.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 hsurj : ∀ b : ℕ , b ∈ Ico 1 (p / 2).succ → ∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmodp p hp).val_min_abs.nat_abs, from λ b hb, ⟨(b / a : zmodp p hp).val_min_abs.nat_abs, Ico.mem.2 ⟨nat.pos_of_ne_zero $ by simp [div_eq_mul_inv, hpa, zmodp.eq_zero_iff_dvd_nat hp b, hpe hb], nat.lt_succ_of_le $ zmodp.nat_abs_val_min_abs_le _⟩, begin rw [zmodp.cast_nat_abs_val_min_abs], split_ifs, { erw [mul_div_cancel' _ hpa, zmodp.val_min_abs, zmod.val_min_abs, zmodp.val_cast_of_lt hp (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat], }, { erw [mul_neg_eq_neg_mul_symm, mul_div_cancel' _ hpa, zmod.nat_abs_val_min_abs_neg, zmod.val_min_abs, zmodp.val_cast_of_lt hp (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat] }, end⟩, have hmem : ∀ x : ℕ, x ∈ Ico 1 (p / 2).succ → (a * x : zmodp p hp).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ, from λ x hx, by simp [hpa, zmodp.eq_zero_iff_dvd_nat hp x, hpe hx, lt_succ_iff, succ_le_iff, nat.pos_iff_ne_zero, zmodp.nat_abs_val_min_abs_le _], multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _) (λ x _, (a * x : zmodp p hp).val_min_abs.nat_abs) hmem (λ _ _, rfl) (inj_on_of_surj_on_of_card_le _ hmem hsurj (le_refl _)) hsurj private lemma gauss_lemma_aux₁ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (hpa : (a : zmodp p hp) ≠ 0) : (a^(p / 2) * (p / 2).fact : zmodp p hp) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmodp p hp).val ≤ p / 2)).card * (p / 2).fact := calc (a ^ (p / 2) * (p / 2).fact : zmodp p hp) = (Ico 1 (p / 2).succ).prod (λ x, a * x) : by rw [prod_mul_distrib, ← prod_nat_cast, ← prod_nat_cast, prod_Ico_id_eq_fact, prod_const, Ico.card, succ_sub_one]; simp ... = (Ico 1 (p / 2).succ).prod (λ x, (a * x : zmodp p hp).val) : by simp ... = (Ico 1 (p / 2).succ).prod (λ x, (if (a * x : zmodp p hp).val ≤ p / 2 then 1 else -1) * (a * x : zmodp p hp).val_min_abs.nat_abs) : prod_congr rfl $ λ _ _, begin simp only [zmodp.cast_nat_abs_val_min_abs], split_ifs; simp end ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmodp p hp).val ≤ p / 2)).card * (Ico 1 (p / 2).succ).prod (λ x, (a * x : zmodp p hp).val_min_abs.nat_abs) : have (Ico 1 (p / 2).succ).prod (λ x, if (a * x : zmodp p hp).val ≤ p / 2 then (1 : zmodp p hp) else -1) = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmodp p hp).val ≤ p / 2)).prod (λ _, -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 : zmodp p hp).val ≤ p / 2)).card * (p / 2).fact : by rw [← prod_nat_cast, finset.prod_eq_multiset_prod, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id hp a hpa, ← finset.prod_eq_multiset_prod, prod_Ico_id_eq_fact] private lemma gauss_lemma_aux₂ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (hpa : (a : zmodp p hp) ≠ 0) : (a^(p / 2) : zmodp p hp) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card := (domain.mul_right_inj (show ((p / 2).fact : zmodp p hp) ≠ 0, by rw [ne.def, zmodp.eq_zero_iff_dvd_nat, hp.dvd_fact, not_le]; exact nat.div_lt_self hp.pos dec_trivial)).1 $ by simpa using gauss_lemma_aux₁ _ hp2 hpa private lemma eisenstein_lemma_aux₁ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (hap : (a : zmodp p hp) ≠ 0) : (((Ico 1 (p / 2).succ).sum (λ x, a * x) : ℕ) : zmod 2) = ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmodp p hp).val))).card + (Ico 1 (p / 2).succ).sum (λ x, x) + ((Ico 1 (p / 2).succ).sum (λ x, (a * x) / p) : ℕ) := have hp2 : (p : zmod 2) = (1 : ℕ), from zmod.eq_iff_modeq_nat.2 hp2, calc (((Ico 1 (p / 2).succ).sum (λ x, a * x) : ℕ) : zmod 2) = (((Ico 1 (p / 2).succ).sum (λ x, (a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) : by simp only [mod_add_div] ... = ((Ico 1 (p / 2).succ).sum (λ x, ((a * x : ℕ) : zmodp p hp).val) : ℕ) + ((Ico 1 (p / 2).succ).sum (λ x, (a * x) / p) : ℕ) : by simp only [zmodp.val_cast_nat]; simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, sum_nat_cast, hp2] ... = _ : congr_arg2 (+) (calc (((Ico 1 (p / 2).succ).sum (λ x, ((a * x : ℕ) : zmodp p hp).val) : ℕ) : zmod 2) = (Ico 1 (p / 2).succ).sum (λ x, ((((a * x : zmodp p hp).val_min_abs + (if (a * x : zmodp p hp).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2)) : by simp only [(zmodp.val_eq_ite_val_min_abs _).symm]; simp [sum_nat_cast] ... = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card + (((Ico 1 (p / 2).succ).sum (λ x, (a * x : zmodp p hp).val_min_abs.nat_abs)) : ℕ) : by simp [sum_add_distrib, finset.sum_ite, hp2, sum_nat_cast] ... = _ : by rw [finset.sum_eq_multiset_sum, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id hp _ hap, ← finset.sum_eq_multiset_sum]; simp [sum_nat_cast]) rfl private lemma eisenstein_lemma_aux₂ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmodp p hp) ≠ 0) : ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmodp p hp).val))).card ≡ (Ico 1 (p / 2).succ).sum (λ x, (x * a) / p) [MOD 2] := have ha2 : (a : zmod 2) = (1 : ℕ), from zmod.eq_iff_modeq_nat.2 ha2, (@zmod.eq_iff_modeq_nat 2 _ _).1 $ sub_eq_zero.1 $ by simpa [finset.mul_sum.symm, mul_comm, ha2, sum_nat_cast, add_neg_eq_iff_eq_add.symm, zmod.neg_eq_self_mod_two] using eq.symm (eisenstein_lemma_aux₁ hp hp2 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.2 $ λ 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 integers point 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 : ℕ} : (Ico 1 (p / 2).succ).sum (λ a, (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] else calc (Ico 1 (p / 2).succ).sum (λ a, (a * q) / p) = (Ico 1 (p / 2).succ).sum (λ a, ((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 {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp {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 : p.prime) (hq0 : (q : zmodp p hp) ≠ 0) : (Ico 1 (p / 2).succ).sum (λ a, (a * q) / p) + (Ico 1 (q / 2).succ).sum (λ a, (a * p) / q) = (p / 2) * (q / 2) := 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 {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp {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)), from 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 [*, nat.lt_succ_iff] at *; tauto) (nat.div_lt_self hp.pos dec_trivial), begin have : (x.1 : zmodp p hp) = 0, { simpa [hq0] using congr_arg (coe : ℕ → zmodp p hp) (le_antisymm hpq hqp) }, rw [fin.eq_iff_veq, zmodp.val_cast_of_lt hp hxp, zmodp.zero_val] at this, simp * at * end, 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.2 $ λ x, by have := le_total (x.2 * p) (x.1 * q); simp; tauto, by rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product]; simp variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q) namespace zmodp def legendre_sym (a p : ℕ) (hp : nat.prime p) : ℤ := if (a : zmodp p hp) = 0 then 0 else if ∃ b : zmodp p hp, b ^ 2 = a then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) (hp : nat.prime p) : (legendre_sym a p hp : zmodp p hp) = (a ^ (p / 2)) := if ha : (a : zmodp p hp) = 0 then by simp [*, legendre_sym, _root_.zero_pow (nat.div_pos hp.two_le (succ_pos 1))] else (nat.prime.eq_two_or_odd hp).elim (λ hp2, begin resetI; subst hp2, suffices : ∀ a : zmodp 2 nat.prime_two, (((ite (a = 0) 0 (ite (∃ (b : zmodp 2 hp), b ^ 2 = a) 1 (-1))) : ℤ) : zmodp 2 nat.prime_two) = a ^ (2 / 2), { exact this a }, exact dec_trivial, end) (λ hp1, have _ := euler_criterion hp ha, have (-1 : zmodp p hp) ≠ 1, from (ne_neg_self hp hp1 zero_ne_one.symm).symm, by cases zmodp.pow_div_two_eq_neg_one_or_one hp ha; simp [legendre_sym, *] at *) lemma legendre_sym_eq_one_or_neg_one (a : ℕ) (hp : nat.prime p) (ha : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = -1 ∨ legendre_sym a p hp = 1 := by unfold legendre_sym; split_ifs; simp * at * /-- 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 : ℕ} (hp1 : p % 2 = 1) (ha0 : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card := have (legendre_sym a p hp : zmodp p hp) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card : ℤ) : zmodp p hp), by rw [legendre_sym_eq_pow, gauss_lemma_aux₂ hp hp1 ha0]; simp, begin cases legendre_sym_eq_one_or_neg_one a hp ha0; cases @neg_one_pow_eq_or ℤ _ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card; simp [*, zmodp.ne_neg_self hp hp1 one_ne_zero, (zmodp.ne_neg_self hp hp1 one_ne_zero).symm] at * end lemma legendre_sym_eq_one_iff {a : ℕ} (ha0 : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = 1 ↔ (∃ b : zmodp p hp, b ^ 2 = a) := by rw [legendre_sym]; split_ifs; finish lemma eisenstein_lemma (hp1 : p % 2 = 1) {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = (-1)^(Ico 1 (p / 2).succ).sum (λ x, (x * a) / p) := by rw [neg_one_pow_eq_pow_mod_two, gauss_lemma hp hp1 ha0, neg_one_pow_eq_pow_mod_two, show _ = _, from eisenstein_lemma_aux₂ hp hp1 ha1 ha0] theorem quadratic_reciprocity (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) : legendre_sym p q hq * legendre_sym q p hp = (-1) ^ ((p / 2) * (q / 2)) := have hpq0 : (p : zmodp q hq) ≠ 0, from zmodp.prime_ne_zero _ hp hpq.symm, have hqp0 : (q : zmodp p hp) ≠ 0, from zmodp.prime_ne_zero _ hq hpq, by rw [eisenstein_lemma _ hq1 hp1 hpq0, eisenstein_lemma _ hp1 hq1 hqp0, ← _root_.pow_add, sum_mul_div_add_sum_mul_div_eq_mul _ hpq0, mul_comm] lemma legendre_sym_two (hp1 : p % 2 = 1) : legendre_sym 2 p hp = (-1) ^ (p / 4 + p / 2) := have hp2 : p ≠ 2, from mt (congr_arg (% 2)) (by simp [hp1]), 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 : zmodp p hp).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 [← mod_add_div p 2, add_comm, hp1]}; exact lt_succ_self _, by rw [← nat.cast_two, ← nat.cast_mul, zmodp.val_cast_of_lt _ h2xp], have hdisj : disjoint ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmodp p hp).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 : zmodp p hp).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 _ hp1 (prime_ne_zero hp prime_two hp2), neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)], refine congr_arg2 _ rfl ((@zmod.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, zmod.neg_eq_self_mod_two, ← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard] end lemma exists_pow_two_eq_two_iff (hp1 : p % 2 = 1) : (∃ a : zmodp p hp, a ^ 2 = 2) ↔ p % 8 = 1 ∨ p % 8 = 7 := have hp2 : ((2 : ℕ) : zmodp p hp) ≠ 0, from zmodp.prime_ne_zero hp prime_two (λ h, by simp * at *), 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 : zmodp p hp) = (2 : ℕ), by simp, ← legendre_sym_eq_one_iff hp hp2, legendre_sym_two hp hp1, 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), revert this hp1, erw [hpm4, hpm2], generalize hm : p % 8 = m, clear hm, revert m, exact dec_trivial end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) (hq1 : q % 2 = 1) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ∃ b : zmodp q hq, b ^ 2 = p := if hpq : p = q then by resetI; subst 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 have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_one hp1) hq1 hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp (ne.symm hpq))] at this, split_ifs at this; simp *; contradiction end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ¬∃ b : zmodp q hq, 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 have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_three hp3) (odd_of_mod_four_eq_three hq3) hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp hpq.symm)] at this, split_ifs at this; simp *; contradiction end end zmodp
be29f374bddeb5cc9a5472fc6029c9e50f5d7677
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/category/Profinite/default.lean
7d6f670dd4df5fb05477faf61be4a7790ee6b3e8
[ "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
11,329
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Calle Sönne -/ import topology.category.CompHaus import topology.connected import topology.subset_properties import topology.locally_constant.basic import category_theory.adjunction.reflective import category_theory.monad.limits import category_theory.limits.constructions.epi_mono import category_theory.Fintype /-! # The category of Profinite Types We construct the category of profinite topological spaces, often called profinite sets -- perhaps they could be called profinite types in Lean. The type of profinite topological spaces is called `Profinite`. It has a category instance and is a fully faithful subcategory of `Top`. The fully faithful functor is called `Profinite_to_Top`. ## Implementation notes A profinite type is defined to be a topological space which is compact, Hausdorff and totally disconnected. ## TODO 0. Link to category of projective limits of finite discrete sets. 1. finite coproducts 2. Clausen/Scholze topology on the category `Profinite`. ## Tags profinite -/ universe u open category_theory /-- The type of profinite topological spaces. -/ structure Profinite := (to_CompHaus : CompHaus) [is_totally_disconnected : totally_disconnected_space to_CompHaus] namespace Profinite /-- Construct a term of `Profinite` from a type endowed with the structure of a compact, Hausdorff and totally disconnected topological space. -/ def of (X : Type*) [topological_space X] [compact_space X] [t2_space X] [totally_disconnected_space X] : Profinite := ⟨⟨⟨X⟩⟩⟩ instance : inhabited Profinite := ⟨Profinite.of pempty⟩ instance category : category Profinite := induced_category.category to_CompHaus instance concrete_category : concrete_category Profinite := induced_category.concrete_category _ instance has_forget₂ : has_forget₂ Profinite Top := induced_category.has_forget₂ _ instance : has_coe_to_sort Profinite Type* := ⟨λ X, X.to_CompHaus⟩ instance {X : Profinite} : totally_disconnected_space X := X.is_totally_disconnected -- We check that we automatically infer that Profinite sets are compact and Hausdorff. example {X : Profinite} : compact_space X := infer_instance example {X : Profinite} : t2_space X := infer_instance @[simp] lemma coe_to_CompHaus {X : Profinite} : (X.to_CompHaus : Type*) = X := rfl @[simp] lemma coe_id (X : Profinite) : (𝟙 X : X → X) = id := rfl @[simp] lemma coe_comp {X Y Z : Profinite} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g : X → Z) = g ∘ f := rfl end Profinite /-- The fully faithful embedding of `Profinite` in `CompHaus`. -/ @[simps, derive [full, faithful]] def Profinite_to_CompHaus : Profinite ⥤ CompHaus := induced_functor _ /-- The fully faithful embedding of `Profinite` in `Top`. This is definitionally the same as the obvious composite. -/ @[simps, derive [full, faithful]] def Profinite.to_Top : Profinite ⥤ Top := forget₂ _ _ @[simp] lemma Profinite.to_CompHaus_to_Top : Profinite_to_CompHaus ⋙ CompHaus_to_Top = Profinite.to_Top := rfl section Profinite local attribute [instance] connected_component_setoid /-- (Implementation) The object part of the connected_components functor from compact Hausdorff spaces to Profinite spaces, given by quotienting a space by its connected components. See: https://stacks.math.columbia.edu/tag/0900 -/ -- Without explicit universe annotations here, Lean introduces two universe variables and -- unhelpfully defines a function `CompHaus.{max u₁ u₂} → Profinite.{max u₁ u₂}`. def CompHaus.to_Profinite_obj (X : CompHaus.{u}) : Profinite.{u} := { to_CompHaus := { to_Top := Top.of (connected_components X), is_compact := quotient.compact_space, is_hausdorff := connected_components.t2 }, is_totally_disconnected := connected_components.totally_disconnected_space } /-- (Implementation) The bijection of homsets to establish the reflective adjunction of Profinite spaces in compact Hausdorff spaces. -/ def Profinite.to_CompHaus_equivalence (X : CompHaus.{u}) (Y : Profinite.{u}) : (CompHaus.to_Profinite_obj X ⟶ Y) ≃ (X ⟶ Profinite_to_CompHaus.obj Y) := { to_fun := λ f, { to_fun := f.1 ∘ quotient.mk, continuous_to_fun := continuous.comp f.2 (continuous_quotient_mk) }, inv_fun := λ g, { to_fun := continuous.connected_components_lift g.2, continuous_to_fun := continuous.connected_components_lift_continuous g.2}, left_inv := λ f, continuous_map.ext $ λ x, quotient.induction_on x $ λ a, rfl, right_inv := λ f, continuous_map.ext $ λ x, rfl } /-- The connected_components functor from compact Hausdorff spaces to profinite spaces, left adjoint to the inclusion functor. -/ def CompHaus.to_Profinite : CompHaus ⥤ Profinite := adjunction.left_adjoint_of_equiv Profinite.to_CompHaus_equivalence (λ _ _ _ _ _, rfl) lemma CompHaus.to_Profinite_obj' (X : CompHaus) : ↥(CompHaus.to_Profinite.obj X) = connected_components X := rfl /-- Finite types are given the discrete topology. -/ def Fintype.discrete_topology (A : Fintype) : topological_space A := ⊥ section discrete_topology local attribute [instance] Fintype.discrete_topology /-- The natural functor from `Fintype` to `Profinite`, endowing a finite type with the discrete topology. -/ @[simps] def Fintype.to_Profinite : Fintype ⥤ Profinite := { obj := λ A, Profinite.of A, map := λ _ _ f, ⟨f⟩ } end discrete_topology end Profinite namespace Profinite /-- An explicit limit cone for a functor `F : J ⥤ Profinite`, defined in terms of `Top.limit_cone`. -/ def limit_cone {J : Type u} [small_category J] (F : J ⥤ Profinite.{u}) : limits.cone F := { X := { to_CompHaus := (CompHaus.limit_cone (F ⋙ Profinite_to_CompHaus)).X, is_totally_disconnected := begin change totally_disconnected_space ↥{u : Π (j : J), (F.obj j) | _}, exact subtype.totally_disconnected_space, end }, π := { app := (CompHaus.limit_cone (F ⋙ Profinite_to_CompHaus)).π.app } } /-- The limit cone `Profinite.limit_cone F` is indeed a limit cone. -/ def limit_cone_is_limit {J : Type u} [small_category J] (F : J ⥤ Profinite.{u}) : limits.is_limit (limit_cone F) := { lift := λ S, (CompHaus.limit_cone_is_limit (F ⋙ Profinite_to_CompHaus)).lift (Profinite_to_CompHaus.map_cone S), uniq' := λ S m h, (CompHaus.limit_cone_is_limit _).uniq (Profinite_to_CompHaus.map_cone S) _ h } /-- The adjunction between CompHaus.to_Profinite and Profinite.to_CompHaus -/ def to_Profinite_adj_to_CompHaus : CompHaus.to_Profinite ⊣ Profinite_to_CompHaus := adjunction.adjunction_of_equiv_left _ _ /-- The category of profinite sets is reflective in the category of compact hausdroff spaces -/ instance to_CompHaus.reflective : reflective Profinite_to_CompHaus := { to_is_right_adjoint := ⟨CompHaus.to_Profinite, Profinite.to_Profinite_adj_to_CompHaus⟩ } noncomputable instance to_CompHaus.creates_limits : creates_limits Profinite_to_CompHaus := monadic_creates_limits _ noncomputable instance to_Top.reflective : reflective Profinite.to_Top := reflective.comp Profinite_to_CompHaus CompHaus_to_Top noncomputable instance to_Top.creates_limits : creates_limits Profinite.to_Top := monadic_creates_limits _ instance has_limits : limits.has_limits Profinite := has_limits_of_has_limits_creates_limits Profinite.to_Top instance has_colimits : limits.has_colimits Profinite := has_colimits_of_reflective Profinite_to_CompHaus noncomputable instance forget_preserves_limits : limits.preserves_limits (forget Profinite) := by apply limits.comp_preserves_limits Profinite.to_Top (forget Top) variables {X Y : Profinite.{u}} (f : X ⟶ Y) /-- Any morphism of profinite spaces is a closed map. -/ lemma is_closed_map : is_closed_map f := CompHaus.is_closed_map _ /-- Any continuous bijection of profinite spaces induces an isomorphism. -/ lemma is_iso_of_bijective (bij : function.bijective f) : is_iso f := begin haveI := CompHaus.is_iso_of_bijective (Profinite_to_CompHaus.map f) bij, exact is_iso_of_fully_faithful Profinite_to_CompHaus _ end /-- Any continuous bijection of profinite spaces induces an isomorphism. -/ noncomputable def iso_of_bijective (bij : function.bijective f) : X ≅ Y := by letI := Profinite.is_iso_of_bijective f bij; exact as_iso f instance forget_reflects_isomorphisms : reflects_isomorphisms (forget Profinite) := ⟨by introsI A B f hf; exact Profinite.is_iso_of_bijective _ ((is_iso_iff_bijective f).mp hf)⟩ /-- Construct an isomorphism from a homeomorphism. -/ @[simps hom inv] def iso_of_homeo (f : X ≃ₜ Y) : X ≅ Y := { hom := ⟨f, f.continuous⟩, inv := ⟨f.symm, f.symm.continuous⟩, hom_inv_id' := by { ext x, exact f.symm_apply_apply x }, inv_hom_id' := by { ext x, exact f.apply_symm_apply x } } /-- Construct a homeomorphism from an isomorphism. -/ @[simps] def homeo_of_iso (f : X ≅ Y) : X ≃ₜ Y := { to_fun := f.hom, inv_fun := f.inv, left_inv := λ x, by { change (f.hom ≫ f.inv) x = x, rw [iso.hom_inv_id, coe_id, id.def] }, right_inv := λ x, by { change (f.inv ≫ f.hom) x = x, rw [iso.inv_hom_id, coe_id, id.def] }, continuous_to_fun := f.hom.continuous, continuous_inv_fun := f.inv.continuous } /-- The equivalence between isomorphisms in `Profinite` and homeomorphisms of topological spaces. -/ @[simps] def iso_equiv_homeo : (X ≅ Y) ≃ (X ≃ₜ Y) := { to_fun := homeo_of_iso, inv_fun := iso_of_homeo, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } lemma epi_iff_surjective {X Y : Profinite.{u}} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin split, { contrapose!, rintros ⟨y, hy⟩ hf, let C := set.range f, have hC : is_closed C := (is_compact_range f.continuous).is_closed, let U := Cᶜ, have hU : is_open U := is_open_compl_iff.mpr hC, have hyU : y ∈ U, { refine set.mem_compl _, rintro ⟨y', hy'⟩, exact hy y' hy' }, have hUy : U ∈ nhds y := hU.mem_nhds hyU, obtain ⟨V, hV, hyV, hVU⟩ := is_topological_basis_clopen.mem_nhds_iff.mp hUy, classical, letI : topological_space (ulift.{u} $ fin 2) := ⊥, let Z := of (ulift.{u} $ fin 2), let g : Y ⟶ Z := ⟨(locally_constant.of_clopen hV).map ulift.up, locally_constant.continuous _⟩, let h : Y ⟶ Z := ⟨λ _, ⟨1⟩, continuous_const⟩, have H : h = g, { rw ← cancel_epi f, ext x, dsimp [locally_constant.of_clopen], rw if_neg, { refl }, refine mt (λ α, hVU α) _, simp only [set.mem_range_self, not_true, not_false_iff, set.mem_compl_eq], }, apply_fun (λ e, (e y).down) at H, dsimp [locally_constant.of_clopen] at H, rw if_pos hyV at H, exact top_ne_bot H }, { rw ← category_theory.epi_iff_surjective, apply faithful_reflects_epi (forget Profinite) }, end lemma mono_iff_injective {X Y : Profinite.{u}} (f : X ⟶ Y) : mono f ↔ function.injective f := begin split, { intro h, haveI : limits.preserves_limits Profinite_to_CompHaus := infer_instance, haveI : mono (Profinite_to_CompHaus.map f) := infer_instance, rwa ← CompHaus.mono_iff_injective }, { rw ← category_theory.mono_iff_injective, apply faithful_reflects_mono (forget Profinite) } end end Profinite
d70b1fe031cf3620502ad47f99c2959a066d42db
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/set_theory/cardinal.lean
7d4d5e54a2c35b41e508050f984c075e94eafe49
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
48,181
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Floris van Doorn -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. ## Main definitions * `cardinal` the type of cardinal numbers (in a given universe). * `cardinal.mk α` or `#α` is the cardinality of `α`. The notation `#` lives in the locale `cardinal`. * There is an instance that `cardinal` forms a `canonically_ordered_comm_semiring`. * Addition `c₁ + c₂` is defined by `cardinal.add_def α β : #α + #β = #(α ⊕ β)`. * Multiplication `c₁ * c₂` is defined by `cardinal.mul_def : #α * #β = #(α * β)`. * The order `c₁ ≤ c₂` is defined by `cardinal.le_def α β : #α ≤ #β ↔ nonempty (α ↪ β)`. * Exponentiation `c₁ ^ c₂` is defined by `cardinal.power_def α β : #α ^ #β = #(β → α)`. * `cardinal.omega` the cardinality of `ℕ`. This definition is universe polymorphic: `cardinal.omega.{u} : cardinal.{u}` (contrast with `ℕ : Type`, which lives in a specific universe). In some cases the universe level has to be given explicitly. * `cardinal.min (I : nonempty ι) (c : ι → cardinal)` is the minimal cardinal in the range of `c`. * `cardinal.succ c` is the successor cardinal, the smallest cardinal larger than `c`. * `cardinal.sum` is the sum of a collection of cardinals. * `cardinal.sup` is the supremum of a collection of cardinals. * `cardinal.powerlt c₁ c₂` or `c₁ ^< c₂` is defined as `sup_{γ < β} α^γ`. ## Main Statements * Cantor's theorem: `cardinal.cantor c : c < 2 ^ c`. * König's theorem: `cardinal.sum_lt_prod` ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. The operation `cardinal.lift` lifts cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/cardinal_ordinal.lean`. * There is an instance `has_pow cardinal`, but this will only fire if Lean already knows that both the base and the exponent live in the same universe. As a workaround, you can add ``` local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow ``` to a file. This notation will work even if Lean doesn't know yet that the base and the exponent live in the same universe (but no exponents in other types can be used). ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega, Cantor's theorem, König's theorem -/ open function set open_locale classical universes u v w x variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk localized "notation `#` := cardinal.mk" in cardinal protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ /-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem le_def (α β : Type u) : mk α ≤ mk β ↔ nonempty (α ↪ β) := iff.rfl theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } protected lemma eq_congr : α ≃ β → # α = # β := λ h, quot.sound ⟨h⟩ noncomputable instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total, decidable_le := classical.dec_rel _ } noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance -- short-circuit type class inference instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : nontrivial cardinal.{u} := ⟨⟨1, 0, ne_zero_iff_nonempty.2 ⟨punit.star⟩⟩⟩ theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ theorem one_lt_iff_nontrivial {α : Type u} : 1 < mk α ↔ nontrivial α := by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp } instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : cardinal.{u}} : a * b = 0 → a = 0 ∨ b = 0 := begin refine quotient.induction_on b _, refine quotient.induction_on a _, intros a b h, contrapose h, simp_rw [not_or_distrib, ← ne.def] at h, have := @prod.nonempty a b (ne_zero_iff_nonempty.mp h.1) (ne_zero_iff_nonempty.mp h.2), exact ne_zero_iff_nonempty.mpr this end instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) @[simp] lemma pow_cast_right (κ : cardinal.{u}) : ∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n | 0 := by simp | (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right] section order_properties open sum protected theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ protected theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩ protected theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := cardinal.add_le_add (le_refl _) protected theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ cardinal.add_le_add_left _ (cardinal.zero_le _)⟩ instance : order_bot cardinal.{u} := { bot := 0, bot_le := cardinal.zero_le, ..cardinal.linear_order } instance : canonically_ordered_comm_semiring cardinal.{u} := { add_le_add_left := λ a b h c, cardinal.add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (cardinal.add_le_add_left _), le_iff_exists_add := @cardinal.le_iff_exists_add, eq_zero_or_eq_zero_of_mul_eq_zero := @cardinal.eq_zero_or_eq_zero_of_mul_eq_zero, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } noncomputable instance : canonically_linear_ordered_add_monoid cardinal.{u} := { .. (infer_instance : canonically_ordered_add_monoid cardinal.{u}), .. cardinal.linear_order } @[simp] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact le_trans (power_le_power_left ha h) (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ end order_properties theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.min_injective _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.min_injective _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩), cases not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.injective h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le } /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨(embedding.refl _).sigma_map $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 := by { rw [← nonpos_iff_eq_zero, sup_le], intro x, exfalso, exact h x } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin suffices : nonempty (Π i, (f i).out) ↔ ∀ i, nonempty (f i).out, { simpa [← ne_zero_iff_nonempty, prod] }, exact classical.nonempty_pi end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b := calc lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{(max u v) w} (lift.{u v} a) = lift.{(max u v) w} (lift.{v u} b) : by simp ... ↔ lift.{u v} a = lift.{v u} b : lift_inj theorem mk_prod {α : Type u} {β : Type v} : mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) := quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩ theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) : sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a := begin apply quotient.induction_on a, intro α, simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id], convert mk_prod using 1, exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩, end /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) lemma mk_nat : mk nat = omega := (lift_id _).symm theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /- properties about the cast from nat -/ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n := by rw [← lift_nat_cast.{u v} n, lift_inj] lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a := by rw [← lift_nat_cast.{u v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [pow_succ', -_root_.add_comm, power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, by simpa only [fintype.card_fin] using fintype.card_le_of_injective f hf, λ h, ⟨(fin.cast_le h).to_embedding⟩⟩ @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ 0 = 1 := by norm_cast theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) : # α ≤ n := begin refine lt_succ.1 (lt_of_not_ge $ λ hn, _), rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn, cases hn with f, refine not_lt_of_le (H $ finset.univ.map f) _, rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin], exact n.lt_succ_self end theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨coe, λ a b, fin.ext⟩⟩ @[simp] theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega := ⟨λ h, ⟨lt_of_le_of_lt (self_le_add_right _ _) h, lt_of_le_of_lt (self_le_add_left _ _) h⟩, λ⟨h1, h2⟩, add_lt_omega h1 h2⟩ theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega := begin split, { intro h, by_cases ha : a = 0, { left, exact ha }, right, by_cases hb : b = 0, { left, exact hb }, right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split, { rw [← mul_one a], refine lt_of_le_of_lt (canonically_ordered_semiring.mul_le_mul (le_refl a) hb) h }, { rw [← _root_.one_mul b], refine lt_of_le_of_lt (canonically_ordered_semiring.mul_le_mul ha (le_refl b)) h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero] end lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < omega ↔ a < omega ∧ b < omega := by simp [mul_lt_omega_iff, ha, hb] theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end lemma eq_one_iff_subsingleton_and_nonempty {α : Type*} : mk α = 1 ↔ (subsingleton α ∧ nonempty α) := calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt ... ↔ subsingleton α ∧ nonempty α : begin apply and_congr le_one_iff_subsingleton, push_neg, rw [one_le_iff_ne_zero, ne_zero_iff_nonempty] end theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype] lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega := begin rw [countable_iff_exists_injective], split, rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩, rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ end lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega := ⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩, λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ lemma mk_int : mk ℤ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma mk_pnat : mk ℕ+ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_set {α : Type u} : mk (set α) = 2 ^ mk α := begin rw [← prop_eq_two, cardinal.power_def (ulift Prop) α, cardinal.eq], exact ⟨equiv.arrow_congr (equiv.refl _) equiv.ulift.symm⟩, end @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α := ⟨embedding.subtype p⟩ theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : mk (subtype p) ≤ mk (subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ := begin split, { intro h, have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h], refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _), rcases cardinal.eq.mp h2 with ⟨f, _⟩, cases f ⟨_, hx⟩ }, { intro, convert mk_emptyc _ } end theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α := quotient.sound ⟨(equiv.set.range f h).symm⟩ lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v u} (mk (range f)) = lift.{u v} (mk α) := begin have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.set.range f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) := lift_mk_eq.mpr ⟨(equiv.set.range f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (λ i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (λ i, mk (f i)) := calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, mk (f i)) : (sum_mk _).symm lemma mk_Union_le {α ι : Type u} (f : ι → set α) : mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ /-- The cardinality of a union is at most the sum of the cardinalities of the two sets. -/ lemma mk_union_le {α : Type u} (S T : set α) : mk (S ∪ T : set α) ≤ mk S + mk T := @mk_union_add_mk_inter α S T ▸ self_le_add_right (mk (S ∪ T : set α)) (mk (S ∩ T : set α)) theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union H⟩ lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α := quotient.sound ⟨equiv.set.sum_compl s⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_set_le (s : set α) : mk s ≤ mk α := mk_subtype_le s lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) : mk {a : α // p (e a)} = mk {b : β // p b} := quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩ lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } := quotient.sound ⟨equiv.set.sep s t⟩ lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : mk (f ⁻¹' s) ≤ mk s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function α^{<β}, defined to be sup_{γ < β} α^γ. We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a higher universe -/ noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} := sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : ∃(s : {s : set c'.out // mk s < c'}), mk s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ := begin rw [powerlt, sup_le], split, { intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) := by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le } end cardinal lemma equiv.cardinal_eq {α β} : α ≃ β → cardinal.mk α = cardinal.mk β := cardinal.eq_congr
0487e323e8398ef30bf27a178186f38683534d06
e514e8b939af519a1d5e9b30a850769d058df4e9
/src/lib_unused/pretty_print.lean
f50004b2c964ff9e34cbd917f9581bac1e4d9b8c
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
4,374
lean
-- import .options -- import .string -- open tactic -- meta def pretty_print (e : expr) (implicits : bool := ff) (full_cnsts := ff) : tactic string := -- do options ← get_options, -- set_options $ options.set_list_bool [ -- (`pp.notation, true), -- (`pp.universes, false), -- (`pp.implicit, implicits), -- (`pp.structure_instances, ¬full_cnsts) -- ], -- t ← pp e, -- set_options options, -- pure t.to_string -- /- -- pp.coercions (Bool) (pretty printer) display coercionss (default: true) -- pp.structure_projections (Bool) (pretty printer) display structure projections using field notation (default: true) -- pp.locals_full_names (Bool) (pretty printer) show full names of locals (default: false) -- pp.annotations (Bool) (pretty printer) display internal annotations (for debugging purposes only) (default: false) -- pp.hide_comp_irrelevant (Bool) (pretty printer) hide terms marked as computationally irrelevant, these marks are introduced by the code generator (default: true) -- pp.unicode (Bool) (pretty printer) use unicode characters (default: true) -- pp.colors (Bool) (pretty printer) use colors (default: false) -- pp.structure_instances (Bool) (pretty printer) display structure instances using the '{ field_name := field_value, ... }' notation or '⟨field_value, ... ⟩' if structure is tagged with [pp_using_anonymous_constructor] attribute (default: true) -- pp.purify_metavars (Bool) (pretty printer) rename internal metavariable names (with "user-friendly" ones) before pretty printing (default: true) -- pp.max_depth (Unsigned Int) (pretty printer) maximum expression depth, after that it will use ellipsis (default: 64) -- pp.notation (Bool) (pretty printer) disable/enable notation (infix, mixfix, postfix operators and unicode characters) (default: true) -- pp.preterm (Bool) (pretty printer) assume the term is a preterm (i.e., a term before elaboration) (default: false) -- pp.implicit (Bool) (pretty printer) display implicit parameters (default: false) -- pp.goal.max_hypotheses (Unsigned Int) (pretty printer) maximum number of hypotheses to be displayed (default: 200) -- pp.private_names (Bool) (pretty printer) display internal names assigned to private declarations (default: false) -- pp.goal.compact (Bool) (pretty printer) try to display goal in a single line when possible (default: false) -- pp.universes (Bool) (pretty printer) display universes (default: false) -- pp.full_names (Bool) (pretty printer) display fully qualified names (default: false) -- pp.purify_locals (Bool) (pretty printer) rename local names to avoid name capture, before pretty printing (default: true) -- pp.strings (Bool) (pretty printer) pretty print string and character literals (default: true) -- pp.all (Bool) (pretty printer) display coercions, implicit parameters, proof terms, fully qualified names, universes, and pp.beta (Bool) (pretty printer) apply beta-reduction when pretty printing (default: false) -- pp.max_steps (Unsigned Int) (pretty printer) maximum number of visited expressions, after that it will use ellipsis (default: 5000) -- pp.width (Unsigned Int) (pretty printer) line width (default: 120) -- pp.proofs (Bool) (pretty printer) if set to false, the type will be displayed instead of the value for every proof appearing as an argument to a function (default: true) -- pp.numerals (Bool) (pretty printer) display nat/num numerals in decimal notation (default: true) -- pp.delayed_abstraction (Bool) (pretty printer) display the location of delayed-abstractions (for debugging purposes) (default: true) -- pp.instantiate_mvars (Bool) (pretty printer) instantiate assigned metavariables before pretty printing terms and goals (default: true) -- pp.structure_instances_qualifier (Bool) (pretty printer) include qualifier 'struct_name .' when displaying structure instances using the '{ struct_name . field_name := field_value, ... }' notation, this option is ignored when pp.structure_instances is false (default: false) -- pp.use_holes (Bool) (pretty printer) use holes '{! !}' when pretty printing metavariables and `sorry` (default: false) -- pp.indent (Unsigned Int) (pretty printer) default indentation (default: 2) -- pp.binder_types (Bool) (pretty printer) display types of lambda and Pi parameters (default: true) -- -/
dcc3d7fecfa087ab25e6049619dac6c1fbeeae9c
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/vm_sorry.lean
5a3d508d1e22e2ace89a5e655a1e83e5380db356
[ "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
428
lean
def half_baked : bool → ℕ | tt := 42 | ff := sorry vm_eval (half_baked tt) vm_eval (half_baked ff) meta def my_partial_fun : bool → ℕ | tt := 42 | ff := undefined vm_eval (my_partial_fun ff) open expr tactic run_command (do v ← to_expr `(half_baked ff) >>= whnf, trace $ to_string v^.is_sorry) example : 0 = 1 := by admit example : 0 = 1 := by mk_sorry >>= exact example : 0 = 1 := by exact sorry
7a43a9ef9e1f32c7a10c50148e881647156dd38f
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/order/order_iso_nat.lean
82426cd812a5128b1f2e9e9e6cfc716bdc25a1a6
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,477
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.nat.basic import data.equiv.denumerable import data.set.finite import order.rel_iso import order.preorder_hom import order.conditionally_complete_lattice import logic.function.iterate namespace rel_embedding variables {α : Type*} {r : α → α → Prop} [is_strict_order α r] /-- If `f` is a strictly `r`-increasing sequence, then this returns `f` as an order embedding. -/ def nat_lt (f : ℕ → α) (H : ∀ n:ℕ, r (f n) (f (n+1))) : ((<) : ℕ → ℕ → Prop) ↪r r := of_monotone f $ λ a b h, begin induction b with b IH, {exact (nat.not_lt_zero _ h).elim}, cases nat.lt_succ_iff_lt_or_eq.1 h with h e, { exact trans (IH h) (H _) }, { subst b, apply H } end @[simp] lemma nat_lt_apply {f : ℕ → α} {H : ∀ n:ℕ, r (f n) (f (n+1))} {n : ℕ} : nat_lt f H n = f n := rfl /-- If `f` is a strictly `r`-decreasing sequence, then this returns `f` as an order embedding. -/ def nat_gt (f : ℕ → α) (H : ∀ n:ℕ, r (f (n+1)) (f n)) : ((>) : ℕ → ℕ → Prop) ↪r r := by haveI := is_strict_order.swap r; exact rel_embedding.swap (nat_lt f H) theorem well_founded_iff_no_descending_seq : well_founded r ↔ ¬ nonempty (((>) : ℕ → ℕ → Prop) ↪r r) := ⟨λ ⟨h⟩ ⟨⟨f, o⟩⟩, suffices ∀ a, acc r a → ∀ n, a ≠ f n, from this (f 0) (h _) 0 rfl, λ a ac, begin induction ac with a _ IH, intros n h, subst a, exact IH (f (n+1)) (o.2 (nat.lt_succ_self _)) _ rfl end, λ N, ⟨λ a, classical.by_contradiction $ λ na, let ⟨f, h⟩ := classical.axiom_of_choice $ show ∀ x : {a // ¬ acc r a}, ∃ y : {a // ¬ acc r a}, r y.1 x.1, from λ ⟨x, h⟩, classical.by_contradiction $ λ hn, h $ ⟨_, λ y h, classical.by_contradiction $ λ na, hn ⟨⟨y, na⟩, h⟩⟩ in N ⟨nat_gt (λ n, (f^[n] ⟨a, na⟩).1) $ λ n, by { rw [function.iterate_succ'], apply h }⟩⟩⟩ end rel_embedding namespace nat variables (s : set ℕ) [decidable_pred s] [infinite s] /-- An order embedding from `ℕ` to itself with a specified range -/ def order_embedding_of_set : ℕ ↪o ℕ := (rel_embedding.order_embedding_of_lt_embedding (rel_embedding.nat_lt (nat.subtype.of_nat s) (λ n, nat.subtype.lt_succ_self _))).trans (order_embedding.subtype s) /-- `nat.subtype.of_nat` as an order isomorphism between `ℕ` and an infinite decidable subset. -/ noncomputable def subtype.order_iso_of_nat : ℕ ≃o s := rel_iso.of_surjective (rel_embedding.order_embedding_of_lt_embedding (rel_embedding.nat_lt (nat.subtype.of_nat s) (λ n, nat.subtype.lt_succ_self _))) nat.subtype.of_nat_surjective variable {s} @[simp] lemma order_embedding_of_set_apply {n : ℕ} : order_embedding_of_set s n = subtype.of_nat s n := rfl @[simp] lemma subtype.order_iso_of_nat_apply {n : ℕ} : subtype.order_iso_of_nat s n = subtype.of_nat s n := by { simp [subtype.order_iso_of_nat] } variable (s) @[simp] lemma order_embedding_of_set_range : set.range (nat.order_embedding_of_set s) = s := begin ext x, rw [set.mem_range, nat.order_embedding_of_set], split; intro h, { rcases h with ⟨y, rfl⟩, simp }, { refine ⟨(nat.subtype.order_iso_of_nat s).symm ⟨x, h⟩, _⟩, simp only [rel_embedding.coe_trans, rel_embedding.order_embedding_of_lt_embedding_apply, rel_embedding.nat_lt_apply, function.comp_app, order_embedding.subtype_apply], rw [← subtype.order_iso_of_nat_apply, order_iso.apply_symm_apply, subtype.coe_mk] } end end nat theorem exists_increasing_or_nonincreasing_subseq' {α : Type*} (r : α → α → Prop) (f : ℕ → α) : ∃ (g : ℕ ↪o ℕ), (∀ n : ℕ, r (f (g n)) (f (g (n + 1)))) ∨ (∀ m n : ℕ, m < n → ¬ r (f (g m)) (f (g n))) := begin classical, let bad : set ℕ := { m | ∀ n, m < n → ¬ r (f m) (f n) }, by_cases hbad : infinite bad, { haveI := hbad, refine ⟨nat.order_embedding_of_set bad, or.intro_right _ (λ m n mn, _)⟩, have h := set.mem_range_self m, rw nat.order_embedding_of_set_range bad at h, exact h _ ((order_embedding.lt_iff_lt _).2 mn) }, { rw [set.infinite_coe_iff, set.infinite, not_not] at hbad, obtain ⟨m, hm⟩ : ∃ m, ∀ n, m ≤ n → ¬ n ∈ bad, { by_cases he : hbad.to_finset.nonempty, { refine ⟨(hbad.to_finset.max' he).succ, λ n hn nbad, nat.not_succ_le_self _ (hn.trans (hbad.to_finset.le_max' n (hbad.mem_to_finset.2 nbad)))⟩ }, { exact ⟨0, λ n hn nbad, he ⟨n, hbad.mem_to_finset.2 nbad⟩⟩ } }, have h : ∀ (n : ℕ), ∃ (n' : ℕ), n < n' ∧ r (f (n + m)) (f (n' + m)), { intro n, have h := hm _ (le_add_of_nonneg_left n.zero_le), simp only [exists_prop, not_not, set.mem_set_of_eq, not_forall] at h, obtain ⟨n', hn1, hn2⟩ := h, obtain ⟨x, hpos, rfl⟩ := exists_pos_add_of_lt hn1, refine ⟨n + x, add_lt_add_left hpos n, _⟩, rw [add_assoc, add_comm x m, ← add_assoc], exact hn2 }, let g' : ℕ → ℕ := @nat.rec (λ _, ℕ) m (λ n gn, nat.find (h gn)), exact ⟨(rel_embedding.nat_lt (λ n, g' n + m) (λ n, nat.add_lt_add_right (nat.find_spec (h (g' n))).1 m)).order_embedding_of_lt_embedding, or.intro_left _ (λ n, (nat.find_spec (h (g' n))).2)⟩ } end theorem exists_increasing_or_nonincreasing_subseq {α : Type*} (r : α → α → Prop) [is_trans α r] (f : ℕ → α) : ∃ (g : ℕ ↪o ℕ), (∀ m n : ℕ, m < n → r (f (g m)) (f (g n))) ∨ (∀ m n : ℕ, m < n → ¬ r (f (g m)) (f (g n))) := begin obtain ⟨g, hr | hnr⟩ := exists_increasing_or_nonincreasing_subseq' r f, { refine ⟨g, or.intro_left _ (λ m n mn, _)⟩, obtain ⟨x, rfl⟩ := le_iff_exists_add.1 (nat.succ_le_iff.2 mn), induction x with x ih, { apply hr }, { apply is_trans.trans _ _ _ _ (hr _), exact ih (lt_of_lt_of_le m.lt_succ_self (nat.le_add_right _ _)) } }, { exact ⟨g, or.intro_right _ hnr⟩ } end /-- The "monotone chain condition" below is sometimes a convenient form of well foundedness. -/ lemma well_founded.monotone_chain_condition (α : Type*) [partial_order α] : well_founded ((>) : α → α → Prop) ↔ ∀ (a : ℕ →ₘ α), ∃ n, ∀ m, n ≤ m → a n = a m := begin split; intros h, { rw well_founded.well_founded_iff_has_max' at h, intros a, have hne : (set.range a).nonempty, { use a 0, simp, }, obtain ⟨x, ⟨n, hn⟩, range_bounded⟩ := h _ hne, use n, intros m hm, rw ← hn at range_bounded, symmetry, apply range_bounded (a m) (set.mem_range_self _) (a.monotone hm), }, { rw rel_embedding.well_founded_iff_no_descending_seq, rintros ⟨a⟩, obtain ⟨n, hn⟩ := h (a.swap : ((<) : ℕ → ℕ → Prop) →r ((<) : α → α → Prop)).to_preorder_hom, exact n.succ_ne_self.symm (rel_embedding.to_preorder_hom_injective _ (hn _ n.le_succ)), }, end /-- Given an eventually-constant monotonic sequence `a₀ ≤ a₁ ≤ a₂ ≤ ...` in a partially-ordered type, `monotonic_sequence_limit_index a` is the least natural number `n` for which `aₙ` reaches the constant value. For sequences that are not eventually constant, `monotonic_sequence_limit_index a` is defined, but is a junk value. -/ noncomputable def monotonic_sequence_limit_index {α : Type*} [partial_order α] (a : ℕ →ₘ α) : ℕ := Inf { n | ∀ m, n ≤ m → a n = a m } /-- The constant value of an eventually-constant monotonic sequence `a₀ ≤ a₁ ≤ a₂ ≤ ...` in a partially-ordered type. -/ noncomputable def monotonic_sequence_limit {α : Type*} [partial_order α] (a : ℕ →ₘ α) := a (monotonic_sequence_limit_index a) lemma well_founded.supr_eq_monotonic_sequence_limit {α : Type*} [complete_lattice α] (h : well_founded ((>) : α → α → Prop)) (a : ℕ →ₘ α) : (⨆ m, a m) = monotonic_sequence_limit a := begin suffices : (⨆ (m : ℕ), a m) ≤ monotonic_sequence_limit a, { exact le_antisymm this (le_supr a _), }, apply supr_le, intros m, by_cases hm : m ≤ monotonic_sequence_limit_index a, { exact a.monotone hm, }, { replace hm := le_of_not_le hm, let S := { n | ∀ m, n ≤ m → a n = a m }, have hInf : Inf S ∈ S, { refine nat.Inf_mem _, rw well_founded.monotone_chain_condition at h, exact h a, }, change Inf S ≤ m at hm, change a m ≤ a (Inf S), rw hInf m hm, }, end
aea21ac6e6a0097027494a501dd36e8e4530457f
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex10.lean
2ebace30399127ca2fe186602dbc23d2c57a8556
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
666
lean
constants A B C : Type constant f : A → B constant g : B → C constant b : B check λ x : A, x -- A → A check λ x : A, b -- A → B check λ x : A, g (f x) -- A → C check λ x, g (f x) -- we can abstract any of the constants in the previous definitions check λ b : B, λ x : A, x -- B → A → A check λ (b : B) (x : A), x -- equivalent to the previous line check λ (g : B → C) (f : A → B) (x : A), g (f x) -- (B → C) → (A → B) → A → C -- we can even abstract over the type check λ (A B : Type) (b : B) (x : A), x check λ (A B C : Type) (g : B → C) (f : A → B) (x : A), g (f x)
ed56c389c65d39e394d18ba5c7ddf04aba382709
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/evalNone.lean
f83f87b4f5afa444c2e82ac62a0cdc0877a33c70
[ "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
27
lean
#eval none #eval [].head?
f45b33759b9dfcaa10e9bbfe73e97a311a222703
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/logic/basic.lean
b26860cabf5c09dae9ed1c80490be7901fbcfbc4
[ "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
61,315
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 -/ import tactic.doc_commands import tactic.reserved_notation /-! # Basic logic properties This file is one of the earliest imports in mathlib. ## Implementation notes Theorems that require decidability hypotheses are in the namespace "decidable". Classical versions are in the namespace "classical". In the presence of automation, this whole file may be unnecessary. On the other hand, maybe it is useful for writing automation. -/ open function local attribute [instance, priority 10] classical.prop_decidable section miscellany /- We add the `inline` attribute to optimize VM computation using these declarations. For example, `if p ∧ q then ... else ...` will not evaluate the decidability of `q` if `p` is false. -/ attribute [inline] and.decidable or.decidable decidable.false xor.decidable iff.decidable decidable.true implies.decidable not.decidable ne.decidable bool.decidable_eq decidable.to_bool attribute [simp] cast_eq cast_heq variables {α : Type*} {β : Type*} /-- An identity function with its main argument implicit. This will be printed as `hidden` even if it is applied to a large term, so it can be used for elision, as done in the `elide` and `unelide` tactics. -/ @[reducible] def hidden {α : Sort*} {a : α} := a /-- Ex falso, the nondependent eliminator for the `empty` type. -/ def empty.elim {C : Sort*} : empty → C. instance : subsingleton empty := ⟨λa, a.elim⟩ instance subsingleton.prod {α β : Type*} [subsingleton α] [subsingleton β] : subsingleton (α × β) := ⟨by { intros a b, cases a, cases b, congr, }⟩ instance : decidable_eq empty := λa, a.elim instance sort.inhabited : inhabited (Sort*) := ⟨punit⟩ instance sort.inhabited' : inhabited (default (Sort*)) := ⟨punit.star⟩ instance psum.inhabited_left {α β} [inhabited α] : inhabited (psum α β) := ⟨psum.inl (default _)⟩ instance psum.inhabited_right {α β} [inhabited β] : inhabited (psum α β) := ⟨psum.inr (default _)⟩ @[priority 10] instance decidable_eq_of_subsingleton {α} [subsingleton α] : decidable_eq α | a b := is_true (subsingleton.elim a b) @[simp] lemma eq_iff_true_of_subsingleton {α : Sort*} [subsingleton α] (x y : α) : x = y ↔ true := by cc /-- If all points are equal to a given point `x`, then `α` is a subsingleton. -/ lemma subsingleton_of_forall_eq {α : Sort*} (x : α) (h : ∀ y, y = x) : subsingleton α := ⟨λ a b, (h a).symm ▸ (h b).symm ▸ rfl⟩ lemma subsingleton_iff_forall_eq {α : Sort*} (x : α) : subsingleton α ↔ ∀ y, y = x := ⟨λ h y, @subsingleton.elim _ h y x, subsingleton_of_forall_eq x⟩ -- TODO[gh-6025]: make this an instance once safe to do so lemma subtype.subsingleton (α : Sort*) [subsingleton α] (p : α → Prop) : subsingleton (subtype p) := ⟨λ ⟨x,_⟩ ⟨y,_⟩, have x = y, from subsingleton.elim _ _, by { cases this, refl }⟩ /-- Add an instance to "undo" coercion transitivity into a chain of coercions, because most simp lemmas are stated with respect to simple coercions and will not match when part of a chain. -/ @[simp] theorem coe_coe {α β γ} [has_coe α β] [has_coe_t β γ] (a : α) : (a : γ) = (a : β) := rfl theorem coe_fn_coe_trans {α β γ δ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ δ] (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl /-- Non-dependent version of `coe_fn_coe_trans`, helps `rw` figure out the argument. -/ theorem coe_fn_coe_trans' {α β γ} {δ : out_param $ _} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ (λ _, δ)] (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl @[simp] theorem coe_fn_coe_base {α β γ} [has_coe α β] [has_coe_to_fun β γ] (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl /-- Non-dependent version of `coe_fn_coe_base`, helps `rw` figure out the argument. -/ theorem coe_fn_coe_base' {α β} {γ : out_param $ _} [has_coe α β] [has_coe_to_fun β (λ _, γ)] (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl theorem coe_sort_coe_trans {α β γ δ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_sort γ δ] (x : α) : @coe_sort α _ _ x = @coe_sort β _ _ x := rfl /-- Many structures such as bundled morphisms coerce to functions so that you can transparently apply them to arguments. For example, if `e : α ≃ β` and `a : α` then you can write `e a` and this is elaborated as `⇑e a`. This type of coercion is implemented using the `has_coe_to_fun` type class. There is one important consideration: If a type coerces to another type which in turn coerces to a function, then it **must** implement `has_coe_to_fun` directly: ```lean structure sparkling_equiv (α β) extends α ≃ β -- if we add a `has_coe` instance, instance {α β} : has_coe (sparkling_equiv α β) (α ≃ β) := ⟨sparkling_equiv.to_equiv⟩ -- then a `has_coe_to_fun` instance **must** be added as well: instance {α β} : has_coe_to_fun (sparkling_equiv α β) := ⟨λ _, α → β, λ f, f.to_equiv.to_fun⟩ ``` (Rationale: if we do not declare the direct coercion, then `⇑e a` is not in simp-normal form. The lemma `coe_fn_coe_base` will unfold it to `⇑↑e a`. This often causes loops in the simplifier.) -/ library_note "function coercion" @[simp] theorem coe_sort_coe_base {α β γ} [has_coe α β] [has_coe_to_sort β γ] (x : α) : @coe_sort α _ _ x = @coe_sort β _ _ x := rfl /-- `pempty` is the universe-polymorphic analogue of `empty`. -/ @[derive decidable_eq] inductive {u} pempty : Sort u /-- Ex falso, the nondependent eliminator for the `pempty` type. -/ def pempty.elim {C : Sort*} : pempty → C. instance subsingleton_pempty : subsingleton pempty := ⟨λa, a.elim⟩ @[simp] lemma not_nonempty_pempty : ¬ nonempty pempty := assume ⟨h⟩, h.elim @[simp] theorem forall_pempty {P : pempty → Prop} : (∀ x : pempty, P x) ↔ true := ⟨λ h, trivial, λ h x, by cases x⟩ @[simp] theorem exists_pempty {P : pempty → Prop} : (∃ x : pempty, P x) ↔ false := ⟨λ h, by { cases h with w, cases w }, false.elim⟩ lemma congr_arg_heq {α} {β : α → Sort*} (f : ∀ a, β a) : ∀ {a₁ a₂ : α}, a₁ = a₂ → f a₁ == f a₂ | a _ rfl := heq.rfl lemma plift.down_inj {α : Sort*} : ∀ (a b : plift α), a.down = b.down → a = b | ⟨a⟩ ⟨b⟩ rfl := rfl -- missing [symm] attribute for ne in core. attribute [symm] ne.symm lemma ne_comm {α} {a b : α} : a ≠ b ↔ b ≠ a := ⟨ne.symm, ne.symm⟩ @[simp] lemma eq_iff_eq_cancel_left {b c : α} : (∀ {a}, a = b ↔ a = c) ↔ (b = c) := ⟨λ h, by rw [← h], λ h a, by rw h⟩ @[simp] lemma eq_iff_eq_cancel_right {a b : α} : (∀ {c}, a = c ↔ b = c) ↔ (a = b) := ⟨λ h, by rw h, λ h a, by rw h⟩ /-- Wrapper for adding elementary propositions to the type class systems. Warning: this can easily be abused. See the rest of this docstring for details. Certain propositions should not be treated as a class globally, but sometimes it is very convenient to be able to use the type class system in specific circumstances. For example, `zmod p` is a field if and only if `p` is a prime number. In order to be able to find this field instance automatically by type class search, we have to turn `p.prime` into an instance implicit assumption. On the other hand, making `nat.prime` a class would require a major refactoring of the library, and it is questionable whether making `nat.prime` a class is desirable at all. The compromise is to add the assumption `[fact p.prime]` to `zmod.field`. In particular, this class is not intended for turning the type class system into an automated theorem prover for first order logic. -/ class fact (p : Prop) : Prop := (out [] : p) lemma fact.elim {p : Prop} (h : fact p) : p := h.1 lemma fact_iff {p : Prop} : fact p ↔ p := ⟨λ h, h.1, λ h, ⟨h⟩⟩ end miscellany /-! ### Declarations about propositional connectives -/ theorem false_ne_true : false ≠ true | h := h.symm ▸ trivial section propositional variables {a b c d : Prop} /-! ### Declarations about `implies` -/ instance : is_refl Prop iff := ⟨iff.refl⟩ instance : is_trans Prop iff := ⟨λ _ _ _, iff.trans⟩ theorem iff_of_eq (e : a = b) : a ↔ b := e ▸ iff.rfl theorem iff_iff_eq : (a ↔ b) ↔ a = b := ⟨propext, iff_of_eq⟩ @[simp] lemma eq_iff_iff {p q : Prop} : (p = q) ↔ (p ↔ q) := iff_iff_eq.symm @[simp] theorem imp_self : (a → a) ↔ true := iff_true_intro id theorem imp_intro {α β : Prop} (h : α) : β → α := λ _, h theorem imp_false : (a → false) ↔ ¬ a := iff.rfl theorem imp_and_distrib {α} : (α → b ∧ c) ↔ (α → b) ∧ (α → c) := ⟨λ h, ⟨λ ha, (h ha).left, λ ha, (h ha).right⟩, λ h ha, ⟨h.left ha, h.right ha⟩⟩ @[simp] theorem and_imp : (a ∧ b → c) ↔ (a → b → c) := iff.intro (λ h ha hb, h ⟨ha, hb⟩) (λ h ⟨ha, hb⟩, h ha hb) theorem iff_def : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff_iff_implies_and_implies _ _ theorem iff_def' : (a ↔ b) ↔ (b → a) ∧ (a → b) := iff_def.trans and.comm theorem imp_true_iff {α : Sort*} : (α → true) ↔ true := iff_true_intro $ λ_, trivial theorem imp_iff_right (ha : a) : (a → b) ↔ b := ⟨λf, f ha, imp_intro⟩ theorem decidable.imp_iff_right_iff [decidable a] : ((a → b) ↔ b) ↔ (a ∨ b) := ⟨λ H, (decidable.em a).imp_right $ λ ha', H.1 $ λ ha, (ha' ha).elim, λ H, H.elim imp_iff_right $ λ hb, ⟨λ hab, hb, λ _ _, hb⟩⟩ @[simp] theorem imp_iff_right_iff : ((a → b) ↔ b) ↔ (a ∨ b) := decidable.imp_iff_right_iff /-! ### Declarations about `not` -/ /-- Ex falso for negation. From `¬ a` and `a` anything follows. This is the same as `absurd` with the arguments flipped, but it is in the `not` namespace so that projection notation can be used. -/ def not.elim {α : Sort*} (H1 : ¬a) (H2 : a) : α := absurd H2 H1 @[reducible] theorem not.imp {a b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a := mt H1 H2 theorem not_not_of_not_imp : ¬(a → b) → ¬¬a := mt not.elim theorem not_of_not_imp {a : Prop} : ¬(a → b) → ¬b := mt imp_intro theorem dec_em (p : Prop) [decidable p] : p ∨ ¬p := decidable.em p theorem dec_em' (p : Prop) [decidable p] : ¬p ∨ p := (dec_em p).swap theorem em (p : Prop) : p ∨ ¬p := classical.em _ theorem em' (p : Prop) : ¬p ∨ p := (em p).swap theorem or_not {p : Prop} : p ∨ ¬p := em _ section eq_or_ne variables {α : Sort*} (x y : α) theorem decidable.eq_or_ne [decidable (x = y)] : x = y ∨ x ≠ y := dec_em $ x = y theorem decidable.ne_or_eq [decidable (x = y)] : x ≠ y ∨ x = y := dec_em' $ x = y theorem eq_or_ne : x = y ∨ x ≠ y := em $ x = y theorem ne_or_eq : x ≠ y ∨ x = y := em' $ x = y end eq_or_ne theorem by_contradiction {p} : (¬p → false) → p := decidable.by_contradiction -- alias by_contradiction ← by_contra theorem by_contra {p} : (¬p → false) → p := decidable.by_contradiction /-- In most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely. The `decidable` namespace contains versions of lemmas from the root namespace that explicitly attempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs. You can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if `classical.choice` appears in the list. -/ library_note "decidable namespace" /-- As mathlib is primarily classical, if the type signature of a `def` or `lemma` does not require any `decidable` instances to state, it is preferable not to introduce any `decidable` instances that are needed in the proof as arguments, but rather to use the `classical` tactic as needed. In the other direction, when `decidable` instances do appear in the type signature, it is better to use explicitly introduced ones rather than allowing Lean to automatically infer classical ones, as these may cause instance mismatch errors later. -/ library_note "decidable arguments" -- See Note [decidable namespace] protected theorem decidable.not_not [decidable a] : ¬¬a ↔ a := iff.intro decidable.by_contradiction not_not_intro /-- The Double Negation Theorem: `¬ ¬ P` is equivalent to `P`. The left-to-right direction, double negation elimination (DNE), is classically true but not constructively. -/ @[simp] theorem not_not : ¬¬a ↔ a := decidable.not_not theorem of_not_not : ¬¬a → a := by_contra -- See Note [decidable namespace] protected theorem decidable.of_not_imp [decidable a] (h : ¬ (a → b)) : a := decidable.by_contradiction (not_not_of_not_imp h) theorem of_not_imp : ¬ (a → b) → a := decidable.of_not_imp -- See Note [decidable namespace] protected theorem decidable.not_imp_symm [decidable a] (h : ¬a → b) (hb : ¬b) : a := decidable.by_contradiction $ hb ∘ h theorem not.decidable_imp_symm [decidable a] : (¬a → b) → ¬b → a := decidable.not_imp_symm theorem not.imp_symm : (¬a → b) → ¬b → a := not.decidable_imp_symm -- See Note [decidable namespace] protected theorem decidable.not_imp_comm [decidable a] [decidable b] : (¬a → b) ↔ (¬b → a) := ⟨not.decidable_imp_symm, not.decidable_imp_symm⟩ theorem not_imp_comm : (¬a → b) ↔ (¬b → a) := decidable.not_imp_comm @[simp] theorem imp_not_self : (a → ¬a) ↔ ¬a := ⟨λ h ha, h ha ha, λ h _, h⟩ theorem decidable.not_imp_self [decidable a] : (¬a → a) ↔ a := by { have := @imp_not_self (¬a), rwa decidable.not_not at this } @[simp] theorem not_imp_self : (¬a → a) ↔ a := decidable.not_imp_self theorem imp.swap : (a → b → c) ↔ (b → a → c) := ⟨swap, swap⟩ theorem imp_not_comm : (a → ¬b) ↔ (b → ¬a) := imp.swap /-! ### Declarations about `xor` -/ @[simp] theorem xor_true : xor true = not := funext $ λ a, by simp [xor] @[simp] theorem xor_false : xor false = id := funext $ λ a, by simp [xor] theorem xor_comm (a b) : xor a b = xor b a := by simp [xor, and_comm, or_comm] instance : is_commutative Prop xor := ⟨xor_comm⟩ @[simp] theorem xor_self (a : Prop) : xor a a = false := by simp [xor] /-! ### Declarations about `and` -/ theorem and_congr_left (h : c → (a ↔ b)) : a ∧ c ↔ b ∧ c := and.comm.trans $ (and_congr_right h).trans and.comm theorem and_congr_left' (h : a ↔ b) : a ∧ c ↔ b ∧ c := and_congr h iff.rfl theorem and_congr_right' (h : b ↔ c) : a ∧ b ↔ a ∧ c := and_congr iff.rfl h theorem not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) := mt and.left theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := mt and.right theorem and.imp_left (h : a → b) : a ∧ c → b ∧ c := and.imp h id theorem and.imp_right (h : a → b) : c ∧ a → c ∧ b := and.imp id h lemma and.right_comm : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b := by simp only [and.left_comm, and.comm] lemma and_and_and_comm (a b c d : Prop) : (a ∧ b) ∧ c ∧ d ↔ (a ∧ c) ∧ b ∧ d := by rw [←and_assoc, @and.right_comm a, and_assoc] lemma and.rotate : a ∧ b ∧ c ↔ b ∧ c ∧ a := by simp only [and.left_comm, and.comm] theorem and_not_self_iff (a : Prop) : a ∧ ¬ a ↔ false := iff.intro (assume h, (h.right) (h.left)) (assume h, h.elim) theorem not_and_self_iff (a : Prop) : ¬ a ∧ a ↔ false := iff.intro (assume ⟨hna, ha⟩, hna ha) false.elim theorem and_iff_left_of_imp {a b : Prop} (h : a → b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, h ha⟩) theorem and_iff_right_of_imp {a b : Prop} (h : b → a) : (a ∧ b) ↔ b := iff.intro and.right (λ hb, ⟨h hb, hb⟩) @[simp] theorem and_iff_left_iff_imp {a b : Prop} : ((a ∧ b) ↔ a) ↔ (a → b) := ⟨λ h ha, (h.2 ha).2, and_iff_left_of_imp⟩ @[simp] theorem and_iff_right_iff_imp {a b : Prop} : ((a ∧ b) ↔ b) ↔ (b → a) := ⟨λ h ha, (h.2 ha).1, and_iff_right_of_imp⟩ @[simp] lemma iff_self_and {p q : Prop} : (p ↔ p ∧ q) ↔ (p → q) := by rw [@iff.comm p, and_iff_left_iff_imp] @[simp] lemma iff_and_self {p q : Prop} : (p ↔ q ∧ p) ↔ (p → q) := by rw [and_comm, iff_self_and] @[simp] lemma and.congr_right_iff : (a ∧ b ↔ a ∧ c) ↔ (a → (b ↔ c)) := ⟨λ h ha, by simp [ha] at h; exact h, and_congr_right⟩ @[simp] lemma and.congr_left_iff : (a ∧ c ↔ b ∧ c) ↔ c → (a ↔ b) := by simp only [and.comm, ← and.congr_right_iff] @[simp] lemma and_self_left : a ∧ a ∧ b ↔ a ∧ b := ⟨λ h, ⟨h.1, h.2.2⟩, λ h, ⟨h.1, h.1, h.2⟩⟩ @[simp] lemma and_self_right : (a ∧ b) ∧ b ↔ a ∧ b := ⟨λ h, ⟨h.1.1, h.2⟩, λ h, ⟨⟨h.1, h.2⟩, h.2⟩⟩ /-! ### Declarations about `or` -/ theorem or_congr_left (h : a ↔ b) : a ∨ c ↔ b ∨ c := or_congr h iff.rfl theorem or_congr_right (h : b ↔ c) : a ∨ b ↔ a ∨ c := or_congr iff.rfl h theorem or.right_comm : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b := by rw [or_assoc, or_assoc, or_comm b] theorem or_of_or_of_imp_of_imp (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d := or.imp h₂ h₃ h₁ theorem or_of_or_of_imp_left (h₁ : a ∨ c) (h : a → b) : b ∨ c := or.imp_left h h₁ theorem or_of_or_of_imp_right (h₁ : c ∨ a) (h : a → b) : c ∨ b := or.imp_right h h₁ theorem or.elim3 (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d := or.elim h ha (assume h₂, or.elim h₂ hb hc) theorem or_imp_distrib : (a ∨ b → c) ↔ (a → c) ∧ (b → c) := ⟨assume h, ⟨assume ha, h (or.inl ha), assume hb, h (or.inr hb)⟩, assume ⟨ha, hb⟩, or.rec ha hb⟩ -- See Note [decidable namespace] protected theorem decidable.or_iff_not_imp_left [decidable a] : a ∨ b ↔ (¬ a → b) := ⟨or.resolve_left, λ h, dite _ or.inl (or.inr ∘ h)⟩ theorem or_iff_not_imp_left : a ∨ b ↔ (¬ a → b) := decidable.or_iff_not_imp_left -- See Note [decidable namespace] protected theorem decidable.or_iff_not_imp_right [decidable b] : a ∨ b ↔ (¬ b → a) := or.comm.trans decidable.or_iff_not_imp_left theorem or_iff_not_imp_right : a ∨ b ↔ (¬ b → a) := decidable.or_iff_not_imp_right -- See Note [decidable namespace] protected theorem decidable.not_imp_not [decidable a] : (¬ a → ¬ b) ↔ (b → a) := ⟨assume h hb, decidable.by_contradiction $ assume na, h na hb, mt⟩ theorem not_imp_not : (¬ a → ¬ b) ↔ (b → a) := decidable.not_imp_not @[simp] theorem or_iff_left_iff_imp : (a ∨ b ↔ a) ↔ (b → a) := ⟨λ h hb, h.1 (or.inr hb), or_iff_left_of_imp⟩ @[simp] theorem or_iff_right_iff_imp : (a ∨ b ↔ b) ↔ (a → b) := by rw [or_comm, or_iff_left_iff_imp] /-! ### Declarations about distributivity -/ /-- `∧` distributes over `∨` (on the left). -/ theorem and_or_distrib_left : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) := ⟨λ ⟨ha, hbc⟩, hbc.imp (and.intro ha) (and.intro ha), or.rec (and.imp_right or.inl) (and.imp_right or.inr)⟩ /-- `∧` distributes over `∨` (on the right). -/ theorem or_and_distrib_right : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := (and.comm.trans and_or_distrib_left).trans (or_congr and.comm and.comm) /-- `∨` distributes over `∧` (on the left). -/ theorem or_and_distrib_left : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) := ⟨or.rec (λha, and.intro (or.inl ha) (or.inl ha)) (and.imp or.inr or.inr), and.rec $ or.rec (imp_intro ∘ or.inl) (or.imp_right ∘ and.intro)⟩ /-- `∨` distributes over `∧` (on the right). -/ theorem and_or_distrib_right : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := (or.comm.trans or_and_distrib_left).trans (and_congr or.comm or.comm) @[simp] lemma or_self_left : a ∨ a ∨ b ↔ a ∨ b := ⟨λ h, h.elim or.inl id, λ h, h.elim or.inl (or.inr ∘ or.inr)⟩ @[simp] lemma or_self_right : (a ∨ b) ∨ b ↔ a ∨ b := ⟨λ h, h.elim id or.inr, λ h, h.elim (or.inl ∘ or.inl) or.inr⟩ /-! Declarations about `iff` -/ theorem iff_of_true (ha : a) (hb : b) : a ↔ b := ⟨λ_, hb, λ _, ha⟩ theorem iff_of_false (ha : ¬a) (hb : ¬b) : a ↔ b := ⟨ha.elim, hb.elim⟩ theorem iff_true_left (ha : a) : (a ↔ b) ↔ b := ⟨λ h, h.1 ha, iff_of_true ha⟩ theorem iff_true_right (ha : a) : (b ↔ a) ↔ b := iff.comm.trans (iff_true_left ha) theorem iff_false_left (ha : ¬a) : (a ↔ b) ↔ ¬b := ⟨λ h, mt h.2 ha, iff_of_false ha⟩ theorem iff_false_right (ha : ¬a) : (b ↔ a) ↔ ¬b := iff.comm.trans (iff_false_left ha) @[simp] lemma iff_mpr_iff_true_intro {P : Prop} (h : P) : iff.mpr (iff_true_intro h) true.intro = h := rfl -- See Note [decidable namespace] protected theorem decidable.not_or_of_imp [decidable a] (h : a → b) : ¬ a ∨ b := if ha : a then or.inr (h ha) else or.inl ha theorem not_or_of_imp : (a → b) → ¬ a ∨ b := decidable.not_or_of_imp -- See Note [decidable namespace] protected theorem decidable.imp_iff_not_or [decidable a] : (a → b) ↔ (¬ a ∨ b) := ⟨decidable.not_or_of_imp, or.neg_resolve_left⟩ theorem imp_iff_not_or : (a → b) ↔ (¬ a ∨ b) := decidable.imp_iff_not_or -- See Note [decidable namespace] protected theorem decidable.imp_or_distrib [decidable a] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by simp [decidable.imp_iff_not_or, or.comm, or.left_comm] theorem imp_or_distrib : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib -- See Note [decidable namespace] protected theorem decidable.imp_or_distrib' [decidable b] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by by_cases b; simp [h, or_iff_right_of_imp ((∘) false.elim)] theorem imp_or_distrib' : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib' theorem not_imp_of_and_not : a ∧ ¬ b → ¬ (a → b) | ⟨ha, hb⟩ h := hb $ h ha -- See Note [decidable namespace] protected theorem decidable.not_imp [decidable a] : ¬(a → b) ↔ a ∧ ¬b := ⟨λ h, ⟨decidable.of_not_imp h, not_of_not_imp h⟩, not_imp_of_and_not⟩ theorem not_imp : ¬(a → b) ↔ a ∧ ¬b := decidable.not_imp -- for monotonicity lemma imp_imp_imp (h₀ : c → a) (h₁ : b → d) : (a → b) → (c → d) := assume (h₂ : a → b), h₁ ∘ h₂ ∘ h₀ -- See Note [decidable namespace] protected theorem decidable.peirce (a b : Prop) [decidable a] : ((a → b) → a) → a := if ha : a then λ h, ha else λ h, h ha.elim theorem peirce (a b : Prop) : ((a → b) → a) → a := decidable.peirce _ _ theorem peirce' {a : Prop} (H : ∀ b : Prop, (a → b) → a) : a := H _ id -- See Note [decidable namespace] protected theorem decidable.not_iff_not [decidable a] [decidable b] : (¬ a ↔ ¬ b) ↔ (a ↔ b) := by rw [@iff_def (¬ a), @iff_def' a]; exact and_congr decidable.not_imp_not decidable.not_imp_not theorem not_iff_not : (¬ a ↔ ¬ b) ↔ (a ↔ b) := decidable.not_iff_not -- See Note [decidable namespace] protected theorem decidable.not_iff_comm [decidable a] [decidable b] : (¬ a ↔ b) ↔ (¬ b ↔ a) := by rw [@iff_def (¬ a), @iff_def (¬ b)]; exact and_congr decidable.not_imp_comm imp_not_comm theorem not_iff_comm : (¬ a ↔ b) ↔ (¬ b ↔ a) := decidable.not_iff_comm -- See Note [decidable namespace] protected theorem decidable.not_iff : ∀ [decidable b], ¬ (a ↔ b) ↔ (¬ a ↔ b) := by intro h; cases h; simp only [h, iff_true, iff_false] theorem not_iff : ¬ (a ↔ b) ↔ (¬ a ↔ b) := decidable.not_iff -- See Note [decidable namespace] protected theorem decidable.iff_not_comm [decidable a] [decidable b] : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := by rw [@iff_def a, @iff_def b]; exact and_congr imp_not_comm decidable.not_imp_comm theorem iff_not_comm : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := decidable.iff_not_comm -- See Note [decidable namespace] protected theorem decidable.iff_iff_and_or_not_and_not [decidable b] : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := by { split; intro h, { rw h; by_cases b; [left,right]; split; assumption }, { cases h with h h; cases h; split; intro; { contradiction <|> assumption } } } theorem iff_iff_and_or_not_and_not : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := decidable.iff_iff_and_or_not_and_not lemma decidable.iff_iff_not_or_and_or_not [decidable a] [decidable b] : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) := begin rw [iff_iff_implies_and_implies a b], simp only [decidable.imp_iff_not_or, or.comm] end lemma iff_iff_not_or_and_or_not : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) := decidable.iff_iff_not_or_and_or_not -- See Note [decidable namespace] protected theorem decidable.not_and_not_right [decidable b] : ¬(a ∧ ¬b) ↔ (a → b) := ⟨λ h ha, h.decidable_imp_symm $ and.intro ha, λ h ⟨ha, hb⟩, hb $ h ha⟩ theorem not_and_not_right : ¬(a ∧ ¬b) ↔ (a → b) := decidable.not_and_not_right /-- Transfer decidability of `a` to decidability of `b`, if the propositions are equivalent. **Important**: this function should be used instead of `rw` on `decidable b`, because the kernel will get stuck reducing the usage of `propext` otherwise, and `dec_trivial` will not work. -/ @[inline] def decidable_of_iff (a : Prop) (h : a ↔ b) [D : decidable a] : decidable b := decidable_of_decidable_of_iff D h /-- Transfer decidability of `b` to decidability of `a`, if the propositions are equivalent. This is the same as `decidable_of_iff` but the iff is flipped. -/ @[inline] def decidable_of_iff' (b : Prop) (h : a ↔ b) [D : decidable b] : decidable a := decidable_of_decidable_of_iff D h.symm /-- Prove that `a` is decidable by constructing a boolean `b` and a proof that `b ↔ a`. (This is sometimes taken as an alternate definition of decidability.) -/ def decidable_of_bool : ∀ (b : bool) (h : b ↔ a), decidable a | tt h := is_true (h.1 rfl) | ff h := is_false (mt h.2 bool.ff_ne_tt) /-! ### De Morgan's laws -/ theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b) | ⟨ha, hb⟩ := or.elim h (absurd ha) (absurd hb) -- See Note [decidable namespace] protected theorem decidable.not_and_distrib [decidable a] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h, if ha : a then or.inr (λ hb, h ⟨ha, hb⟩) else or.inl ha, not_and_of_not_or_not⟩ -- See Note [decidable namespace] protected theorem decidable.not_and_distrib' [decidable b] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h, if hb : b then or.inl (λ ha, h ⟨ha, hb⟩) else or.inr hb, not_and_of_not_or_not⟩ /-- One of de Morgan's laws: the negation of a conjunction is logically equivalent to the disjunction of the negations. -/ theorem not_and_distrib : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := decidable.not_and_distrib @[simp] theorem not_and : ¬ (a ∧ b) ↔ (a → ¬ b) := and_imp theorem not_and' : ¬ (a ∧ b) ↔ b → ¬a := not_and.trans imp_not_comm /-- One of de Morgan's laws: the negation of a disjunction is logically equivalent to the conjunction of the negations. -/ theorem not_or_distrib : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := ⟨λ h, ⟨λ ha, h (or.inl ha), λ hb, h (or.inr hb)⟩, λ ⟨h₁, h₂⟩ h, or.elim h h₁ h₂⟩ -- See Note [decidable namespace] protected theorem decidable.or_iff_not_and_not [decidable a] [decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) := by rw [← not_or_distrib, decidable.not_not] theorem or_iff_not_and_not : a ∨ b ↔ ¬ (¬a ∧ ¬b) := decidable.or_iff_not_and_not -- See Note [decidable namespace] protected theorem decidable.and_iff_not_or_not [decidable a] [decidable b] : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := by rw [← decidable.not_and_distrib, decidable.not_not] theorem and_iff_not_or_not : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := decidable.and_iff_not_or_not end propositional /-! ### Declarations about equality -/ section equality variables {α : Sort*} {a b : α} @[simp] theorem heq_iff_eq : a == b ↔ a = b := ⟨eq_of_heq, heq_of_eq⟩ theorem proof_irrel_heq {p q : Prop} (hp : p) (hq : q) : hp == hq := have p = q, from propext ⟨λ _, hq, λ _, hp⟩, by subst q; refl theorem ne_of_mem_of_not_mem {α β} [has_mem α β] {s : β} {a b : α} (h : a ∈ s) : b ∉ s → a ≠ b := mt $ λ e, e ▸ h lemma ne_of_apply_ne {α β : Sort*} (f : α → β) {x y : α} (h : f x ≠ f y) : x ≠ y := λ (w : x = y), h (congr_arg f w) theorem eq_equivalence : equivalence (@eq α) := ⟨eq.refl, @eq.symm _, @eq.trans _⟩ /-- Transport through trivial families is the identity. -/ @[simp] lemma eq_rec_constant {α : Sort*} {a a' : α} {β : Sort*} (y : β) (h : a = a') : (@eq.rec α a (λ a, β) y a' h) = y := by { cases h, refl, } @[simp] lemma eq_mp_eq_cast {α β : Sort*} (h : α = β) : eq.mp h = cast h := rfl @[simp] lemma eq_mpr_eq_cast {α β : Sort*} (h : α = β) : eq.mpr h = cast h.symm := rfl @[simp] lemma cast_cast : ∀ {α β γ : Sort*} (ha : α = β) (hb : β = γ) (a : α), cast hb (cast ha a) = cast (ha.trans hb) a | _ _ _ rfl rfl a := rfl @[simp] lemma congr_refl_left {α β : Sort*} (f : α → β) {a b : α} (h : a = b) : congr (eq.refl f) h = congr_arg f h := rfl @[simp] lemma congr_refl_right {α β : Sort*} {f g : α → β} (h : f = g) (a : α) : congr h (eq.refl a) = congr_fun h a := rfl @[simp] lemma congr_arg_refl {α β : Sort*} (f : α → β) (a : α) : congr_arg f (eq.refl a) = eq.refl (f a) := rfl @[simp] lemma congr_fun_rfl {α β : Sort*} (f : α → β) (a : α) : congr_fun (eq.refl f) a = eq.refl (f a) := rfl @[simp] lemma congr_fun_congr_arg {α β γ : Sort*} (f : α → β → γ) {a a' : α} (p : a = a') (b : β) : congr_fun (congr_arg f p) b = congr_arg (λ a, f a b) p := rfl lemma heq_of_cast_eq : ∀ {α β : Sort*} {a : α} {a' : β} (e : α = β) (h₂ : cast e a = a'), a == a' | α ._ a a' rfl h := eq.rec_on h (heq.refl _) lemma cast_eq_iff_heq {α β : Sort*} {a : α} {a' : β} {e : α = β} : cast e a = a' ↔ a == a' := ⟨heq_of_cast_eq _, λ h, by cases h; refl⟩ lemma rec_heq_of_heq {β} {C : α → Sort*} {x : C a} {y : β} (eq : a = b) (h : x == y) : @eq.rec α a C x b eq == y := by subst eq; exact h protected lemma eq.congr {x₁ x₂ y₁ y₂ : α} (h₁ : x₁ = y₁) (h₂ : x₂ = y₂) : (x₁ = x₂) ↔ (y₁ = y₂) := by { subst h₁, subst h₂ } lemma eq.congr_left {x y z : α} (h : x = y) : x = z ↔ y = z := by rw [h] lemma eq.congr_right {x y z : α} (h : x = y) : z = x ↔ z = y := by rw [h] lemma congr_arg2 {α β γ : Type*} (f : α → β → γ) {x x' : α} {y y' : β} (hx : x = x') (hy : y = y') : f x y = f x' y' := by { subst hx, subst hy } end equality /-! ### Declarations about quantifiers -/ section quantifiers variables {α : Sort*} {β : Sort*} {p q : α → Prop} {b : Prop} lemma forall_imp (h : ∀ a, p a → q a) : (∀ a, p a) → ∀ a, q a := λ h' a, h a (h' a) lemma forall₂_congr {p q : α → β → Prop} (h : ∀ a b, p a b ↔ q a b) : (∀ a b, p a b) ↔ (∀ a b, q a b) := forall_congr (λ a, forall_congr (h a)) lemma forall₃_congr {γ : Sort*} {p q : α → β → γ → Prop} (h : ∀ a b c, p a b c ↔ q a b c) : (∀ a b c, p a b c) ↔ (∀ a b c, q a b c) := forall_congr (λ a, forall₂_congr (h a)) lemma forall₄_congr {γ δ : Sort*} {p q : α → β → γ → δ → Prop} (h : ∀ a b c d, p a b c d ↔ q a b c d) : (∀ a b c d, p a b c d) ↔ (∀ a b c d, q a b c d) := forall_congr (λ a, forall₃_congr (h a)) lemma Exists.imp (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists_imp_exists h p lemma exists_imp_exists' {p : α → Prop} {q : β → Prop} (f : α → β) (hpq : ∀ a, p a → q (f a)) (hp : ∃ a, p a) : ∃ b, q b := exists.elim hp (λ a hp', ⟨_, hpq _ hp'⟩) lemma exists₂_congr {p q : α → β → Prop} (h : ∀ a b, p a b ↔ q a b) : (∃ a b, p a b) ↔ (∃ a b, q a b) := exists_congr (λ a, exists_congr (h a)) lemma exists₃_congr {γ : Sort*} {p q : α → β → γ → Prop} (h : ∀ a b c, p a b c ↔ q a b c) : (∃ a b c, p a b c) ↔ (∃ a b c, q a b c) := exists_congr (λ a, exists₂_congr (h a)) lemma exists₄_congr {γ δ : Sort*} {p q : α → β → γ → δ → Prop} (h : ∀ a b c d, p a b c d ↔ q a b c d) : (∃ a b c d, p a b c d) ↔ (∃ a b c d, q a b c d) := exists_congr (λ a, exists₃_congr (h a)) theorem forall_swap {p : α → β → Prop} : (∀ x y, p x y) ↔ ∀ y x, p x y := ⟨swap, swap⟩ theorem exists_swap {p : α → β → Prop} : (∃ x y, p x y) ↔ ∃ y x, p x y := ⟨λ ⟨x, y, h⟩, ⟨y, x, h⟩, λ ⟨y, x, h⟩, ⟨x, y, h⟩⟩ @[simp] theorem forall_exists_index {q : (∃ x, p x) → Prop} : (∀ h, q h) ↔ ∀ x (h : p x), q ⟨x, h⟩ := ⟨λ h x hpx, h ⟨x, hpx⟩, λ h ⟨x, hpx⟩, h x hpx⟩ theorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b := forall_exists_index /-- Extract an element from a existential statement, using `classical.some`. -/ -- This enables projection notation. @[reducible] noncomputable def Exists.some {p : α → Prop} (P : ∃ a, p a) : α := classical.some P /-- Show that an element extracted from `P : ∃ a, p a` using `P.some` satisfies `p`. -/ lemma Exists.some_spec {p : α → Prop} (P : ∃ a, p a) : p (P.some) := classical.some_spec P --theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x := --forall_imp_of_exists_imp h theorem not_exists_of_forall_not (h : ∀ x, ¬ p x) : ¬ ∃ x, p x := exists_imp_distrib.2 h @[simp] theorem not_exists : (¬ ∃ x, p x) ↔ ∀ x, ¬ p x := exists_imp_distrib theorem not_forall_of_exists_not : (∃ x, ¬ p x) → ¬ ∀ x, p x | ⟨x, hn⟩ h := hn (h x) -- See Note [decidable namespace] protected theorem decidable.not_forall {p : α → Prop} [decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := ⟨not.decidable_imp_symm $ λ nx x, nx.decidable_imp_symm $ λ h, ⟨x, h⟩, not_forall_of_exists_not⟩ @[simp] theorem not_forall {p : α → Prop} : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := decidable.not_forall -- See Note [decidable namespace] protected theorem decidable.not_forall_not [decidable (∃ x, p x)] : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := (@decidable.not_iff_comm _ _ _ (decidable_of_iff (¬ ∃ x, p x) not_exists)).1 not_exists theorem not_forall_not : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := decidable.not_forall_not -- See Note [decidable namespace] protected theorem decidable.not_exists_not [∀ x, decidable (p x)] : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := by simp [decidable.not_not] @[simp] theorem not_exists_not : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := decidable.not_exists_not theorem forall_imp_iff_exists_imp [ha : nonempty α] : ((∀ x, p x) → b) ↔ ∃ x, p x → b := let ⟨a⟩ := ha in ⟨λ h, not_forall_not.1 $ λ h', classical.by_cases (λ hb : b, h' a $ λ _, hb) (λ hb, hb $ h $ λ x, (not_imp.1 (h' x)).1), λ ⟨x, hx⟩ h, hx (h x)⟩ -- TODO: duplicate of a lemma in core theorem forall_true_iff : (α → true) ↔ true := implies_true_iff α -- Unfortunately this causes simp to loop sometimes, so we -- add the 2 and 3 cases as simp lemmas instead theorem forall_true_iff' (h : ∀ a, p a ↔ true) : (∀ a, p a) ↔ true := iff_true_intro (λ _, of_iff_true (h _)) @[simp] theorem forall_2_true_iff {β : α → Sort*} : (∀ a, β a → true) ↔ true := forall_true_iff' $ λ _, forall_true_iff @[simp] theorem forall_3_true_iff {β : α → Sort*} {γ : Π a, β a → Sort*} : (∀ a (b : β a), γ a b → true) ↔ true := forall_true_iff' $ λ _, forall_2_true_iff lemma exists_unique.exists {α : Sort*} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) @[simp] lemma exists_unique_iff_exists {α : Sort*} [subsingleton α] {p : α → Prop} : (∃! x, p x) ↔ ∃ x, p x := ⟨λ h, h.exists, Exists.imp $ λ x hx, ⟨hx, λ y _, subsingleton.elim y x⟩⟩ @[simp] theorem forall_const (α : Sort*) [i : nonempty α] : (α → b) ↔ b := ⟨i.elim, λ hb x, hb⟩ @[simp] theorem exists_const (α : Sort*) [i : nonempty α] : (∃ x : α, b) ↔ b := ⟨λ ⟨x, h⟩, h, i.elim exists.intro⟩ theorem exists_unique_const (α : Sort*) [i : nonempty α] [subsingleton α] : (∃! x : α, b) ↔ b := by simp theorem forall_and_distrib : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := ⟨λ h, ⟨λ x, (h x).left, λ x, (h x).right⟩, λ ⟨h₁, h₂⟩ x, ⟨h₁ x, h₂ x⟩⟩ theorem exists_or_distrib : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := ⟨λ ⟨x, hpq⟩, hpq.elim (λ hpx, or.inl ⟨x, hpx⟩) (λ hqx, or.inr ⟨x, hqx⟩), λ hepq, hepq.elim (λ ⟨x, hpx⟩, ⟨x, or.inl hpx⟩) (λ ⟨x, hqx⟩, ⟨x, or.inr hqx⟩)⟩ @[simp] theorem exists_and_distrib_left {q : Prop} {p : α → Prop} : (∃x, q ∧ p x) ↔ q ∧ (∃x, p x) := ⟨λ ⟨x, hq, hp⟩, ⟨hq, x, hp⟩, λ ⟨hq, x, hp⟩, ⟨x, hq, hp⟩⟩ @[simp] theorem exists_and_distrib_right {q : Prop} {p : α → Prop} : (∃x, p x ∧ q) ↔ (∃x, p x) ∧ q := by simp [and_comm] @[simp] theorem forall_eq {a' : α} : (∀a, a = a' → p a) ↔ p a' := ⟨λ h, h a' rfl, λ h a e, e.symm ▸ h⟩ @[simp] theorem forall_eq' {a' : α} : (∀a, a' = a → p a) ↔ p a' := by simp [@eq_comm _ a'] theorem and_forall_ne (a : α) : (p a ∧ ∀ b ≠ a, p b) ↔ ∀ b, p b := by simp only [← @forall_eq _ p a, ← forall_and_distrib, ← or_imp_distrib, classical.em, forall_const] -- this lemma is needed to simplify the output of `list.mem_cons_iff` @[simp] theorem forall_eq_or_imp {a' : α} : (∀ a, a = a' ∨ q a → p a) ↔ p a' ∧ ∀ a, q a → p a := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] theorem exists_eq {a' : α} : ∃ a, a = a' := ⟨_, rfl⟩ @[simp] theorem exists_eq' {a' : α} : ∃ a, a' = a := ⟨_, rfl⟩ @[simp] theorem exists_eq_left {a' : α} : (∃ a, a = a' ∧ p a) ↔ p a' := ⟨λ ⟨a, e, h⟩, e ▸ h, λ h, ⟨_, rfl, h⟩⟩ @[simp] theorem exists_eq_right {a' : α} : (∃ a, p a ∧ a = a') ↔ p a' := (exists_congr $ by exact λ a, and.comm).trans exists_eq_left @[simp] theorem exists_eq_right_right {a' : α} : (∃ (a : α), p a ∧ b ∧ a = a') ↔ p a' ∧ b := ⟨λ ⟨_, hp, hq, rfl⟩, ⟨hp, hq⟩, λ ⟨hp, hq⟩, ⟨a', hp, hq, rfl⟩⟩ @[simp] theorem exists_eq_right_right' {a' : α} : (∃ (a : α), p a ∧ b ∧ a' = a) ↔ p a' ∧ b := ⟨λ ⟨_, hp, hq, rfl⟩, ⟨hp, hq⟩, λ ⟨hp, hq⟩, ⟨a', hp, hq, rfl⟩⟩ @[simp] theorem exists_apply_eq_apply (f : α → β) (a' : α) : ∃ a, f a = f a' := ⟨a', rfl⟩ @[simp] theorem exists_apply_eq_apply' (f : α → β) (a' : α) : ∃ a, f a' = f a := ⟨a', rfl⟩ @[simp] theorem exists_exists_and_eq_and {f : α → β} {p : α → Prop} {q : β → Prop} : (∃ b, (∃ a, p a ∧ f a = b) ∧ q b) ↔ ∃ a, p a ∧ q (f a) := ⟨λ ⟨b, ⟨a, ha, hab⟩, hb⟩, ⟨a, ha, hab.symm ▸ hb⟩, λ ⟨a, hp, hq⟩, ⟨f a, ⟨a, hp, rfl⟩, hq⟩⟩ @[simp] theorem exists_exists_eq_and {f : α → β} {p : β → Prop} : (∃ b, (∃ a, f a = b) ∧ p b) ↔ ∃ a, p (f a) := ⟨λ ⟨b, ⟨a, ha⟩, hb⟩, ⟨a, ha.symm ▸ hb⟩, λ ⟨a, ha⟩, ⟨f a, ⟨a, rfl⟩, ha⟩⟩ @[simp] lemma exists_or_eq_left (y : α) (p : α → Prop) : ∃ (x : α), x = y ∨ p x := ⟨y, or.inl rfl⟩ @[simp] lemma exists_or_eq_right (y : α) (p : α → Prop) : ∃ (x : α), p x ∨ x = y := ⟨y, or.inr rfl⟩ @[simp] lemma exists_or_eq_left' (y : α) (p : α → Prop) : ∃ (x : α), y = x ∨ p x := ⟨y, or.inl rfl⟩ @[simp] lemma exists_or_eq_right' (y : α) (p : α → Prop) : ∃ (x : α), p x ∨ y = x := ⟨y, or.inr rfl⟩ @[simp] theorem forall_apply_eq_imp_iff {f : α → β} {p : β → Prop} : (∀ a, ∀ b, f a = b → p b) ↔ (∀ a, p (f a)) := ⟨λ h a, h a (f a) rfl, λ h a b hab, hab ▸ h a⟩ @[simp] theorem forall_apply_eq_imp_iff' {f : α → β} {p : β → Prop} : (∀ b, ∀ a, f a = b → p b) ↔ (∀ a, p (f a)) := by { rw forall_swap, simp } @[simp] theorem forall_eq_apply_imp_iff {f : α → β} {p : β → Prop} : (∀ a, ∀ b, b = f a → p b) ↔ (∀ a, p (f a)) := by simp [@eq_comm _ _ (f _)] @[simp] theorem forall_eq_apply_imp_iff' {f : α → β} {p : β → Prop} : (∀ b, ∀ a, b = f a → p b) ↔ (∀ a, p (f a)) := by { rw forall_swap, simp } @[simp] theorem forall_apply_eq_imp_iff₂ {f : α → β} {p : α → Prop} {q : β → Prop} : (∀ b, ∀ a, p a → f a = b → q b) ↔ ∀ a, p a → q (f a) := ⟨λ h a ha, h (f a) a ha rfl, λ h b a ha hb, hb ▸ h a ha⟩ @[simp] theorem exists_eq_left' {a' : α} : (∃ a, a' = a ∧ p a) ↔ p a' := by simp [@eq_comm _ a'] @[simp] theorem exists_eq_right' {a' : α} : (∃ a, p a ∧ a' = a) ↔ p a' := by simp [@eq_comm _ a'] theorem exists_comm {p : α → β → Prop} : (∃ a b, p a b) ↔ ∃ b a, p a b := ⟨λ ⟨a, b, h⟩, ⟨b, a, h⟩, λ ⟨b, a, h⟩, ⟨a, b, h⟩⟩ theorem and.exists {p q : Prop} {f : p ∧ q → Prop} : (∃ h, f h) ↔ ∃ hp hq, f ⟨hp, hq⟩ := ⟨λ ⟨h, H⟩, ⟨h.1, h.2, H⟩, λ ⟨hp, hq, H⟩, ⟨⟨hp, hq⟩, H⟩⟩ theorem forall_or_of_or_forall (h : b ∨ ∀x, p x) (x) : b ∨ p x := h.imp_right $ λ h₂, h₂ x -- See Note [decidable namespace] protected theorem decidable.forall_or_distrib_left {q : Prop} {p : α → Prop} [decidable q] : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := ⟨λ h, if hq : q then or.inl hq else or.inr $ λ x, (h x).resolve_left hq, forall_or_of_or_forall⟩ theorem forall_or_distrib_left {q : Prop} {p : α → Prop} : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := decidable.forall_or_distrib_left -- See Note [decidable namespace] protected theorem decidable.forall_or_distrib_right {q : Prop} {p : α → Prop} [decidable q] : (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := by simp [or_comm, decidable.forall_or_distrib_left] theorem forall_or_distrib_right {q : Prop} {p : α → Prop} : (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := decidable.forall_or_distrib_right /-- A predicate holds everywhere on the image of a surjective functions iff it holds everywhere. -/ theorem forall_iff_forall_surj {α β : Type*} {f : α → β} (h : function.surjective f) {P : β → Prop} : (∀ a, P (f a)) ↔ ∀ b, P b := ⟨λ ha b, by cases h b with a hab; rw ←hab; exact ha a, λ hb a, hb $ f a⟩ @[simp] theorem exists_prop {p q : Prop} : (∃ h : p, q) ↔ p ∧ q := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩⟩ theorem exists_unique_prop {p q : Prop} : (∃! h : p, q) ↔ p ∧ q := by simp @[simp] theorem exists_false : ¬ (∃a:α, false) := assume ⟨a, h⟩, h @[simp] lemma exists_unique_false : ¬ (∃! (a : α), false) := assume ⟨a, h, h'⟩, h theorem Exists.fst {p : b → Prop} : Exists p → b | ⟨h, _⟩ := h theorem Exists.snd {p : b → Prop} : ∀ h : Exists p, p h.fst | ⟨_, h⟩ := h theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ h' : p, q h') ↔ q h := @forall_const (q h) p ⟨h⟩ theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ h' : p, q h') ↔ q h := @exists_const (q h) p ⟨h⟩ theorem exists_unique_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃! h' : p, q h') ↔ q h := @exists_unique_const (q h) p ⟨h⟩ _ theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬ p) : (∀ h' : p, q h') ↔ true := iff_true_intro $ λ h, hn.elim h theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬ p → ¬ (∃ h' : p, q h') := mt Exists.fst @[congr] lemma exists_prop_congr {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : Exists q ↔ ∃ h : p', q' (hp.2 h) := ⟨λ ⟨_, _⟩, ⟨hp.1 ‹_›, (hq _).1 ‹_›⟩, λ ⟨_, _⟩, ⟨_, (hq _).2 ‹_›⟩⟩ @[congr] lemma exists_prop_congr' {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : Exists q = ∃ h : p', q' (hp.2 h) := propext (exists_prop_congr hq _) @[simp] lemma exists_true_left (p : true → Prop) : (∃ x, p x) ↔ p true.intro := exists_prop_of_true _ @[simp] lemma exists_false_left (p : false → Prop) : ¬ ∃ x, p x := exists_prop_of_false not_false lemma exists_unique.unique {α : Sort*} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := unique_of_exists_unique h py₁ py₂ @[congr] lemma forall_prop_congr {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) ↔ ∀ h : p', q' (hp.2 h) := ⟨λ h1 h2, (hq _).1 (h1 (hp.2 _)), λ h1 h2, (hq _).2 (h1 (hp.1 h2))⟩ @[congr] lemma forall_prop_congr' {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) = ∀ h : p', q' (hp.2 h) := propext (forall_prop_congr hq _) @[simp] lemma forall_true_left (p : true → Prop) : (∀ x, p x) ↔ p true.intro := forall_prop_of_true _ @[simp] lemma forall_false_left (p : false → Prop) : (∀ x, p x) ↔ true := forall_prop_of_false not_false lemma exists_unique.elim2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π x (h : p x), Prop} {b : Prop} (h₂ : ∃! x (h : p x), q x h) (h₁ : ∀ x (h : p x), q x h → (∀ y (hy : p y), q y hy → y = x) → b) : b := begin simp only [exists_unique_iff_exists] at h₂, apply h₂.elim, exact λ x ⟨hxp, hxq⟩ H, h₁ x hxp hxq (λ y hyp hyq, H y ⟨hyp, hyq⟩) end lemma exists_unique.intro2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π (x : α) (h : p x), Prop} (w : α) (hp : p w) (hq : q w hp) (H : ∀ y (hy : p y), q y hy → y = w) : ∃! x (hx : p x), q x hx := begin simp only [exists_unique_iff_exists], exact exists_unique.intro w ⟨hp, hq⟩ (λ y ⟨hyp, hyq⟩, H y hyp hyq) end lemma exists_unique.exists2 {α : Sort*} {p : α → Sort*} {q : Π (x : α) (h : p x), Prop} (h : ∃! x (hx : p x), q x hx) : ∃ x (hx : p x), q x hx := h.exists.imp (λ x hx, hx.exists) lemma exists_unique.unique2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π (x : α) (hx : p x), Prop} (h : ∃! x (hx : p x), q x hx) {y₁ y₂ : α} (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁) (hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ := begin simp only [exists_unique_iff_exists] at h, exact h.unique ⟨hpy₁, hqy₁⟩ ⟨hpy₂, hqy₂⟩ end end quantifiers /-! ### Classical lemmas -/ namespace classical variables {α : Sort*} {p : α → Prop} theorem cases {p : Prop → Prop} (h1 : p true) (h2 : p false) : ∀a, p a := assume a, cases_on a h1 h2 /- use shortened names to avoid conflict when classical namespace is open. -/ noncomputable lemma dec (p : Prop) : decidable p := -- see Note [classical lemma] by apply_instance noncomputable lemma dec_pred (p : α → Prop) : decidable_pred p := -- see Note [classical lemma] by apply_instance noncomputable lemma dec_rel (p : α → α → Prop) : decidable_rel p := -- see Note [classical lemma] by apply_instance noncomputable lemma dec_eq (α : Sort*) : decidable_eq α := -- see Note [classical lemma] by apply_instance /-- We make decidability results that depends on `classical.choice` noncomputable lemmas. * We have to mark them as noncomputable, because otherwise Lean will try to generate bytecode for them, and fail because it depends on `classical.choice`. * We make them lemmas, and not definitions, because otherwise later definitions will raise \"failed to generate bytecode\" errors when writing something like `letI := classical.dec_eq _`. Cf. <https://leanprover-community.github.io/archive/stream/113488-general/topic/noncomputable.20theorem.html> -/ library_note "classical lemma" /-- Construct a function from a default value `H0`, and a function to use if there exists a value satisfying the predicate. -/ @[elab_as_eliminator] noncomputable def {u} exists_cases {C : Sort u} (H0 : C) (H : ∀ a, p a → C) : C := if h : ∃ a, p a then H (classical.some h) (classical.some_spec h) else H0 lemma some_spec2 {α : Sort*} {p : α → Prop} {h : ∃a, p a} (q : α → Prop) (hpq : ∀a, p a → q a) : q (some h) := hpq _ $ some_spec _ /-- A version of classical.indefinite_description which is definitionally equal to a pair -/ noncomputable def subtype_of_exists {α : Type*} {P : α → Prop} (h : ∃ x, P x) : {x // P x} := ⟨classical.some h, classical.some_spec h⟩ /-- A version of `by_contradiction` that uses types instead of propositions. -/ protected noncomputable def by_contradiction' {α : Sort*} (H : ¬ (α → false)) : α := classical.choice $ peirce _ false $ λ h, (H $ λ a, h ⟨a⟩).elim /-- `classical.by_contradiction'` is equivalent to lean's axiom `classical.choice`. -/ def choice_of_by_contradiction' {α : Sort*} (contra : ¬ (α → false) → α) : nonempty α → α := λ H, contra H.elim end classical /-- This function has the same type as `exists.rec_on`, and can be used to case on an equality, but `exists.rec_on` can only eliminate into Prop, while this version eliminates into any universe using the axiom of choice. -/ @[elab_as_eliminator] noncomputable def {u} exists.classical_rec_on {α} {p : α → Prop} (h : ∃ a, p a) {C : Sort u} (H : ∀ a, p a → C) : C := H (classical.some h) (classical.some_spec h) /-! ### Declarations about bounded quantifiers -/ section bounded_quantifiers variables {α : Sort*} {r p q : α → Prop} {P Q : ∀ x, p x → Prop} {b : Prop} theorem bex_def : (∃ x (h : p x), q x) ↔ ∃ x, p x ∧ q x := ⟨λ ⟨x, px, qx⟩, ⟨x, px, qx⟩, λ ⟨x, px, qx⟩, ⟨x, px, qx⟩⟩ theorem bex.elim {b : Prop} : (∃ x h, P x h) → (∀ a h, P a h → b) → b | ⟨a, h₁, h₂⟩ h' := h' a h₁ h₂ theorem bex.intro (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ x (h : p x), P x h := ⟨a, h₁, h₂⟩ theorem ball_congr (H : ∀ x h, P x h ↔ Q x h) : (∀ x h, P x h) ↔ (∀ x h, Q x h) := forall_congr $ λ x, forall_congr (H x) theorem bex_congr (H : ∀ x h, P x h ↔ Q x h) : (∃ x h, P x h) ↔ (∃ x h, Q x h) := exists_congr $ λ x, exists_congr (H x) theorem bex_eq_left {a : α} : (∃ x (_ : x = a), p x) ↔ p a := by simp only [exists_prop, exists_eq_left] theorem ball.imp_right (H : ∀ x h, (P x h → Q x h)) (h₁ : ∀ x h, P x h) (x h) : Q x h := H _ _ $ h₁ _ _ theorem bex.imp_right (H : ∀ x h, (P x h → Q x h)) : (∃ x h, P x h) → ∃ x h, Q x h | ⟨x, h, h'⟩ := ⟨_, _, H _ _ h'⟩ theorem ball.imp_left (H : ∀ x, p x → q x) (h₁ : ∀ x, q x → r x) (x) (h : p x) : r x := h₁ _ $ H _ h theorem bex.imp_left (H : ∀ x, p x → q x) : (∃ x (_ : p x), r x) → ∃ x (_ : q x), r x | ⟨x, hp, hr⟩ := ⟨x, H _ hp, hr⟩ theorem ball_of_forall (h : ∀ x, p x) (x) : p x := h x theorem forall_of_ball (H : ∀ x, p x) (h : ∀ x, p x → q x) (x) : q x := h x $ H x theorem bex_of_exists (H : ∀ x, p x) : (∃ x, q x) → ∃ x (_ : p x), q x | ⟨x, hq⟩ := ⟨x, H x, hq⟩ theorem exists_of_bex : (∃ x (_ : p x), q x) → ∃ x, q x | ⟨x, _, hq⟩ := ⟨x, hq⟩ @[simp] theorem bex_imp_distrib : ((∃ x h, P x h) → b) ↔ (∀ x h, P x h → b) := by simp theorem not_bex : (¬ ∃ x h, P x h) ↔ ∀ x h, ¬ P x h := bex_imp_distrib theorem not_ball_of_bex_not : (∃ x h, ¬ P x h) → ¬ ∀ x h, P x h | ⟨x, h, hp⟩ al := hp $ al x h -- See Note [decidable namespace] protected theorem decidable.not_ball [decidable (∃ x h, ¬ P x h)] [∀ x h, decidable (P x h)] : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := ⟨not.decidable_imp_symm $ λ nx x h, nx.decidable_imp_symm $ λ h', ⟨x, h, h'⟩, not_ball_of_bex_not⟩ theorem not_ball : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := decidable.not_ball theorem ball_true_iff (p : α → Prop) : (∀ x, p x → true) ↔ true := iff_true_intro (λ h hrx, trivial) theorem ball_and_distrib : (∀ x h, P x h ∧ Q x h) ↔ (∀ x h, P x h) ∧ (∀ x h, Q x h) := iff.trans (forall_congr $ λ x, forall_and_distrib) forall_and_distrib theorem bex_or_distrib : (∃ x h, P x h ∨ Q x h) ↔ (∃ x h, P x h) ∨ (∃ x h, Q x h) := iff.trans (exists_congr $ λ x, exists_or_distrib) exists_or_distrib theorem ball_or_left_distrib : (∀ x, p x ∨ q x → r x) ↔ (∀ x, p x → r x) ∧ (∀ x, q x → r x) := iff.trans (forall_congr $ λ x, or_imp_distrib) forall_and_distrib theorem bex_or_left_distrib : (∃ x (_ : p x ∨ q x), r x) ↔ (∃ x (_ : p x), r x) ∨ (∃ x (_ : q x), r x) := by simp only [exists_prop]; exact iff.trans (exists_congr $ λ x, or_and_distrib_right) exists_or_distrib end bounded_quantifiers namespace classical local attribute [instance] prop_decidable theorem not_ball {α : Sort*} {p : α → Prop} {P : Π (x : α), p x → Prop} : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := _root_.not_ball end classical lemma ite_eq_iff {α} {p : Prop} [decidable p] {a b c : α} : (if p then a else b) = c ↔ p ∧ a = c ∨ ¬p ∧ b = c := by by_cases p; simp * @[simp] lemma ite_eq_left_iff {α} {p : Prop} [decidable p] {a b : α} : (if p then a else b) = a ↔ (¬p → b = a) := by by_cases p; simp * @[simp] lemma ite_eq_right_iff {α} {p : Prop} [decidable p] {a b : α} : (if p then a else b) = b ↔ (p → a = b) := by by_cases p; simp * lemma ite_eq_or_eq {α} {p : Prop} [decidable p] (a b : α) : ite p a b = a ∨ ite p a b = b := decidable.by_cases (λ h, or.inl (if_pos h)) (λ h, or.inr (if_neg h)) /-! ### Declarations about `nonempty` -/ section nonempty variables {α β : Type*} {γ : α → Type*} attribute [simp] nonempty_of_inhabited @[priority 20] instance has_zero.nonempty [has_zero α] : nonempty α := ⟨0⟩ @[priority 20] instance has_one.nonempty [has_one α] : nonempty α := ⟨1⟩ lemma exists_true_iff_nonempty {α : Sort*} : (∃a:α, true) ↔ nonempty α := iff.intro (λ⟨a, _⟩, ⟨a⟩) (λ⟨a⟩, ⟨a, trivial⟩) @[simp] lemma nonempty_Prop {p : Prop} : nonempty p ↔ p := iff.intro (assume ⟨h⟩, h) (assume h, ⟨h⟩) lemma not_nonempty_iff_imp_false {α : Sort*} : ¬ nonempty α ↔ α → false := ⟨λ h a, h ⟨a⟩, λ h ⟨a⟩, h a⟩ @[simp] lemma nonempty_sigma : nonempty (Σa:α, γ a) ↔ (∃a:α, nonempty (γ a)) := iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩) @[simp] lemma nonempty_subtype {α} {p : α → Prop} : nonempty (subtype p) ↔ (∃a:α, p a) := iff.intro (assume ⟨⟨a, h⟩⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a, h⟩⟩) @[simp] lemma nonempty_prod : nonempty (α × β) ↔ (nonempty α ∧ nonempty β) := iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩) @[simp] lemma nonempty_pprod {α β} : nonempty (pprod α β) ↔ (nonempty α ∧ nonempty β) := iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩) @[simp] lemma nonempty_sum : nonempty (α ⊕ β) ↔ (nonempty α ∨ nonempty β) := iff.intro (assume ⟨h⟩, match h with sum.inl a := or.inl ⟨a⟩ | sum.inr b := or.inr ⟨b⟩ end) (assume h, match h with or.inl ⟨a⟩ := ⟨sum.inl a⟩ | or.inr ⟨b⟩ := ⟨sum.inr b⟩ end) @[simp] lemma nonempty_psum {α β} : nonempty (psum α β) ↔ (nonempty α ∨ nonempty β) := iff.intro (assume ⟨h⟩, match h with psum.inl a := or.inl ⟨a⟩ | psum.inr b := or.inr ⟨b⟩ end) (assume h, match h with or.inl ⟨a⟩ := ⟨psum.inl a⟩ | or.inr ⟨b⟩ := ⟨psum.inr b⟩ end) @[simp] lemma nonempty_psigma {α} {β : α → Sort*} : nonempty (psigma β) ↔ (∃a:α, nonempty (β a)) := iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩) @[simp] lemma nonempty_empty : ¬ nonempty empty := assume ⟨h⟩, h.elim @[simp] lemma nonempty_ulift : nonempty (ulift α) ↔ nonempty α := iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩) @[simp] lemma nonempty_plift {α} : nonempty (plift α) ↔ nonempty α := iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩) @[simp] lemma nonempty.forall {α} {p : nonempty α → Prop} : (∀h:nonempty α, p h) ↔ (∀a, p ⟨a⟩) := iff.intro (assume h a, h _) (assume h ⟨a⟩, h _) @[simp] lemma nonempty.exists {α} {p : nonempty α → Prop} : (∃h:nonempty α, p h) ↔ (∃a, p ⟨a⟩) := iff.intro (assume ⟨⟨a⟩, h⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a⟩, h⟩) lemma classical.nonempty_pi {α} {β : α → Sort*} : nonempty (Πa:α, β a) ↔ (∀a:α, nonempty (β a)) := iff.intro (assume ⟨f⟩ a, ⟨f a⟩) (assume f, ⟨assume a, classical.choice $ f a⟩) /-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued) `inhabited` instance. `classical.inhabited_of_nonempty` already exists, in `core/init/classical.lean`, but the assumption is not a type class argument, which makes it unsuitable for some applications. -/ noncomputable def classical.inhabited_of_nonempty' {α} [h : nonempty α] : inhabited α := ⟨classical.choice h⟩ /-- Using `classical.choice`, extracts a term from a `nonempty` type. -/ @[reducible] protected noncomputable def nonempty.some {α} (h : nonempty α) : α := classical.choice h /-- Using `classical.choice`, extracts a term from a `nonempty` type. -/ @[reducible] protected noncomputable def classical.arbitrary (α) [h : nonempty α] : α := classical.choice h /-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty. `nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/ lemma nonempty.map {α β} (f : α → β) : nonempty α → nonempty β | ⟨h⟩ := ⟨f h⟩ protected lemma nonempty.map2 {α β γ : Sort*} (f : α → β → γ) : nonempty α → nonempty β → nonempty γ | ⟨x⟩ ⟨y⟩ := ⟨f x y⟩ protected lemma nonempty.congr {α β} (f : α → β) (g : β → α) : nonempty α ↔ nonempty β := ⟨nonempty.map f, nonempty.map g⟩ lemma nonempty.elim_to_inhabited {α : Sort*} [h : nonempty α] {p : Prop} (f : inhabited α → p) : p := h.elim $ f ∘ inhabited.mk instance {α β} [h : nonempty α] [h2 : nonempty β] : nonempty (α × β) := h.elim $ λ g, h2.elim $ λ g2, ⟨⟨g, g2⟩⟩ end nonempty lemma subsingleton_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : subsingleton α := ⟨λ x, false.elim $ not_nonempty_iff_imp_false.mp h x⟩ section ite /-- A `dite` whose results do not actually depend on the condition may be reduced to an `ite`. -/ @[simp] lemma dite_eq_ite (P : Prop) [decidable P] {α : Sort*} (x y : α) : dite P (λ h, x) (λ h, y) = ite P x y := rfl /-- A function applied to a `dite` is a `dite` of that function applied to each of the branches. -/ lemma apply_dite {α β : Sort*} (f : α → β) (P : Prop) [decidable P] (x : P → α) (y : ¬P → α) : f (dite P x y) = dite P (λ h, f (x h)) (λ h, f (y h)) := by { by_cases h : P; simp [h] } /-- A function applied to a `ite` is a `ite` of that function applied to each of the branches. -/ lemma apply_ite {α β : Sort*} (f : α → β) (P : Prop) [decidable P] (x y : α) : f (ite P x y) = ite P (f x) (f y) := apply_dite f P (λ _, x) (λ _, y) /-- A two-argument function applied to two `dite`s is a `dite` of that two-argument function applied to each of the branches. -/ lemma apply_dite2 {α β γ : Sort*} (f : α → β → γ) (P : Prop) [decidable P] (a : P → α) (b : ¬P → α) (c : P → β) (d : ¬P → β) : f (dite P a b) (dite P c d) = dite P (λ h, f (a h) (c h)) (λ h, f (b h) (d h)) := by { by_cases h : P; simp [h] } /-- A two-argument function applied to two `ite`s is a `ite` of that two-argument function applied to each of the branches. -/ lemma apply_ite2 {α β γ : Sort*} (f : α → β → γ) (P : Prop) [decidable P] (a b : α) (c d : β) : f (ite P a b) (ite P c d) = ite P (f a c) (f b d) := apply_dite2 f P (λ _, a) (λ _, b) (λ _, c) (λ _, d) /-- A 'dite' producing a `Pi` type `Π a, β a`, applied to a value `x : α` is a `dite` that applies either branch to `x`. -/ lemma dite_apply {α : Sort*} {β : α → Sort*} (P : Prop) [decidable P] (f : P → Π a, β a) (g : ¬ P → Π a, β a) (x : α) : (dite P f g) x = dite P (λ h, f h x) (λ h, g h x) := by { by_cases h : P; simp [h] } /-- A 'ite' producing a `Pi` type `Π a, β a`, applied to a value `x : α` is a `ite` that applies either branch to `x` -/ lemma ite_apply {α : Sort*} {β : α → Sort*} (P : Prop) [decidable P] (f g : Π a, β a) (x : α) : (ite P f g) x = ite P (f x) (g x) := dite_apply P (λ _, f) (λ _, g) x /-- Negation of the condition `P : Prop` in a `dite` is the same as swapping the branches. -/ @[simp] lemma dite_not {α : Sort*} (P : Prop) [decidable P] (x : ¬ P → α) (y : ¬¬ P → α) : dite (¬ P) x y = dite P (λ h, y (not_not_intro h)) x := by { by_cases h : P; simp [h] } /-- Negation of the condition `P : Prop` in a `ite` is the same as swapping the branches. -/ @[simp] lemma ite_not {α : Sort*} (P : Prop) [decidable P] (x y : α) : ite (¬ P) x y = ite P y x := dite_not P (λ _, x) (λ _, y) lemma ite_and {α} {p q : Prop} [decidable p] [decidable q] {x y : α} : ite (p ∧ q) x y = ite p (ite q x y) y := by { by_cases hp : p; by_cases hq : q; simp [hp, hq] } end ite
fa3239b9700de2b74890791ffae87501b6896544
82e44445c70db0f03e30d7be725775f122d72f3e
/src/order/iterate.lean
26da753200741d3cfe641c112e9faeddaebff717
[ "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
6,450
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import order.basic import logic.function.iterate import data.nat.basic /-! # Inequalities on iterates In this file we prove some inequalities comparing `f^[n] x` and `g^[n] x` where `f` and `g` are two self-maps that commute with each other. Current selection of inequalities is motivated by formalization of the rotation number of a circle homeomorphism. -/ variables {α : Type*} namespace monotone variables [preorder α] {f : α → α} {x y : ℕ → α} lemma seq_le_seq (hf : monotone f) (n : ℕ) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n ≤ y n := begin induction n with n ihn, { exact h₀ }, { refine (hx _ n.lt_succ_self).trans ((hf $ ihn _ _).trans (hy _ n.lt_succ_self)), exact λ k hk, hx _ (hk.trans n.lt_succ_self), exact λ k hk, hy _ (hk.trans n.lt_succ_self) } end lemma seq_pos_lt_seq_of_lt_of_le (hf : monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) < f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n < y n := begin induction n with n ihn, { exact hn.false.elim }, suffices : x n ≤ y n, from (hx n n.lt_succ_self).trans_le ((hf this).trans $ hy n n.lt_succ_self), cases n, { exact h₀ }, refine (ihn n.zero_lt_succ (λ k hk, hx _ _) (λ k hk, hy _ _)).le; exact hk.trans n.succ.lt_succ_self end lemma seq_pos_lt_seq_of_le_of_lt (hf : monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) < y (k + 1)) : x n < y n := hf.order_dual.seq_pos_lt_seq_of_lt_of_le hn h₀ hy hx lemma seq_lt_seq_of_lt_of_le (hf : monotone f) (n : ℕ) (h₀ : x 0 < y 0) (hx : ∀ k < n, x (k + 1) < f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n < y n := by { cases n, exacts [h₀, hf.seq_pos_lt_seq_of_lt_of_le n.zero_lt_succ h₀.le hx hy] } lemma seq_lt_seq_of_le_of_lt (hf : monotone f) (n : ℕ) (h₀ : x 0 < y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) < y (k + 1)) : x n < y n := hf.order_dual.seq_lt_seq_of_lt_of_le n h₀ hy hx end monotone namespace function section preorder variables [preorder α] {f : α → α} lemma id_le_iterate_of_id_le (h : id ≤ f) : ∀ n, id ≤ (f^[n]) | 0 := by { rw function.iterate_zero, exact le_rfl } | (n + 1) := λ x, begin rw function.iterate_succ_apply', exact (id_le_iterate_of_id_le n x).trans (h _), end lemma iterate_le_id_of_le_id (h : f ≤ id) : ∀ n, (f^[n]) ≤ id := @id_le_iterate_of_id_le (order_dual α) _ f h lemma iterate_le_iterate_of_id_le (h : id ≤ f) {m n : ℕ} (hmn : m ≤ n) : f^[m] ≤ (f^[n]) := begin rw [←nat.add_sub_cancel' hmn, add_comm, function.iterate_add], exact λ x, id_le_iterate_of_id_le h _ _, end lemma iterate_le_iterate_of_le_id (h : f ≤ id) {m n : ℕ} (hmn : m ≤ n) : f^[n] ≤ (f^[m]) := @iterate_le_iterate_of_id_le (order_dual α) _ f h m n hmn end preorder namespace commute section preorder variables [preorder α] {f g : α → α} lemma iterate_le_of_map_le (h : commute f g) (hf : monotone f) (hg : monotone g) {x} (hx : f x ≤ g x) (n : ℕ) : f^[n] x ≤ (g^[n]) x := by refine hf.seq_le_seq n _ (λ k hk, _) (λ k hk, _); simp [iterate_succ' f, h.iterate_right _ _, hg.iterate _ hx] lemma iterate_pos_lt_of_map_lt (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x} (hx : f x < g x) {n} (hn : 0 < n) : f^[n] x < (g^[n]) x := by refine hf.seq_pos_lt_seq_of_le_of_lt hn _ (λ k hk, _) (λ k hk, _); simp [iterate_succ' f, h.iterate_right _ _, hg.iterate _ hx] lemma iterate_pos_lt_of_map_lt' (h : commute f g) (hf : strict_mono f) (hg : monotone g) {x} (hx : f x < g x) {n} (hn : 0 < n) : f^[n] x < (g^[n]) x := @iterate_pos_lt_of_map_lt (order_dual α) _ g f h.symm hg.order_dual hf.order_dual x hx n hn end preorder variables [linear_order α] {f g : α → α} lemma iterate_pos_lt_iff_map_lt (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x n} (hn : 0 < n) : f^[n] x < (g^[n]) x ↔ f x < g x := begin rcases lt_trichotomy (f x) (g x) with H|H|H, { simp only [*, iterate_pos_lt_of_map_lt] }, { simp only [*, h.iterate_eq_of_map_eq, lt_irrefl] }, { simp only [lt_asymm H, lt_asymm (h.symm.iterate_pos_lt_of_map_lt' hg hf H hn)] } end lemma iterate_pos_lt_iff_map_lt' (h : commute f g) (hf : strict_mono f) (hg : monotone g) {x n} (hn : 0 < n) : f^[n] x < (g^[n]) x ↔ f x < g x := @iterate_pos_lt_iff_map_lt (order_dual α) _ _ _ h.symm hg.order_dual hf.order_dual x n hn lemma iterate_pos_le_iff_map_le (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x n} (hn : 0 < n) : f^[n] x ≤ (g^[n]) x ↔ f x ≤ g x := by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt' hg hf hn) lemma iterate_pos_le_iff_map_le' (h : commute f g) (hf : strict_mono f) (hg : monotone g) {x n} (hn : 0 < n) : f^[n] x ≤ (g^[n]) x ↔ f x ≤ g x := by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt hg hf hn) lemma iterate_pos_eq_iff_map_eq (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x n} (hn : 0 < n) : f^[n] x = (g^[n]) x ↔ f x = g x := by simp only [le_antisymm_iff, h.iterate_pos_le_iff_map_le hf hg hn, h.symm.iterate_pos_le_iff_map_le' hg hf hn] end commute end function namespace monotone open function section variables {β : Type*} [preorder β] {f : α → α} {g : β → β} {h : α → β} lemma le_iterate_comp_of_le (hg : monotone g) (H : ∀ x, h (f x) ≤ g (h x)) (n : ℕ) (x : α) : h (f^[n] x) ≤ (g^[n] (h x)) := by refine hg.seq_le_seq n _ (λ k hk, _) (λ k hk, _); simp [iterate_succ', H _] lemma iterate_comp_le_of_le (hg : monotone g) (H : ∀ x, g (h x) ≤ h (f x)) (n : ℕ) (x : α) : g^[n] (h x) ≤ h (f^[n] x) := hg.order_dual.le_iterate_comp_of_le H n x end variables [preorder α] {f g : α → α} /-- If `f ≤ g` and `f` is monotone, then `f^[n] ≤ g^[n]`. -/ lemma iterate_le_of_le (hf : monotone f) (h : f ≤ g) (n : ℕ) : f^[n] ≤ (g^[n]) := hf.iterate_comp_le_of_le h n /-- If `f ≤ g` and `f` is monotone, then `f^[n] ≤ g^[n]`. -/ lemma iterate_ge_of_ge (hg : monotone g) (h : f ≤ g) (n : ℕ) : f^[n] ≤ (g^[n]) := hg.order_dual.iterate_le_of_le h n end monotone
538e9acbccf33059085ad4e6cd0f4796c39554ae
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/upper_lower.lean
d52a2b05f96bc96f02b862c81ebf0e2373e64275
[ "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
7,711
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.order.group.defs import data.set.pointwise.smul import order.upper_lower.basic /-! # Algebraic operations on upper/lower sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Upper/lower sets are preserved under pointwise algebraic operations in ordered groups. -/ open function set open_locale pointwise section ordered_comm_monoid variables {α : Type*} [ordered_comm_monoid α] {s : set α} {x : α} @[to_additive] lemma is_upper_set.smul_subset (hs : is_upper_set s) (hx : 1 ≤ x) : x • s ⊆ s := smul_set_subset_iff.2 $ λ y, hs $ le_mul_of_one_le_left' hx @[to_additive] lemma is_lower_set.smul_subset (hs : is_lower_set s) (hx : x ≤ 1) : x • s ⊆ s := smul_set_subset_iff.2 $ λ y, hs $ mul_le_of_le_one_left' hx end ordered_comm_monoid section ordered_comm_group variables {α : Type*} [ordered_comm_group α] {s t : set α} {a : α} @[to_additive] lemma is_upper_set.smul (hs : is_upper_set s) : is_upper_set (a • s) := hs.image $ order_iso.mul_left _ @[to_additive] lemma is_lower_set.smul (hs : is_lower_set s) : is_lower_set (a • s) := hs.image $ order_iso.mul_left _ @[to_additive] lemma set.ord_connected.smul (hs : s.ord_connected) : (a • s).ord_connected := begin rw [←hs.upper_closure_inter_lower_closure, smul_set_inter], exact (upper_closure _).upper.smul.ord_connected.inter (lower_closure _).lower.smul.ord_connected, end @[to_additive] lemma is_upper_set.mul_left (ht : is_upper_set t) : is_upper_set (s * t) := by { rw [←smul_eq_mul, ←bUnion_smul_set], exact is_upper_set_Union₂ (λ x hx, ht.smul) } @[to_additive] lemma is_upper_set.mul_right (hs : is_upper_set s) : is_upper_set (s * t) := by { rw mul_comm, exact hs.mul_left } @[to_additive] lemma is_lower_set.mul_left (ht : is_lower_set t) : is_lower_set (s * t) := ht.to_dual.mul_left @[to_additive] lemma is_lower_set.mul_right (hs : is_lower_set s) : is_lower_set (s * t) := hs.to_dual.mul_right @[to_additive] lemma is_upper_set.inv (hs : is_upper_set s) : is_lower_set s⁻¹ := λ x y h, hs $ inv_le_inv' h @[to_additive] lemma is_lower_set.inv (hs : is_lower_set s) : is_upper_set s⁻¹ := λ x y h, hs $ inv_le_inv' h @[to_additive] lemma is_upper_set.div_left (ht : is_upper_set t) : is_lower_set (s / t) := by { rw div_eq_mul_inv, exact ht.inv.mul_left } @[to_additive] lemma is_upper_set.div_right (hs : is_upper_set s) : is_upper_set (s / t) := by { rw div_eq_mul_inv, exact hs.mul_right } @[to_additive] lemma is_lower_set.div_left (ht : is_lower_set t) : is_upper_set (s / t) := ht.to_dual.div_left @[to_additive] lemma is_lower_set.div_right (hs : is_lower_set s) : is_lower_set (s / t) := hs.to_dual.div_right namespace upper_set @[to_additive] instance : has_one (upper_set α) := ⟨Ici 1⟩ @[to_additive] instance : has_mul (upper_set α) := ⟨λ s t, ⟨image2 (*) s t, s.2.mul_right⟩⟩ @[to_additive] instance : has_div (upper_set α) := ⟨λ s t, ⟨image2 (/) s t, s.2.div_right⟩⟩ @[to_additive] instance : has_smul α (upper_set α) := ⟨λ a s, ⟨(•) a '' s, s.2.smul⟩⟩ @[simp, norm_cast, to_additive] lemma coe_one : ((1 : upper_set α) : set α) = set.Ici 1 := rfl @[simp, norm_cast, to_additive] lemma coe_smul (a : α) (s : upper_set α) : (↑(a • s) : set α) = a • s := rfl @[simp, norm_cast, to_additive] lemma coe_mul (s t : upper_set α) : (↑(s * t) : set α) = s * t := rfl @[simp, norm_cast, to_additive] lemma coe_div (s t : upper_set α) : (↑(s / t) : set α) = s / t := rfl @[simp, to_additive] lemma Ici_one : Ici (1 : α) = 1 := rfl @[to_additive] instance : mul_action α (upper_set α) := set_like.coe_injective.mul_action _ coe_smul @[to_additive] instance : comm_semigroup (upper_set α) := { mul := (*), ..(set_like.coe_injective.comm_semigroup _ coe_mul : comm_semigroup (upper_set α)) } @[to_additive] private lemma one_mul (s : upper_set α) : 1 * s = s := set_like.coe_injective $ (subset_mul_right _ left_mem_Ici).antisymm' $ by { rw [←smul_eq_mul, ←bUnion_smul_set], exact Union₂_subset (λ _, s.upper.smul_subset) } @[to_additive] instance : comm_monoid (upper_set α) := { one := 1, one_mul := one_mul, mul_one := λ s, by { rw mul_comm, exact one_mul _ }, ..upper_set.comm_semigroup } end upper_set namespace lower_set @[to_additive] instance : has_one (lower_set α) := ⟨Iic 1⟩ @[to_additive] instance : has_mul (lower_set α) := ⟨λ s t, ⟨image2 (*) s t, s.2.mul_right⟩⟩ @[to_additive] instance : has_div (lower_set α) := ⟨λ s t, ⟨image2 (/) s t, s.2.div_right⟩⟩ @[to_additive] instance : has_smul α (lower_set α) := ⟨λ a s, ⟨(•) a '' s, s.2.smul⟩⟩ @[simp, norm_cast, to_additive] lemma coe_smul (a : α) (s : lower_set α) : (↑(a • s) : set α) = a • s := rfl @[simp, norm_cast, to_additive] lemma coe_mul (s t : lower_set α) : (↑(s * t) : set α) = s * t := rfl @[simp, norm_cast, to_additive] lemma coe_div (s t : lower_set α) : (↑(s / t) : set α) = s / t := rfl @[simp, to_additive] lemma Iic_one : Iic (1 : α) = 1 := rfl @[to_additive] instance : mul_action α (lower_set α) := set_like.coe_injective.mul_action _ coe_smul @[to_additive] instance : comm_semigroup (lower_set α) := { mul := (*), ..(set_like.coe_injective.comm_semigroup _ coe_mul : comm_semigroup (lower_set α)) } @[to_additive] private lemma one_mul (s : lower_set α) : 1 * s = s := set_like.coe_injective $ (subset_mul_right _ right_mem_Iic).antisymm' $ by { rw [←smul_eq_mul, ←bUnion_smul_set], exact Union₂_subset (λ _, s.lower.smul_subset) } @[to_additive] instance : comm_monoid (lower_set α) := { one := 1, one_mul := one_mul, mul_one := λ s, by { rw mul_comm, exact one_mul _ }, ..lower_set.comm_semigroup } end lower_set variables (a s t) @[simp, to_additive] lemma upper_closure_one : upper_closure (1 : set α) = 1 := upper_closure_singleton _ @[simp, to_additive] lemma lower_closure_one : lower_closure (1 : set α) = 1 := lower_closure_singleton _ @[simp, to_additive] lemma upper_closure_smul : upper_closure (a • s) = a • upper_closure s := upper_closure_image $ order_iso.mul_left a @[simp, to_additive] lemma lower_closure_smul : lower_closure (a • s) = a • lower_closure s := lower_closure_image $ order_iso.mul_left a @[to_additive] lemma mul_upper_closure : s * upper_closure t = upper_closure (s * t) := by simp_rw [←smul_eq_mul, ←bUnion_smul_set, upper_closure_Union, upper_closure_smul, upper_set.coe_infi₂, upper_set.coe_smul] @[to_additive] lemma mul_lower_closure : s * lower_closure t = lower_closure (s * t) := by simp_rw [←smul_eq_mul, ←bUnion_smul_set, lower_closure_Union, lower_closure_smul, lower_set.coe_supr₂, lower_set.coe_smul] @[to_additive] lemma upper_closure_mul : ↑(upper_closure s) * t = upper_closure (s * t) := by { simp_rw mul_comm _ t, exact mul_upper_closure _ _ } @[to_additive] lemma lower_closure_mul : ↑(lower_closure s) * t = lower_closure (s * t) := by { simp_rw mul_comm _ t, exact mul_lower_closure _ _ } @[simp, to_additive] lemma upper_closure_mul_distrib : upper_closure (s * t) = upper_closure s * upper_closure t := set_like.coe_injective $ by rw [upper_set.coe_mul, mul_upper_closure, upper_closure_mul, upper_set.upper_closure] @[simp, to_additive] lemma lower_closure_mul_distrib : lower_closure (s * t) = lower_closure s * lower_closure t := set_like.coe_injective $ by rw [lower_set.coe_mul, mul_lower_closure, lower_closure_mul, lower_set.lower_closure] end ordered_comm_group
4ccd6d54deddd91e4d667939b945545b95acbccd
618003631150032a5676f229d13a079ac875ff77
/src/init_/default.lean
90e311ab851dc224d83bb49c2ee5b91bba70ac49
[ "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
78
lean
import init_.algebra import init_.data.nat.lemmas import init_.data.int.order
5fb021afe51cc97b1bcdb0ff6844f39174b39b08
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/hf.lean
bd02c4d57b953967e0f43cee6b4a5b3c9259aea8
[ "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
25,405
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Hereditarily finite sets: finite sets whose elements are all hereditarily finite sets. Remark: all definitions compute, however the performace is quite poor since we implement this module using a bijection from (finset nat) to nat, and this bijection is implemeted using the Ackermann coding. -/ import data.nat data.finset.equiv data.list open nat binary algebra open - [notations] finset definition hf := nat namespace hf local attribute hf [reducible] protected definition prio : num := num.succ std.priority.default protected definition is_inhabited [instance] : inhabited hf := nat.is_inhabited protected definition has_decidable_eq [reducible] [instance] : decidable_eq hf := nat.has_decidable_eq definition of_finset (s : finset hf) : hf := @equiv.to_fun _ _ finset_nat_equiv_nat s definition to_finset (h : hf) : finset hf := @equiv.inv _ _ finset_nat_equiv_nat h definition to_nat (h : hf) : nat := h definition of_nat (n : nat) : hf := n lemma to_finset_of_finset (s : finset hf) : to_finset (of_finset s) = s := @equiv.left_inv _ _ finset_nat_equiv_nat s lemma of_finset_to_finset (s : hf) : of_finset (to_finset s) = s := @equiv.right_inv _ _ finset_nat_equiv_nat s lemma to_finset_inj {s₁ s₂ : hf} : to_finset s₁ = to_finset s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse of_finset_to_finset h lemma of_finset_inj {s₁ s₂ : finset hf} : of_finset s₁ = of_finset s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse to_finset_of_finset h /- empty -/ definition empty : hf := of_finset (finset.empty) notation `∅` := hf.empty /- insert -/ definition insert (a s : hf) : hf := of_finset (finset.insert a (to_finset s)) /- mem -/ definition mem (a : hf) (s : hf) : Prop := finset.mem a (to_finset s) infix ∈ := mem notation [priority finset.prio] a ∉ b := ¬ mem a b lemma insert_lt_of_not_mem {a s : hf} : a ∉ s → s < insert a s := begin unfold [insert, of_finset, equiv.to_fun, finset_nat_equiv_nat, mem, to_finset, equiv.inv], intro h, rewrite [finset.to_nat_insert h], rewrite [to_nat_of_nat, -zero_add s at {1}], apply add_lt_add_right, apply pow_pos_of_pos _ dec_trivial end lemma insert_lt_insert_of_not_mem_of_not_mem_of_lt {a s₁ s₂ : hf} : a ∉ s₁ → a ∉ s₂ → s₁ < s₂ → insert a s₁ < insert a s₂ := begin unfold [insert, of_finset, equiv.to_fun, finset_nat_equiv_nat, mem, to_finset, equiv.inv], intro h₁ h₂ h₃, rewrite [finset.to_nat_insert h₁], rewrite [finset.to_nat_insert h₂, *to_nat_of_nat], apply add_lt_add_left h₃ end open decidable protected definition decidable_mem [instance] : ∀ a s, decidable (a ∈ s) := λ a s, finset.decidable_mem a (to_finset s) lemma insert_le (a s : hf) : s ≤ insert a s := by_cases (suppose a ∈ s, by rewrite [↑insert, insert_eq_of_mem this, of_finset_to_finset]) (suppose a ∉ s, le_of_lt (insert_lt_of_not_mem this)) lemma not_mem_empty (a : hf) : a ∉ ∅ := begin unfold [mem, empty], rewrite to_finset_of_finset, apply finset.not_mem_empty end lemma mem_insert (a s : hf) : a ∈ insert a s := begin unfold [mem, insert], rewrite to_finset_of_finset, apply finset.mem_insert end lemma mem_insert_of_mem {a s : hf} (b : hf) : a ∈ s → a ∈ insert b s := begin unfold [mem, insert], intros, rewrite to_finset_of_finset, apply finset.mem_insert_of_mem, assumption end lemma eq_or_mem_of_mem_insert {a b s : hf} : a ∈ insert b s → a = b ∨ a ∈ s := begin unfold [mem, insert], rewrite to_finset_of_finset, intros, apply eq_or_mem_of_mem_insert, assumption end theorem mem_of_mem_insert_of_ne {x a : hf} {s : hf} : x ∈ insert a s → x ≠ a → x ∈ s := begin unfold [mem, insert], rewrite to_finset_of_finset, intros, apply mem_of_mem_insert_of_ne, repeat assumption end protected theorem ext {s₁ s₂ : hf} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := assume h, assert to_finset s₁ = to_finset s₂, from finset.ext h, assert of_finset (to_finset s₁) = of_finset (to_finset s₂), by rewrite this, by rewrite [*of_finset_to_finset at this]; exact this theorem insert_eq_of_mem {a : hf} {s : hf} : a ∈ s → insert a s = s := begin unfold mem, intro h, unfold [mem, insert], rewrite (finset.insert_eq_of_mem h), rewrite of_finset_to_finset end protected theorem induction [recursor 4] {P : hf → Prop} (h₁ : P empty) (h₂ : ∀ (a s : hf), a ∉ s → P s → P (insert a s)) (s : hf) : P s := assert P (of_finset (to_finset s)), from @finset.induction _ _ _ h₁ (λ a s nain ih, begin unfold [mem, insert] at h₂, rewrite -(to_finset_of_finset s) at nain, have P (insert a (of_finset s)), by exact h₂ a (of_finset s) nain ih, rewrite [↑insert at this, to_finset_of_finset at this], exact this end) (to_finset s), by rewrite of_finset_to_finset at this; exact this lemma insert_le_insert_of_le {a s₁ s₂ : hf} : a ∈ s₁ ∨ a ∉ s₂ → s₁ ≤ s₂ → insert a s₁ ≤ insert a s₂ := suppose a ∈ s₁ ∨ a ∉ s₂, suppose s₁ ≤ s₂, by_cases (suppose s₁ = s₂, by rewrite this) (suppose s₁ ≠ s₂, have s₁ < s₂, from lt_of_le_of_ne `s₁ ≤ s₂` `s₁ ≠ s₂`, by_cases (suppose a ∈ s₁, by_cases (suppose a ∈ s₂, by rewrite [insert_eq_of_mem `a ∈ s₁`, insert_eq_of_mem `a ∈ s₂`]; assumption) (suppose a ∉ s₂, by rewrite [insert_eq_of_mem `a ∈ s₁`]; exact le.trans `s₁ ≤ s₂` !insert_le)) (suppose a ∉ s₁, by_cases (suppose a ∈ s₂, or.elim `a ∈ s₁ ∨ a ∉ s₂` (by contradiction) (by contradiction)) (suppose a ∉ s₂, le_of_lt (insert_lt_insert_of_not_mem_of_not_mem_of_lt `a ∉ s₁` `a ∉ s₂` `s₁ < s₂`)))) /- union -/ definition union (s₁ s₂ : hf) : hf := of_finset (finset.union (to_finset s₁) (to_finset s₂)) infix [priority hf.prio] ∪ := union theorem mem_union_left {a : hf} {s₁ : hf} (s₂ : hf) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := begin unfold mem, intro h, unfold union, rewrite to_finset_of_finset, apply finset.mem_union_left _ h end theorem mem_union_l {a : hf} {s₁ : hf} {s₂ : hf} : a ∈ s₁ → a ∈ s₁ ∪ s₂ := mem_union_left s₂ theorem mem_union_right {a : hf} {s₂ : hf} (s₁ : hf) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := begin unfold mem, intro h, unfold union, rewrite to_finset_of_finset, apply finset.mem_union_right _ h end theorem mem_union_r {a : hf} {s₂ : hf} {s₁ : hf} : a ∈ s₂ → a ∈ s₁ ∪ s₂ := mem_union_right s₁ theorem mem_or_mem_of_mem_union {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∪ s₂ → a ∈ s₁ ∨ a ∈ s₂ := begin unfold [mem, union], rewrite to_finset_of_finset, intro h, apply finset.mem_or_mem_of_mem_union h end theorem mem_union_iff {a : hf} (s₁ s₂ : hf) : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := iff.intro (λ h, mem_or_mem_of_mem_union h) (λ d, or.elim d (λ i, mem_union_left _ i) (λ i, mem_union_right _ i)) theorem mem_union_eq {a : hf} (s₁ s₂ : hf) : (a ∈ s₁ ∪ s₂) = (a ∈ s₁ ∨ a ∈ s₂) := propext !mem_union_iff theorem union.comm (s₁ s₂ : hf) : s₁ ∪ s₂ = s₂ ∪ s₁ := hf.ext (λ a, by rewrite [*mem_union_eq]; exact or.comm) theorem union.assoc (s₁ s₂ s₃ : hf) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := hf.ext (λ a, by rewrite [*mem_union_eq]; exact or.assoc) theorem union.left_comm (s₁ s₂ s₃ : hf) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union.comm union.assoc s₁ s₂ s₃ theorem union.right_comm (s₁ s₂ s₃ : hf) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union.comm union.assoc s₁ s₂ s₃ theorem union_self (s : hf) : s ∪ s = s := hf.ext (λ a, iff.intro (λ ain, or.elim (mem_or_mem_of_mem_union ain) (λ i, i) (λ i, i)) (λ i, mem_union_left _ i)) theorem union_empty (s : hf) : s ∪ ∅ = s := hf.ext (λ a, iff.intro (suppose a ∈ s ∪ ∅, or.elim (mem_or_mem_of_mem_union this) (λ i, i) (λ i, absurd i !not_mem_empty)) (suppose a ∈ s, mem_union_left _ this)) theorem empty_union (s : hf) : ∅ ∪ s = s := calc ∅ ∪ s = s ∪ ∅ : union.comm ... = s : union_empty /- inter -/ definition inter (s₁ s₂ : hf) : hf := of_finset (finset.inter (to_finset s₁) (to_finset s₂)) infix [priority hf.prio] ∩ := inter theorem mem_of_mem_inter_left {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∩ s₂ → a ∈ s₁ := begin unfold mem, unfold inter, rewrite to_finset_of_finset, intro h, apply finset.mem_of_mem_inter_left h end theorem mem_of_mem_inter_right {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∩ s₂ → a ∈ s₂ := begin unfold mem, unfold inter, rewrite to_finset_of_finset, intro h, apply finset.mem_of_mem_inter_right h end theorem mem_inter {a : hf} {s₁ s₂ : hf} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := begin unfold mem, intro h₁ h₂, unfold inter, rewrite to_finset_of_finset, apply finset.mem_inter h₁ h₂ end theorem mem_inter_iff (a : hf) (s₁ s₂ : hf) : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := iff.intro (λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h)) (λ h, mem_inter (and.elim_left h) (and.elim_right h)) theorem mem_inter_eq (a : hf) (s₁ s₂ : hf) : (a ∈ s₁ ∩ s₂) = (a ∈ s₁ ∧ a ∈ s₂) := propext !mem_inter_iff theorem inter.comm (s₁ s₂ : hf) : s₁ ∩ s₂ = s₂ ∩ s₁ := hf.ext (λ a, by rewrite [*mem_inter_eq]; exact and.comm) theorem inter.assoc (s₁ s₂ s₃ : hf) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := hf.ext (λ a, by rewrite [*mem_inter_eq]; exact and.assoc) theorem inter.left_comm (s₁ s₂ s₃ : hf) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter.comm inter.assoc s₁ s₂ s₃ theorem inter.right_comm (s₁ s₂ s₃ : hf) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter.comm inter.assoc s₁ s₂ s₃ theorem inter_self (s : hf) : s ∩ s = s := hf.ext (λ a, iff.intro (λ h, mem_of_mem_inter_right h) (λ h, mem_inter h h)) theorem inter_empty (s : hf) : s ∩ ∅ = ∅ := hf.ext (λ a, iff.intro (suppose a ∈ s ∩ ∅, absurd (mem_of_mem_inter_right this) !not_mem_empty) (suppose a ∈ ∅, absurd this !not_mem_empty)) theorem empty_inter (s : hf) : ∅ ∩ s = ∅ := calc ∅ ∩ s = s ∩ ∅ : inter.comm ... = ∅ : inter_empty /- card -/ definition card (s : hf) : nat := finset.card (to_finset s) theorem card_empty : card ∅ = 0 := rfl lemma ne_empty_of_card_eq_succ {s : hf} {n : nat} : card s = succ n → s ≠ ∅ := by intros; substvars; contradiction /- erase -/ definition erase (a : hf) (s : hf) : hf := of_finset (erase a (to_finset s)) theorem mem_erase (a : hf) (s : hf) : a ∉ erase a s := begin unfold [mem, erase], rewrite to_finset_of_finset, apply finset.mem_erase end theorem card_erase_of_mem {a : hf} {s : hf} : a ∈ s → card (erase a s) = pred (card s) := begin unfold mem, intro h, unfold [erase, card], rewrite to_finset_of_finset, apply finset.card_erase_of_mem h end theorem card_erase_of_not_mem {a : hf} {s : hf} : a ∉ s → card (erase a s) = card s := begin unfold [mem], intro h, unfold [erase, card], rewrite to_finset_of_finset, apply finset.card_erase_of_not_mem h end theorem erase_empty (a : hf) : erase a ∅ = ∅ := rfl theorem ne_of_mem_erase {a b : hf} {s : hf} : b ∈ erase a s → b ≠ a := by intro h beqa; subst b; exact absurd h !mem_erase theorem mem_of_mem_erase {a b : hf} {s : hf} : b ∈ erase a s → b ∈ s := begin unfold [erase, mem], rewrite to_finset_of_finset, intro h, apply mem_of_mem_erase h end theorem mem_erase_of_ne_of_mem {a b : hf} {s : hf} : a ≠ b → a ∈ s → a ∈ erase b s := begin intro h₁, unfold mem, intro h₂, unfold erase, rewrite to_finset_of_finset, apply mem_erase_of_ne_of_mem h₁ h₂ end theorem mem_erase_iff (a b : hf) (s : hf) : a ∈ erase b s ↔ a ∈ s ∧ a ≠ b := iff.intro (assume H, and.intro (mem_of_mem_erase H) (ne_of_mem_erase H)) (assume H, mem_erase_of_ne_of_mem (and.right H) (and.left H)) theorem mem_erase_eq (a b : hf) (s : hf) : a ∈ erase b s = (a ∈ s ∧ a ≠ b) := propext !mem_erase_iff theorem erase_insert {a : hf} {s : hf} : a ∉ s → erase a (insert a s) = s := begin unfold [mem, erase, insert], intro h, rewrite [to_finset_of_finset, finset.erase_insert h, of_finset_to_finset] end theorem insert_erase {a : hf} {s : hf} : a ∈ s → insert a (erase a s) = s := begin unfold mem, intro h, unfold [insert, erase], rewrite [to_finset_of_finset, finset.insert_erase h, of_finset_to_finset] end /- subset -/ definition subset (s₁ s₂ : hf) : Prop := finset.subset (to_finset s₁) (to_finset s₂) infix [priority hf.prio] ⊆ := subset theorem empty_subset (s : hf) : ∅ ⊆ s := begin unfold [empty, subset], rewrite to_finset_of_finset, apply finset.empty_subset (to_finset s) end theorem subset.refl (s : hf) : s ⊆ s := begin unfold [subset], apply finset.subset.refl (to_finset s) end theorem subset.trans {s₁ s₂ s₃ : hf} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := begin unfold [subset], intro h₁ h₂, apply finset.subset.trans h₁ h₂ end theorem mem_of_subset_of_mem {s₁ s₂ : hf} {a : hf} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := begin unfold [subset, mem], intro h₁ h₂, apply finset.mem_of_subset_of_mem h₁ h₂ end theorem subset.antisymm {s₁ s₂ : hf} : s₁ ⊆ s₂ → s₂ ⊆ s₁ → s₁ = s₂ := begin unfold [subset], intro h₁ h₂, apply to_finset_inj (finset.subset.antisymm h₁ h₂) end -- alternative name theorem eq_of_subset_of_subset {s₁ s₂ : hf} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := subset.antisymm H₁ H₂ theorem subset_of_forall {s₁ s₂ : hf} : (∀x, x ∈ s₁ → x ∈ s₂) → s₁ ⊆ s₂ := begin unfold [mem, subset], intro h, apply finset.subset_of_forall h end theorem subset_insert (s : hf) (a : hf) : s ⊆ insert a s := begin unfold [subset, insert], rewrite to_finset_of_finset, apply finset.subset_insert (to_finset s) end theorem eq_empty_of_subset_empty {x : hf} (H : x ⊆ ∅) : x = ∅ := subset.antisymm H (empty_subset x) theorem subset_empty_iff (x : hf) : x ⊆ ∅ ↔ x = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) theorem erase_subset_erase (a : hf) {s t : hf} : s ⊆ t → erase a s ⊆ erase a t := begin unfold [subset, erase], intro h, rewrite *to_finset_of_finset, apply finset.erase_subset_erase a h end theorem erase_subset (a : hf) (s : hf) : erase a s ⊆ s := begin unfold [subset, erase], rewrite to_finset_of_finset, apply finset.erase_subset a (to_finset s) end theorem erase_eq_of_not_mem {a : hf} {s : hf} : a ∉ s → erase a s = s := begin unfold [mem, erase], intro h, rewrite [finset.erase_eq_of_not_mem h, of_finset_to_finset] end theorem erase_insert_subset (a : hf) (s : hf) : erase a (insert a s) ⊆ s := begin unfold [erase, insert, subset], rewrite [*to_finset_of_finset], apply finset.erase_insert_subset a (to_finset s) end theorem erase_subset_of_subset_insert {a : hf} {s t : hf} (H : s ⊆ insert a t) : erase a s ⊆ t := hf.subset.trans (!hf.erase_subset_erase H) (erase_insert_subset a t) theorem insert_erase_subset (a : hf) (s : hf) : s ⊆ insert a (erase a s) := decidable.by_cases (assume ains : a ∈ s, by rewrite [!insert_erase ains]; apply subset.refl) (assume nains : a ∉ s, suffices s ⊆ insert a s, by rewrite [erase_eq_of_not_mem nains]; assumption, subset_insert s a) theorem insert_subset_insert (a : hf) {s t : hf} : s ⊆ t → insert a s ⊆ insert a t := begin unfold [subset, insert], intro h, rewrite *to_finset_of_finset, apply finset.insert_subset_insert a h end theorem subset_insert_of_erase_subset {s t : hf} {a : hf} (H : erase a s ⊆ t) : s ⊆ insert a t := subset.trans (insert_erase_subset a s) (!insert_subset_insert H) theorem subset_insert_iff (s t : hf) (a : hf) : s ⊆ insert a t ↔ erase a s ⊆ t := iff.intro !erase_subset_of_subset_insert !subset_insert_of_erase_subset theorem le_of_subset {s₁ s₂ : hf} : s₁ ⊆ s₂ → s₁ ≤ s₂ := begin revert s₂, induction s₁ with a s₁ nain ih, take s₂, suppose ∅ ⊆ s₂, !zero_le, take s₂, suppose insert a s₁ ⊆ s₂, assert a ∈ s₂, from mem_of_subset_of_mem this !mem_insert, have a ∉ erase a s₂, from !mem_erase, have s₁ ⊆ erase a s₂, from subset_of_forall (take x xin, by_cases (suppose x = a, by subst x; contradiction) (suppose x ≠ a, have x ∈ s₂, from mem_of_subset_of_mem `insert a s₁ ⊆ s₂` (mem_insert_of_mem _ `x ∈ s₁`), mem_erase_of_ne_of_mem `x ≠ a` `x ∈ s₂`)), have s₁ ≤ erase a s₂, from ih _ this, assert insert a s₁ ≤ insert a (erase a s₂), from insert_le_insert_of_le (or.inr `a ∉ erase a s₂`) this, by rewrite [insert_erase `a ∈ s₂` at this]; exact this end /- image -/ definition image (f : hf → hf) (s : hf) : hf := of_finset (finset.image f (to_finset s)) theorem image_empty (f : hf → hf) : image f ∅ = ∅ := rfl theorem mem_image_of_mem (f : hf → hf) {s : hf} {a : hf} : a ∈ s → f a ∈ image f s := begin unfold [mem, image], intro h, rewrite to_finset_of_finset, apply finset.mem_image_of_mem f h end theorem mem_image {f : hf → hf} {s : hf} {a : hf} {b : hf} (H1 : a ∈ s) (H2 : f a = b) : b ∈ image f s := eq.subst H2 (mem_image_of_mem f H1) theorem exists_of_mem_image {f : hf → hf} {s : hf} {b : hf} : b ∈ image f s → ∃a, a ∈ s ∧ f a = b := begin unfold [mem, image], rewrite to_finset_of_finset, intro h, apply finset.exists_of_mem_image h end theorem mem_image_iff (f : hf → hf) {s : hf} {y : hf} : y ∈ image f s ↔ ∃x, x ∈ s ∧ f x = y := begin unfold [mem, image], rewrite to_finset_of_finset, apply finset.mem_image_iff end theorem mem_image_eq (f : hf → hf) {s : hf} {y : hf} : y ∈ image f s = ∃x, x ∈ s ∧ f x = y := propext (mem_image_iff f) theorem mem_image_of_mem_image_of_subset {f : hf → hf} {s t : hf} {y : hf} (H1 : y ∈ image f s) (H2 : s ⊆ t) : y ∈ image f t := obtain x `x ∈ s` `f x = y`, from exists_of_mem_image H1, have x ∈ t, from mem_of_subset_of_mem H2 `x ∈ s`, show y ∈ image f t, from mem_image `x ∈ t` `f x = y` theorem image_insert (f : hf → hf) (s : hf) (a : hf) : image f (insert a s) = insert (f a) (image f s) := begin unfold [image, insert], rewrite [*to_finset_of_finset, finset.image_insert] end open function lemma image_compose {f : hf → hf} {g : hf → hf} {s : hf} : image (f∘g) s = image f (image g s) := begin unfold image, rewrite [*to_finset_of_finset, finset.image_compose] end lemma image_subset {a b : hf} (f : hf → hf) : a ⊆ b → image f a ⊆ image f b := begin unfold [subset, image], intro h, rewrite *to_finset_of_finset, apply finset.image_subset f h end theorem image_union (f : hf → hf) (s t : hf) : image f (s ∪ t) = image f s ∪ image f t := begin unfold [image, union], rewrite [*to_finset_of_finset, finset.image_union] end /- powerset -/ definition powerset (s : hf) : hf := of_finset (finset.image of_finset (finset.powerset (to_finset s))) prefix [priority hf.prio] `𝒫`:100 := powerset theorem powerset_empty : 𝒫 ∅ = insert ∅ ∅ := rfl theorem powerset_insert {a : hf} {s : hf} : a ∉ s → 𝒫 (insert a s) = 𝒫 s ∪ image (insert a) (𝒫 s) := begin unfold [mem, powerset, insert, union, image], rewrite [*to_finset_of_finset], intro h, have (λ (x : finset hf), of_finset (finset.insert a x)) = (λ (x : finset hf), of_finset (finset.insert a (to_finset (of_finset x)))), from funext (λ x, by rewrite to_finset_of_finset), rewrite [finset.powerset_insert h, finset.image_union, -*finset.image_compose,↑compose,this] end theorem mem_powerset_iff_subset (s : hf) : ∀ x : hf, x ∈ 𝒫 s ↔ x ⊆ s := begin intro x, unfold [mem, powerset, subset], rewrite [to_finset_of_finset, finset.mem_image_eq], apply iff.intro, suppose (∃ (w : finset hf), finset.mem w (finset.powerset (to_finset s)) ∧ of_finset w = x), obtain w h₁ h₂, from this, begin subst x, rewrite to_finset_of_finset, exact iff.mp !finset.mem_powerset_iff_subset h₁ end, suppose finset.subset (to_finset x) (to_finset s), assert finset.mem (to_finset x) (finset.powerset (to_finset s)), from iff.mpr !finset.mem_powerset_iff_subset this, exists.intro (to_finset x) (and.intro this (of_finset_to_finset x)) end theorem subset_of_mem_powerset {s t : hf} (H : s ∈ 𝒫 t) : s ⊆ t := iff.mp (mem_powerset_iff_subset t s) H theorem mem_powerset_of_subset {s t : hf} (H : s ⊆ t) : s ∈ 𝒫 t := iff.mpr (mem_powerset_iff_subset t s) H theorem empty_mem_powerset (s : hf) : ∅ ∈ 𝒫 s := mem_powerset_of_subset (empty_subset s) /- hf as lists -/ open - [notations] list definition of_list (s : list hf) : hf := @equiv.to_fun _ _ list_nat_equiv_nat s definition to_list (h : hf) : list hf := @equiv.inv _ _ list_nat_equiv_nat h lemma to_list_of_list (s : list hf) : to_list (of_list s) = s := @equiv.left_inv _ _ list_nat_equiv_nat s lemma of_list_to_list (s : hf) : of_list (to_list s) = s := @equiv.right_inv _ _ list_nat_equiv_nat s lemma to_list_inj {s₁ s₂ : hf} : to_list s₁ = to_list s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse of_list_to_list h lemma of_list_inj {s₁ s₂ : list hf} : of_list s₁ = of_list s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse to_list_of_list h definition nil : hf := of_list list.nil lemma empty_eq_nil : ∅ = nil := rfl definition cons (a l : hf) : hf := of_list (list.cons a (to_list l)) infixr :: := cons lemma cons_ne_nil (a l : hf) : a::l ≠ nil := by contradiction lemma head_eq_of_cons_eq {h₁ h₂ t₁ t₂ : hf} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := begin unfold cons, intro h, apply list.head_eq_of_cons_eq (of_list_inj h) end lemma tail_eq_of_cons_eq {h₁ h₂ t₁ t₂ : hf} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := begin unfold cons, intro h, apply to_list_inj (list.tail_eq_of_cons_eq (of_list_inj h)) end lemma cons_inj {a : hf} : injective (cons a) := take l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe /- append -/ definition append (l₁ l₂ : hf) : hf := of_list (list.append (to_list l₁) (to_list l₂)) notation l₁ ++ l₂ := append l₁ l₂ theorem append_nil_left [simp] (t : hf) : nil ++ t = t := begin unfold [nil, append], rewrite [to_list_of_list, list.append_nil_left, of_list_to_list] end theorem append_cons [simp] (x s t : hf) : (x::s) ++ t = x::(s ++ t) := begin unfold [cons, append], rewrite [*to_list_of_list, list.append_cons] end theorem append_nil_right [simp] (t : hf) : t ++ nil = t := begin unfold [nil, append], rewrite [to_list_of_list, list.append_nil_right, of_list_to_list] end theorem append.assoc [simp] (s t u : hf) : s ++ t ++ u = s ++ (t ++ u) := begin unfold append, rewrite [*to_list_of_list, list.append.assoc] end /- length -/ definition length (l : hf) : nat := list.length (to_list l) theorem length_nil [simp] : length nil = 0 := begin unfold [length, nil] end theorem length_cons [simp] (x t : hf) : length (x::t) = length t + 1 := begin unfold [length, cons], rewrite to_list_of_list end theorem length_append [simp] (s t : hf) : length (s ++ t) = length s + length t := begin unfold [length, append], rewrite [to_list_of_list, list.length_append] end theorem eq_nil_of_length_eq_zero {l : hf} : length l = 0 → l = nil := begin unfold [length, nil], intro h, rewrite [-list.eq_nil_of_length_eq_zero h, of_list_to_list] end theorem ne_nil_of_length_eq_succ {l : hf} {n : nat} : length l = succ n → l ≠ nil := begin unfold [length, nil], intro h₁ h₂, subst l, rewrite to_list_of_list at h₁, contradiction end /- head and tail -/ definition head (l : hf) : hf := list.head (to_list l) theorem head_cons [simp] (a l : hf) : head (a::l) = a := begin unfold [head, cons], rewrite to_list_of_list end private lemma to_list_ne_list_nil {s : hf} : s ≠ nil → to_list s ≠ list.nil := begin unfold nil, intro h, suppose to_list s = list.nil, by rewrite [-this at h, of_list_to_list at h]; exact absurd rfl h end theorem head_append [simp] (t : hf) {s : hf} : s ≠ nil → head (s ++ t) = head s := begin unfold [nil, head, append], rewrite to_list_of_list, suppose s ≠ of_list list.nil, by rewrite [list.head_append _ (to_list_ne_list_nil this)] end definition tail (l : hf) : hf := of_list (list.tail (to_list l)) theorem tail_nil [simp] : tail nil = nil := begin unfold [tail, nil] end theorem tail_cons [simp] (a l : hf) : tail (a::l) = l := begin unfold [tail, cons], rewrite [to_list_of_list, list.tail_cons, of_list_to_list] end theorem cons_head_tail {l : hf} : l ≠ nil → (head l)::(tail l) = l := begin unfold [nil, head, tail, cons], suppose l ≠ of_list list.nil, by rewrite [to_list_of_list, list.cons_head_tail (to_list_ne_list_nil this), of_list_to_list] end end hf
bbf248b17eceb17d406131684b50b56f756ba1ff
9028d228ac200bbefe3a711342514dd4e4458bff
/src/topology/homeomorph.lean
38d6ff17708e31c4d5505f4004c1ffeaadf51f71
[ "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
9,995
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, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton -/ import topology.dense_embedding open set variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- α and β are homeomorph, also called topological isomoph -/ @[nolint has_inhabited_instance] -- not all spaces are homeomorphic to each other structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends α ≃ β := (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') (continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity') infix ` ≃ₜ `:25 := homeomorph namespace homeomorph variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] instance : has_coe_to_fun (α ≃ₜ β) := ⟨λ_, α → β, λe, e.to_equiv⟩ @[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) : ((homeomorph.mk a b c) : α → β) = a := rfl lemma coe_eq_to_equiv (h : α ≃ₜ β) (a : α) : h a = h.to_equiv a := rfl /-- Identity map is a homeomorphism. -/ protected def refl (α : Type*) [topological_space α] : α ≃ₜ α := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. equiv.refl α } /-- Composition of two homeomorphisms. -/ protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ := { continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun, continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun, .. equiv.trans h₁.to_equiv h₂.to_equiv } /-- Inverse of a homeomorphism. -/ protected def symm (h : α ≃ₜ β) : β ≃ₜ α := { continuous_to_fun := h.continuous_inv_fun, continuous_inv_fun := h.continuous_to_fun, .. h.to_equiv.symm } @[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) : ((homeomorph.mk a b c).symm : β → α) = a.symm := rfl @[continuity] protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun /-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/ def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β := have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm ... = f.symm x : by rw hg x), { to_fun := f, inv_fun := g, left_inv := by convert f.left_inv, right_inv := by convert f.right_inv, continuous_to_fun := f.continuous, continuous_inv_fun := by convert f.symm.continuous } lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id := funext $ assume a, h.to_equiv.left_inv a lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id := funext $ assume a, h.to_equiv.right_inv a lemma range_coe (h : α ≃ₜ β) : range h = univ := eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩ lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h := funext h.symm.to_equiv.image_eq_preimage lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h := (funext h.to_equiv.image_eq_preimage).symm lemma induced_eq {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) : tβ.induced h = tα := le_antisymm (calc topological_space.induced ⇑h tβ ≤ _ : induced_mono (coinduced_le_iff_le_induced.1 h.symm.continuous) ... ≤ tα : by rw [induced_compose, symm_comp_self, induced_id] ; exact le_refl _) (coinduced_le_iff_le_induced.1 h.continuous) lemma coinduced_eq {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) : tα.coinduced h = tβ := le_antisymm h.continuous begin have : (tβ.coinduced h.symm).coinduced h ≤ tα.coinduced h := coinduced_mono h.symm.continuous, rwa [coinduced_compose, self_comp_symm, coinduced_id] at this, end protected lemma embedding (h : α ≃ₜ β) : embedding h := ⟨⟨h.induced_eq.symm⟩, h.to_equiv.injective⟩ lemma compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s := h.embedding.compact_iff_compact_image.symm lemma compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s := by rw ← image_symm; exact h.symm.compact_image protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h := { dense := assume a, by rw [h.range_coe, closure_univ]; trivial, inj := h.to_equiv.injective, induced := (induced_iff_nhds_eq _).2 (assume a, by rw [← nhds_induced, h.induced_eq]) } protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := begin assume s, rw ← h.preimage_symm, exact h.symm.continuous s end protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := begin assume s, rw ← h.preimage_symm, exact continuous_iff_is_closed.1 (h.symm.continuous) _ end protected lemma closed_embedding (h : α ≃ₜ β) : closed_embedding h := closed_embedding_of_embedding_closed h.embedding h.is_closed_map @[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s := begin refine ⟨λ hs, _, h.continuous_to_fun s⟩, rw [← (image_preimage_eq h.to_equiv.surjective : _ = s)], exact h.is_open_map _ hs end /-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/ def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) : α ≃ₜ β := { continuous_to_fun := h₁, continuous_inv_fun := begin intros s hs, convert ← h₂ s hs using 1, apply e.image_eq_preimage end, .. e } lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) : continuous_on (h ∘ f) s ↔ continuous_on f s := begin split, { assume H, have : continuous_on (h.symm ∘ (h ∘ f)) s := h.symm.continuous.comp_continuous_on H, rwa [← function.comp.assoc h.symm h f, symm_comp_self h] at this }, { exact λ H, h.continuous.comp_continuous_on H } end lemma comp_continuous_iff (h : α ≃ₜ β) (f : γ → α) : continuous (h ∘ f) ↔ continuous f := by simp [continuous_iff_continuous_on_univ, comp_continuous_on_iff] protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h := ⟨h.to_equiv.surjective, h.coinduced_eq.symm⟩ /-- If two sets are equal, then they are homeomorphic. -/ def set_congr {s t : set α} (h : s = t) : s ≃ₜ t := { continuous_to_fun := continuous_subtype_mk _ continuous_subtype_val, continuous_inv_fun := continuous_subtype_mk _ continuous_subtype_val, .. equiv.set_congr h } /-- Sum of two homeomorphisms. -/ def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ := { continuous_to_fun := continuous_sum_rec (continuous_inl.comp h₁.continuous) (continuous_inr.comp h₂.continuous), continuous_inv_fun := continuous_sum_rec (continuous_inl.comp h₁.symm.continuous) (continuous_inr.comp h₂.symm.continuous), .. h₁.to_equiv.sum_congr h₂.to_equiv } /-- Product of two homeomorphisms. -/ def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ := { continuous_to_fun := continuous.prod_mk (h₁.continuous.comp continuous_fst) (h₂.continuous.comp continuous_snd), continuous_inv_fun := continuous.prod_mk (h₁.symm.continuous.comp continuous_fst) (h₂.symm.continuous.comp continuous_snd), .. h₁.to_equiv.prod_congr h₂.to_equiv } section variables (α β γ) /-- `α × β` is homeomorphic to `β × α`. -/ def prod_comm : α × β ≃ₜ β × α := { continuous_to_fun := continuous.prod_mk continuous_snd continuous_fst, continuous_inv_fun := continuous.prod_mk continuous_snd continuous_fst, .. equiv.prod_comm α β } /-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/ def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) := { continuous_to_fun := continuous.prod_mk (continuous_fst.comp continuous_fst) (continuous.prod_mk (continuous_snd.comp continuous_fst) continuous_snd), continuous_inv_fun := continuous.prod_mk (continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd), .. equiv.prod_assoc α β γ } end /-- `ulift α` is homeomorphic to `α`. -/ def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α := { continuous_to_fun := continuous_ulift_down, continuous_inv_fun := continuous_ulift_up, .. equiv.ulift } section distrib /-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/ def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ := homeomorph.symm $ homeomorph.homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm (continuous_sum_rec ((continuous_inl.comp continuous_fst).prod_mk continuous_snd) ((continuous_inr.comp continuous_fst).prod_mk continuous_snd)) (is_open_map_sum (open_embedding_inl.prod open_embedding_id).is_open_map (open_embedding_inr.prod open_embedding_id).is_open_map) /-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/ def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ := (prod_comm _ _).trans $ sum_prod_distrib.trans $ sum_congr (prod_comm _ _) (prod_comm _ _) variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] /-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/ def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) := homeomorph.symm $ homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm (continuous_sigma $ λ i, continuous.prod_mk (continuous_sigma_mk.comp continuous_fst) continuous_snd) (is_open_map_sigma $ λ i, (open_embedding.prod open_embedding_sigma_mk open_embedding_id).is_open_map) end distrib end homeomorph
7e97e69ba578f2409da14647b6294499cff4fea8
d450724ba99f5b50b57d244eb41fef9f6789db81
/src/instructor/lectures/lecture_27b.lean
d1c88bb868ee03fc75261f51bf18e685877c1281
[]
no_license
jakekauff/CS2120F21
4f009adeb4ce4a148442b562196d66cc6c04530c
e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad
refs/heads/main
1,693,841,880,030
1,637,604,848,000
1,637,604,848,000
399,946,698
0
0
null
null
null
null
UTF-8
Lean
false
false
13,642
lean
import .lecture_26 import data.set namespace relations section functions variables {α β γ : Type} (r : α → β → Prop) local infix `≺`:50 := r /- SINGLE-VALUED BINARY RELATION -/ def single_valued := ∀ {x : α} {y z : β}, r x y → r x z → y = z #check @single_valued -- property of a relation /- Exercises: Which of the following are single-valued? - r = {(0,1), (0,2)} - r = {(1,0), (2,0)} - the unit circle on ℝ - r = {(-1,0), (0,-1), (1,0), (0,1)} - y = x^2 - x = y^2 - y = + / - square root x - f(x) = 3x+1 - y = sin x - x = sin y -/ /- FUNCTION A single-valued binary relation is also called a function (sometimes a functional binary relation). -/ def function := single_valued r /- One possible property of a relation, r, is the property of being a function, i.e., of r being single-valued. Single-valuedness is a predicate on relations. (This idea is isn't definable in first order predicate logic.) -/ #check @function /- The same vocabulary applies to functions as to relations, as functions are just special cases (single-valued) of otherwise arbitrary binary relations. As with any relation, for example, a function has a domain, α, a domain of definition, and a co-domain, β. As with any relation, the set of pairs of a function (that we're specifying) is is some subset of α × β; or equivalently it is in the powerset of α × β. When you want to express the idea that you have an arbitrary relation (possible a function) from α to β, you may write either of the following: - let r ⊆ α × β be any relation from α → β - let r ∈ 𝒫 (α × β) be any relation, α → β - let r : α → β be any binary relation Be sure you see that these are equivalent statements! A key point is that in addition to a set of pairs a function (or relation) has a domain of definition and a co-domain. Keeping track of exactly how a set of pairs relates to its domain and codomain sets is essential. -/ /- FOR A RELATION TO BE "DEFINED" FOR A VALUE Property: We say that a function is "defined" for some value, (a : α), if there is some (b : β), such that the pair, (a,b) is "in" r, i.e., (r a b) is true. -/ def defined (a : α) := ∃ (b : β), r a b /- Examples: Which is partial, which is total? - the positive square root function for x ∈ ℝ (dom def) - the positive square root function for x ∈ ℝ, x ≥ 0 -/ /- THE TOTAL vs PARTIAL FUNCTION DICHOTOMY Property: We say that a function is "total" if it is defined for every value in its domain. Note that this usage of the word "total" is completely distinct from what we learned earlier for relations in general. It's thus better to use "strongly connected" for relations to mean every object is related to another in at least one direction, and to use total to refer to a function that is defined on every element of its domain. -/ def total_function := function r ∧ ∀ (a : α), defined r a /- At this point we expect that for a total function, r, dom_of_def r = domain r. At one key juncture you use the axiom of set extensionality to convert the goal as an equality into that goal as a bi-implication. After that it's basic predicate logical reasoning, rather than more reasoning in set theory terms. -/ example : total_function r → dom_of_def r = dom r := begin assume total_r, cases total_r with func_r defall, unfold dom_of_def, unfold dom, apply set.ext, assume x, split, -- forwards assume h, unfold defined at defall, unfold defined at defall, -- goal completed -- backwards assume h, exact defall x, end /- With that proof down as an example, we return to complete our list of properties of functions: - total - partial - strictly partial Here are the definitions for the remaning two. -/ def strictly_partial_fun := function r ∧ ¬total_function r def partial_function := function r -- includes total funs /- Mathematicians generally consider the set of partial functions to include the total functions. We will use the term "strictly partial" function to mean a function, f, that is not total, where dom_of_def f ⊊ dom f. (Be sure you see that the subset symbol here means subset but not equal. That's what the slash through the bottom line in the symbol means: strict subset.) -/ /- SURJECTIVE FUNCTIONS A function that "covers" its codomain (where every value in the codomain is an "output" for some value in its domain) is said to map its domain *onto* its entire codomain. Mathematicians will say that such a function is "onto," or "surjective." -/ def surjective := total_function r ∧ ∀ (b : β), ∃ a : α, r a b /- Should this be true? -/ example : surjective r → image_set r (dom r) = { b : β | true } := begin -- homework (on your own ungraded but please do it!) end /- Which of the following functions are surjective? - y = log x, viewed as a function from ℝ → ℝ⁺ As written, the question is, um, tricky. Let's analyze it. Then we'll give simpler questions. First a little background on logarithmic and exponential functions. Simply put, exponentiation raises a base to an exponent to produce an output, while the logarithm takes and converts it into the exponent to which the base is raised to give the input. From basic algebra, the log (base 10) function, y = log(x), is defined for any positive real, x, and is equal to the exponent to which the base (here 10) must be raised to produce x. Therefore as usually defined its domain of definition is the *positive reals* and its co-domain is (*all of*) the reals. Now consider the question again. The domain of definition of log is the positive reals, so if we expand the domain to all the reals, then the resulting function becomes partial. On the other side, if we restrict the range to the positive reals, then we are excluding from the function all those values in the interval (0,1) from the input side in order to restrict the output to values greater than 0. Self homework: Graph this function. - λ x, log x : ℝ+ → ℝ, bijective? - y = x^2, viewed as a function from ℝ → ℝ - y = x, viewed as a function from ℝ → ℝ - y = sin x, viewed as a function from ℝ → ℝ - y = sin x, as a function from ℝ to [-1,1] ∈ ℝ -/ /- INJECTIVE FUNCTION We have seen that for a relation to be a function, it cannot be "one-to-many" (some x value is associated with more than one y value). On the other hand, it is possible for a function to associate many x values with a single y value. There can be no fan-out from x/domain values to y/codomain values, but there can be fan-in from x to y values. Which is the following functions exhibits "fan-in", with different x values associated with the same y values? y = x y = sin x x = 1 (trick question) y = 1 y = x^2 on ℝ y = x^2 on ℝ⁺ (the positive reals) -/ def injective := total_function r ∧ ∀ {x y : α} {z : β}, r x z → r y z → x = y /- We will often want to know that a function does not map multiple x values to the same y value. Example: in a company, we will very like want a function that maps each employee to an employee ID number *unique* to that employee. Rather than being "many to one" we call such a function "one-to-one." We also say that such a function has the property of being *injective*. -/ /- We will often want to know that a function does not map multiple x values to the same y value. Example: in a company, we will very like want a function that maps each employee to an employee ID number *unique* to that employee. Rather than being "many to one" we call such a function "one-to-one." We also say that such a function has the property of being *injective*. There is yet another way to understand the concept. -/ /- BIJECTIVE FUNCTIONS -/ /- Finally, a function is called one-to-one and onto, or *bijective* if it is both surjective and injective. In this case, it has to map every element of its domain -/ def bijective := surjective r ∧ injective r /- An essential property of any bijective relation is that it puts the elements of the domain and codomain into a one-to-one correspondence. That we've assumed that a function is total is important here. Here's a counterexample: consider the relation from dom = {1,2,3} to codom = {A, B} with r = {(1,A), (2,B)}. This function is injective and surjective but it clearly does not establish a 1-1 correspondence. We can define what it means for a strictly partial function to be surjective or injective (we don't do it formally here). We say that a partial function is surjective or injective if its domain restriction to its domain of definition (making it total) meets the definitions given above. Note that our use of the term, one-to-one, here is completely distinct from its use in the definition of an injective function. An injective function is said to be "one-to-one" in the sense that it's not many to one: you can't have f(x) = k and f(y)=k where x ≠ y. A one-to-one correspondence *between two sets*, on the other hand, is a pairing of elements that associates each element of one set with a unique single element of the other set, and vice versa. -/ /- Question: Is the inverse of a function always a function. Think about the function, y = x^2. What is its inverse? Is it's inverse a function? There's your answer. A critical property of a bijective function, on the other hand, is that its inverse is also a bijective function. It is easy to see: just reverse the "arrows" in a one-to-one correspondence between two sets. A function who inverse is a function is said to be invertible (as a function, as every relation has and inverse that is again a relation). -/ /- EXERCISE #1: Prove that the inverse of a bijective function is a function. Ok, yes, we will work this one out for you! But you should really read and understand it. Then the rest shouldn't be too bad. -/ example : bijective r → function (inverse r) := begin /- Assume hypothesis -/ assume r_bij, /- Unfold definitions and, from definitions, deduce all the basic facts we'll have to work with. -/ cases r_bij with r_sur r_inj, cases r_inj with r_tot r_one_to_one, cases r_sur with r_tot r_onto, unfold total_function at r_tot, cases r_tot with r_fun alldef, unfold function at r_fun, unfold single_valued at r_fun, unfold defined at alldef, /- What remains to be shown is that the inverse of r is function. Expanding the definition of function, that means r inverse is single-valued. Let's see. -/ unfold function, unfold single_valued, /- To show that r inverse (mapping β values back to α values) r is single-valued, assume that b is some value of type β (in the codomain of r) and show that if r inverse maps b is mapped to both a1 and a2 then a1 = a2. -/ assume b a1 a2 irba1 irba2, /- Key insight: (inverse r) b a means r a b. In other words, r b a is in r inverse (it contains the pair (b, a)) if and only if (a, b) is in r, i.e., r a b. -/ unfold inverse at irba1 irba2, /- With those pairs now turned around, by the injectivity of r, we're there! -/ apply r_one_to_one irba1 irba2, end /- Just to set expectations: The reality is that I explored numerous ways of writing this proof. Often a first proof will be confusing, messy, etc. Most proofs of theorems you see in most mathematics books are gems, polished in their presentations by generations of mathematicians. It took me a little while to get to this proof script and the sequence of reasoning steps and intermediate proof states it traverses. -/ /- INJECTIVE AND SURJECTIVE *PARTIAL* FUNCTIONS Okay, we actually are now able to to define just what is means for a *partial* function to be injective, surjective, bijective, which is that it is so when its domain is restricted to its domain of definition, rendering it total (at which point the preceding definition applies). -/ def injectivep := function r ∧ injective (dom_res r (dom_of_def r)) def surjectivep := function r ∧ surjective (dom_res r (dom_of_def r)) def bijectivep := function r ∧ bijective (dom_res r (dom_of_def r)) -- EXERCISE #2: Prove that the inverse of a bijective function is bijective. example : bijective r → bijective (inverse r) := begin end /- EXERCISE #3: Prove that the inverse of the inverse of a bijective function is that function. -/ example : bijective r → (r = inverse (inverse r)) := begin end /- EXERCISE #4: Formally state and prove that every injective function has a *function* as an inverse. -/ example : injective r → function (inverse r) := _ -- hint: remember recent work /- EXERCISE #5. Is bijectivity transitive? In other words, if the relations, s and r, are both bijective, then is the composition, s after r, also always bijective? Now we'll see. -/ open relations -- for definition of composition /- Check the following proposition. True? prove it for all. False? Present a counterexample. -/ def bij_trans (s : β → γ → Prop) (r : α → β → Prop) : bijective r → bijective s → bijective (composition s r) := _ /- In general, an operation (such as inverse, here) that, when applied twice, is the identity, is said to be an involution. Relational inverse on bijective functions is involutive in this sense. A visualization: each green ball here goes to a red ball there and the inverse takes each red ball right back to the green ball from which it came, leaving the original green ball as the end result, as well. An identity function. -/ end functions end relations
32986ba5062627e64fba5e620e72f7c121a409b1
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/library/tools/smt2/solvers/z3.lean
17ab0020a2e3672f814fd6966af539d5cff5b864
[ "Apache-2.0" ]
permissive
pcmoritz/lean
6a8575115a724af933678d829b4f791a0cb55beb
35eba0107e4cc8a52778259bb5392300267bfc29
refs/heads/master
1,607,896,326,092
1,490,752,175,000
1,490,752,175,000
86,612,290
0
0
null
1,490,809,641,000
1,490,809,641,000
null
UTF-8
Lean
false
false
817
lean
import system.io import system.process import data.buffer open process structure z3_instance [io.interface] : Type := (process : child io.handle) def spawn [ioi : io.interface] : process → io (child io.handle) := io.interface.process.spawn def z3_instance.start [io.interface] : io z3_instance := do let proc : process := { cmd := "z3", args := ["-smt2", "-in"], stdin := stdio.piped, stdout := stdio.piped }, z3_instance.mk <$> spawn proc def z3_instance.raw [io.interface] (z3 : z3_instance) (cmd : string) : io string := do let z3_stdin := z3.process.stdin, let z3_stdout := z3.process.stdout, let cs := cmd.reverse.to_buffer, io.fs.write z3_stdin cs, io.fs.close z3_stdin, -- need read all res ← io.fs.read z3_stdout 1024, return res.to_string
f6dd0b621c8ba70eac05ac1455f7afbab5bdc021
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world6/level5.lean
1b38fa34f4a59cb06b42917f2b61fad5f8767796
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
2,369
lean
/- # Proposition world. ## Level 5 : `P → (Q → P)`. In this level, our goal is to construct an implication, like in level 2. ``` ⊢ P → (Q → P) ``` So $P$ and $Q$ are propositions, and our goal is to prove that $P\implies(Q\implies P)$. We don't know whether $P$, $Q$ are true or false, so initially this seems like a bit of a tall order. But let's give it a go. Delete the `sorry` and let's think about how to proceed. Our goal is `P → X` for some true/false statement $X$, and if our goal is to construct an implication then we almost always want to use the `intro` tactic from level 2, Lean's version of "assume $P$", or more precisely "assume $p$ is a proof of $P$". So let's start with `intro p,` and we then find ourselves in this state: ``` P Q : Prop, p : P ⊢ Q → P ``` We now have a proof $p$ of $P$ and we are supposed to be constructing a proof of $Q\implies P$. So let's assume that $Q$ is true and try and prove that $P$ is true. We assume $Q$ like this: `intro q,` and now we have to prove $P$, but have a proof handy: `exact p,` -/ /- Lemma : no-side-bar For any propositions $P$ and $Q$, we always have $P\implies(Q\implies P)$. -/ example (P Q : Prop) : P → (Q → P) := begin end /- A mathematician would treat the proposition $P\implies(Q\implies P)$ as the same as the proposition $P\land Q\implies P$, because to give a proof of either of these is just to give a method which takes a proof of $P$ and a proof of $Q$, and returns a proof of $P$. Thinking of the goal as $P\land Q\implies P$ we see why it is provable. ## Did you notice? I wrote `P → (Q → P)` but Lean just writes `P → Q → P`. This is because computer scientists adopt the convention that `→` is *right associative*, which is a fancy way of saying "when we write `P → Q → R`, we mean `P → (Q → R)`. Mathematicians would never dream of writing something as ambiguous as $P\implies Q\implies R$ (they are not really interested in proving abstract propositions, they would rather work with concrete ones such as Fermat's Last Theorem), so they do not have a convention for where the brackets go. It's important to remember Lean's convention though, or else you will get confused. If your goal is `P → Q → R` then you need to know whether `intro h` will create `h : P` or `h : P → Q`. Make sure you understand which one. -/
348db1430a5eccc077ed4bb1731e343e6fdea364
618003631150032a5676f229d13a079ac875ff77
/src/control/traversable/lemmas.lean
f6f6300dcd913538319b64b84e89f898b8faf420
[ "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
3,682
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Lemmas about traversing collections. Inspired by: The Essence of the Iterator Pattern Jeremy Gibbons and Bruno César dos Santos Oliveira In Journal of Functional Programming. Vol. 19. No. 3&4. Pages 377−402. 2009. <http://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf> -/ import control.traversable.basic import control.applicative universe variables 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 : β → γ def pure_transformation : applicative_transformation id F := { app := @pure F _, preserves_pure' := λ α x, rfl, preserves_seq' := λ α β f x, by simp; 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; simp [id_traverse]; refl @[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; simp [comp_traverse] lemma traverse_eq_map_id' (f : β → γ) : traverse (id.mk ∘ f) = id.mk ∘ (map f : t β → t γ) := by ext;rw traverse_eq_map_id -- @[functor_norm] lemma traverse_map' (g : α → β) (h : β → G γ) : traverse (h ∘ g) = (traverse h ∘ map g : t α → G (t γ)) := by ext; simp [traverse_map] lemma map_traverse' (g : α → G β) (h : β → γ) : traverse (map h ∘ g) = (map (map h) ∘ traverse g : t α → G (t γ)) := by ext; simp [map_traverse] lemma naturality_pf (η : applicative_transformation F G) (f : α → F β) : traverse (@η _ ∘ f) = @η _ ∘ (traverse f : t α → F (t β)) := by ext; simp [naturality] end traversable
1a6fe64c6e734e84acbeb0460714f4b82a6c9474
19a24126e4b7677703434d80717041622a5f1d61
/theorem_proving_in_lean/3.Propositions_and_Proofs.lean
66cea137126ccc8b758589fc833f0935c8ead8e3
[]
no_license
JoseBalado/lean-notes
f5ff8d4c99ba8c1f79d7894ba0f130fa4eb09695
0b579f83988cc844ac1ff0592d885061959a852e
refs/heads/master
1,587,743,561,316
1,567,181,955,000
1,567,181,955,000
172,086,145
0
0
null
null
null
null
UTF-8
Lean
false
false
15,452
lean
-- p q r s are used in all the examples so they are defined only here variables p q r s : Prop -- Conjunction -- Prove p, q -> p ∧ q example (hp : p) (hq : q): p ∧ q := and.intro hp hq -- Prove p ∧ q -> q example (h : p ∧ q) : p := and.elim_left h -- Prove p ∧ q -> p example (h : p ∧ q) : q := and.elim_right h -- Some examples of type assignment variables (h : p) (i : q) #check and.elim_left ⟨h, i⟩ #reduce and.elim_left ⟨h, i⟩ #check and.elim_right ⟨h, i⟩ #reduce and.elim_right ⟨h, i⟩ #check (⟨h, i⟩ : p ∧ q) #reduce (⟨h, i⟩ : p ∧ q) -- Prove q ∧ p → p ∧ q example (h : p ∧ q) : q ∧ p := and.intro (and.elim_right h) (and.elim_left h) -- Lean allows us to use anonymous constructor notation ⟨arg1, arg2, ...⟩ -- In situations like these, when the relevant type is an inductive type and can be inferred from the context. -- In particular, we can often write ⟨hp, hq⟩ instead of and.intro hp hq: example (h : p ∧ q) : q ∧ p := ⟨and.elim_right h, and.elim_left h⟩ -- More examples of using the constructor notation example (h : p ∧ q) : q ∧ p ∧ q:= ⟨h.right, ⟨h.left, h.right⟩⟩ example (h : p ∧ q) : q ∧ p ∧ q:= ⟨h.right, h.left, h.right⟩ -- Disjunction -- ∨ introduction left example (hp : p): p ∨ q := or.intro_left q hp -- ∨ introduction right example (hq : q): p ∨ q := or.intro_right p hq -- Prove p ∨ p → p example (h: p ∨ p): p := or.elim h (assume hpr : p, show p, from hpr) (assume hpl : p, show p, from hpl) -- Prove p ∨ p → p, simplified notation example (h: p ∨ p): p := or.elim h (assume hpr : p, hpr) (assume hpl : p, hpl) -- Prove p ∨ q, p → r, q -> r, -> r example (h : p ∨ q) (i : p → r) (j : q -> r) : r := or.elim h (assume hp : p, show r, from i hp) (assume hq : q, show r, from j hq) -- Prove p ∨ q → q ∨ p example (h : p ∨ q) : q ∨ p := or.elim h (assume hp : p, show q ∨ p, from or.intro_right q hp) (assume hq : q, show q ∨ p, from or.intro_left p hq) -- Modus tollens, deriving a contradiction from p to obtain false. -- Everything follows from false, in this case ¬p -- order of propositions matters when using absurd example (hpq : p → q) (hnq : ¬q) : ¬p := assume hp : p, show false, from hnq (hpq hp) -- Equivalent to the previous one example (hpq : p → q) (hnq : ¬q) : ¬p := assume hp : p, show false, from false.elim (hnq (hpq hp)) -- Equivalent to the previous one example (hpq : p → q) (hnq : ¬q) : ¬p := assume hp : p, show false, from (hnq (hpq hp)) -- More examples of false and absurd use example (hp : p) (hnp : ¬p) : q := false.elim (hnp hp) -- order of propositions matters when using absurd example (hp : p) (hnp : ¬p) : q := absurd hp hnp -- Prove ¬p → q → (q → p) → r, premise ¬p must be added example (hnp : ¬p) (hq : q) (hqp : q → p): r := false.elim (hnp (hqp hq)) -- equivalent proove as the above example (hnp : ¬p) (hq : q) (hqp : q → p): r := absurd (hqp hq) hnp -- Other variant from the above -- Prove ¬p → q → (q → p) → r, premise ¬p must be added example (hnp : ¬ p) (hnpq : ¬p → q) (hqp : q → p): r := absurd (hqp (hnpq hnp)) hnp example (hnp : ¬ p) (hnpq : ¬p → q) (hqp : q → p): r := false.elim (hnp (hqp (hnpq hnp))) -- Prove p ∧ q ↔ q ∧ p example : (p ∧ q) ↔ (q ∧ p) := iff.intro (assume h : p ∧ q, show q ∧ p, from and.intro (and.elim_right h) (and.elim_left h)) (assume h : q ∧ p, show p ∧ q, from and.intro (and.elim_right h) (and.elim_left h)) -- Derive q ∧ p from p ∧ q example (h : p ∧ q) : (q ∧ p) := and.intro (and.elim_right h) (and.elim_left h) -- Define a theorem and use the anomimous constructor to prove p ∧ q ↔ q ∧ p theorem and_swap : p ∧ q ↔ q ∧ p := ⟨ λ h, ⟨h.right, h.left⟩, λ h, ⟨h.right, h.left⟩ ⟩ -- Prove, using and_swap theorem that p ∧ q → q ∧ p example (h : p ∧ q) : q ∧ p := (and_swap p q).mp h -- Introducing auxiliary subgoals with `have` example (h : p ∧ q) : q ∧ p := have hp : p, from and.left h, have hq : q, from and.right h, show q ∧ p, from and.intro hq hp -- Introducing auxiliary subgoals with `suffices` example (h : p ∧ q) : q ∧ p := have hp : p, from and.left h, suffices hq : q, from and.intro hq hp, show q, from and.right h -- Classical logic -- Prove double negation -- To use `em` we can invoke it using classical namespace like so: `classical.em` -- or import the classical module with 'open classical' and just use 'em' directly, -- no need to prefix it with namespace name theorem dne {p : Prop} (h : ¬¬p) : p := or.elim (classical.em p) (assume hp : p, show p, from hp) (assume hnp : ¬p, show p, from absurd hnp h) -- Prove double negation, p is defined at the top of the file as p : Prop, -- so no need to add {p : Prop} to the premises example (h : ¬¬p) : p := or.elim (classical.em p) (assume hp : p, show p, from hp) (assume hnp : ¬p, show p, from absurd hnp h) -- Proof by cases example (h : ¬¬p) : p := classical.by_cases (assume h1 : p, h1) (assume h1 : ¬p, absurd h1 h) -- Proof by contradiction example (h : ¬¬p) : p := classical.by_contradiction (assume h1 : ¬p, absurd h1 h) example (h : ¬¬p) : p := classical.by_contradiction (assume h1 : ¬p, show false, from h h1) -- Prove ¬(p ∧ q) → ¬p ∨ ¬q example (h : ¬(p ∧ q)) : ¬p ∨ ¬q := or.elim (classical.em p) (assume hp : p, or.inr (show ¬q, from assume hq : q, h ⟨hp, hq⟩)) (assume hnp : ¬p, show ¬p ∨ ¬q, from or.inl hnp) -- Prove p ∧ q → (p → q) := example : p ∧ q → (p → q) := assume hpq : p ∧ q, assume hp : p, show q, from and.elim_right hpq -- Prove p → q → (p ∧ q) := example : p → q → (p ∧ q) := assume hp : p, assume hq : q, show p ∧ q, from and.intro hp hq -- 3.6. Examples of Propositional Validities -- commutativity of ∧ and ∨ -- Prove p ∨ q ↔ q ∨ p example : p ∨ q ↔ q ∨ p := iff.intro (assume h : p ∨ q, show q ∨ p, from or.elim h (assume hp : p, show q ∨ p, from or.intro_right q hp) (assume hq : q, show q ∨ p, from or.intro_left p hq)) (assume h : q ∨ p, show p ∨ q, from or.elim h (assume hq : q, show p ∨ q, from or.intro_right p hq) (assume hp : p, show p ∨ q, from or.intro_left q hp)) -- Associativity of ∧ and ∨ -- -- Prove (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := iff.intro (assume hpqr : (p ∧ q) ∧ r, show p ∧ (q ∧ r), from ⟨hpqr.left.left, ⟨hpqr.left.right, hpqr.right⟩⟩) (assume hpqr : p ∧ (q ∧ r), show (p ∧ q) ∧ r, from ⟨⟨hpqr.left, hpqr.right.left⟩, hpqr.right.right⟩) -- Prove (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := iff.intro (assume hpqr : (p ∨ q) ∨ r, show p ∨ (q ∨ r), from or.elim hpqr (assume hpq : p ∨ q, show p ∨ (q ∨ r), from or.elim hpq (assume hp : p, show p ∨ (q ∨ r), from or.inl hp) (assume hq : q, show p ∨ (q ∨ r), from or.inr (or.inl hq))) (assume hr : r, show p ∨ (q ∨ r), from or.inr (or.inr hr))) (assume hpqr : p ∨ (q ∨ r), show (p ∨ q) ∨ r, from or.elim hpqr (assume hp : p, show (p ∨ q) ∨ r, from or.inl (or.inl hp)) (assume hqr : q ∨ r, show (p ∨ q) ∨ r, from or.elim hqr (assume hq: q, show (p ∨ q) ∨ r, from or.inl (or.inr hq )) (assume hr : r, show (p ∨ q) ∨ r, from or.inr hr))) -- Distributivity -- -- Prove p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := iff.intro (assume h : p ∧ (q ∨ r), have hp : p, from h.left, or.elim (h.right) (assume hq : q, show (p ∧ q) ∨ (p ∧ r), from or.inl ⟨hp, hq⟩) (assume hr : r, show (p ∧ q) ∨ (p ∧ r), from or.inr ⟨hp, hr⟩)) (assume h : (p ∧ q) ∨ (p ∧ r), or.elim h (assume hpq : (p ∧ q), show p ∧ (q ∨ r), from and.intro hpq.left (or.inl hpq.right)) (assume hpr : (p ∧ r), show p ∧ (q ∨ r), from and.intro hpr.left (or.inr hpr.right))) -- Prove p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := sorry example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := iff.intro (assume h: p ∨ (q ∧ r), show (p ∨ q) ∧ (p ∨ r), from or.elim h (assume hp: p, show (p ∨ q) ∧ (p ∨ r), from ⟨or.inl hp, or.inl hp⟩) (assume hqr: (q ∧ r), show (p ∨ q) ∧ (p ∨ r), from ⟨or.inr hqr.left, or.inr hqr.right⟩)) (assume h: (p ∨ q) ∧ (p ∨ r), show p ∨ (q ∧ r), from or.elim (h.left) (assume hp : p, show p ∨ (q ∧ r), from or.inl hp) (assume hq : q, show p ∨ (q ∧ r), from or.elim h.right (assume hp : p, show p ∨ (q ∧ r), from or.inl hp) (assume hr : r, show p ∨ (q ∧ r), from or.inr ⟨hq, hr⟩) )) -- Other properties -- Prove (p → (q → r)) ↔ (p ∧ q → r) example : (p → (q → r)) ↔ (p ∧ q → r) := iff.intro (assume hpqr : p → (q → r), show p ∧ q → r, from (assume hpq : p ∧ q, have hp : p, from hpq.left, have hq : q, from hpq.right, show r, from (hpqr hp) hq)) (assume hpqr : (p ∧ q → r), show (p → (q → r)), from (assume hp : p, show q → r, from (assume hq, show r, from (hpqr ⟨hp, hq⟩)))) -- Prove ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := iff.intro (assume hpqr : (p ∨ q) → r, show (p → r) ∧ (q → r), from ⟨(assume hp : p, show r, from hpqr(or.inl hp)), (assume hq : q, show r, from hpqr(or.inr hq))⟩) (assume hprqr : (p → r) ∧ (q → r), show (p ∨ q) → r, from (assume hpq : p ∨ q, show r, from or.elim hpq (assume hp : p, show r, from hprqr.left hp) (assume hq : q, show r, from hprqr.right hq) ) ) -- Prove ¬(p ∨ q) ↔ ¬p ∧ ¬q := sorry example (p q : Prop) : ¬(p ∨ q) ↔ ¬p ∧ ¬q := ⟨λ h, ⟨λ hp, h (or.inl hp), λ hq, h (or.inr hq)⟩, λ hn h, or.elim h hn.1 hn.2⟩ -- Another proof for ¬(p ∨ q) ↔ ¬p ∧ ¬q := sorry example (p q : Prop) : ¬(p ∨ q) ↔ ¬p ∧ ¬q := iff.intro (assume hnpq : ¬(p ∨ q), show ¬p ∧ ¬q, from and.intro (assume hp : p, show false, from hnpq (or.inl hp)) (assume hq : q, show false, from hnpq (or.inr hq))) (assume (hnpnq : ¬p ∧ ¬q), show ¬(p ∨ q), from assume hnpq : p ∨ q, show false, from or.elim hnpq (and.left hnpnq) (and.right hnpnq)) -- Prove ¬p ∨ ¬q → ¬(p ∧ q) := sorry example : ¬p ∨ ¬q → ¬(p ∧ q) := (assume hnpnq : ¬p ∨ ¬q, assume hpq : p ∧ q, show false, from (or.elim hnpnq (assume hnp : ¬p, show false, from hnp (and.left hpq)) (assume hnq : ¬q, show false, from hnq (and.right hpq)) ) ) -- Prove ¬(p ∧ ¬p) := sorry example : ¬(p ∧ ¬p) := assume h : p ∧ ¬p, show false, from h.right h.left example : ¬(p ∧ ¬p) := assume h, absurd h.left h.right -- Prove p ∧ ¬q → ¬(p → q) example : p ∧ ¬q → ¬(p → q) := assume hpnq : p ∧ ¬ q, assume hpq : p → q, absurd (hpq hpnq.left) hpnq.right example : p ∧ ¬q → ¬(p → q) := assume hpnq : p ∧ ¬ q, assume hpq : p → q, show false, from hpnq.right (hpq hpnq.left) -- Prove ¬p → (p → q) := sorry example : ¬p → (p → q) := assume hnp, assume hp, absurd hp hnp example : ¬p → (p → q) := assume hnp, assume hp, show q , from absurd hp hnp example : ¬p → (p → q) := assume hp, assume hnp, show q , from false.elim(hp hnp) -- Prove (¬p ∨ q) → (p → q) example : (¬p ∨ q) → (p → q) := (assume hnpq : ¬p ∨ q, or.elim hnpq (assume hnp : ¬p, assume hp : p, show q, from absurd hp hnp) (assume hq : q, assume hp : p, show q, from hq)) example : (¬p ∨ q) → (p → q) := (assume hnpq : ¬p ∨ q, or.elim hnpq (assume hnp : ¬p, assume hp : p, show q, from false.elim (hnp hp)) (assume hq : q, assume hp : p, show q, from hq)) -- Prove p ∨ false ↔ p example : p ∨ false ↔ p := iff.intro (assume hpf, or.elim hpf (assume hp, show p, from hp) (assume false, show p, from false.elim)) (assume hp, show p ∨ false, from or.inl hp) -- Prove p ∧ false ↔ false example : p ∧ false ↔ false := iff.intro (assume hpf, show false, from hpf.right) (assume hf, show p ∧ false, from and.intro (show p, from hf.elim) hf) -- Prove ¬(p ↔ ¬p) example : ¬(p ↔ ¬p) := assume hpnp, have hnp : ¬ p, from assume hp : p, show false, from (hpnp.elim_left hp) hp, show false, from hnp (hpnp.elim_right hnp) -- Prove (p → q) → (¬q → ¬p) example : (p → q) → (¬q → ¬p) := assume hpq, assume hnq, assume hp, show false, from hnq (hpq hp) example : (p → q) → (¬q → ¬p) := assume hpq, assume hnq, assume hp, absurd (hpq hp) hnq -- these require classical reasoning open classical -- Prove (p → r ∨ s) → ((p → r) ∨ (p → s)) example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := (assume hprs, show (p → r) ∨ (p → s), from sorry) example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := (assume hprs, assume hp, show (p → r) ∨ (p → s), from sorry) example (h : ¬¬p) : p := by_cases (assume h1 : p, h1) (assume h1 : ¬p, absurd h1 h) example (h : ¬¬p) : p := by_contradiction (assume h1 : ¬p, show false, from h h1) example (h : ¬(p ∧ q)) : ¬p ∨ ¬q := or.elim (em p) (assume hp : p, or.inr (show ¬q, from assume hq : q, h ⟨hp, hq⟩)) (assume hp : ¬p, or.inl hp) -- Prove ¬(p ∧ q) → ¬p ∨ ¬q example : ¬(p ∧ q) → ¬p ∨ ¬q := assume hnpq, or.elim (em p) (assume hp, show ¬p ∨ ¬q, from or.inr (assume hq, hnpq (and.intro hp hq))) (assume hnp, show ¬p ∨ ¬q, from or.inl hnp) -- Prove: ¬(p ∧ ¬q) → (p → q) example : ¬(p ∧ ¬q) → (p → q) := assume hnpnq : ¬(p ∧ ¬q), show p → q, from (assume hp: p, show q, from by_contradiction (assume hnq: ¬q, show false, from hnpnq (and.intro hp hnq))) -- Prove ¬(p → q) → p ∧ ¬q example : ¬(p → q) → p ∧ ¬q := assume hnpq : ¬(p → q), show p ∧ ¬q, from by_contradiction ( assume hnpnq : ¬(p ∧ ¬q), show false, from hnpq (assume hp: p, show q, from by_contradiction (assume hnq: ¬q, show false, from hnpnq (and.intro hp hnq)) ) ) -- Prove (p → q) → (¬p ∨ q) example : (p → q) → (¬p ∨ q) := assume hpq : p → q, show ¬p ∨ q, from or.elim (em p) (assume hp, show ¬p ∨ q, from or.inr(hpq hp)) (assume hnp, show ¬p ∨ q, from or.inl hnp) -- Prove (¬q → ¬p) → (p → q) example : (¬q → ¬p) → (p → q) := assume hnpnq : ¬q → ¬p, show p → q, from ( assume hp: p, show q, from by_contradiction ( assume hnq: ¬q, show false, from (hnpnq hnq) hp ) ) -- Prove p ∨ ¬p example : p ∨ ¬p := by_contradiction(assume hnpnp: ¬(p ∨ ¬p), show false, from or.elim (em p) (assume hp : p, show false, from false.elim(hnpnp (or.inl hp))) (assume hnp : ¬p, show false, from false.elim(hnpnp (or.inr hnp))) ) -- Prove (((p → q) → p) → p) example : (((p → q) → p) → p) := assume hpqp : (p → q) → p, show p, from by_contradiction( assume hnp : ¬p, show false, from false.elim( hnp (hpqp (assume hp : p, show q, from false.elim(hnp hp))) ) )
220cc28a82b04c68517cded8d8ef7465e8adab44
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/geometry/manifold/cont_mdiff_map.lean
e5c95ee2813fd26e3cb8a937e75cfab404dba337
[ "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,421
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import geometry.manifold.cont_mdiff import topology.continuous_function.basic /-! # Smooth bundled map > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define the type `cont_mdiff_map` of `n` times continuously differentiable bundled maps. -/ variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E'] {H : Type*} [topological_space H] {H' : Type*} [topological_space H'] (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') (M : Type*) [topological_space M] [charted_space H M] (M' : Type*) [topological_space M'] [charted_space H' M'] {E'' : Type*} [normed_add_comm_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] -- declare a manifold `N` over the pair `(F, G)`. {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] {G : Type*} [topological_space G] {J : model_with_corners 𝕜 F G} {N : Type*} [topological_space N] [charted_space G N] (n : ℕ∞) /-- Bundled `n` times continuously differentiable maps. -/ def cont_mdiff_map := {f : M → M' // cont_mdiff I I' n f} /-- Bundled smooth maps. -/ @[reducible] def smooth_map := cont_mdiff_map I I' M M' ⊤ localized "notation (name := cont_mdiff_map) `C^` n `⟮` I `, ` M `; ` I' `, ` M' `⟯` := cont_mdiff_map I I' M M' n" in manifold localized "notation (name := cont_mdiff_map.self) `C^` n `⟮` I `, ` M `; ` k `⟯` := cont_mdiff_map I (model_with_corners_self k k) M k n" in manifold open_locale manifold namespace cont_mdiff_map variables {I} {I'} {M} {M'} {n} instance fun_like : fun_like C^n⟮I, M; I', M'⟯ M (λ _, M') := { coe := subtype.val, coe_injective' := subtype.coe_injective } protected lemma cont_mdiff (f : C^n⟮I, M; I', M'⟯) : cont_mdiff I I' n f := f.prop protected lemma smooth (f : C^∞⟮I, M; I', M'⟯) : smooth I I' f := f.prop instance : has_coe C^n⟮I, M; I', M'⟯ C(M, M') := ⟨λ f, ⟨f, f.cont_mdiff.continuous⟩⟩ attribute [to_additive_ignore_args 21] cont_mdiff_map cont_mdiff_map.fun_like cont_mdiff_map.continuous_map.has_coe variables {f g : C^n⟮I, M; I', M'⟯} @[simp] lemma coe_fn_mk (f : M → M') (hf : cont_mdiff I I' n f) : ((by exact subtype.mk f hf : C^n⟮I, M; I', M'⟯) : M → M') = f := rfl lemma coe_inj ⦃f g : C^n⟮I, M; I', M'⟯⦄ (h : (f : M → M') = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext h instance : continuous_map_class C^n⟮I, M; I', M'⟯ M M' := { coe := (λ f, ⇑f), coe_injective' := coe_inj, map_continuous := λ f, f.cont_mdiff.continuous } /-- The identity as a smooth map. -/ def id : C^n⟮I, M; I, M⟯ := ⟨id, cont_mdiff_id⟩ /-- The composition of smooth maps, as a smooth map. -/ def comp (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) : C^n⟮I, M; I'', M''⟯ := { val := λ a, f (g a), property := f.cont_mdiff.comp g.cont_mdiff, } @[simp] lemma comp_apply (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) (x : M) : f.comp g x = f (g x) := rfl instance [inhabited M'] : inhabited C^n⟮I, M; I', M'⟯ := ⟨⟨λ _, default, cont_mdiff_const⟩⟩ /-- Constant map as a smooth map -/ def const (y : M') : C^n⟮I, M; I', M'⟯ := ⟨λ x, y, cont_mdiff_const⟩ /-- The first projection of a product, as a smooth map. -/ def fst : C^n⟮I.prod I', M × M'; I, M⟯ := ⟨prod.fst, cont_mdiff_fst⟩ /-- The second projection of a product, as a smooth map. -/ def snd : C^n⟮I.prod I', M × M'; I', M'⟯ := ⟨prod.snd, cont_mdiff_snd⟩ /-- Given two smooth maps `f` and `g`, this is the smooth map `x ↦ (f x, g x)`. -/ def prod_mk (f : C^n⟮J, N; I, M⟯) (g : C^n⟮J, N; I', M'⟯) : C^n⟮J, N; I.prod I', M × M'⟯ := ⟨λ x, (f x, g x), f.2.prod_mk g.2⟩ end cont_mdiff_map instance continuous_linear_map.has_coe_to_cont_mdiff_map : has_coe (E →L[𝕜] E') C^n⟮𝓘(𝕜, E), E; 𝓘(𝕜, E'), E'⟯ := ⟨λ f, ⟨f.to_fun, f.cont_mdiff⟩⟩