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
1f1bcb14d518e6f50953be14e30e22e864d2a7ee
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/iterated_deriv.lean
2ec5217cc9e8341442859957b955e43a32014629
[ "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
7,816
lean
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import data.nat.interval import data.polynomial.derivative import tactic.linarith /-! # Theory of iterated derivative We define and prove some lemmas about iterated (formal) derivative for polynomials over a semiring. -/ noncomputable theory open finset nat polynomial open_locale big_operators polynomial namespace polynomial universes u variable {R : Type u} section semiring variables [semiring R] (r : R) (f p q : R[X]) (n k : ℕ) /-- `iterated_deriv f n` is the `n`-th formal derivative of the polynomial `f` -/ def iterated_deriv : R[X] := derivative ^[n] f @[simp] lemma iterated_deriv_zero_right : iterated_deriv f 0 = f := rfl lemma iterated_deriv_succ : iterated_deriv f (n + 1) = (iterated_deriv f n).derivative := by rw [iterated_deriv, iterated_deriv, function.iterate_succ'] @[simp] lemma iterated_deriv_zero_left : iterated_deriv (0 : R[X]) n = 0 := begin induction n with n hn, { exact iterated_deriv_zero_right _ }, { rw [iterated_deriv_succ, hn, derivative_zero] }, end @[simp] lemma iterated_deriv_add : iterated_deriv (p + q) n = iterated_deriv p n + iterated_deriv q n := begin induction n with n ih, { simp only [iterated_deriv_zero_right], }, { simp only [iterated_deriv_succ, ih, derivative_add] } end @[simp] lemma iterated_deriv_smul {S : Type*} [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] (s : S) : iterated_deriv (s • p) n = s • iterated_deriv p n := begin induction n with n ih, { simp only [iterated_deriv_zero_right] }, { simp only [iterated_deriv_succ, ih, derivative_smul] } end @[simp] lemma iterated_deriv_X_zero : iterated_deriv (X : R[X]) 0 = X := by simp only [iterated_deriv_zero_right] @[simp] lemma iterated_deriv_X_one : iterated_deriv (X : R[X]) 1 = 1 := by simp only [iterated_deriv, derivative_X, function.iterate_one] @[simp] lemma iterated_deriv_X (h : 1 < n) : iterated_deriv (X : R[X]) n = 0 := begin induction n with n ih, { exfalso, exact nat.not_lt_zero 1 h }, { simp only [iterated_deriv_succ], by_cases H : n = 1, { rw H, simp only [iterated_deriv_X_one, derivative_one] }, { replace h : 1 < n := array.push_back_idx h (ne.symm H), rw ih h, simp only [derivative_zero] } } end @[simp] lemma iterated_deriv_C_zero : iterated_deriv (C r) 0 = C r := by simp only [iterated_deriv_zero_right] @[simp] lemma iterated_deriv_C (h : 0 < n) : iterated_deriv (C r) n = 0 := begin induction n with n ih, { exfalso, exact nat.lt_asymm h h }, { by_cases H : n = 0, { rw [iterated_deriv_succ, H], simp only [iterated_deriv_C_zero, derivative_C] }, { replace h : 0 < n := nat.pos_of_ne_zero H, rw [iterated_deriv_succ, ih h], simp only [derivative_zero] } } end @[simp] lemma iterated_deriv_one_zero : iterated_deriv (1 : R[X]) 0 = 1 := by simp only [iterated_deriv_zero_right] @[simp] lemma iterated_deriv_one : 0 < n → iterated_deriv (1 : R[X]) n = 0 := λ h, begin have eq1 : (1 : R[X]) = C 1 := by simp only [ring_hom.map_one], rw eq1, exact iterated_deriv_C _ _ h, end lemma coeff_iterated_deriv_as_prod_Ico : ∀ m : ℕ, (iterated_deriv f k).coeff m = (∏ i in Ico m.succ (m + k.succ), i) • (f.coeff (m+k)) := begin induction k with k ih, { simp only [add_zero, forall_const, one_smul, Ico_self, eq_self_iff_true, iterated_deriv_zero_right, prod_empty] }, { intro m, rw [iterated_deriv_succ, coeff_derivative, ih (m+1), ← nat.cast_add_one, ← nsmul_eq_mul', smul_smul, mul_comm], apply congr_arg2, { have set_eq : (Ico m.succ (m + k.succ.succ)) = (Ico (m + 1).succ (m + 1 + k.succ)) ∪ {m+1}, { simp_rw [← Ico_succ_singleton, union_comm, succ_eq_add_one, add_comm (k + 1), add_assoc], rw [Ico_union_Ico_eq_Ico]; simp_rw [add_le_add_iff_left, le_add_self], }, rw [set_eq, prod_union, prod_singleton], { rw [disjoint_singleton_right, mem_Ico], exact λ h, (nat.lt_succ_self _).not_le h.1 } }, { exact congr_arg _ (succ_add m k) } }, end lemma coeff_iterated_deriv_as_prod_range : ∀ m : ℕ, (iterated_deriv f k).coeff m = (∏ i in range k, (m + k - i)) • f.coeff (m + k) := begin induction k with k ih, { simp }, intro m, calc (f.iterated_deriv k.succ).coeff m = (∏ i in range k, (m + k.succ - i)) • f.coeff (m + k.succ) * (m + 1) : by rw [iterated_deriv_succ, coeff_derivative, ih m.succ, succ_add, add_succ] ... = ((∏ i in range k, (m + k.succ - i)) * (m + 1)) • f.coeff (m + k.succ) : by rw [← nat.cast_add_one, ← nsmul_eq_mul', smul_smul, mul_comm] ... = (∏ i in range k.succ, (m + k.succ - i)) • f.coeff (m + k.succ) : by rw [prod_range_succ, add_tsub_assoc_of_le k.le_succ, succ_sub le_rfl, tsub_self] end lemma iterated_deriv_eq_zero_of_nat_degree_lt (h : f.nat_degree < n) : iterated_deriv f n = 0 := begin ext m, rw [coeff_iterated_deriv_as_prod_range, coeff_zero, coeff_eq_zero_of_nat_degree_lt, smul_zero], linarith end lemma iterated_deriv_mul : iterated_deriv (p * q) n = ∑ k in range n.succ, n.choose k • (iterated_deriv p (n - k) * iterated_deriv q k) := begin induction n with n IH, { simp }, calc (p * q).iterated_deriv n.succ = (∑ (k : ℕ) in range n.succ, (n.choose k) • (p.iterated_deriv (n - k) * q.iterated_deriv k)).derivative : by rw [iterated_deriv_succ, IH] ... = ∑ (k : ℕ) in range n.succ, (n.choose k) • (p.iterated_deriv (n - k + 1) * q.iterated_deriv k) + ∑ (k : ℕ) in range n.succ, (n.choose k) • (p.iterated_deriv (n - k) * q.iterated_deriv (k + 1)) : by simp_rw [derivative_sum, derivative_smul, derivative_mul, iterated_deriv_succ, smul_add, sum_add_distrib] ... = (∑ (k : ℕ) in range n.succ, (n.choose k.succ) • (p.iterated_deriv (n - k) * q.iterated_deriv (k + 1)) + 1 • (p.iterated_deriv n.succ * q.iterated_deriv 0)) + ∑ (k : ℕ) in range n.succ, (n.choose k) • (p.iterated_deriv (n - k) * q.iterated_deriv (k + 1)) : _ ... = ∑ (k : ℕ) in range n.succ, (n.choose k) • (p.iterated_deriv (n - k) * q.iterated_deriv (k + 1)) + ∑ (k : ℕ) in range n.succ, (n.choose k.succ) • (p.iterated_deriv (n - k) * q.iterated_deriv (k + 1)) + 1 • (p.iterated_deriv n.succ * q.iterated_deriv 0) : by rw [add_comm, add_assoc] ... = ∑ (i : ℕ) in range n.succ, ((n+1).choose (i+1)) • (p.iterated_deriv (n + 1 - (i+1)) * q.iterated_deriv (i+1)) + 1 • (p.iterated_deriv n.succ * q.iterated_deriv 0) : by simp_rw [choose_succ_succ, succ_sub_succ, add_smul, sum_add_distrib] ... = ∑ (k : ℕ) in range n.succ.succ, (n.succ.choose k) • (p.iterated_deriv (n.succ - k) * q.iterated_deriv k) : by rw [sum_range_succ' _ n.succ, choose_zero_right, tsub_zero], congr, refine (sum_range_succ' _ _).trans (congr_arg2 (+) _ _), { rw [sum_range_succ, nat.choose_succ_self, zero_smul, add_zero], refine sum_congr rfl (λ k hk, _), rw mem_range at hk, congr, rw [tsub_add_eq_add_tsub (nat.succ_le_of_lt hk), nat.succ_sub_succ] }, { rw [choose_zero_right, tsub_zero] }, end end semiring section ring variables [ring R] (p q : R[X]) (n : ℕ) @[simp] lemma iterated_deriv_neg : iterated_deriv (-p) n = - iterated_deriv p n := begin induction n with n ih, { simp only [iterated_deriv_zero_right] }, { simp only [iterated_deriv_succ, ih, derivative_neg] } end @[simp] lemma iterated_deriv_sub : iterated_deriv (p - q) n = iterated_deriv p n - iterated_deriv q n := by rw [sub_eq_add_neg, iterated_deriv_add, iterated_deriv_neg, ←sub_eq_add_neg] end ring end polynomial
d1b1c7242d1d0937afe9a0b064e414340baa32ec
531456391187e1b7678c24ddaf3d6470b4dba971
/library/init/meta/expr.lean
870f25275929c6bd55a82889c0c354a8a02826b6
[ "Apache-2.0" ]
permissive
tigerneil/lean
7e4834cb9b03027c0e3ba42efd8c1a4f52389c9c
8f31cff99bca2c5dd7fcd425de1ff1cb8e4e150a
refs/heads/master
1,606,890,672,381
1,499,580,201,000
1,499,580,305,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,243
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.level init.category.monad init.meta.rb_map universes u v structure pos := (line : nat) (column : nat) instance : decidable_eq pos | ⟨l₁, c₁⟩ ⟨l₂, c₂⟩ := if h₁ : l₁ = l₂ then if h₂ : c₁ = c₂ then is_true (eq.rec_on h₁ (eq.rec_on h₂ rfl)) else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₂ h₂)) else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₁ h₁)) meta instance : has_to_format pos := ⟨λ ⟨l, c⟩, "⟨" ++ l ++ ", " ++ c ++ "⟩"⟩ inductive binder_info | default | implicit | strict_implicit | inst_implicit | aux_decl instance : has_repr binder_info := ⟨λ bi, match bi with | binder_info.default := "default" | binder_info.implicit := "implicit" | binder_info.strict_implicit := "strict_implicit" | binder_info.inst_implicit := "inst_implicit" | binder_info.aux_decl := "aux_decl" end⟩ meta constant macro_def : Type /-- Reflect a C++ expr object. The VM replaces it with the C++ implementation. -/ meta inductive expr (elaborated : bool := tt) | var {} : nat → expr | sort {} : level → expr | const {} : name → list level → expr | mvar : name → expr → expr | local_const : name → name → binder_info → expr → expr | app : expr → expr → expr | lam : name → binder_info → expr → expr → expr | pi : name → binder_info → expr → expr → expr | elet : name → expr → expr → expr → expr | macro : macro_def → list expr → expr variable {elab : bool} meta instance : inhabited expr := ⟨expr.sort level.zero⟩ meta constant expr.macro_def_name (d : macro_def) : name meta def expr.mk_var (n : nat) : expr := expr.var n /- Expressions can be annotated using the annotation macro. -/ meta constant expr.is_annotation : expr elab → option (name × expr elab) meta def expr.erase_annotations : expr elab → expr elab | e := match e.is_annotation with | some (_, a) := expr.erase_annotations a | none := e end /-- Compares expressions, including binder names. -/ meta constant expr.has_decidable_eq : decidable_eq expr attribute [instance] expr.has_decidable_eq /-- Compares expressions while ignoring binder names. -/ meta constant expr.alpha_eqv : expr → expr → bool notation a ` =ₐ `:50 b:50 := expr.alpha_eqv a b = bool.tt protected meta constant expr.to_string : expr elab → string meta instance : has_to_string (expr elab) := ⟨expr.to_string⟩ meta instance : has_to_format (expr elab) := ⟨λ e, e.to_string⟩ /- Coercion for letting users write (f a) instead of (expr.app f a) -/ meta instance : has_coe_to_fun (expr elab) := { F := λ e, expr elab → expr elab, coe := λ e, expr.app e } meta constant expr.hash : expr → nat /-- Compares expressions, ignoring binder names, and sorting by hash. -/ meta constant expr.lt : expr → expr → bool /-- Compares expressions, ignoring binder names. -/ meta constant expr.lex_lt : expr → expr → bool /-- Compares expressions, ignoring binder names, and sorting by hash. -/ meta def expr.cmp (a b : expr) : ordering := if expr.lt a b then ordering.lt else if a =ₐ b then ordering.eq else ordering.gt meta constant expr.fold {α : Type} : expr → α → (expr → nat → α → α) → α meta constant expr.replace : expr → (expr → nat → option expr) → expr meta constant expr.abstract_local : expr → name → expr meta constant expr.abstract_locals : expr → list name → expr meta def expr.abstract : expr → expr → expr | e (expr.local_const n m bi t) := e.abstract_local n | e _ := e meta constant expr.instantiate_univ_params : expr → list (name × level) → expr meta constant expr.instantiate_var : expr → expr → expr meta constant expr.instantiate_vars : expr → list expr → expr protected meta constant expr.subst : expr elab → expr elab → expr elab meta constant expr.has_var : expr → bool meta constant expr.has_var_idx : expr → nat → bool meta constant expr.has_local : expr → bool meta constant expr.has_meta_var : expr → bool meta constant expr.lift_vars : expr → nat → nat → expr meta constant expr.lower_vars : expr → nat → nat → expr protected meta constant expr.pos : expr elab → option pos /-- `copy_pos_info src tgt` copies position information from `src` to `tgt`. -/ meta constant expr.copy_pos_info : expr → expr → expr meta constant expr.is_internal_cnstr : expr → option unsigned meta constant expr.get_nat_value : expr → option nat meta constant expr.collect_univ_params : expr → list name /-- `occurs e t` returns `tt` iff `e` occurs in `t` -/ meta constant expr.occurs : expr → expr → bool meta constant expr.has_local_in : expr → name_set → bool /-- (reflected a) is a special opaque container for a closed `expr` representing `a`. It can only be obtained via type class inference, which will use the representation of `a` in the calling context. Local constants in the representation are replaced by nested inference of `reflected` instances. The quotation expression `(a) (outside of patterns) is equivalent to `reflect a` and thus can be used as an explicit way of inferring an instance of `reflected a`. -/ meta def reflected {α : Sort u} : α → Type := λ _, expr @[inline] meta def reflected.to_expr {α : Sort u} {a : α} : reflected a → expr := id @[inline] meta def reflected.subst {α : Sort v} {β : α → Sort u} {f : Π a : α, β a} {a : α} : reflected f → reflected a → reflected (f a) := expr.subst meta constant expr.reflect (e : expr elab) : reflected e meta constant string.reflect (s : string) : reflected s attribute [class] reflected attribute [instance] expr.reflect string.reflect attribute [irreducible] reflected reflected.subst reflected.to_expr @[inline] meta instance {α : Sort u} (a : α) : has_coe (reflected a) expr := ⟨reflected.to_expr⟩ meta def reflect {α : Sort u} (a : α) [h : reflected a] : reflected a := h meta instance {α} (a : α) : has_to_format (reflected a) := ⟨λ h, to_fmt h.to_expr⟩ namespace expr open decidable /-- Compares expressions, ignoring binder names, and sorting by hash. -/ meta instance : has_ordering expr := ⟨ expr.cmp ⟩ meta def mk_true : expr := const `true [] meta def mk_false : expr := const `false [] /-- Returns the sorry macro with the given type. -/ meta constant mk_sorry (type : expr) : expr /-- Checks whether e is sorry, and returns its type. -/ meta constant is_sorry (e : expr) : option expr meta def instantiate_local (n : name) (s : expr) (e : expr) : expr := instantiate_var (abstract_local e n) s meta def instantiate_locals (s : list (name × expr)) (e : expr) : expr := instantiate_vars (abstract_locals e (list.reverse (list.map prod.fst s))) (list.map prod.snd s) meta def is_var : expr → bool | (var _) := tt | _ := ff meta def app_of_list : expr → list expr → expr | f [] := f | f (p::ps) := app_of_list (f p) ps meta def is_app : expr → bool | (app f a) := tt | e := ff meta def app_fn : expr → expr | (app f a) := f | a := a meta def app_arg : expr → expr | (app f a) := a | a := a meta def get_app_fn : expr elab → expr elab | (app f a) := get_app_fn f | a := a meta def get_app_num_args : expr → nat | (app f a) := get_app_num_args f + 1 | e := 0 meta def get_app_args_aux : list expr → expr → list expr | r (app f a) := get_app_args_aux (a::r) f | r e := r meta def get_app_args : expr → list expr := get_app_args_aux [] meta def mk_app : expr → list expr → expr | e [] := e | e (x::xs) := mk_app (e x) xs meta def ith_arg_aux : expr → nat → expr | (app f a) 0 := a | (app f a) (n+1) := ith_arg_aux f n | e _ := e meta def ith_arg (e : expr) (i : nat) : expr := ith_arg_aux e (get_app_num_args e - i - 1) meta def const_name : expr elab → name | (const n ls) := n | e := name.anonymous meta def is_constant : expr elab → bool | (const n ls) := tt | e := ff meta def is_local_constant : expr → bool | (local_const n m bi t) := tt | e := ff meta def local_uniq_name : expr → name | (local_const n m bi t) := n | e := name.anonymous meta def local_pp_name : expr elab → name | (local_const x n bi t) := n | e := name.anonymous meta def local_type : expr elab → expr elab | (local_const _ _ _ t) := t | e := e meta def is_aux_decl : expr → bool | (local_const _ _ binder_info.aux_decl _) := tt | _ := ff meta def is_constant_of : expr → name → bool | (const n₁ ls) n₂ := n₁ = n₂ | e n := ff meta def is_app_of (e : expr) (n : name) : bool := is_constant_of (get_app_fn e) n meta def is_napp_of (e : expr) (c : name) (n : nat) : bool := is_app_of e c ∧ get_app_num_args e = n meta def is_false : expr → bool | `(false) := tt | _ := ff meta def is_not : expr → option expr | `(not %%a) := some a | `(%%a → false) := some a | e := none meta def is_and : expr → option (expr × expr) | `(and %%α %%β) := some (α, β) | _ := none meta def is_or : expr → option (expr × expr) | `(or %%α %%β) := some (α, β) | _ := none meta def is_iff : expr → option (expr × expr) | `((%%a : Prop) ↔ %%b) := some (a, b) | _ := none meta def is_eq : expr → option (expr × expr) | `((%%a : %%_) = %%b) := some (a, b) | _ := none meta def is_ne : expr → option (expr × expr) | `((%%a : %%_) ≠ %%b) := some (a, b) | _ := none meta def is_bin_arith_app (e : expr) (op : name) : option (expr × expr) := if is_napp_of e op 4 then some (app_arg (app_fn e), app_arg e) else none meta def is_lt (e : expr) : option (expr × expr) := is_bin_arith_app e ``has_lt.lt meta def is_gt (e : expr) : option (expr × expr) := is_bin_arith_app e ``gt meta def is_le (e : expr) : option (expr × expr) := is_bin_arith_app e ``has_le.le meta def is_ge (e : expr) : option (expr × expr) := is_bin_arith_app e ``ge meta def is_heq : expr → option (expr × expr × expr × expr) | `(@heq %%α %%a %%β %%b) := some (α, a, β, b) | _ := none meta def is_pi : expr → bool | (pi _ _ _ _) := tt | e := ff meta def is_arrow : expr → bool | (pi _ _ _ b) := bnot (has_var b) | e := ff meta def is_let : expr → bool | (elet _ _ _ _) := tt | e := ff meta def binding_name : expr → name | (pi n _ _ _) := n | (lam n _ _ _) := n | e := name.anonymous meta def binding_info : expr → binder_info | (pi _ bi _ _) := bi | (lam _ bi _ _) := bi | e := binder_info.default meta def binding_domain : expr → expr | (pi _ _ d _) := d | (lam _ _ d _) := d | e := e meta def binding_body : expr → expr | (pi _ _ _ b) := b | (lam _ _ _ b) := b | e := e meta def is_numeral : expr → bool | `(@has_zero.zero %%α %%s) := tt | `(@has_one.one %%α %%s) := tt | `(@bit0 %%α %%s %%v) := is_numeral v | `(@bit1 %%α %%s₁ %%s₂ %%v) := is_numeral v | _ := ff meta def imp (a b : expr) : expr := pi `_ binder_info.default a b meta def lambdas : list expr → expr → expr | (local_const uniq pp info t :: es) f := lam pp info t (abstract_local (lambdas es f) uniq) | _ f := f meta def pis : list expr → expr → expr | (local_const uniq pp info t :: es) f := pi pp info t (abstract_local (pis es f) uniq) | _ f := f open format private meta def p := λ xs, paren (format.join (list.intersperse " " xs)) meta def to_raw_fmt : expr elab → format | (var n) := p ["var", to_fmt n] | (sort l) := p ["sort", to_fmt l] | (const n ls) := p ["const", to_fmt n, to_fmt ls] | (mvar n t) := p ["mvar", to_fmt n, to_raw_fmt t] | (local_const n m bi t) := p ["local_const", to_fmt n, to_fmt m, to_raw_fmt t] | (app e f) := p ["app", to_raw_fmt e, to_raw_fmt f] | (lam n bi e t) := p ["lam", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t] | (pi n bi e t) := p ["pi", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t] | (elet n g e f) := p ["elet", to_fmt n, to_raw_fmt g, to_raw_fmt e, to_raw_fmt f] | (macro d args) := sbracket (format.join (list.intersperse " " ("macro" :: to_fmt (macro_def_name d) :: args.map to_raw_fmt))) meta def mfold {α : Type} {m : Type → Type} [monad m] (e : expr) (a : α) (fn : expr → nat → α → m α) : m α := fold e (return a) (λ e n a, a >>= fn e n) end expr @[reducible] meta def expr_map (data : Type) := rb_map expr data namespace expr_map export rb_map (hiding mk) meta def mk (data : Type) : expr_map data := rb_map.mk expr data end expr_map meta def mk_expr_map {data : Type} : expr_map data := expr_map.mk data @[reducible] meta def expr_set := rb_set expr meta def mk_expr_set : expr_set := mk_rb_set
c51edf689adb0449f273ac369bf7757f288f42d0
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/elabCmd.lean
6e35a70017e40d7137e89f8acd4334e7264b55f2
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
671
lean
import Lean open Lean open Lean.Elab open Lean.Elab.Term def getCtors (c : Name) : TermElabM (List Name) := do let env ← getEnv; (match env.find? c with | some (ConstantInfo.inductInfo val) => pure val.ctors | _ => pure []) def elabAnonCtor (args : Array Syntax) (τ : Expr) : TermElabM Expr := match τ.getAppFn with | Expr.const C _ _ => do let ctors ← getCtors C; (match ctors with | [c] => do let stx ← `($(Lean.mkIdent c) $args*); elabTerm stx τ -- error handling | _ => unreachable!) | _ => unreachable! elab "foo⟨" args:term,* "⟩" : term <= τ => do elabAnonCtor args τ example : Nat × Nat := foo⟨1, 2⟩
9186cfd4b354e3df199845a4a8e5f1ce7462a044
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/measure/haar/quotient.lean
5bd1067dbc4e5b7eb79ad367ec02b88d79d6e7a6
[ "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
18,289
lean
/- Copyright (c) 2022 Alex Kontorovich and Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex Kontorovich, Heather Macbeth -/ import measure_theory.measure.haar.basic import measure_theory.group.fundamental_domain import algebra.group.opposite /-! # Haar quotient measure > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we consider properties of fundamental domains and measures for the action of a subgroup of a group `G` on `G` itself. ## Main results * `measure_theory.is_fundamental_domain.smul_invariant_measure_map `: given a subgroup `Γ` of a topological group `G`, the pushforward to the coset space `G ⧸ Γ` of the restriction of a both left- and right-invariant measure on `G` to a fundamental domain `𝓕` is a `G`-invariant measure on `G ⧸ Γ`. * `measure_theory.is_fundamental_domain.is_mul_left_invariant_map `: given a normal subgroup `Γ` of a topological group `G`, the pushforward to the quotient group `G ⧸ Γ` of the restriction of a both left- and right-invariant measure on `G` to a fundamental domain `𝓕` is a left-invariant measure on `G ⧸ Γ`. Note that a group `G` with Haar measure that is both left and right invariant is called **unimodular**. -/ noncomputable theory open set measure_theory topological_space measure_theory.measure quotient_group open_locale pointwise measure_theory topology big_operators nnreal ennreal variables {G : Type*} [group G] [measurable_space G] [topological_space G] [topological_group G] [borel_space G] {μ : measure G} {Γ : subgroup G} /-- Measurability of the action of the topological group `G` on the left-coset space `G/Γ`. -/ @[to_additive "Measurability of the action of the additive topological group `G` on the left-coset space `G/Γ`."] instance quotient_group.has_measurable_smul [measurable_space (G ⧸ Γ)] [borel_space (G ⧸ Γ)] : has_measurable_smul G (G ⧸ Γ) := { measurable_const_smul := λ g, (continuous_const_smul g).measurable, measurable_smul_const := λ x, (quotient_group.continuous_smul₁ x).measurable } variables {𝓕 : set G} (h𝓕 : is_fundamental_domain Γ.opposite 𝓕 μ) include h𝓕 variables [countable Γ] [measurable_space (G ⧸ Γ)] [borel_space (G ⧸ Γ)] /-- The pushforward to the coset space `G ⧸ Γ` of the restriction of a both left- and right- invariant measure on `G` to a fundamental domain `𝓕` is a `G`-invariant measure on `G ⧸ Γ`. -/ @[to_additive "The pushforward to the coset space `G ⧸ Γ` of the restriction of a both left- and right-invariant measure on an additive topological group `G` to a fundamental domain `𝓕` is a `G`-invariant measure on `G ⧸ Γ`."] lemma measure_theory.is_fundamental_domain.smul_invariant_measure_map [μ.is_mul_left_invariant] [μ.is_mul_right_invariant] : smul_invariant_measure G (G ⧸ Γ) (measure.map quotient_group.mk (μ.restrict 𝓕)) := { measure_preimage_smul := begin let π : G → G ⧸ Γ := quotient_group.mk, have meas_π : measurable π := continuous_quotient_mk.measurable, have 𝓕meas : null_measurable_set 𝓕 μ := h𝓕.null_measurable_set, intros g A hA, have meas_πA : measurable_set (π ⁻¹' A) := measurable_set_preimage meas_π hA, rw [measure.map_apply meas_π hA, measure.map_apply meas_π (measurable_set_preimage (measurable_const_smul g) hA), measure.restrict_apply₀' 𝓕meas, measure.restrict_apply₀' 𝓕meas], set π_preA := π ⁻¹' A, have : (quotient_group.mk ⁻¹' ((λ (x : G ⧸ Γ), g • x) ⁻¹' A)) = has_mul.mul g ⁻¹' π_preA, { ext1, simp }, rw this, have : μ (has_mul.mul g ⁻¹' π_preA ∩ 𝓕) = μ (π_preA ∩ has_mul.mul (g⁻¹) ⁻¹' 𝓕), { transitivity μ (has_mul.mul g ⁻¹' (π_preA ∩ has_mul.mul g⁻¹ ⁻¹' 𝓕)), { rw preimage_inter, congr, rw [← preimage_comp, comp_mul_left, mul_left_inv], ext, simp, }, rw measure_preimage_mul, }, rw this, have h𝓕_translate_fundom : is_fundamental_domain Γ.opposite (g • 𝓕) μ := h𝓕.smul_of_comm g, rw [h𝓕.measure_set_eq h𝓕_translate_fundom meas_πA, ← preimage_smul_inv], refl, rintros ⟨γ, γ_in_Γ⟩, ext, have : π (x * (mul_opposite.unop γ)) = π (x) := by simpa [quotient_group.eq'] using γ_in_Γ, simp [(•), this], end } /-- Assuming `Γ` is a normal subgroup of a topological group `G`, the pushforward to the quotient group `G ⧸ Γ` of the restriction of a both left- and right-invariant measure on `G` to a fundamental domain `𝓕` is a left-invariant measure on `G ⧸ Γ`. -/ @[to_additive "Assuming `Γ` is a normal subgroup of an additive topological group `G`, the pushforward to the quotient group `G ⧸ Γ` of the restriction of a both left- and right-invariant measure on `G` to a fundamental domain `𝓕` is a left-invariant measure on `G ⧸ Γ`."] lemma measure_theory.is_fundamental_domain.is_mul_left_invariant_map [subgroup.normal Γ] [μ.is_mul_left_invariant] [μ.is_mul_right_invariant] : (measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕)).is_mul_left_invariant := { map_mul_left_eq_self := begin intros x, apply measure.ext, intros A hA, obtain ⟨x₁, _⟩ := @quotient.exists_rep _ (quotient_group.left_rel Γ) x, haveI := h𝓕.smul_invariant_measure_map, convert measure_preimage_smul x₁ ((measure.map quotient_group.mk) (μ.restrict 𝓕)) A using 1, rw [← h, measure.map_apply], { refl, }, { exact measurable_const_mul _, }, { exact hA, }, end } /-- Given a normal subgroup `Γ` of a topological group `G` with Haar measure `μ`, which is also right-invariant, and a finite volume fundamental domain `𝓕`, the pushforward to the quotient group `G ⧸ Γ` of the restriction of `μ` to `𝓕` is a multiple of Haar measure on `G ⧸ Γ`. -/ @[to_additive "Given a normal subgroup `Γ` of an additive topological group `G` with Haar measure `μ`, which is also right-invariant, and a finite volume fundamental domain `𝓕`, the pushforward to the quotient group `G ⧸ Γ` of the restriction of `μ` to `𝓕` is a multiple of Haar measure on `G ⧸ Γ`."] lemma measure_theory.is_fundamental_domain.map_restrict_quotient [t2_space (G ⧸ Γ)] [second_countable_topology (G ⧸ Γ)] (K : positive_compacts (G ⧸ Γ)) [subgroup.normal Γ] [measure_theory.measure.is_haar_measure μ] [μ.is_mul_right_invariant] (h𝓕_finite : μ 𝓕 < ⊤) : measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕) = (μ (𝓕 ∩ (quotient_group.mk' Γ) ⁻¹' K)) • (measure_theory.measure.haar_measure K) := begin let π : G →* G ⧸ Γ := quotient_group.mk' Γ, have meas_π : measurable π := continuous_quotient_mk.measurable, have 𝓕meas : null_measurable_set 𝓕 μ := h𝓕.null_measurable_set, haveI : is_finite_measure (μ.restrict 𝓕) := ⟨by { rw [measure.restrict_apply₀' 𝓕meas, univ_inter], exact h𝓕_finite }⟩, -- the measure is left-invariant, so by the uniqueness of Haar measure it's enough to show that -- it has the stated size on the reference compact set `K`. haveI : (measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕)).is_mul_left_invariant := h𝓕.is_mul_left_invariant_map, rw [measure.haar_measure_unique (measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕)) K, measure.map_apply meas_π, measure.restrict_apply₀' 𝓕meas, inter_comm], exact K.is_compact.measurable_set, end /-- Given a normal subgroup `Γ` of a topological group `G` with Haar measure `μ`, which is also right-invariant, and a finite volume fundamental domain `𝓕`, the quotient map to `G ⧸ Γ` is measure-preserving between appropriate multiples of Haar measure on `G` and `G ⧸ Γ`. -/ @[to_additive measure_preserving_quotient_add_group.mk' "Given a normal subgroup `Γ` of an additive topological group `G` with Haar measure `μ`, which is also right-invariant, and a finite volume fundamental domain `𝓕`, the quotient map to `G ⧸ Γ` is measure-preserving between appropriate multiples of Haar measure on `G` and `G ⧸ Γ`."] lemma measure_preserving_quotient_group.mk' [t2_space (G ⧸ Γ)] [second_countable_topology (G ⧸ Γ)] (K : positive_compacts (G ⧸ Γ)) [subgroup.normal Γ] [measure_theory.measure.is_haar_measure μ] [μ.is_mul_right_invariant] (h𝓕_finite : μ 𝓕 < ⊤) (c : ℝ≥0) (h : μ (𝓕 ∩ (quotient_group.mk' Γ) ⁻¹' K) = c) : measure_preserving (quotient_group.mk' Γ) (μ.restrict 𝓕) (c • (measure_theory.measure.haar_measure K)) := { measurable := continuous_quotient_mk.measurable, map_eq := by rw [h𝓕.map_restrict_quotient K h𝓕_finite, h]; refl } section local notation `μ_𝓕` := measure.map (@quotient_group.mk G _ Γ) (μ.restrict 𝓕) /-- The `ess_sup` of a function `g` on the quotient space `G ⧸ Γ` with respect to the pushforward of the restriction, `μ_𝓕`, of a right-invariant measure `μ` to a fundamental domain `𝓕`, is the same as the `ess_sup` of `g`'s lift to the universal cover `G` with respect to `μ`. -/ @[to_additive "The `ess_sup` of a function `g` on the additive quotient space `G ⧸ Γ` with respect to the pushforward of the restriction, `μ_𝓕`, of a right-invariant measure `μ` to a fundamental domain `𝓕`, is the same as the `ess_sup` of `g`'s lift to the universal cover `G` with respect to `μ`."] lemma ess_sup_comp_quotient_group_mk [μ.is_mul_right_invariant] {g : G ⧸ Γ → ℝ≥0∞} (g_ae_measurable : ae_measurable g μ_𝓕) : ess_sup g μ_𝓕 = ess_sup (λ (x : G), g x) μ := begin have hπ : measurable (quotient_group.mk : G → G ⧸ Γ) := continuous_quotient_mk.measurable, rw ess_sup_map_measure g_ae_measurable hπ.ae_measurable, refine h𝓕.ess_sup_measure_restrict _, rintros ⟨γ, hγ⟩ x, dsimp, congr' 1, exact quotient_group.mk_mul_of_mem x hγ, end /-- Given a quotient space `G ⧸ Γ` where `Γ` is `countable`, and the restriction, `μ_𝓕`, of a right-invariant measure `μ` on `G` to a fundamental domain `𝓕`, a set in the quotient which has `μ_𝓕`-measure zero, also has measure zero under the folding of `μ` under the quotient. Note that, if `Γ` is infinite, then the folded map will take the value `∞` on any open set in the quotient! -/ @[to_additive "Given an additive quotient space `G ⧸ Γ` where `Γ` is `countable`, and the restriction, `μ_𝓕`, of a right-invariant measure `μ` on `G` to a fundamental domain `𝓕`, a set in the quotient which has `μ_𝓕`-measure zero, also has measure zero under the folding of `μ` under the quotient. Note that, if `Γ` is infinite, then the folded map will take the value `∞` on any open set in the quotient!"] lemma _root_.measure_theory.is_fundamental_domain.absolutely_continuous_map [μ.is_mul_right_invariant] : map (quotient_group.mk : G → G ⧸ Γ) μ ≪ map (quotient_group.mk : G → G ⧸ Γ) (μ.restrict 𝓕) := begin set π : G → G ⧸ Γ := quotient_group.mk, have meas_π : measurable π := continuous_quotient_mk.measurable, apply absolutely_continuous.mk, intros s s_meas hs, rw map_apply meas_π s_meas at hs ⊢, rw measure.restrict_apply at hs, apply h𝓕.measure_zero_of_invariant _ _ hs, { intros γ, ext g, rw [set.mem_smul_set_iff_inv_smul_mem, mem_preimage, mem_preimage], congrm _ ∈ s, convert quotient_group.mk_mul_of_mem g (γ⁻¹).2, }, exact measurable_set_preimage meas_π s_meas, end local attribute [-instance] quotient.measurable_space /-- This is a simple version of the **Unfolding Trick**: Given a subgroup `Γ` of a group `G`, the integral of a function `f` on `G` with respect to a right-invariant measure `μ` is equal to the integral over the quotient `G ⧸ Γ` of the automorphization of `f`. -/ @[to_additive "This is a simple version of the **Unfolding Trick**: Given a subgroup `Γ` of an additive group `G`, the integral of a function `f` on `G` with respect to a right-invariant measure `μ` is equal to the integral over the quotient `G ⧸ Γ` of the automorphization of `f`."] lemma quotient_group.integral_eq_integral_automorphize {E : Type*} [normed_add_comm_group E] [complete_space E] [normed_space ℝ E] [μ.is_mul_right_invariant] {f : G → E} (hf₁ : integrable f μ) (hf₂ : ae_strongly_measurable (automorphize f) μ_𝓕) : ∫ x : G, f x ∂μ = ∫ x : G ⧸ Γ, automorphize f x ∂μ_𝓕 := calc ∫ x : G, f x ∂μ = ∑' γ : Γ.opposite, ∫ x in 𝓕, f (γ • x) ∂μ : h𝓕.integral_eq_tsum'' f hf₁ ... = ∫ x in 𝓕, ∑' γ : Γ.opposite, f (γ • x) ∂μ : begin rw integral_tsum, { exact λ i, (hf₁.1.comp_quasi_measure_preserving (measure_preserving_smul i μ).quasi_measure_preserving).restrict, }, { rw ← h𝓕.lintegral_eq_tsum'' (λ x, ‖f x‖₊), exact ne_of_lt hf₁.2, }, end ... = ∫ x : G ⧸ Γ, automorphize f x ∂μ_𝓕 : (integral_map continuous_quotient_mk.ae_measurable hf₂).symm /-- This is the **Unfolding Trick**: Given a subgroup `Γ` of a group `G`, the integral of a function `f` on `G` times the lift to `G` of a function `g` on the quotient `G ⧸ Γ` with respect to a right-invariant measure `μ` on `G`, is equal to the integral over the quotient of the automorphization of `f` times `g`. -/ lemma quotient_group.integral_mul_eq_integral_automorphize_mul {K : Type*} [normed_field K] [complete_space K] [normed_space ℝ K] [μ.is_mul_right_invariant] {f : G → K} (f_ℒ_1 : integrable f μ) {g : G ⧸ Γ → K} (hg : ae_strongly_measurable g μ_𝓕) (g_ℒ_infinity : ess_sup (λ x, ↑‖g x‖₊) μ_𝓕 ≠ ∞) (F_ae_measurable : ae_strongly_measurable (quotient_group.automorphize f) μ_𝓕) : ∫ x : G, g (x : G ⧸ Γ) * (f x) ∂μ = ∫ x : G ⧸ Γ, g x * (quotient_group.automorphize f x) ∂μ_𝓕 := begin let π : G → G ⧸ Γ := quotient_group.mk, have H₀ : quotient_group.automorphize ((g ∘ π) * f) = g * (quotient_group.automorphize f) := quotient_group.automorphize_smul_left f g, calc ∫ (x : G), g (π x) * f x ∂μ = ∫ (x : G ⧸ Γ), quotient_group.automorphize ((g ∘ π) * f) x ∂μ_𝓕 : _ ... = ∫ (x : G ⧸ Γ), g x * (quotient_group.automorphize f x) ∂μ_𝓕 : by simp [H₀], have meas_π : measurable π := continuous_quotient_mk.measurable, have H₁ : integrable ((g ∘ π) * f) μ, { have : ae_strongly_measurable (λ x : G, g (x : G ⧸ Γ)) μ, { refine (ae_strongly_measurable_of_absolutely_continuous _ _ hg).comp_measurable meas_π, exact h𝓕.absolutely_continuous_map }, refine integrable.ess_sup_smul f_ℒ_1 this _, { have hg' : ae_strongly_measurable (λ x, ↑‖g x‖₊) μ_𝓕 := (ennreal.continuous_coe.comp continuous_nnnorm).comp_ae_strongly_measurable hg, rw [← ess_sup_comp_quotient_group_mk h𝓕 hg'.ae_measurable], exact g_ℒ_infinity } }, have H₂ : ae_strongly_measurable (quotient_group.automorphize ((g ∘ π) * f)) μ_𝓕, { simp_rw [H₀], exact hg.mul F_ae_measurable }, apply quotient_group.integral_eq_integral_automorphize h𝓕 H₁ H₂, end end section variables {G' : Type*} [add_group G'] [measurable_space G'] [topological_space G'] [topological_add_group G'] [borel_space G'] {μ' : measure G'} {Γ' : add_subgroup G'} [countable Γ'] [measurable_space (G' ⧸ Γ')] [borel_space (G' ⧸ Γ')] {𝓕' : set G'} local notation `μ_𝓕` := measure.map (@quotient_add_group.mk G' _ Γ') (μ'.restrict 𝓕') /-- This is the **Unfolding Trick**: Given an additive subgroup `Γ'` of an additive group `G'`, the integral of a function `f` on `G'` times the lift to `G'` of a function `g` on the quotient `G' ⧸ Γ'` with respect to a right-invariant measure `μ` on `G'`, is equal to the integral over the quotient of the automorphization of `f` times `g`. -/ lemma quotient_add_group.integral_mul_eq_integral_automorphize_mul {K : Type*} [normed_field K] [complete_space K] [normed_space ℝ K] [μ'.is_add_right_invariant] {f : G' → K} (f_ℒ_1 : integrable f μ') {g : G' ⧸ Γ' → K} (hg : ae_strongly_measurable g μ_𝓕) (g_ℒ_infinity : ess_sup (λ x, ↑‖g x‖₊) μ_𝓕 ≠ ∞) (F_ae_measurable : ae_strongly_measurable (quotient_add_group.automorphize f) μ_𝓕) (h𝓕 : is_add_fundamental_domain Γ'.opposite 𝓕' μ') : ∫ x : G', g (x : G' ⧸ Γ') * (f x) ∂μ' = ∫ x : G' ⧸ Γ', g x * (quotient_add_group.automorphize f x) ∂μ_𝓕 := begin let π : G' → G' ⧸ Γ' := quotient_add_group.mk, have H₀ : quotient_add_group.automorphize ((g ∘ π) * f) = g * (quotient_add_group.automorphize f) := quotient_add_group.automorphize_smul_left f g, calc ∫ (x : G'), g (π x) * f x ∂μ' = ∫ (x : G' ⧸ Γ'), quotient_add_group.automorphize ((g ∘ π) * f) x ∂μ_𝓕 : _ ... = ∫ (x : G' ⧸ Γ'), g x * (quotient_add_group.automorphize f x) ∂μ_𝓕 : by simp [H₀], have meas_π : measurable π := continuous_quotient_mk.measurable, have H₁ : integrable ((g ∘ π) * f) μ', { have : ae_strongly_measurable (λ x : G', g (x : G' ⧸ Γ')) μ', { refine (ae_strongly_measurable_of_absolutely_continuous _ _ hg).comp_measurable meas_π, exact h𝓕.absolutely_continuous_map }, refine integrable.ess_sup_smul f_ℒ_1 this _, { have hg' : ae_strongly_measurable (λ x, ↑‖g x‖₊) μ_𝓕 := (ennreal.continuous_coe.comp continuous_nnnorm).comp_ae_strongly_measurable hg, rw [← ess_sup_comp_quotient_add_group_mk h𝓕 hg'.ae_measurable], exact g_ℒ_infinity } }, have H₂ : ae_strongly_measurable (quotient_add_group.automorphize ((g ∘ π) * f)) μ_𝓕, { simp_rw [H₀], exact hg.mul F_ae_measurable }, apply quotient_add_group.integral_eq_integral_automorphize h𝓕 H₁ H₂, end end attribute [to_additive quotient_group.integral_mul_eq_integral_automorphize_mul] quotient_add_group.integral_mul_eq_integral_automorphize_mul
610930535f246c156dfa582df57a19b5b4b1fa67
1169362316cbb36a5f4ae286e8419e4e5163f569
/src/syntax.lean
689326cb56b6ce69d3f5e86f806c8870b8e413e4
[]
no_license
fpvandoorn/formal_logic
21687f7e621fdd9124a06a5b3a5a9c5a6ae40cc6
adbe6d70399310842525ff05ff97e29f30dd4282
refs/heads/master
1,585,666,688,414
1,539,046,655,000
1,539,046,655,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,821
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The syntax of simple type theory, i.e. inductive definitions of types and terms. Notes: When it comes to basic types, type constructors, and constants, we distinguish between "built in" and "user" objects. The former are fixed for the implementation, and the implementation can refer to them directly (for example, logical connectives, arithmetic symbols, types like nat and bool, and type constructors like list, sum, and prod). TODO: Factor out types for constants, basic types, etc. These can include more information about the environment, source, pretty-printing, etc. TODO: We do not have "local_constants". It is probably best to have these as special sorts of constants, but we can revisit this decision. TODO: For now, we won't handle polymorphic types, though we will eventually (mostly following HOL light). TODO: For now, use naive equality tests. We can worry about more efficient tests (e.g. with unique id's) later, if necessary. TODO: if we replace each `= tt` by a coercion to bool, things break in some places. They are fixable, but then something more dramatic breaks in fol.syntax and the terms are huge. -/ import data.list /- TODO: move these -/ @[simp] theorem if_neg_eq {α : Type*} (p : Prop) [decidable p] (a b : α) : (if ¬ p then a else b) = (if p then b else a) := begin by_cases h : p; simp [h], end theorem to_bool_eq_to_bool (p q : Prop) [decidable p] [decidable q] : (to_bool p = to_bool q) ↔ (p ↔ q) := by by_cases p; simp [h] namespace list @[simp] theorem not_cons_prefix_nil {α : Type*} (a : α) (l : list α) : ¬ a :: l <+: nil := by { unfold is_prefix, intro h, cases h, contradiction } @[simp] theorem cons_prefix_cons {α : Type*} (a₁ a₂ : α) (l₁ l₂ : list α) : a₁ :: l₁ <+: a₂ :: l₂ ↔ a₁ = a₂ ∧ l₁ <+: l₂ := begin unfold is_prefix, split; intro h, { cases h with l h, split, apply head_eq_of_cons_eq h, existsi l, apply tail_eq_of_cons_eq h}, cases h with h₀ h₁, cases h₁ with l h₁, existsi l, rw [h₀, ← h₁], simp end theorem length_le_of_prefix {α : Type*} {l₁ l₂ : list α} (h : l₁ <+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_prefix h theorem prefix_iff_eq_of_length_eq {α : Type*} {l₁ l₂ : list α} (h : length l₁ = length l₂) : l₁ <+: l₂ ↔ (l₁ = l₂) := by { split, { intro h', exact eq_of_prefix_of_length_eq h' h}, intro h', rw h'} theorem drop_succ {α : Type*} (n : nat) (l : list α) : drop n.succ l = drop n (drop 1 l) := by induction l; simp theorem drop_eq_nil {α : Type*} (n : nat) (l : list α) : drop n l = [] ↔ n ≥ l.length:= begin revert n, induction l with a l ih; simp, { apply nat.zero_le }, intro n, cases n with n; simp, { rw add_comm, apply nat.zero_lt_succ }, rw ih, rw [add_comm, ge, ge, nat.succ_le_succ_iff] end end list namespace hol /- Instead of option, we'll have failure produce error messages. But we will not use the full-blown exception monad or do anything fancy, to make it easier to reason about these programs. TODO: not using this yet. -/ inductive except (α : Type*) | ok : α → except | fail : string → except /- Types -/ namespace type /- basic types -/ @[derive has_reflect, derive decidable_eq] inductive basic : Type | user : ℕ → basic | prop | nat | int | bool | unit namespace basic def repr : basic → string | (user n) := "(basic.user " ++ n.repr ++ ")" | prop := "basic.prop" | nat := "basic.nat" | int := "basic.int" | bool := "basic.bool" | unit := "basic.unit" instance : has_repr basic := ⟨repr⟩ end basic /- type constructors -/ namespace constructor @[derive has_reflect, derive decidable_eq] inductive kind | user : nat → kind | list | prod | sum end constructor @[derive has_reflect, derive decidable_eq] structure constructor := (symb : constructor.kind) (arity : nat) namespace constructor def user (n arity : nat) : constructor := ⟨kind.user n, arity⟩ def list : constructor := ⟨kind.list, 1⟩ def prod : constructor := ⟨kind.prod, 2⟩ def sum : constructor := ⟨kind.sum, 2⟩ def repr : constructor → string | ⟨kind.user n, a⟩ := "(constructor.user " ++ n.repr ++ " " ++ a.repr ++")" | ⟨kind.list, _⟩ := "constructor.list" | ⟨kind.prod, _⟩ := "constructor.list" | ⟨kind.sum, _⟩ := "constructor.list" instance : has_repr constructor := ⟨repr⟩ end constructor end type /- The types themselves Notes: To avoid a nested inductive type, we'll use iterated application for constructors. Basic and arrow types are really special cases of constructors, but we'll keep them separate. -/ @[derive has_reflect, derive decidable_eq] inductive type | Var : nat → type | Basic : hol.type.basic → type | Arr : type → type → type | Constructor : hol.type.constructor → type | App : type → type → type namespace type def repr : type → string | (Var n) := "(Var " ++ n.repr ++ ")" | (Basic b) := "(Basic " ++ b.repr ++ ")" | (Arr t₁ t₂) := "(Arr " ++ t₁.repr ++ " " ++ t₂.repr ++")" | (Constructor c) := "(Constructor " ++ c.repr ++ ")" | (App t₁ t₂) := "(App " ++ t₁.repr ++ " " ++ t₂.repr ++ ")" instance : has_repr type := ⟨repr⟩ -- `arities_ok t l` says the type `t` iteratively applied to `l` makes sense def arities_ok_aux : type → list type → bool | (Var n) l := l.empty | (Basic b) l := l.empty | (Arr t₁ t₂) l := arities_ok_aux t₁ l && arities_ok_aux t₂ l && l.empty | (Constructor c) l := c.arity = l.length | (App t₁ t₂) l := arities_ok_aux t₂ [] && arities_ok_aux t₁ (t₂ :: l) def arities_ok (t : type) : bool := arities_ok_aux t [] /-- Returns the domain of an arrow type, or the type itself if it is not an arrow. -/ @[simp] def domain : type → type | (type.Arr t₁ t₂) := t₁ | t := t /-- Returns the codomain of an arrow type, or the type itself if it is not an arrow. -/ @[simp] def codomain : type → type | (type.Arr t₁ t₂) := t₂ | t := t @[simp] def get_arg_types : type → list type | (type.Arr t₁ t₂) := t₁ :: get_arg_types t₂ | _ := [] @[simp] def num_arg_types : type → nat | (type.Arr t₁ t₂) := num_arg_types t₂ + 1 | _ := 0 lemma length_get_arg_types (t : type) : t.get_arg_types.length = t.num_arg_types := by induction t; simp [*] @[simp] def get_return_type : type → type | (type.Arr t₁ t₂) := get_return_type t₂ | t := t @[simp] def mk_fn_type : list type → type → type | [] ret := ret | (a :: as) ret := (type.Arr a (mk_fn_type as ret)) theorem mk_fn_type_eq (t : type) : t = mk_fn_type (get_arg_types t) (get_return_type t) := by { induction t; simp [get_arg_types, get_return_type, mk_fn_type], assumption } @[simp] theorem get_return_type_codomain (t : type) : get_return_type (t.codomain) = get_return_type t := by induction t; simp theorem get_arg_types_codomain (t : type) : get_arg_types (t.codomain) = t.get_arg_types.drop 1 := by induction t; simp @[simp] def is_arrow : type → bool | (Arr t₁ t₂) := tt | _ := ff theorem is_arrow_mk_fn_type (ts : list type) (t : type) (h : t.is_arrow = ff) : (mk_fn_type ts t).is_arrow = (ts ≠ []) := by induction ts; simp [h] theorem is_arrow_get_return_type_eq_ff (t : type) : t.get_return_type.is_arrow = ff := by induction t; simp [*] theorem eq_of_is_arrow (t : type) (h : is_arrow t = tt) : t = Arr (domain t) (codomain t) := by cases t; simp at h; trivial lemma cons_prefix_get_arg_types (ty ty' : type) (tys : list type) : (ty :: tys) <+: ty'.get_arg_types ↔ is_arrow ty' = tt ∧ ty = ty'.domain ∧ tys <+: ty'.codomain.get_arg_types := by cases ty'; simp end type /- convenient type constructors -/ section open type -- TODO: mark these as reducible? def mk_prop := Basic basic.prop def mk_nat := Basic basic.nat def mk_int := Basic basic.int def mk_unit := Basic basic.int def mk_bool := Basic basic.bool def mk_user_type (n : ℕ) := Basic (basic.user n) def mk_list_type (t : type) : type := App (Constructor constructor.list) t def mk_prod_type (t₁ t₂ : type) : type := App (App (Constructor constructor.prod) t₁) t₂ def mk_sum_type (t₁ t₂ : type) : type := App (App (Constructor constructor.sum) t₁) t₂ --notation t₁ ` ⇒ `:65 t₂ := Arr t₁ t₂ infixr ` ⇒ ` := Arr theorem arities_ok_mk_prop : arities_ok mk_prop := by simp [mk_prop, arities_ok, arities_ok_aux, list.empty] theorem arities_ok_mk_nat : arities_ok mk_nat := by simp [mk_nat, arities_ok, arities_ok_aux, list.empty] theorem arities_ok_mk_int : arities_ok mk_int := by simp [mk_int, arities_ok, arities_ok_aux, list.empty] theorem arities_ok_mk_list_type (t : type) (h : arities_ok t = tt) : arities_ok (mk_list_type t) = tt := by { simp [arities_ok] at *, simp [mk_list_type, arities_ok_aux, h, constructor.list] } theorem arities_ok_mk_prod_type (t₁ t₂ : type) (h₁ : arities_ok t₁ = tt) (h₂ : arities_ok t₂ = tt) : arities_ok (mk_prod_type t₁ t₂) = tt := by { simp [arities_ok] at *, simp [mk_prod_type, arities_ok_aux, h₁, h₂, constructor.prod] } theorem arities_ok_mk_sum_type (t₁ t₂ : type) (h₁ : arities_ok t₁ = tt) (h₂ : arities_ok t₂ = tt) : arities_ok (mk_sum_type t₁ t₂) = tt := by { simp [arities_ok] at *, simp [mk_sum_type, arities_ok_aux, h₁, h₂, constructor.sum] } end /- Terms -/ namespace term /- constants -/ namespace const @[derive has_reflect, derive decidable_eq] inductive kind | user : nat → kind | true | false | not | and | or | implies | iff | all | ex | add | mul | sub | bval : bool → kind | nval : nat → kind end const -- instantiations are for polymorphic constants @[derive has_reflect, derive decidable_eq] structure const := (symb : const.kind) (type : type) (insts : list hol.type) namespace const def user (n : nat) (t : hol.type) (l : list hol.type) : const := ⟨kind.user n, t, l⟩ def true : const := ⟨kind.true, mk_prop, []⟩ def false : const := ⟨kind.false, mk_prop, []⟩ def not : const := ⟨kind.not, mk_prop ⇒ mk_prop, []⟩ def and : const := ⟨kind.and, mk_prop ⇒ (mk_prop ⇒ mk_prop), []⟩ def or : const := ⟨kind.or, mk_prop ⇒ (mk_prop ⇒ mk_prop), []⟩ def implies : const := ⟨kind.implies, mk_prop ⇒ (mk_prop ⇒ mk_prop), []⟩ def iff : const := ⟨kind.iff, mk_prop ⇒ (mk_prop ⇒ mk_prop), []⟩ def add : const := ⟨kind.add, mk_nat ⇒ (mk_nat ⇒ mk_nat), []⟩ def mul : const := ⟨kind.mul, mk_nat ⇒ (mk_nat ⇒ mk_nat), []⟩ def sub : const := ⟨kind.sub, mk_nat ⇒ (mk_nat ⇒ mk_nat), []⟩ def tt : const := ⟨kind.bval tt, mk_bool, []⟩ def ff : const := ⟨kind.bval ff, mk_bool, []⟩ def nval (n : nat) : const := ⟨kind.nval n, mk_nat, []⟩ def repr : const → string | ⟨kind.user n, t, l⟩ := "(const.user " ++ n.repr ++ " " ++ t.repr ++ " " ++ l.repr ++ ")" | ⟨kind.true, _, _⟩ := "const.true" | ⟨kind.false, _, _⟩ := "const.false" | ⟨kind.not, _, _⟩ := "const.not" | ⟨kind.and, _, _⟩ := "const.and" | ⟨kind.or, _, _⟩ := "const.or" | ⟨kind.implies, _, _⟩ := "const.implies" | ⟨kind.iff, _, _⟩ := "const.iff" | ⟨kind.all, _, _⟩ := "const.all" | ⟨kind.ex, _, _⟩ := "const.ex" | ⟨kind.add, _, _⟩ := "const.add" | ⟨kind.mul, _, _⟩ := "const.mul" | ⟨kind.sub, _, _⟩ := "const.sub" | ⟨kind.bval bool.tt, _, _⟩ := "const.tt" | ⟨kind.bval bool.ff, _, _⟩ := "const.ff" | ⟨kind.nval n, _, _⟩ := "(const.nval " ++ n.repr ++ ")" instance : has_repr const := ⟨repr⟩ -- TODO: delete this? def is_connective : const → bool | ⟨kind.true, t, l⟩ := if t = mk_prop then l.empty else bool.ff | ⟨kind.false, t, l⟩ := if t = mk_prop then l.empty else bool.ff | ⟨kind.not, t, l⟩ := if t = (mk_prop ⇒ mk_prop) then l.empty else bool.ff | ⟨kind.and, t, l⟩ := if t = (mk_prop ⇒ mk_prop ⇒ mk_prop) then l.empty else bool.ff | ⟨kind.or, t, l⟩ := if t = (mk_prop ⇒ mk_prop ⇒ mk_prop) then l.empty else bool.ff | ⟨kind.implies, t, l⟩ := if t = (mk_prop ⇒ mk_prop ⇒ mk_prop) then l.empty else bool.ff | ⟨kind.iff, t, l⟩ := if t = (mk_prop ⇒ mk_prop ⇒ mk_prop) then l.empty else bool.ff | _ := bool.ff end const end term /- the terms themselves -/ @[derive has_reflect, derive decidable_eq] inductive term | Var : nat → term | Const : hol.term.const → term | App : term → term → term -- application | Abs : string → hol.type → term → term -- the string gives the preferred name namespace term -- TODO: not needed? def sizeof' : term → nat | (Var n) := 0 | (Const n) := 0 | (App s t) := sizeof' s + sizeof' t + 1 | (Abs s ty t) := sizeof t + 1 instance : has_sizeof term := ⟨sizeof'⟩ def repr : term → string | (Var n) := "(Var " ++ n.repr ++ ")" | (Const c) := "(Const " ++ c.repr ++ ")" | (App t₁ t₂) := "(App " ++ t₁.repr ++ t₂.repr ++ ")" | (Abs s ty t) := "(Abs " ++ _root_.repr s ++ " " ++ ty.repr ++ " " ++ t.repr ++ ")" /-- Infers the type of a term, given an assignment to free variables. Assumes the expression is well-typed-/ def typeof : term → list type → type | (Var n) σ := if h : n < σ.length then σ.nth_le n h else mk_nat | (Const c) σ := c.type | (App t₁ t₂) σ := (typeof t₁ σ).codomain | (Abs s ty t) σ := ty ⇒ typeof t (ty :: σ) inductive is_well_typed : term → list type → Prop | wt_var (n : ℕ) (σ : list type) (h : n < σ.length) : is_well_typed (Var n) σ | wt_const (c : const) (σ : list type) : is_well_typed (Const c) σ | wt_app (t₁ t₂ : term) (σ : list type) (h₁ : is_well_typed t₁ σ) (h₂ : is_well_typed t₂ σ) (h₃ : (typeof t₁ σ).is_arrow = tt) (h₄ : (typeof t₁ σ).domain = typeof t₂ σ) : is_well_typed (App t₁ t₂) σ | wt_abs (s : string) (ty : type) (t : term) (σ : list type) (h₁ : is_well_typed t (ty :: σ)) : is_well_typed (Abs s ty t) σ /-- Infers the type of a term, given an assignment to free variables. Returns none of expression is not well-typed. -/ def typeof_p : term → list type → option type | (Var n) σ := σ.nth n | (Const c) σ := some c.type | (App t₁ t₂) σ := match typeof_p t₁ σ, typeof_p t₂ σ with | (some (type.Arr u v)), (some w) := if u = w then some v else none | _ , _ := none end | (Abs s ty t) σ := match typeof_p t (ty :: σ) with | some ty₂ := some (type.Arr ty ty₂) | _ := none end -- a boolean version @[simp] def is_well_typed_b : term → list type → bool | (Var n) σ := if n < σ.length then tt else ff | (Const c) σ := tt | (App t₁ t₂) σ := is_well_typed_b t₁ σ && is_well_typed_b t₂ σ && (typeof t₁ σ).is_arrow && ((typeof t₁ σ).domain = typeof t₂ σ) | (Abs s ty t) σ := is_well_typed_b t (ty :: σ) theorem is_well_typed_iff (t : term) : ∀ σ, is_well_typed t σ ↔ (is_well_typed_b t σ = tt) := begin induction t with _ _ _ _ h₁ h₂ _ ty _ h, {intro σ, split, {intro h, cases h; simp [*]}, intro h, simp at h, constructor, assumption}, {intro σ, split, {intro h, cases h; simp [*]}, intro h, simp at h, constructor}, {intro σ, simp [(h₁ σ).symm, (h₂ σ).symm], split, {intro h, cases h; simp [*]}, intro h, constructor; simp [*]}, {intro σ, simp [(h (ty::σ)).symm], split, {intro h, cases h, assumption}, intro h, constructor; simp [*]} end @[simp] def is_var : term → bool | (Var n) := tt | _ := ff def var_num : term → nat | (Var n) := n | _ := 0 @[simp] def is_const : term → bool | (Const c) := tt | _ := ff @[simp] def is_app : term → bool | (App f a) := tt | _ := ff def app_fn : term → term | (App f a) := f | t := t def app_arg : term → term | (App f a) := a | t := t @[simp] def get_app_fn : term → term | (App f a) := get_app_fn f | t := t def get_app_num_args : term → ℕ | (App f a) := get_app_num_args f + 1 | t := 0 def get_app_args_aux : term → list term → list term | (App t₁ t₂) args := get_app_args_aux t₁ (t₂ :: args) | (Var n) args := args | (Const c) args := args | (Abs s ty t) args := args def get_app_args (t : term) : list term := get_app_args_aux t [] @[simp] def mk_app : term → list term → term | t [] := t | t (a::as) := mk_app (App t a) as theorem mk_app_get_app_aux (t : term) : ∀ as, mk_app (get_app_fn t) (get_app_args_aux t as) = mk_app t as := by induction t; simp [get_app_fn, get_app_args_aux, mk_app, *] theorem mk_app_get_app (t : term) : mk_app (get_app_fn t) (get_app_args t) = t := by simp [get_app_args, mk_app_get_app_aux, mk_app] theorem is_well_typed_mk_app (l : list term) (σ : list type) : ∀ t, is_well_typed (mk_app t l) σ ↔ is_well_typed t σ ∧ (∀ t' ∈ l, is_well_typed t' σ) ∧ l.map (λ t', typeof t' σ) <+: (t.typeof σ).get_arg_types := begin induction l with t' l' ih, { simp [list.nil_prefix] }, simp, intro t, rw [ih (App t t')], simp [is_well_typed_iff], split, { intro h, simp [*, typeof] at *, rcases h with ⟨⟨h₀, h₁, h₂, h₃⟩, h₄, h₅⟩, split, exact h₄, rw [type.eq_of_is_arrow _ h₂], simp, rw [h₃], simp, exact h₅}, intro h, rcases h with ⟨h, ⟨h₀, h₁⟩, h₂⟩, have h₃ := (type.cons_prefix_get_arg_types _ _ _).mp h₂, rcases h₃ with ⟨h₃, h₄, h₅⟩, simp [h, h₀, h₁, h₃, h₄, h₅, typeof], assumption end theorem is_well_typed_iff' {t : term} {σ : list type} : t.is_well_typed σ ↔ is_well_typed (t.get_app_fn) σ ∧ (∀ t' ∈ t.get_app_args, is_well_typed t' σ) ∧ t.get_app_args.map (λ t', typeof t' σ) <+: (t.get_app_fn.typeof σ).get_arg_types := by { rw [← mk_app_get_app t, is_well_typed_mk_app], simp [mk_app_get_app] } theorem typeof_mk_app (t: term) (as : list term) (σ : list type) : typeof (mk_app t as) σ = type.mk_fn_type (((t.typeof σ).get_arg_types).drop (as.length)) (t.typeof σ).get_return_type := begin revert t, induction as with a as ih, { intro t, simp, rw ← type.mk_fn_type_eq (t.typeof σ) }, intro t, simp, rw (ih (App t a)), simp [typeof], rw [add_comm, list.drop_add], simp [type.get_arg_types_codomain] end theorem typeof_mk_app_is_arrow (t: term) (as : list term) (σ : list type) : (typeof (mk_app t as) σ).is_arrow = (as.length < (t.typeof σ).num_arg_types) := begin rw [typeof_mk_app, type.is_arrow_mk_fn_type, to_bool_eq_to_bool, ne, list.drop_eq_nil, lt_iff_not_ge, type.length_get_arg_types], --simp [- bool.to_bool_not], apply type.is_arrow_get_return_type_eq_ff end theorem length_le_num_arg_types_typeof {t: term} {as : list term} {σ : list type} (h : is_well_typed (mk_app t as) σ) : as.length ≤ (t.typeof σ).num_arg_types := begin have : as.map (λ t', typeof t' σ) <+: (t.typeof σ).get_arg_types, from ((is_well_typed_mk_app as σ t).mp h).right.right, have := list.length_le_of_prefix this, simpa [type.length_get_arg_types] end theorem length_get_app_args_of_not_is_arrow {t : term} {σ : list type} (h : (t.typeof σ).is_arrow = ff) (h' : t.is_well_typed σ) : t.get_app_args.length = (t.get_app_fn.typeof σ).num_arg_types := begin rw ← mk_app_get_app t at h h', have : t.get_app_args.length ≤ (t.get_app_fn.typeof σ).num_arg_types, from length_le_num_arg_types_typeof h', by {apply le_antisymm this, rw typeof_mk_app_is_arrow at h, simp at h, exact h } end theorem get_arg_types_typeof_get_app_fn {t : term} {σ : list type} (h : (t.typeof σ).is_arrow = ff) (h' : t.is_well_typed σ) : (t.get_app_fn.typeof σ).get_arg_types = t.get_app_args.map (λ t', t'.typeof σ) := begin have : t.get_app_args.length = (t.get_app_fn.typeof σ).num_arg_types, from length_get_app_args_of_not_is_arrow h h', rw ← mk_app_get_app t at h h', have : t.get_app_args.map (λ t', typeof t' σ) <+: (t.get_app_fn.typeof σ).get_arg_types, from ((is_well_typed_mk_app t.get_app_args σ t.get_app_fn).mp h').right.right, have : t.get_app_args.map (λ t', typeof t' σ) = (t.get_app_fn.typeof σ).get_arg_types, by { apply list.eq_of_prefix_of_length_eq this, rw type.length_get_arg_types, simp, assumption}, exact this.symm end theorem is_well_typed_of_not_is_arrow {t : term} {σ : list type} (h : (t.typeof σ).is_arrow = ff) : t.is_well_typed σ ↔ is_well_typed (t.get_app_fn) σ ∧ (∀ t' ∈ t.get_app_args, is_well_typed t' σ) ∧ t.get_app_args.map (λ t', typeof t' σ) = (t.get_app_fn.typeof σ).get_arg_types := begin split; intro h', { have h₀ := is_well_typed_iff'.mp h', rcases h₀ with ⟨h₀, h₁, h₂⟩, split, apply h₀, split, apply h₁, apply list.eq_of_prefix_of_length_eq h₂, simp, rw length_get_app_args_of_not_is_arrow h h', rw [type.length_get_arg_types] }, rw is_well_typed_iff', rcases h' with ⟨h₀, h₁, h₂⟩, split, apply h₀, split, apply h₁, rw h₂ end theorem typeof_eq_of_not_is_arrow {t : term} {σ : list type} (h : (t.typeof σ).is_arrow = ff) (h' : t.is_well_typed σ) : t.typeof σ = ((t.get_app_fn).typeof σ).get_return_type := begin have h₀ : t.typeof σ = (mk_app t.get_app_fn t.get_app_args).typeof σ, by rw mk_app_get_app, transitivity, exact h₀, rw [typeof_mk_app, length_get_app_args_of_not_is_arrow h h', ← type.length_get_arg_types], rw (list.drop_eq_nil _ _).mpr, simp, apply le_refl end lemma type_is_not_arrow' {t : term} {σ : list type} (h : is_well_typed t σ) : (t.typeof σ).is_arrow = ff ↔ (t.get_app_fn.typeof σ).get_arg_types = (t.get_app_args).map (λ t', t'.typeof σ) := begin split, { intro h₀, rw [get_arg_types_typeof_get_app_fn h₀ h] }, intro h, rw ← mk_app_get_app t, rw typeof_mk_app, have : (get_app_args t).length = (t.get_app_fn.typeof σ).get_arg_types.length, by { rw h, simp }, rw this, rw (list.drop_eq_nil _ _).mpr (le_refl _), apply type.is_arrow_get_return_type_eq_ff end -- an inductive characterization of well typed terms whose types are not arrows theorem type_is_not_arrow_iff (σ : list type) : ∀ t : term, t.is_well_typed σ → ((t.typeof σ).is_arrow = ff ↔ (t.is_var = tt ∧ (t.typeof σ).is_arrow = ff) ∨ (t.is_const = tt ∧ (t.typeof σ).is_arrow = ff) ∨ (t.is_app = tt ∧ (t.get_app_fn.typeof σ).get_arg_types = t.get_app_args.map (λ t', t'.typeof σ))) := begin intro t, induction t with _ _ t₁ t₂ ih₁ ih₂; simp, { intro h', simp [type_is_not_arrow' h'] }, simp [typeof] end end term end hol
5e541a0a24d3c9bd64430e7dbda4fd7f9ba2ced7
9ee042bf34eebe0464f0f80c0db14ceb048dab10
/stage0/src/Lean/Elab/Declaration.lean
43845e5217d3dd5780a61012c3973c40f9379122
[ "Apache-2.0" ]
permissive
dexmagic/lean4
7507e7b07dc9f49db45df5ebd011886367dc2a6c
48764b60d5bac337eaff4bf8a3d63a216e1d9e03
refs/heads/master
1,692,156,265,016
1,633,276,980,000
1,633,339,480,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,615
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.CollectLevelParams import Lean.Elab.DeclUtil import Lean.Elab.DefView import Lean.Elab.Inductive import Lean.Elab.Structure import Lean.Elab.MutualDef import Lean.Elab.DeclarationRange namespace Lean.Elab.Command open Meta /- Auxiliary function for `expandDeclNamespace?` -/ def expandDeclIdNamespace? (declId : Syntax) : Option (Name × Syntax) := let (id, optUnivDeclStx) := expandDeclIdCore declId let scpView := extractMacroScopes id match scpView.name with | Name.str Name.anonymous s _ => none | Name.str pre s _ => let nameNew := { scpView with name := Name.mkSimple s }.review if declId.isIdent then some (pre, mkIdentFrom declId nameNew) else some (pre, declId.setArg 0 (mkIdentFrom declId nameNew)) | _ => none /- given declarations such as `@[...] def Foo.Bla.f ...` return `some (Foo.Bla, @[...] def f ...)` -/ def expandDeclNamespace? (stx : Syntax) : Option (Name × Syntax) := if !stx.isOfKind `Lean.Parser.Command.declaration then none else let decl := stx[1] let k := decl.getKind if k == ``Lean.Parser.Command.abbrev || k == ``Lean.Parser.Command.def || k == ``Lean.Parser.Command.theorem || k == ``Lean.Parser.Command.constant || k == ``Lean.Parser.Command.axiom || k == ``Lean.Parser.Command.inductive || k == ``Lean.Parser.Command.classInductive || k == ``Lean.Parser.Command.structure then match expandDeclIdNamespace? decl[1] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 1 declId)) | none => none else if k == ``Lean.Parser.Command.instance then let optDeclId := decl[3] if optDeclId.isNone then none else match expandDeclIdNamespace? optDeclId[0] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 3 (optDeclId.setArg 0 declId))) | none => none else none def elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do -- leading_parser "axiom " >> declId >> declSig let declId := stx[1] let (binders, typeStx) := expandDeclSig stx[2] let scopeLevelNames ← getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← expandDeclId declId modifiers addDeclarationRanges declName stx runTermElabM declName fun vars => Term.withLevelNames allUserLevelNames $ Term.elabBinders binders.getArgs fun xs => do Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.beforeElaboration let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let type ← instantiateMVars type let type ← mkForallFVars xs type let type ← mkForallFVars vars type (usedOnly := true) let (type, _) ← Term.levelMVarToParam type let usedParams := collectLevelParams {} type |>.params match sortDeclLevelParams scopeLevelNames allUserLevelNames usedParams with | Except.error msg => throwErrorAt stx msg | Except.ok levelParams => let decl := Declaration.axiomDecl { name := declName, levelParams := levelParams, type := type, isUnsafe := modifiers.isUnsafe } Term.ensureNoUnassignedMVars decl addDecl decl Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking if isExtern (← getEnv) declName then compileDecl decl Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation /- leading_parser "inductive " >> declId >> optDeclSig >> optional ":=" >> many ctor leading_parser atomic (group ("class " >> "inductive ")) >> declId >> optDeclSig >> optional ":=" >> many ctor >> optDeriving -/ private def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := do checkValidInductiveModifier modifiers let (binders, type?) := expandOptDeclSig decl[2] let declId := decl[1] let ⟨name, declName, levelNames⟩ ← expandDeclId declId modifiers addDeclarationRanges declName decl let ctors ← decl[4].getArgs.mapM fun ctor => withRef ctor do -- def ctor := leading_parser " | " >> declModifiers >> ident >> optional inferMod >> optDeclSig let ctorModifiers ← elabModifiers ctor[1] if ctorModifiers.isPrivate && modifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' inductive datatype" if ctorModifiers.isProtected && modifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' inductive datatype" checkValidCtorModifier ctorModifiers let ctorName := ctor.getIdAt 2 let ctorName := declName ++ ctorName let ctorName ← withRef ctor[2] $ applyVisibility ctorModifiers.visibility ctorName let inferMod := !ctor[3].isNone let (binders, type?) := expandOptDeclSig ctor[4] addDocString' ctorName ctorModifiers.docString? addAuxDeclarationRanges ctorName ctor ctor[2] pure { ref := ctor, modifiers := ctorModifiers, declName := ctorName, inferMod := inferMod, binders := binders, type? := type? : CtorView } let classes ← getOptDerivingClasses decl[5] pure { ref := decl modifiers := modifiers shortDeclName := name declName := declName levelNames := levelNames binders := binders type? := type? ctors := ctors derivingClasses := classes } private def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := inductiveSyntaxToView modifiers decl def elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let v ← inductiveSyntaxToView modifiers stx elabInductiveViews #[v] def elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let modifiers := modifiers.addAttribute { name := `class } let v ← classInductiveSyntaxToView modifiers stx elabInductiveViews #[v] def getTerminationBy? (stx : Syntax) : Option Syntax := let decl := stx[1] let k := decl.getKind if k == ``Parser.Command.def || k == ``Parser.Command.theorem || k == ``Parser.Command.instance then let args := decl.getArgs args[args.size - 2].getOptional? else none @[builtinCommandElab declaration] def elabDeclaration : CommandElab := fun stx => match expandDeclNamespace? stx with | some (ns, newStx) => do let ns := mkIdentFrom stx ns let newStx ← `(namespace $ns:ident $newStx end $ns:ident) withMacroExpansion stx newStx $ elabCommand newStx | none => do let modifiers ← elabModifiers stx[0] let decl := stx[1] let declKind := decl.getKind if declKind == ``Lean.Parser.Command.«axiom» then elabAxiom modifiers decl else if declKind == ``Lean.Parser.Command.«inductive» then elabInductive modifiers decl else if declKind == ``Lean.Parser.Command.classInductive then elabClassInductive modifiers decl else if declKind == ``Lean.Parser.Command.«structure» then elabStructure modifiers decl else if isDefLike decl then elabMutualDef #[stx] (getTerminationBy? stx) else throwError "unexpected declaration" /- Return true if all elements of the mutual-block are inductive declarations. -/ private def isMutualInductive (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] let declKind := decl.getKind declKind == `Lean.Parser.Command.inductive private def elabMutualInductive (elems : Array Syntax) : CommandElabM Unit := do let views ← elems.mapM fun stx => do let modifiers ← elabModifiers stx[0] inductiveSyntaxToView modifiers stx[1] elabInductiveViews views /- Return true if all elements of the mutual-block are definitions/theorems/abbrevs. -/ private def isMutualDef (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] isDefLike decl private def isMutualPreambleCommand (stx : Syntax) : Bool := let k := stx.getKind k == ``Lean.Parser.Command.variable || k == ``Lean.Parser.Command.universe || k == ``Lean.Parser.Command.check || k == ``Lean.Parser.Command.set_option || k == ``Lean.Parser.Command.open private partial def splitMutualPreamble (elems : Array Syntax) : Option (Array Syntax × Array Syntax) := let rec loop (i : Nat) : Option (Array Syntax × Array Syntax) := if h : i < elems.size then let elem := elems.get ⟨i, h⟩ if isMutualPreambleCommand elem then loop (i+1) else if i == 0 then none -- `mutual` block does not contain any preamble commands else some (elems[0:i], elems[i:elems.size]) else none -- a `mutual` block containing only preamble commands is not a valid `mutual` block loop 0 @[builtinMacro Lean.Parser.Command.mutual] def expandMutualNamespace : Macro := fun stx => do let mut ns? := none let mut elemsNew := #[] for elem in stx[1].getArgs do match ns?, expandDeclNamespace? elem with | _, none => elemsNew := elemsNew.push elem | none, some (ns, elem) => ns? := some ns; elemsNew := elemsNew.push elem | some nsCurr, some (nsNew, elem) => if nsCurr == nsNew then elemsNew := elemsNew.push elem else Macro.throwErrorAt elem s!"conflicting namespaces in mutual declaration, using namespace '{nsNew}', but used '{nsCurr}' in previous declaration" match ns? with | some ns => let ns := mkIdentFrom stx ns let stxNew := stx.setArg 1 (mkNullNode elemsNew) `(namespace $ns:ident $stxNew end $ns:ident) | none => Macro.throwUnsupported @[builtinMacro Lean.Parser.Command.mutual] def expandMutualElement : Macro := fun stx => do let mut elemsNew := #[] let mut modified := false for elem in stx[1].getArgs do match (← expandMacro? elem) with | some elemNew => elemsNew := elemsNew.push elemNew; modified := true | none => elemsNew := elemsNew.push elem if modified then pure $ stx.setArg 1 (mkNullNode elemsNew) else Macro.throwUnsupported @[builtinMacro Lean.Parser.Command.mutual] def expandMutualPreamble : Macro := fun stx => match splitMutualPreamble stx[1].getArgs with | none => Macro.throwUnsupported | some (preamble, rest) => do let secCmd ← `(section) let newMutual := stx.setArg 1 (mkNullNode rest) let endCmd ← `(end) pure $ mkNullNode (#[secCmd] ++ preamble ++ #[newMutual] ++ #[endCmd]) @[builtinCommandElab «mutual»] def elabMutual : CommandElab := fun stx => do let terminationBy? := stx[3].getOptional? if isMutualInductive stx then unless terminationBy?.isNone do throwErrorAt stx[3] "invalid 'termination_by' in mutually inductive datatype declaration" elabMutualInductive stx[1].getArgs else if isMutualDef stx then for arg in stx[1].getArgs do if let some bad := getTerminationBy? arg then throwErrorAt bad "invalid 'termination_by' in 'mutual' block, it must be used after the 'end' keyword" elabMutualDef stx[1].getArgs terminationBy? else throwError "invalid mutual block" /- leading_parser "attribute " >> "[" >> sepBy1 (eraseAttr <|> Term.attrInstance) ", " >> "]" >> many1 ident -/ @[builtinCommandElab «attribute»] def elabAttr : CommandElab := fun stx => do let mut attrInsts := #[] let mut toErase := #[] for attrKindStx in stx[2].getSepArgs do if attrKindStx.getKind == ``Lean.Parser.Command.eraseAttr then let attrName := attrKindStx[1].getId.eraseMacroScopes unless isAttribute (← getEnv) attrName do throwError "unknown attribute [{attrName}]" toErase := toErase.push attrName else attrInsts := attrInsts.push attrKindStx let attrs ← elabAttrs attrInsts let idents := stx[4].getArgs for ident in idents do withRef ident <| liftTermElabM none do let declName ← resolveGlobalConstNoOverloadWithInfo ident Term.applyAttributes declName attrs for attrName in toErase do Attribute.erase declName attrName def expandInitCmd (builtin : Bool) : Macro := fun stx => do let optVisibility := stx[0] let optHeader := stx[2] let doSeq := stx[3] let attrId := mkIdentFrom stx $ if builtin then `builtinInit else `init if optHeader.isNone then unless optVisibility.isNone do Macro.throwError "invalid initialization command, 'visibility' modifer is not allowed" `(@[$attrId:ident]def initFn : IO Unit := do $doSeq) else let id := optHeader[0] let type := optHeader[1][1] if optVisibility.isNone then `(def initFn : IO $type := do $doSeq @[$attrId:ident initFn] constant $id : $type) else if optVisibility[0].getKind == ``Parser.Command.private then `(def initFn : IO $type := do $doSeq @[$attrId:ident initFn] private constant $id : $type) else if optVisibility[0].getKind == ``Parser.Command.protected then `(def initFn : IO $type := do $doSeq @[$attrId:ident initFn] protected constant $id : $type) else Macro.throwError "unexpected visibility annotation" @[builtinMacro Lean.Parser.Command.«initialize»] def expandInitialize : Macro := expandInitCmd (builtin := false) @[builtinMacro Lean.Parser.Command.«builtin_initialize»] def expandBuiltinInitialize : Macro := expandInitCmd (builtin := true) end Lean.Elab.Command
e7118a9233d0327e02e94feaf7e3c8f03300d113
ac89c256db07448984849346288e0eeffe8b20d0
/src/Lean/Meta/LevelDefEq.lean
cf8a6dbd691ec76d493e213e8a2afd04a1f03e99
[ "Apache-2.0" ]
permissive
chepinzhang/lean4
002cc667f35417a418f0ebc9cb4a44559bb0ccac
24fe2875c68549b5481f07c57eab4ad4a0ae5305
refs/heads/master
1,688,942,838,326
1,628,801,942,000
1,628,801,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,378
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.CollectMVars import Lean.Util.ReplaceExpr import Lean.Meta.Basic import Lean.Meta.InferType namespace Lean.Meta private partial def decAux? : Level → MetaM (Option Level) | Level.zero _ => return none | Level.param _ _ => return none | Level.mvar mvarId _ => do let mctx ← getMCtx match mctx.getLevelAssignment? mvarId with | some u => decAux? u | none => if (← isReadOnlyLevelMVar mvarId) then return none else let u ← mkFreshLevelMVar assignLevelMVar mvarId (mkLevelSucc u) return u | Level.succ u _ => return u | u => let process (u v : Level) : MetaM (Option Level) := do match (← decAux? u) with | none => return none | some u => do match (← decAux? v) with | none => return none | some v => return mkLevelMax' u v match u with | Level.max u v _ => process u v /- Remark: If `decAux? v` returns `some ...`, then `imax u v` is equivalent to `max u v`. -/ | Level.imax u v _ => process u v | _ => unreachable! def decLevel? (u : Level) : MetaM (Option Level) := do let mctx ← getMCtx match (← decAux? u) with | some v => return some v | none => do modify fun s => { s with mctx := mctx } return none def decLevel (u : Level) : MetaM Level := do match (← decLevel? u) with | some u => return u | none => throwError "invalid universe level, {u} is not greater than 0" /- This method is useful for inferring universe level parameters for function that take arguments such as `{α : Type u}`. Recall that `Type u` is `Sort (u+1)` in Lean. Thus, given `α`, we must infer its universe level, and then decrement 1 to obtain `u`. -/ def getDecLevel (type : Expr) : MetaM Level := do decLevel (← getLevel type) /-- Return true iff `lvl` occurs in `max u_1 ... u_n` and `lvl != u_i` for all `i in [1, n]`. That is, `lvl` is a proper level subterm of some `u_i`. -/ private def strictOccursMax (lvl : Level) : Level → Bool | Level.max u v _ => visit u || visit v | _ => false where visit : Level → Bool | Level.max u v _ => visit u || visit v | u => u != lvl && lvl.occurs u /-- `mkMaxArgsDiff mvarId (max u_1 ... (mvar mvarId) ... u_n) v` => `max v u_1 ... u_n` -/ private def mkMaxArgsDiff (mvarId : MVarId) : Level → Level → Level | Level.max u v _, acc => mkMaxArgsDiff mvarId v <| mkMaxArgsDiff mvarId u acc | l@(Level.mvar id _), acc => if id != mvarId then mkLevelMax' acc l else acc | l, acc => mkLevelMax' acc l /-- Solve `?m =?= max ?m v` by creating a fresh metavariable `?n` and assigning `?m := max ?n v` -/ private def solveSelfMax (mvarId : MVarId) (v : Level) : MetaM Unit := do assert! v.isMax let n ← mkFreshLevelMVar assignLevelMVar mvarId <| mkMaxArgsDiff mvarId v n private def postponeIsLevelDefEq (lhs : Level) (rhs : Level) : MetaM Unit := do let ref ← getRef let ctx ← read trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}" modifyPostponed fun postponed => postponed.push { lhs := lhs, rhs := rhs, ref := ref, ctx? := ctx.defEqCtx? } mutual private partial def solve (u v : Level) : MetaM LBool := do match u, v with | Level.mvar mvarId _, _ => if (← isReadOnlyLevelMVar mvarId) then return LBool.undef else if !u.occurs v then assignLevelMVar u.mvarId! v return LBool.true else if v.isMax && !strictOccursMax u v then solveSelfMax u.mvarId! v return LBool.true else return LBool.undef | _, Level.mvar .. => LBool.undef -- Let `solve v u` to handle this case | Level.zero _, Level.max v₁ v₂ _ => Bool.toLBool <$> (isLevelDefEqAux levelZero v₁ <&&> isLevelDefEqAux levelZero v₂) | Level.zero _, Level.imax _ v₂ _ => Bool.toLBool <$> isLevelDefEqAux levelZero v₂ | Level.zero _, Level.succ .. => return LBool.false | Level.succ u _, v => if v.isParam then return LBool.false else if u.isMVar && u.occurs v then return LBool.undef else match (← Meta.decLevel? v) with | some v => Bool.toLBool <$> isLevelDefEqAux u v | none => return LBool.undef | _, _ => return LBool.undef partial def isLevelDefEqAux : Level → Level → MetaM Bool | Level.succ lhs _, Level.succ rhs _ => isLevelDefEqAux lhs rhs | lhs, rhs => do if lhs.getLevelOffset == rhs.getLevelOffset then return lhs.getOffset == rhs.getOffset else trace[Meta.isLevelDefEq.step] "{lhs} =?= {rhs}" let lhs' ← instantiateLevelMVars lhs let lhs' := lhs'.normalize let rhs' ← instantiateLevelMVars rhs let rhs' := rhs'.normalize if lhs != lhs' || rhs != rhs' then isLevelDefEqAux lhs' rhs' else let r ← solve lhs rhs; if r != LBool.undef then return r == LBool.true else let r ← solve rhs lhs; if r != LBool.undef then return r == LBool.true else do let mctx ← getMCtx if !mctx.hasAssignableLevelMVar lhs && !mctx.hasAssignableLevelMVar rhs then let ctx ← read if ctx.config.isDefEqStuckEx && (lhs.isMVar || rhs.isMVar) then do trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}" Meta.throwIsDefEqStuck else return false else postponeIsLevelDefEq lhs rhs return true end def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => return true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => return false private def getNumPostponed : MetaM Nat := do return (← getPostponed).size open Std (PersistentArray) def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do let ps ← getPostponed setPostponed {} return ps /-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/ private def exposeRelevantUniverses (e : Expr) (p : Level → Bool) : Expr := e.replace fun | Expr.const _ us _ => if us.any p then some (e.setPPUniverses true) else none | Expr.sort u _ => if p u then some (e.setPPUniverses true) else none | _ => none private def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do match entry.ctx? with | none => return m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}" | some ctx => withLCtx ctx.lctx ctx.localInstances do let s := entry.lhs.collectMVars entry.rhs.collectMVars /- `p u` is true if it contains a universe metavariable in `s` -/ let p (u : Level) := u.any fun | Level.mvar m _ => s.contains m | _ => false let lhs := exposeRelevantUniverses (← instantiateMVars ctx.lhs) p let rhs := exposeRelevantUniverses (← instantiateMVars ctx.rhs) p try addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD m!"{lhs} : {← inferType lhs}"}\nwith{indentD m!"{rhs} : {← inferType rhs}"}" catch _ => addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD lhs}\nwith{indentD rhs}" def mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "stuck at solving universe constraint" entry def mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "failed to solve universe constraint" entry private def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool := traceCtx `Meta.isLevelDefEq.postponed.step do let ps ← getResetPostponed for p in ps do unless (← withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do if exceptionOnFailure then throwError (← mkLevelErrorMessage p) else return false return true partial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do if (← getNumPostponed) == 0 then return true else traceCtx `Meta.isLevelDefEq.postponed do let rec loop : MetaM Bool := do let numPostponed ← getNumPostponed if numPostponed == 0 then return true else trace[Meta.isLevelDefEq.postponed] "processing #{numPostponed} postponed is-def-eq level constraints" if !(← processPostponedStep exceptionOnFailure) then return false else let numPostponed' ← getNumPostponed if numPostponed' == 0 then return true else if numPostponed' < numPostponed then loop else trace[Meta.isLevelDefEq.postponed] "no progress solving pending is-def-eq level constraints" return mayPostpone loop /-- `checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if `processPostponed` return true and `x` returned `true`. If `mayPostpone == false`, all new postponed universe level constraints must be solved before returning. We currently try to postpone universe constraints as much as possible, even when by postponing them we are not sure whether `x` really succeeded or not. -/ @[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do let s ← saveState let postponed ← getResetPostponed try if (← x) then if (← processPostponed mayPostpone) then let newPostponed ← getPostponed setPostponed (postponed ++ newPostponed) return true else s.restore return false else s.restore return false catch ex => s.restore throw ex def isLevelDefEq (u v : Level) : MetaM Bool := traceCtx `Meta.isLevelDefEq do let b ← checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v trace[Meta.isLevelDefEq] "{u} =?= {v} ... {if b then "success" else "failure"}" return b def isExprDefEq (t s : Expr) : MetaM Bool := traceCtx `Meta.isDefEq <| withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do let b ← checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s trace[Meta.isDefEq] "{t} =?= {s} ... {if b then "success" else "failure"}" return b abbrev isDefEq (t s : Expr) : MetaM Bool := isExprDefEq t s def isExprDefEqGuarded (a b : Expr) : MetaM Bool := do try isExprDefEq a b catch _ => return false abbrev isDefEqGuarded (t s : Expr) : MetaM Bool := isExprDefEqGuarded t s def isDefEqNoConstantApprox (t s : Expr) : MetaM Bool := approxDefEq <| isDefEq t s builtin_initialize registerTraceClass `Meta.isLevelDefEq registerTraceClass `Meta.isLevelDefEq.step registerTraceClass `Meta.isLevelDefEq.postponed end Lean.Meta
a9a4b53163d51524f2e93fe875a0373323ad9755
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/DiscrTree.lean
6eb3309feac49dcaf6f4d51f6ed4a22b31a21199
[ "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
9,342
lean
import Lean.Format open Lean def List.insert {α} [BEq α] (as : List α) (a : α) : List α := if as.contains a then as else a::as inductive Term | var : Nat → Term | app : String → Array Term → Term instance : Inhabited Term := ⟨Term.var 0⟩ inductive Key | var : Key | sym : String → Nat → Key instance : Inhabited Key := ⟨Key.var⟩ def Key.beq : Key → Key → Bool | Key.var, Key.var => true | Key.sym k₁ a₁, Key.sym k₂ a₂ => k₁ == k₂ && a₁ == a₂ | _, _ => false instance : BEq Key := ⟨Key.beq⟩ def Key.lt : Key → Key → Bool | Key.var, Key.var => false | Key.var, _ => true | Key.sym k₁ a₁, Key.sym k₂ a₂ => k₁ < k₂ || (k₁ == k₂ && a₁ < a₂) | _, _ => false instance : Less Key := ⟨fun k₁ k₂ => k₁.lt k₂⟩ def Key.format : Key → Format | Key.var => "*" | Key.sym k a => if a > 0 then k ++ "." ++ fmt a else k instance : HasFormat Key := ⟨Key.format⟩ def Term.key : Term → Key | Term.var _ => Key.var | Term.app f as => Key.sym f as.size def Term.args : Term → Array Term | Term.var _ => #[] | Term.app f as => as -- TODO: root should be a persistent hash map inductive Trie (α : Type) | node (vals : List α) (children : Array (Key × Trie)) : Trie namespace Trie def empty {α} : Trie α := node [] #[] instance {α} : Inhabited (Trie α) := ⟨empty⟩ partial def appendTodoAux (as : Array Term) : Nat → Array Term → Array Term | 0, todo => todo | i+1, todo => appendTodoAux i (todo.push (as.get! i)) def appendTodo (todo : Array Term) (as : Array Term) : Array Term := appendTodoAux as as.size todo partial def createNodes {α} (v : α) : Array Term → Trie α | todo => if todo.isEmpty then node [v] #[] else let t := todo.back; let todo := todo.pop; node [] #[(t.key, createNodes (appendTodo todo t.args))] partial def insertAux {α} [BEq α] (v : α) : Array Term → Trie α → Trie α | todo, node vs cs => if todo.isEmpty then node (vs.insert v) cs else let t := todo.back; let todo := todo.pop; let todo := appendTodo todo t.args; let k := t.key; node vs $ Id.run $ cs.binInsertM (fun a b => a.1 < b.1) (fun ⟨_, s⟩ => (k, insertAux todo s)) -- merge with existing (fun _ => (k, createNodes v todo)) -- add new node (k, arbitrary _) def insert {α} [BEq α] (d : Trie α) (k : Term) (v : α) : Trie α := let todo : Array Term := Array.mkEmpty 32; let todo := todo.push k; insertAux v todo d partial def format {α} [HasFormat α] : Trie α → Format | node vs cs => Format.group $ Format.paren $ "node" ++ (if vs.isEmpty then Format.nil else " " ++ fmt vs) ++ Format.join (cs.toList.map $ fun ⟨k, c⟩ => Format.line ++ Format.paren (fmt k ++ " => " ++ format c)) instance {α} [HasFormat α] : HasFormat (Trie α) := ⟨format⟩ @[specialize] partial def foldMatchAux {α β} {m : Type → Type} [Monad m] (f : β → α → m β) : Array Term → Trie α → β → m β | todo, node vs cs, b => if todo.isEmpty then vs.foldlM f b else if cs.isEmpty then pure b else let t := todo.back; let todo := todo.pop; let first := cs.get! 0; let k := t.key; match k with | Key.var => if first.1 == Key.var then foldMatchAux todo first.2 b else pure b | Key.sym _ _ => do match cs.binSearch (k, arbitrary _) (fun a b => a.1 < b.1) with | none => if first.1 == Key.var then foldMatchAux todo first.2 b else pure b | some c => do b ← if first.1 == Key.var then foldMatchAux todo first.2 b else pure b; let todo := appendTodo todo t.args; foldMatchAux todo c.2 b @[specialize] def foldMatch {α β} {m : Type → Type} [Monad m] (d : Trie α) (k : Term) (f : β → α → m β) (b : β) : m β := let todo : Array Term := Array.mkEmpty 32; let todo := todo.push k; foldMatchAux f todo d b /-- Return all (approximate) matches (aka generalizations) of the term `k` -/ def getMatch {α} (d : Trie α) (k : Term) : Array α := Id.run $ d.foldMatch k (fun (r : Array α) v => pure $ r.push v) #[] @[specialize] partial def foldUnifyAux {α β} {m : Type → Type} [Monad m] (f : β → α → m β) : Nat → Array Term → Trie α → β → m β | skip+1, todo, node vs cs, b => if cs.isEmpty then pure b else cs.foldlM (fun b ⟨k, c⟩ => match k with | Key.var => foldUnifyAux skip todo c b | Key.sym _ a => foldUnifyAux (skip + a) todo c b) b | 0, todo, node vs cs, b => if todo.isEmpty then vs.foldlM f b else if cs.isEmpty then pure b else let t := todo.back; let todo := todo.pop; let first := cs.get! 0; let k := t.key; match k with | Key.var => cs.foldlM (fun b ⟨k, c⟩ => match k with | Key.var => foldUnifyAux 0 todo c b | Key.sym _ a => foldUnifyAux a todo c b) b | Key.sym _ _ => do match cs.binSearch (k, arbitrary _) (fun a b => a.1 < b.1) with | none => if first.1 == Key.var then foldUnifyAux 0 todo first.2 b else pure b | some c => do b ← if first.1 == Key.var then foldUnifyAux 0 todo first.2 b else pure b; let todo := appendTodo todo t.args; foldUnifyAux 0 todo c.2 b @[specialize] def foldUnify {α β} {m : Type → Type} [Monad m] (d : Trie α) (k : Term) (f : β → α → m β) (b : β) : m β := let todo : Array Term := Array.mkEmpty 32; let todo := todo.push k; foldUnifyAux f 0 todo d b /-- Return all candidate unifiers of the term `k` -/ def getUnify {α} (d : Trie α) (k : Term) : Array α := Id.run $ d.foldUnify k (fun (r : Array α) v => pure $ r.push v) #[] end Trie def mkApp (s : String) (cs : Array Term) := Term.app s cs def mkConst (s : String) := Term.app s #[] def mkVar (i : Nat) := Term.var i def tst1 : IO Unit := let d := @Trie.empty Nat; let t := mkApp "f" #[mkApp "g" #[mkConst "a"], mkApp "g" #[mkConst "b"]]; let d := d.insert t 10; let t := mkApp "f" #[mkApp "h" #[mkConst "a", mkVar 0], mkConst "b"]; let d := d.insert t 20; let t := mkApp "f" #[mkConst "b", mkConst "c", mkConst "d"]; let d := d.insert t 20; let d := (20:Nat).fold (fun i (d : Trie Nat) => let t := mkApp "f" #[mkApp "h" #[mkConst "a", mkVar 0], mkApp "f" #[mkConst ("c" ++ toString i)]]; d.insert t i) d; let d := (20:Nat).fold (fun i (d : Trie Nat) => let t := mkApp "f" #[mkApp "g" #[mkConst ("a" ++ toString i)], mkApp "g" #[mkConst "b"]]; d.insert t i) d; -- let t := mkApp "g" [mkApp "h" [mkConst "a"]]; -- let d := d.insert t 10; IO.println (format d) #eval tst1 def check (as bs : Array Nat) : IO Unit := let as := as.qsort (fun a b => a < b); let bs := bs.qsort (fun a b => a < b); unless (as == bs) $ throw $ IO.userError "check failed" def tst2 : IO Unit := do let d := @Trie.empty Nat; let d := d.insert (mkApp "f" #[mkVar 0, mkConst "a"]) 1; -- f * a let d := d.insert (mkApp "f" #[mkConst "b", mkVar 0]) 2; -- f b * let d := d.insert (mkApp "f" #[mkVar 0, mkVar 0]) 3; -- f * * let d := d.insert (mkApp "f" #[mkVar 0, mkConst "b"]) 4; -- f * b let d := d.insert (mkApp "f" #[mkApp "h" #[mkVar 0], mkConst "b"]) 5; -- f (h *) b let d := d.insert (mkApp "f" #[mkApp "h" #[mkConst "a"], mkConst "b"]) 6; -- f (h a) b let d := d.insert (mkApp "f" #[mkApp "h" #[mkConst "a"], mkVar 1]) 7; -- f (h a) * let d := d.insert (mkApp "f" #[mkApp "h" #[mkConst "a"], mkVar 0]) 8; -- f (h a) * let d := d.insert (mkApp "f" #[mkApp "h" #[mkVar 0], mkApp "h" #[mkConst "b"]]) 9; -- f (h *) (h b) let d := d.insert (mkApp "g" #[mkVar 0, mkConst "a"]) 10; -- g * a let d := d.insert (mkApp "g" #[mkConst "b", mkVar 0]) 11; -- g b * let d := d.insert (mkApp "g" #[mkVar 0, mkVar 0]) 12; -- g * * let d := d.insert (mkApp "g" #[mkApp "h" #[mkConst "a"], mkConst "b"]) 13; -- g (h a) b let d := d.insert (mkApp "g" #[mkApp "h" #[mkConst "a"], mkVar 1]) 14; -- g (h a) * IO.println (format d); let vs := d.getMatch (mkApp "f" #[mkApp "h" #[mkConst "a"], mkApp "h" #[mkConst "b"]]); -- f (h a) (h b) check vs #[3, 7, 8, 9]; let vs := d.getMatch (mkApp "f" #[mkConst "b", mkConst "a"]); -- f a b check vs #[1, 2, 3]; let vs := d.getMatch (mkApp "g" #[mkConst "b", mkConst "b"]); -- g b b check vs #[11, 12]; let vs := d.getUnify (mkApp "f" #[mkApp "h" #[mkVar 0], mkApp "h" #[mkVar 0]]); -- f (h *) (h *) check vs #[3, 7, 8, 9]; let vs := d.getUnify (mkApp "f" #[mkApp "h" #[mkVar 0], mkVar 0]); -- f (h *) * check vs #[1, 3, 4, 5, 6, 7, 8, 9]; let vs := d.getUnify (mkApp "f" #[mkApp "h" #[mkConst "b"], mkVar 0]); -- f (h b) * check vs #[1, 3, 4, 5, 9]; let vs := d.getUnify (mkVar 0); -- * check vs (List.iota 14).toArray; let vs := d.getUnify (mkApp "g" #[mkVar 0, mkConst "b"]); -- g * b check vs #[11, 12, 13, 14]; let vs := d.getUnify (mkApp "g" #[mkApp "h" #[mkVar 0], mkConst "b"]); -- g (h *) b check vs #[12, 13, 14]; let vs := d.getUnify (mkApp "g" #[mkApp "h" #[mkConst "b"], mkVar 0]); -- g (h b) * check vs #[10, 12]; pure () #eval tst2
24ff88e09ef54ad8bdb7239749a6f9fd722e08c5
e953c38599905267210b87fb5d82dcc3e52a4214
/hott/types/prod.hlean
7d6cb44442a8cfbd0dc9f2e524babd88cdb37742
[ "Apache-2.0" ]
permissive
c-cube/lean
563c1020bff98441c4f8ba60111fef6f6b46e31b
0fb52a9a139f720be418dafac35104468e293b66
refs/heads/master
1,610,753,294,113
1,440,451,356,000
1,440,499,588,000
41,748,334
0
0
null
1,441,122,656,000
1,441,122,656,000
null
UTF-8
Lean
false
false
6,821
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 Ported from Coq HoTT Theorems about products -/ open eq equiv is_equiv is_trunc prod prod.ops unit equiv.ops variables {A A' B B' C D : Type} {a a' a'' : A} {b b₁ b₂ b' b'' : B} {u v w : A × B} namespace prod protected definition eta (u : A × B) : (pr₁ u, pr₂ u) = u := by cases u; apply idp definition pair_eq [unfold 7 8] (pa : a = a') (pb : b = b') : (a, b) = (a', b') := by cases pa; cases pb; apply idp definition prod_eq [unfold 3 4 5 6] (H₁ : u.1 = v.1) (H₂ : u.2 = v.2) : u = v := by cases u; cases v; exact pair_eq H₁ H₂ /- Projections of paths from a total space -/ definition eq_pr1 (p : u = v) : u.1 = v.1 := ap pr1 p definition eq_pr2 (p : u = v) : u.2 = v.2 := ap pr2 p namespace ops postfix `..1`:(max+1) := eq_pr1 postfix `..2`:(max+1) := eq_pr2 end ops open ops definition pair_prod_eq (p : u.1 = v.1) (q : u.2 = v.2) : ((prod_eq p q)..1, (prod_eq p q)..2) = (p, q) := by induction u; induction v;esimp at *;induction p;induction q;reflexivity definition prod_eq_pr1 (p : u.1 = v.1) (q : u.2 = v.2) : (prod_eq p q)..1 = p := (pair_prod_eq p q)..1 definition prod_eq_pr2 (p : u.1 = v.1) (q : u.2 = v.2) : (prod_eq p q)..2 = q := (pair_prod_eq p q)..2 definition prod_eq_eta (p : u = v) : prod_eq (p..1) (p..2) = p := by induction p; induction u; reflexivity /- the uncurried version of prod_eq. We will prove that this is an equivalence -/ definition prod_eq_unc (H : u.1 = v.1 × u.2 = v.2) : u = v := by cases H with H₁ H₂;exact prod_eq H₁ H₂ definition pair_prod_eq_unc : Π(pq : u.1 = v.1 × u.2 = v.2), ((prod_eq_unc pq)..1, (prod_eq_unc pq)..2) = pq | pair_prod_eq_unc (pq₁, pq₂) := pair_prod_eq pq₁ pq₂ definition prod_eq_unc_pr1 (pq : u.1 = v.1 × u.2 = v.2) : (prod_eq_unc pq)..1 = pq.1 := (pair_prod_eq_unc pq)..1 definition prod_eq_unc_pr2 (pq : u.1 = v.1 × u.2 = v.2) : (prod_eq_unc pq)..2 = pq.2 := (pair_prod_eq_unc pq)..2 definition prod_eq_unc_eta (p : u = v) : prod_eq_unc (p..1, p..2) = p := prod_eq_eta p definition is_equiv_prod_eq [instance] (u v : A × B) : is_equiv (prod_eq_unc : u.1 = v.1 × u.2 = v.2 → u = v) := adjointify prod_eq_unc (λp, (p..1, p..2)) prod_eq_unc_eta pair_prod_eq_unc definition prod_eq_equiv (u v : A × B) : (u = v) ≃ (u.1 = v.1 × u.2 = v.2) := (equiv.mk prod_eq_unc _)⁻¹ᵉ /- Transport -/ definition prod_transport {P Q : A → Type} {a a' : A} (p : a = a') (u : P a × Q a) : p ▸ u = (p ▸ u.1, p ▸ u.2) := by induction p; induction u; reflexivity /- Functorial action -/ variables (f : A → A') (g : B → B') definition prod_functor [unfold 7] (u : A × B) : A' × B' := (f u.1, g u.2) definition ap_prod_functor (p : u.1 = v.1) (q : u.2 = v.2) : ap (prod_functor f g) (prod_eq p q) = prod_eq (ap f p) (ap g q) := by induction u; induction v; esimp at *; induction p; induction q; reflexivity /- Equivalences -/ definition is_equiv_prod_functor [instance] [H : is_equiv f] [H : is_equiv g] : is_equiv (prod_functor f g) := begin apply adjointify _ (prod_functor f⁻¹ g⁻¹), intro u, induction u, rewrite [▸*,right_inv f,right_inv g], intro u, induction u, rewrite [▸*,left_inv f,left_inv g], end definition prod_equiv_prod_of_is_equiv [H : is_equiv f] [H : is_equiv g] : A × B ≃ A' × B' := equiv.mk (prod_functor f g) _ definition prod_equiv_prod (f : A ≃ A') (g : B ≃ B') : A × B ≃ A' × B' := equiv.mk (prod_functor f g) _ definition prod_equiv_prod_left (g : B ≃ B') : A × B ≃ A × B' := prod_equiv_prod equiv.refl g definition prod_equiv_prod_right (f : A ≃ A') : A × B ≃ A' × B := prod_equiv_prod f equiv.refl /- Symmetry -/ definition is_equiv_flip [instance] (A B : Type) : is_equiv (@flip A B) := adjointify flip flip (λu, destruct u (λb a, idp)) (λu, destruct u (λa b, idp)) definition prod_comm_equiv (A B : Type) : A × B ≃ B × A := equiv.mk flip _ /- Associativity -/ definition prod_assoc_equiv (A B C : Type) : A × (B × C) ≃ (A × B) × C := begin fapply equiv.MK, { intro z, induction z with a z, induction z with b c, exact (a, b, c)}, { intro z, induction z with z c, induction z with a b, exact (a, (b, c))}, { intro z, induction z with z c, induction z with a b, reflexivity}, { intro z, induction z with a z, induction z with b c, reflexivity}, end definition prod_contr_equiv (A B : Type) [H : is_contr B] : A × B ≃ A := equiv.MK pr1 (λx, (x, !center)) (λx, idp) (λx, by cases x with a b; exact pair_eq idp !center_eq) definition prod_unit_equiv (A : Type) : A × unit ≃ A := !prod_contr_equiv /- Universal mapping properties -/ definition is_equiv_prod_rec [instance] (P : A × B → Type) : is_equiv (prod.rec : (Πa b, P (a, b)) → Πu, P u) := adjointify _ (λg a b, g (a, b)) (λg, eq_of_homotopy (λu, by induction u;reflexivity)) (λf, idp) definition equiv_prod_rec (P : A × B → Type) : (Πa b, P (a, b)) ≃ (Πu, P u) := equiv.mk prod.rec _ definition imp_imp_equiv_prod_imp (A B C : Type) : (A → B → C) ≃ (A × B → C) := !equiv_prod_rec definition prod_corec_unc [unfold 4] {P Q : A → Type} (u : (Πa, P a) × (Πa, Q a)) (a : A) : P a × Q a := (u.1 a, u.2 a) definition is_equiv_prod_corec (P Q : A → Type) : is_equiv (prod_corec_unc : (Πa, P a) × (Πa, Q a) → Πa, P a × Q a) := adjointify _ (λg, (λa, (g a).1, λa, (g a).2)) (by intro g; apply eq_of_homotopy; intro a; esimp; induction (g a); reflexivity) (by intro h; induction h with f g; reflexivity) definition equiv_prod_corec (P Q : A → Type) : ((Πa, P a) × (Πa, Q a)) ≃ (Πa, P a × Q a) := equiv.mk _ !is_equiv_prod_corec definition imp_prod_imp_equiv_imp_prod (A B C : Type) : (A → B) × (A → C) ≃ (A → (B × C)) := !equiv_prod_corec definition is_trunc_prod (A B : Type) (n : trunc_index) [HA : is_trunc n A] [HB : is_trunc n B] : is_trunc n (A × B) := begin revert A B HA HB, induction n with n IH, all_goals intro A B HA HB, { fapply is_contr.mk, exact (!center, !center), intro u, apply prod_eq, all_goals apply center_eq}, { apply is_trunc_succ_intro, intro u v, apply is_trunc_equiv_closed_rev, apply prod_eq_equiv, exact IH _ _ _ _} end end prod attribute prod.is_trunc_prod [instance] [priority 1505]
b4b18528f761ce1131cdcbc9feb6df4487d9a6fa
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Util/CollectLevelParams.lean
82ae8170fbc43047c85d54872d3350eb495a7b66
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
2,213
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.Expr namespace Lean namespace CollectLevelParams structure State where visitedLevel : LevelSet := {} visitedExpr : ExprSet := {} params : Array Name := #[] instance : Inhabited State := ⟨{}⟩ abbrev Visitor := State → State mutual partial def visitLevel (u : Level) : Visitor := fun s => if !u.hasParam || s.visitedLevel.contains u then s else collect u { s with visitedLevel := s.visitedLevel.insert u } partial def collect : Level → Visitor | .succ v => visitLevel v | .max u v => visitLevel v ∘ visitLevel u | .imax u v => visitLevel v ∘ visitLevel u | .param n => fun s => { s with params := s.params.push n } | _ => id end mutual partial def visitExpr (e : Expr) : Visitor := fun s => if !e.hasLevelParam then s else if s.visitedExpr.contains e then s else main e { s with visitedExpr := s.visitedExpr.insert e } partial def main : Expr → Visitor | .proj _ _ s => visitExpr s | .forallE _ d b _ => visitExpr b ∘ visitExpr d | .lam _ d b _ => visitExpr b ∘ visitExpr d | .letE _ t v b _ => visitExpr b ∘ visitExpr v ∘ visitExpr t | .app f a => visitExpr a ∘ visitExpr f | .mdata _ b => visitExpr b | .const _ us => fun s => us.foldl (fun s u => visitLevel u s) s | .sort u => visitLevel u | _ => id end partial def State.getUnusedLevelParam (s : CollectLevelParams.State) (pre : Name := `v) : Level := let v := mkLevelParam pre; if s.visitedLevel.contains v then let rec loop (i : Nat) := let v := mkLevelParam (pre.appendIndexAfter i); if s.visitedLevel.contains v then loop (i+1) else v loop 1 else v end CollectLevelParams def collectLevelParams (s : CollectLevelParams.State) (e : Expr) : CollectLevelParams.State := CollectLevelParams.main e s def CollectLevelParams.State.collect (s : CollectLevelParams.State) (e : Expr) : CollectLevelParams.State := collectLevelParams s e end Lean
57c2fe4cf0bc9f584cdc461a5d0b33b412a0be21
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/dsimp_at1.lean
7cb34d792692571f57aa07bd50e0f0e3554b68f7
[ "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
315
lean
open tactic constants (A : Type.{1}) (x y : A) noncomputable definition f (z : A) : A := z attribute [defeq] definition f.def (z:A) : f z = z := rfl definition foo (z₁ z₂ : A) : f z₁ = f z₂ → z₁ = z₂ := by do H ← intro `H, trace_state, dsimp_at H, trace_state, assumption
2c7b770e8884a6a7b93c39582b6739f246919159
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/ring_hom/integral.lean
09c56649a254985de9b3ee30203caa9ea97ae6b7
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
1,177
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import ring_theory.ring_hom_properties /-! # The meta properties of integral ring homomorphisms. -/ namespace ring_hom open_locale tensor_product open tensor_product algebra.tensor_product lemma is_integral_stable_under_composition : stable_under_composition (λ R S _ _ f, by exactI f.is_integral) := by { introv R hf hg, exactI ring_hom.is_integral_trans _ _ hf hg } lemma is_integral_respects_iso : respects_iso (λ R S _ _ f, by exactI f.is_integral) := begin apply is_integral_stable_under_composition.respects_iso, introv x, resetI, rw ← e.apply_symm_apply x, apply ring_hom.is_integral_map end lemma is_integral_stable_under_base_change : stable_under_base_change (λ R S _ _ f, by exactI f.is_integral) := begin refine stable_under_base_change.mk _ is_integral_respects_iso _, introv h x, resetI, apply tensor_product.induction_on x, { apply is_integral_zero }, { intros x y, exact is_integral.tmul x (h y) }, { intros x y hx hy, exact is_integral_add _ hx hy } end end ring_hom
65ffd2ca7993b6c7e172fe8ebf64f3b908fbba49
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/convex/extreme.lean
cde58f3eb43ff2b0c4bd43b9fd7b098090c78f76
[ "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,570
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import analysis.convex.hull /-! # Extreme sets This file defines extreme sets and extreme points for sets in a module. An extreme set of `A` is a subset of `A` that is as far as it can get in any outward direction: If point `x` is in it and point `y ∈ A`, then the line passing through `x` and `y` leaves `A` at `x`. This is an analytic notion of "being on the side of". It is weaker than being exposed (see `is_exposed.is_extreme`). ## Main declarations * `is_extreme 𝕜 A B`: States that `B` is an extreme set of `A` (in the literature, `A` is often implicit). * `set.extreme_points 𝕜 A`: Set of extreme points of `A` (corresponding to extreme singletons). * `convex.mem_extreme_points_iff_convex_diff`: A useful equivalent condition to being an extreme point: `x` is an extreme point iff `A \ {x}` is convex. ## Implementation notes The exact definition of extremeness has been carefully chosen so as to make as many lemmas unconditional (in particular, the Krein-Milman theorem doesn't need the set to be convex!). In practice, `A` is often assumed to be a convex set. ## References See chapter 8 of [Barry Simon, *Convexity*][simon2011] ## TODO Define intrinsic frontier and prove lemmas related to extreme sets and points. More not-yet-PRed stuff is available on the branch `sperner_again`. -/ open_locale classical affine open set variables (𝕜 : Type*) {E : Type*} section has_scalar variables [ordered_semiring 𝕜] [add_comm_monoid E] [has_scalar 𝕜 E] /-- A set `B` is an extreme subset of `A` if `B ⊆ A` and all points of `B` only belong to open segments whose ends are in `B`. -/ def is_extreme (A B : set E) : Prop := B ⊆ A ∧ ∀ x₁ x₂ ∈ A, ∀ x ∈ B, x ∈ open_segment 𝕜 x₁ x₂ → x₁ ∈ B ∧ x₂ ∈ B /-- A point `x` is an extreme point of a set `A` if `x` belongs to no open segment with ends in `A`, except for the obvious `open_segment x x`. -/ def set.extreme_points (A : set E) : set E := {x ∈ A | ∀ (x₁ x₂ ∈ A), x ∈ open_segment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x} @[refl] protected lemma is_extreme.refl (A : set E) : is_extreme 𝕜 A A := ⟨subset.rfl, λ x₁ hx₁A x₂ hx₂A x hxA hx, ⟨hx₁A, hx₂A⟩⟩ variables {𝕜} {A B C : set E} {x : E} protected lemma is_extreme.rfl : is_extreme 𝕜 A A := is_extreme.refl 𝕜 A @[trans] protected lemma is_extreme.trans (hAB : is_extreme 𝕜 A B) (hBC : is_extreme 𝕜 B C) : is_extreme 𝕜 A C := begin refine ⟨subset.trans hBC.1 hAB.1, λ x₁ hx₁A x₂ hx₂A x hxC hx, _⟩, obtain ⟨hx₁B, hx₂B⟩ := hAB.2 x₁ hx₁A x₂ hx₂A x (hBC.1 hxC) hx, exact hBC.2 x₁ hx₁B x₂ hx₂B x hxC hx, end protected lemma is_extreme.antisymm : anti_symmetric (is_extreme 𝕜 : set E → set E → Prop) := λ A B hAB hBA, subset.antisymm hBA.1 hAB.1 instance : is_partial_order (set E) (is_extreme 𝕜) := { refl := is_extreme.refl 𝕜, trans := λ A B C, is_extreme.trans, antisymm := is_extreme.antisymm } lemma is_extreme.inter (hAB : is_extreme 𝕜 A B) (hAC : is_extreme 𝕜 A C) : is_extreme 𝕜 A (B ∩ C) := begin use subset.trans (inter_subset_left _ _) hAB.1, rintro x₁ x₂ hx₁A hx₂A x ⟨hxB, hxC⟩ hx, obtain ⟨hx₁B, hx₂B⟩ := hAB.2 x₁ x₂ hx₁A hx₂A x hxB hx, obtain ⟨hx₁C, hx₂C⟩ := hAC.2 x₁ x₂ hx₁A hx₂A x hxC hx, exact ⟨⟨hx₁B, hx₁C⟩, hx₂B, hx₂C⟩, end protected lemma is_extreme.mono (hAC : is_extreme 𝕜 A C) (hBA : B ⊆ A) (hCB : C ⊆ B) : is_extreme 𝕜 B C := ⟨hCB, λ x₁ hx₁B x₂ hx₂B x hxC hx, hAC.2 x₁ (hBA hx₁B) x₂ (hBA hx₂B) x hxC hx⟩ lemma is_extreme_Inter {ι : Type*} [nonempty ι] {F : ι → set E} (hAF : ∀ i : ι, is_extreme 𝕜 A (F i)) : is_extreme 𝕜 A (⋂ i : ι, F i) := begin obtain i := classical.arbitrary ι, use Inter_subset_of_subset i (hAF i).1, rintro x₁ x₂ hx₁A hx₂A x hxF hx, simp_rw mem_Inter at ⊢ hxF, have h := λ i, (hAF i).2 x₁ x₂ hx₁A hx₂A x (hxF i) hx, exact ⟨λ i, (h i).1, λ i, (h i).2⟩, end lemma is_extreme_bInter {F : set (set E)} (hF : F.nonempty) (hAF : ∀ B ∈ F, is_extreme 𝕜 A B) : is_extreme 𝕜 A (⋂ B ∈ F, B) := begin obtain ⟨B, hB⟩ := hF, refine ⟨(bInter_subset_of_mem hB).trans (hAF B hB).1, λ x₁ x₂ hx₁A hx₂A x hxF hx, _⟩, simp_rw mem_Inter₂ at ⊢ hxF, have h := λ B hB, (hAF B hB).2 x₁ x₂ hx₁A hx₂A x (hxF B hB) hx, exact ⟨λ B hB, (h B hB).1, λ B hB, (h B hB).2⟩, end lemma is_extreme_sInter {F : set (set E)} (hF : F.nonempty) (hAF : ∀ B ∈ F, is_extreme 𝕜 A B) : is_extreme 𝕜 A (⋂₀ F) := begin obtain ⟨B, hB⟩ := hF, refine ⟨(sInter_subset_of_mem hB).trans (hAF B hB).1, λ x₁ x₂ hx₁A hx₂A x hxF hx, _⟩, simp_rw mem_sInter at ⊢ hxF, have h := λ B hB, (hAF B hB).2 x₁ x₂ hx₁A hx₂A x (hxF B hB) hx, exact ⟨λ B hB, (h B hB).1, λ B hB, (h B hB).2⟩, end lemma extreme_points_def : x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ ∀ (x₁ x₂ ∈ A), x ∈ open_segment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x := iff.rfl /-- x is an extreme point to A iff {x} is an extreme set of A. -/ lemma mem_extreme_points_iff_extreme_singleton : x ∈ A.extreme_points 𝕜 ↔ is_extreme 𝕜 A {x} := begin refine ⟨_, λ hx, ⟨singleton_subset_iff.1 hx.1, λ x₁ x₂ hx₁ hx₂, hx.2 x₁ x₂ hx₁ hx₂ x rfl⟩⟩, rintro ⟨hxA, hAx⟩, use singleton_subset_iff.2 hxA, rintro x₁ x₂ hx₁A hx₂A y (rfl : y = x), exact hAx x₁ x₂ hx₁A hx₂A, end lemma extreme_points_subset : A.extreme_points 𝕜 ⊆ A := λ x hx, hx.1 @[simp] lemma extreme_points_empty : (∅ : set E).extreme_points 𝕜 = ∅ := subset_empty_iff.1 extreme_points_subset @[simp] lemma extreme_points_singleton : ({x} : set E).extreme_points 𝕜 = {x} := extreme_points_subset.antisymm $ singleton_subset_iff.2 ⟨mem_singleton x, λ x₁ hx₁ x₂ hx₂ _, ⟨hx₁, hx₂⟩⟩ lemma inter_extreme_points_subset_extreme_points_of_subset (hBA : B ⊆ A) : B ∩ A.extreme_points 𝕜 ⊆ B.extreme_points 𝕜 := λ x ⟨hxB, hxA⟩, ⟨hxB, λ x₁ hx₁ x₂ hx₂ hx, hxA.2 x₁ (hBA hx₁) x₂ (hBA hx₂) hx⟩ lemma is_extreme.extreme_points_subset_extreme_points (hAB : is_extreme 𝕜 A B) : B.extreme_points 𝕜 ⊆ A.extreme_points 𝕜 := λ x hx, mem_extreme_points_iff_extreme_singleton.2 (hAB.trans (mem_extreme_points_iff_extreme_singleton.1 hx)) lemma is_extreme.extreme_points_eq (hAB : is_extreme 𝕜 A B) : B.extreme_points 𝕜 = B ∩ A.extreme_points 𝕜 := subset.antisymm (λ x hx, ⟨hx.1, hAB.extreme_points_subset_extreme_points hx⟩) (inter_extreme_points_subset_extreme_points_of_subset hAB.1) end has_scalar section ordered_semiring variables {𝕜} [ordered_semiring 𝕜] [add_comm_group E] [module 𝕜 E] {A B : set E} {x : E} lemma is_extreme.convex_diff (hA : convex 𝕜 A) (hAB : is_extreme 𝕜 A B) : convex 𝕜 (A \ B) := convex_iff_open_segment_subset.2 (λ x₁ x₂ ⟨hx₁A, hx₁B⟩ ⟨hx₂A, hx₂B⟩ x hx, ⟨hA.open_segment_subset hx₁A hx₂A hx, λ hxB, hx₁B (hAB.2 x₁ hx₁A x₂ hx₂A x hxB hx).1⟩) end ordered_semiring section linear_ordered_ring variables {𝕜} [linear_ordered_ring 𝕜] [add_comm_group E] [module 𝕜 E] variables [densely_ordered 𝕜] [no_zero_smul_divisors 𝕜 E] {A B : set E} {x : E} /-- A useful restatement using `segment`: `x` is an extreme point iff the only (closed) segments that contain it are those with `x` as one of their endpoints. -/ lemma mem_extreme_points_iff_forall_segment : x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ ∀ (x₁ x₂ ∈ A), x ∈ segment 𝕜 x₁ x₂ → x₁ = x ∨ x₂ = x := begin refine and_congr_right (λ hxA, forall₄_congr $ λ x₁ h₁ x₂ h₂, _), split, { rw ← insert_endpoints_open_segment, rintro H (rfl|rfl|hx), exacts [or.inl rfl, or.inr rfl, or.inl $ (H hx).1] }, { intros H hx, rcases H (open_segment_subset_segment _ _ _ hx) with rfl | rfl, exacts [⟨rfl, (left_mem_open_segment_iff.1 hx).symm⟩, ⟨right_mem_open_segment_iff.1 hx, rfl⟩] } end lemma convex.mem_extreme_points_iff_convex_diff (hA : convex 𝕜 A) : x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ convex 𝕜 (A \ {x}) := begin use λ hx, ⟨hx.1, (mem_extreme_points_iff_extreme_singleton.1 hx).convex_diff hA⟩, rintro ⟨hxA, hAx⟩, refine mem_extreme_points_iff_forall_segment.2 ⟨hxA, λ x₁ hx₁ x₂ hx₂ hx, _⟩, rw convex_iff_segment_subset at hAx, by_contra' h, exact (hAx ⟨hx₁, λ hx₁, h.1 (mem_singleton_iff.2 hx₁)⟩ ⟨hx₂, λ hx₂, h.2 (mem_singleton_iff.2 hx₂)⟩ hx).2 rfl, end lemma convex.mem_extreme_points_iff_mem_diff_convex_hull_diff (hA : convex 𝕜 A) : x ∈ A.extreme_points 𝕜 ↔ x ∈ A \ convex_hull 𝕜 (A \ {x}) := by rw [hA.mem_extreme_points_iff_convex_diff, hA.convex_remove_iff_not_mem_convex_hull_remove, mem_diff] lemma extreme_points_convex_hull_subset : (convex_hull 𝕜 A).extreme_points 𝕜 ⊆ A := begin rintro x hx, rw (convex_convex_hull 𝕜 _).mem_extreme_points_iff_convex_diff at hx, by_contra, exact (convex_hull_min (subset_diff.2 ⟨subset_convex_hull 𝕜 _, disjoint_singleton_right.2 h⟩) hx.2 hx.1).2 rfl, apply_instance end end linear_ordered_ring
34bd7446e7b165737d82b2dd7eb80c0285ae786d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/localization/integer.lean
65928aeded7b10b3951cd0f9cd8adf6fe8b1cf80
[ "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
5,501
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import ring_theory.localization.basic /-! # Integer elements of a localization > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions * `is_localization.is_integer` is a predicate stating that `x : S` is in the image of `R` ## Implementation notes See `src/ring_theory/localization/basic.lean` for a design overview. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] {M : submonoid R} {S : Type*} [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] open function open_locale big_operators namespace is_localization section variables (R) {M S} -- TODO: define a subalgebra of `is_integer`s /-- Given `a : S`, `S` a localization of `R`, `is_integer R a` iff `a` is in the image of the localization map from `R` to `S`. -/ def is_integer (a : S) : Prop := a ∈ (algebra_map R S).range end lemma is_integer_zero : is_integer R (0 : S) := subring.zero_mem _ lemma is_integer_one : is_integer R (1 : S) := subring.one_mem _ lemma is_integer_add {a b : S} (ha : is_integer R a) (hb : is_integer R b) : is_integer R (a + b) := subring.add_mem _ ha hb lemma is_integer_mul {a b : S} (ha : is_integer R a) (hb : is_integer R b) : is_integer R (a * b) := subring.mul_mem _ ha hb lemma is_integer_smul {a : R} {b : S} (hb : is_integer R b) : is_integer R (a • b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, (algebra_map R S).map_mul, algebra.smul_def] end variables (M) {S} [is_localization M S] /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the right, matching the argument order in `localization_map.surj`. -/ lemma exists_integer_multiple' (a : S) : ∃ (b : M), is_integer R (a * algebra_map R S b) := let ⟨⟨num, denom⟩, h⟩ := is_localization.surj _ a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩ /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the left, matching the argument order in the `has_smul` instance. -/ lemma exists_integer_multiple (a : S) : ∃ (b : M), is_integer R ((b : R) • a) := by { simp_rw [algebra.smul_def, mul_comm _ a], apply exists_integer_multiple' } /-- We can clear the denominators of a `finset`-indexed family of fractions. -/ lemma exist_integer_multiples {ι : Type*} (s : finset ι) (f : ι → S) : ∃ (b : M), ∀ i ∈ s, is_localization.is_integer R ((b : R) • f i) := begin haveI := classical.prop_decidable, refine ⟨∏ i in s, (sec M (f i)).2, λ i hi, ⟨_, _⟩⟩, { exact (∏ j in s.erase i, (sec M (f j)).2) * (sec M (f i)).1 }, rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←(algebra_map R S).map_mul, ← algebra.smul_def], congr' 2, refine trans _ ((submonoid.subtype M).map_prod _ _).symm, rw [mul_comm, ←finset.prod_insert (s.not_mem_erase i), finset.insert_erase hi], refl end /-- We can clear the denominators of a finite indexed family of fractions. -/ lemma exist_integer_multiples_of_finite {ι : Type*} [finite ι] (f : ι → S) : ∃ (b : M), ∀ i, is_localization.is_integer R ((b : R) • f i) := begin casesI nonempty_fintype ι, obtain ⟨b, hb⟩ := exist_integer_multiples M finset.univ f, exact ⟨b, λ i, hb i (finset.mem_univ _)⟩ end /-- We can clear the denominators of a finite set of fractions. -/ lemma exist_integer_multiples_of_finset (s : finset S) : ∃ (b : M), ∀ a ∈ s, is_integer R ((b : R) • a) := exist_integer_multiples M s id /-- A choice of a common multiple of the denominators of a `finset`-indexed family of fractions. -/ noncomputable def common_denom {ι : Type*} (s : finset ι) (f : ι → S) : M := (exist_integer_multiples M s f).some /-- The numerator of a fraction after clearing the denominators of a `finset`-indexed family of fractions. -/ noncomputable def integer_multiple {ι : Type*} (s : finset ι) (f : ι → S) (i : s) : R := ((exist_integer_multiples M s f).some_spec i i.prop).some @[simp] lemma map_integer_multiple {ι : Type*} (s : finset ι) (f : ι → S) (i : s) : algebra_map R S (integer_multiple M s f i) = common_denom M s f • f i := ((exist_integer_multiples M s f).some_spec _ i.prop).some_spec /-- A choice of a common multiple of the denominators of a finite set of fractions. -/ noncomputable def common_denom_of_finset (s : finset S) : M := common_denom M s id /-- The finset of numerators after clearing the denominators of a finite set of fractions. -/ noncomputable def finset_integer_multiple [decidable_eq R] (s : finset S) : finset R := s.attach.image (λ t, integer_multiple M s id t) open_locale pointwise lemma finset_integer_multiple_image [decidable_eq R] (s : finset S) : algebra_map R S '' (finset_integer_multiple M s) = common_denom_of_finset M s • s := begin delta finset_integer_multiple common_denom, rw finset.coe_image, ext, split, { rintro ⟨_, ⟨x, -, rfl⟩, rfl⟩, rw map_integer_multiple, exact set.mem_image_of_mem _ x.prop }, { rintro ⟨x, hx, rfl⟩, exact ⟨_, ⟨⟨x, hx⟩, s.mem_attach _, rfl⟩, map_integer_multiple M s id _⟩ } end end is_localization
a7c7bf63d02bc0c9d6dc7c17db1eddac400a9b10
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/omega/misc.lean
2931b7282e1eb79ed7eaa8a72f7ee2b71fd36163
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,161
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- Miscellaneous. -/ import tactic.localized variables {α β γ : Type} namespace omega lemma fun_mono_2 {p : α → β → γ} {a1 a2 : α} {b1 b2 : β} : a1 = a2 → b1 = b2 → (p a1 b1 = p a2 b2) := λ h1 h2, by rw [h1, h2] lemma pred_mono_2 {p : α → β → Prop} {a1 a2 : α} {b1 b2 : β} : a1 = a2 → b1 = b2 → (p a1 b1 ↔ p a2 b2) := λ h1 h2, by rw [h1, h2] lemma pred_mono_2' {c : Prop → Prop → Prop} {a1 a2 b1 b2 : Prop} : (a1 ↔ a2) → (b1 ↔ b2) → (c a1 b1 ↔ c a2 b2) := λ h1 h2, by rw [h1, h2] /-- Update variable assignment for a specific variable and leave everything else unchanged -/ def update (m : nat) (a : α) (v : nat → α) : nat → α | n := if n = m then a else v n localized "notation (name := omega.update) v ` ⟨`m` ↦ `a`⟩` := omega.update m a v" in omega lemma update_eq (m : nat) (a : α) (v : nat → α) : (v ⟨m ↦ a⟩) m = a := by simp only [update, if_pos rfl] lemma update_eq_of_ne {m : nat} {a : α} {v : nat → α} (k : nat) : k ≠ m → update m a v k = v k := by {intro h1, unfold update, rw if_neg h1} /-- Assign a new value to the zeroth variable, and push all other assignments up by 1 -/ def update_zero (a : α) (v : nat → α) : nat → α | 0 := a | (k+1) := v k open tactic /-- Intro with a fresh name -/ meta def intro_fresh : tactic unit := do n ← mk_fresh_name, intro n, skip /-- Revert an expr if it passes the given test -/ meta def revert_cond (t : expr → tactic unit) (x : expr) : tactic unit := (t x >> revert x >> skip) <|> skip /-- Revert all exprs in the context that pass the given test -/ meta def revert_cond_all (t : expr → tactic unit) : tactic unit := do hs ← local_context, mmap (revert_cond t) hs, skip /-- Try applying a tactic to each of the element in a list until success, and return the first successful result -/ meta def app_first {α β : Type} (t : α → tactic β) : list α → tactic β | [] := failed | (a :: as) := t a <|> app_first as end omega
e831bf04493240f4a6ce6b17c00a5632030e586a
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/group/pi.lean
67837111d62309d76b6dc6e81fe52e3def805e3c
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
9,137
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import data.pi import data.set.function import tactic.pi_instances import algebra.group.hom_instances /-! # Pi instances for groups and monoids This file defines instances for group, monoid, semigroup and related structures on Pi types. -/ universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) namespace pi @[to_additive] instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field instance semigroup_with_zero [∀ i, semigroup_with_zero $ f i] : semigroup_with_zero (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance mul_one_class [∀ i, mul_one_class $ f i] : mul_one_class (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) }; tactic.pi_instance_derive_field @[simp] lemma pow_apply [∀ i, monoid $ f i] (n : ℕ) : (x^n) i = (x i)^n := begin induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end @[to_additive] instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) }; tactic.pi_instance_derive_field @[to_additive] instance div_inv_monoid [∀ i, div_inv_monoid $ f i] : div_inv_monoid (Π i : I, f i) := { div_eq_mul_inv := λ x y, funext (λ i, div_eq_mul_inv (x i) (y i)), .. pi.monoid, .. pi.has_div, .. pi.has_inv } @[to_additive] instance group [∀ i, group $ f i] : group (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, div := has_div.div, npow := λ n x i, npow n (x i), gpow := λ n x i, gpow n (x i) }; tactic.pi_instance_derive_field @[to_additive] instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, div := has_div.div, npow := λ n x i, npow n (x i), gpow := λ n x i, gpow n (x i) }; tactic.pi_instance_derive_field @[to_additive add_left_cancel_semigroup] instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) := by refine_struct { mul := (*) }; tactic.pi_instance_derive_field @[to_additive add_right_cancel_semigroup] instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) := by refine_struct { mul := (*) }; tactic.pi_instance_derive_field @[to_additive add_left_cancel_monoid] instance left_cancel_monoid [∀ i, left_cancel_monoid $ f i] : left_cancel_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) }; tactic.pi_instance_derive_field @[to_additive add_right_cancel_monoid] instance right_cancel_monoid [∀ i, right_cancel_monoid $ f i] : right_cancel_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i), .. }; tactic.pi_instance_derive_field @[to_additive add_cancel_monoid] instance cancel_monoid [∀ i, cancel_monoid $ f i] : cancel_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) }; tactic.pi_instance_derive_field @[to_additive add_cancel_comm_monoid] instance cancel_comm_monoid [∀ i, cancel_comm_monoid $ f i] : cancel_comm_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) }; tactic.pi_instance_derive_field instance mul_zero_class [∀ i, mul_zero_class $ f i] : mul_zero_class (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field instance mul_zero_one_class [∀ i, mul_zero_one_class $ f i] : mul_zero_one_class (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field instance monoid_with_zero [∀ i, monoid_with_zero $ f i] : monoid_with_zero (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) }; tactic.pi_instance_derive_field instance comm_monoid_with_zero [∀ i, comm_monoid_with_zero $ f i] : comm_monoid_with_zero (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) }; tactic.pi_instance_derive_field section instance_lemmas open function variables {α β γ : Type*} @[simp, to_additive] lemma const_one [has_one β] : const α (1 : β) = 1 := rfl @[simp, to_additive] lemma comp_one [has_one β] {f : β → γ} : f ∘ 1 = const α (f 1) := rfl @[simp, to_additive] lemma one_comp [has_one γ] {f : α → β} : (1 : β → γ) ∘ f = 1 := rfl end instance_lemmas end pi section monoid_hom variables (f) [Π i, mul_one_class (f i)] /-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. This is `function.eval i` as a `monoid_hom`. -/ @[to_additive "Evaluation of functions into an indexed collection of additive monoids at a point is an additive monoid homomorphism. This is `function.eval i` as an `add_monoid_hom`.", simps] def pi.eval_monoid_hom (i : I) : (Π i, f i) →* f i := { to_fun := λ g, g i, map_one' := pi.one_apply i, map_mul' := λ x y, pi.mul_apply _ _ i, } /-- Coercion of a `monoid_hom` into a function is itself a `monoid_hom`. See also `monoid_hom.eval`. -/ @[to_additive "Coercion of an `add_monoid_hom` into a function is itself a `add_monoid_hom`. See also `add_monoid_hom.eval`. ", simps] def monoid_hom.coe_fn (α β : Type*) [mul_one_class α] [comm_monoid β] : (α →* β) →* (α → β) := { to_fun := λ g, g, map_one' := rfl, map_mul' := λ x y, rfl, } end monoid_hom section single variables [decidable_eq I] open pi variables (f) /-- The zero-preserving homomorphism including a single value into a dependent family of values, as functions supported at a point. This is the `zero_hom` version of `pi.single`. -/ @[simps] def zero_hom.single [Π i, has_zero $ f i] (i : I) : zero_hom (f i) (Π i, f i) := { to_fun := single i, map_zero' := single_zero i } /-- The additive monoid homomorphism including a single additive monoid into a dependent family of additive monoids, as functions supported at a point. This is the `add_monoid_hom` version of `pi.single`. -/ @[simps] def add_monoid_hom.single [Π i, add_zero_class $ f i] (i : I) : f i →+ Π i, f i := { to_fun := single i, map_add' := single_op₂ (λ _, (+)) (λ _, zero_add _) _, .. (zero_hom.single f i) } /-- The multiplicative homomorphism including a single `mul_zero_class` into a dependent family of `mul_zero_class`es, as functions supported at a point. This is the `mul_hom` version of `pi.single`. -/ @[simps] def mul_hom.single [Π i, mul_zero_class $ f i] (i : I) : mul_hom (f i) (Π i, f i) := { to_fun := single i, map_mul' := single_op₂ (λ _, (*)) (λ _, zero_mul _) _, } variables {f} lemma pi.single_add [Π i, add_zero_class $ f i] (i : I) (x y : f i) : single i (x + y) = single i x + single i y := (add_monoid_hom.single f i).map_add x y lemma pi.single_neg [Π i, add_group $ f i] (i : I) (x : f i) : single i (-x) = -single i x := (add_monoid_hom.single f i).map_neg x lemma pi.single_sub [Π i, add_group $ f i] (i : I) (x y : f i) : single i (x - y) = single i x - single i y := (add_monoid_hom.single f i).map_sub x y lemma pi.single_mul [Π i, mul_zero_class $ f i] (i : I) (x y : f i) : single i (x * y) = single i x * single i y := (mul_hom.single f i).map_mul x y end single section piecewise @[to_additive] lemma set.piecewise_mul [Π i, has_mul (f i)] (s : set I) [Π i, decidable (i ∈ s)] (f₁ f₂ g₁ g₂ : Π i, f i) : s.piecewise (f₁ * f₂) (g₁ * g₂) = s.piecewise f₁ g₁ * s.piecewise f₂ g₂ := s.piecewise_op₂ _ _ _ _ (λ _, (*)) @[to_additive] lemma pi.piecewise_inv [Π i, has_inv (f i)] (s : set I) [Π i, decidable (i ∈ s)] (f₁ g₁ : Π i, f i) : s.piecewise (f₁⁻¹) (g₁⁻¹) = (s.piecewise f₁ g₁)⁻¹ := s.piecewise_op f₁ g₁ (λ _ x, x⁻¹) @[to_additive] lemma pi.piecewise_div [Π i, has_div (f i)] (s : set I) [Π i, decidable (i ∈ s)] (f₁ f₂ g₁ g₂ : Π i, f i) : s.piecewise (f₁ / f₂) (g₁ / g₂) = s.piecewise f₁ g₁ / s.piecewise f₂ g₂ := s.piecewise_op₂ _ _ _ _ (λ _, (/)) end piecewise
e73585b3f4c5c50ed833533d911e7569b59b545d
94637389e03c919023691dcd05bd4411b1034aa5
/src/zzz_junk/04_type_library/04_box.lean
317fe49f05ece31f7a0a65f55d0feda345abca0e
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
410
lean
namespace hidden /- This polymorpmic box type allows one to enclose/wrap a value of any ordinary computational type (of type, Type) "in" a box structure. Using "structure" to define this type as specified here provide a projection function with the same name, val, as the field who value it projects (i.e., accesses and returns). -/ universe u structure box (α : Type u) : Type u := (val : α) end hidden
bf939b2e25ec2578e1b985240db157ff8a0afc66
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/types/num.hlean
dc7b8b10ac85a355931a3c0bacfd4810fe2edf0f
[ "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
17,884
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import types.bool tools.helper_tactics open bool eq eq.ops decidable helper_tactics namespace pos_num theorem succ_not_is_one (a : pos_num) : is_one (succ a) = ff := pos_num.rec_on a rfl (take n iH, rfl) (take n iH, rfl) theorem succ_one : succ one = bit0 one theorem succ_bit1 (a : pos_num) : succ (bit1 a) = bit0 (succ a) theorem succ_bit0 (a : pos_num) : succ (bit0 a) = bit1 a theorem ne_of_bit0_ne_bit0 {a b : pos_num} (H₁ : bit0 a ≠ bit0 b) : a ≠ b := suppose a = b, absurd rfl (this ▸ H₁) theorem ne_of_bit1_ne_bit1 {a b : pos_num} (H₁ : bit1 a ≠ bit1 b) : a ≠ b := suppose a = b, absurd rfl (this ▸ H₁) theorem pred_succ : Π (a : pos_num), pred (succ a) = a | one := rfl | (bit0 a) := by rewrite succ_bit0 | (bit1 a) := calc pred (succ (bit1 a)) = cond (is_one (succ a)) one (bit1 (pred (succ a))) : rfl ... = cond ff one (bit1 (pred (succ a))) : succ_not_is_one ... = bit1 (pred (succ a)) : rfl ... = bit1 a : pred_succ a section variables (a b : pos_num) theorem one_add_one : one + one = bit0 one theorem one_add_bit0 : one + (bit0 a) = bit1 a theorem one_add_bit1 : one + (bit1 a) = succ (bit1 a) theorem bit0_add_one : (bit0 a) + one = bit1 a theorem bit1_add_one : (bit1 a) + one = succ (bit1 a) theorem bit0_add_bit0 : (bit0 a) + (bit0 b) = bit0 (a + b) theorem bit0_add_bit1 : (bit0 a) + (bit1 b) = bit1 (a + b) theorem bit1_add_bit0 : (bit1 a) + (bit0 b) = bit1 (a + b) theorem bit1_add_bit1 : (bit1 a) + (bit1 b) = succ (bit1 (a + b)) theorem one_mul : one * a = a end theorem mul_one : Π a, a * one = a | one := rfl | (bit1 n) := calc bit1 n * one = bit0 (n * one) + one : rfl ... = bit0 n + one : mul_one n ... = bit1 n : bit0_add_one | (bit0 n) := calc bit0 n * one = bit0 (n * one) : rfl ... = bit0 n : mul_one n theorem decidable_eq [instance] : Π (a b : pos_num), decidable (a = b) | one one := inl rfl | one (bit0 b) := inr (by contradiction) | one (bit1 b) := inr (by contradiction) | (bit0 a) one := inr (by contradiction) | (bit0 a) (bit0 b) := match decidable_eq a b with | inl H₁ := inl (by rewrite H₁) | inr H₁ := inr (by intro H; injection H; contradiction) end | (bit0 a) (bit1 b) := inr (by contradiction) | (bit1 a) one := inr (by contradiction) | (bit1 a) (bit0 b) := inr (by contradiction) | (bit1 a) (bit1 b) := match decidable_eq a b with | inl H₁ := inl (by rewrite H₁) | inr H₁ := inr (by intro H; injection H; contradiction) end local notation a < b := (lt a b = tt) local notation a ` ≮ `:50 b:50 := (lt a b = ff) theorem lt_one_right_eq_ff : Π a : pos_num, a ≮ one | one := rfl | (bit0 a) := rfl | (bit1 a) := rfl theorem lt_one_succ_eq_tt : Π a : pos_num, one < succ a | one := rfl | (bit0 a) := rfl | (bit1 a) := rfl theorem lt_of_lt_bit0_bit0 {a b : pos_num} (H : bit0 a < bit0 b) : a < b := H theorem lt_of_lt_bit0_bit1 {a b : pos_num} (H : bit1 a < bit0 b) : a < b := H theorem lt_of_lt_bit1_bit1 {a b : pos_num} (H : bit1 a < bit1 b) : a < b := H theorem lt_of_lt_bit1_bit0 {a b : pos_num} (H : bit0 a < bit1 b) : a < succ b := H theorem lt_bit0_bit0_eq_lt (a b : pos_num) : lt (bit0 a) (bit0 b) = lt a b := rfl theorem lt_bit1_bit1_eq_lt (a b : pos_num) : lt (bit1 a) (bit1 b) = lt a b := rfl theorem lt_bit1_bit0_eq_lt (a b : pos_num) : lt (bit1 a) (bit0 b) = lt a b := rfl theorem lt_bit0_bit1_eq_lt_succ (a b : pos_num) : lt (bit0 a) (bit1 b) = lt a (succ b) := rfl theorem lt_irrefl : Π (a : pos_num), a ≮ a | one := rfl | (bit0 a) := begin rewrite lt_bit0_bit0_eq_lt, apply lt_irrefl end | (bit1 a) := begin rewrite lt_bit1_bit1_eq_lt, apply lt_irrefl end theorem ne_of_lt_eq_tt : Π {a b : pos_num}, a < b → a = b → empty | one ⌞one⌟ H₁ (eq.refl one) := absurd H₁ ff_ne_tt | (bit0 a) ⌞(bit0 a)⌟ H₁ (eq.refl (bit0 a)) := begin rewrite lt_bit0_bit0_eq_lt at H₁, apply ne_of_lt_eq_tt H₁ (eq.refl a) end | (bit1 a) ⌞(bit1 a)⌟ H₁ (eq.refl (bit1 a)) := begin rewrite lt_bit1_bit1_eq_lt at H₁, apply ne_of_lt_eq_tt H₁ (eq.refl a) end theorem lt_base : Π a : pos_num, a < succ a | one := rfl | (bit0 a) := begin rewrite [succ_bit0, lt_bit0_bit1_eq_lt_succ], apply lt_base end | (bit1 a) := begin rewrite [succ_bit1, lt_bit1_bit0_eq_lt], apply lt_base end theorem lt_step : Π {a b : pos_num}, a < b → a < succ b | one one H := rfl | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := begin rewrite [succ_bit0, lt_bit0_bit1_eq_lt_succ, lt_bit0_bit0_eq_lt at H], apply lt_step H end | (bit0 a) (bit1 b) H := begin rewrite [succ_bit1, lt_bit0_bit0_eq_lt, lt_bit0_bit1_eq_lt_succ at H], exact H end | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite [succ_bit0, lt_bit1_bit1_eq_lt, lt_bit1_bit0_eq_lt at H], exact H end | (bit1 a) (bit1 b) H := begin rewrite [succ_bit1, lt_bit1_bit0_eq_lt, lt_bit1_bit1_eq_lt at H], apply lt_step H end theorem lt_of_lt_succ_succ : Π {a b : pos_num}, succ a < succ b → a < b | one one H := absurd H ff_ne_tt | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := begin rewrite [succ_bit0 at H, succ_one at H, lt_bit1_bit0_eq_lt at H], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H end | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := by exact H | (bit1 a) one H := begin rewrite [succ_bit1 at H, succ_one at H, lt_bit0_bit0_eq_lt at H], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff (succ a)) H end | (bit1 a) (bit0 b) H := begin rewrite [succ_bit1 at H, succ_bit0 at H, lt_bit0_bit1_eq_lt_succ at H], rewrite lt_bit1_bit0_eq_lt, apply lt_of_lt_succ_succ H end | (bit1 a) (bit1 b) H := begin rewrite [lt_bit1_bit1_eq_lt, *succ_bit1 at H, lt_bit0_bit0_eq_lt at H], apply lt_of_lt_succ_succ H end theorem lt_succ_succ : Π {a b : pos_num}, a < b → succ a < succ b | one one H := absurd H ff_ne_tt | one (bit0 b) H := begin rewrite [succ_bit0, succ_one, lt_bit0_bit1_eq_lt_succ], apply lt_one_succ_eq_tt end | one (bit1 b) H := begin rewrite [succ_one, succ_bit1, lt_bit0_bit0_eq_lt], apply lt_one_succ_eq_tt end | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := by exact H | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite [succ_bit1, succ_bit0, lt_bit0_bit1_eq_lt_succ, lt_bit1_bit0_eq_lt at H], apply lt_succ_succ H end | (bit1 a) (bit1 b) H := begin rewrite [lt_bit1_bit1_eq_lt at H, *succ_bit1, lt_bit0_bit0_eq_lt], apply lt_succ_succ H end theorem lt_of_lt_succ : Π {a b : pos_num}, succ a < b → a < b | one one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := begin rewrite [succ_bit0 at H, lt_bit1_bit1_eq_lt at H, lt_bit0_bit1_eq_lt_succ], apply lt_step H end | (bit1 a) one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | (bit1 a) (bit0 b) H := begin rewrite [lt_bit1_bit0_eq_lt, succ_bit1 at H, lt_bit0_bit0_eq_lt at H], apply lt_of_lt_succ H end | (bit1 a) (bit1 b) H := begin rewrite [succ_bit1 at H, lt_bit0_bit1_eq_lt_succ at H, lt_bit1_bit1_eq_lt], apply lt_of_lt_succ_succ H end theorem lt_of_lt_succ_of_ne : Π {a b : pos_num}, a < succ b → a ≠ b → a < b | one one H₁ H₂ := absurd rfl H₂ | one (bit0 b) H₁ H₂ := rfl | one (bit1 b) H₁ H₂ := rfl | (bit0 a) one H₁ H₂ := begin rewrite [succ_one at H₁, lt_bit0_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [lt_bit0_bit0_eq_lt, succ_bit0 at H₁, lt_bit0_bit1_eq_lt_succ at H₁], apply lt_of_lt_succ_of_ne H₁ (ne_of_bit0_ne_bit0 H₂) end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [succ_bit1 at H₁, lt_bit0_bit0_eq_lt at H₁, lt_bit0_bit1_eq_lt_succ], exact H₁ end | (bit1 a) one H₁ H₂ := begin rewrite [succ_one at H₁, lt_bit1_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [succ_bit0 at H₁, lt_bit1_bit1_eq_lt at H₁, lt_bit1_bit0_eq_lt], exact H₁ end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [succ_bit1 at H₁, lt_bit1_bit0_eq_lt at H₁, lt_bit1_bit1_eq_lt], apply lt_of_lt_succ_of_ne H₁ (ne_of_bit1_ne_bit1 H₂) end theorem lt_trans : Π {a b c : pos_num}, a < b → b < c → a < c | one b (bit0 c) H₁ H₂ := rfl | one b (bit1 c) H₁ H₂ := rfl | a (bit0 b) one H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | a (bit1 b) one H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | (bit0 a) (bit0 b) (bit0 c) H₁ H₂ := begin rewrite lt_bit0_bit0_eq_lt at *, apply lt_trans H₁ H₂ end | (bit0 a) (bit0 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at *, lt_bit0_bit0_eq_lt at H₁], apply lt_trans H₁ H₂ end | (bit0 a) (bit1 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at H₁, lt_bit1_bit0_eq_lt at H₂, lt_bit0_bit0_eq_lt], apply @by_cases (a = b), begin intro H, rewrite -H at H₂, exact H₂ end, begin intro H, apply lt_trans (lt_of_lt_succ_of_ne H₁ H) H₂ end end | (bit0 a) (bit1 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at *, lt_bit1_bit1_eq_lt at H₂], apply lt_trans H₁ (lt_succ_succ H₂) end | (bit1 a) (bit0 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit0_bit0_eq_lt at H₂, lt_bit1_bit0_eq_lt at *], apply lt_trans H₁ H₂ end | (bit1 a) (bit0 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit1_bit0_eq_lt at H₁, lt_bit0_bit1_eq_lt_succ at H₂, lt_bit1_bit1_eq_lt], apply @by_cases (b = c), begin intro H, rewrite H at H₁, exact H₁ end, begin intro H, apply lt_trans H₁ (lt_of_lt_succ_of_ne H₂ H) end end | (bit1 a) (bit1 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit1_bit1_eq_lt at H₁, lt_bit1_bit0_eq_lt at H₂, lt_bit1_bit0_eq_lt], apply lt_trans H₁ H₂ end | (bit1 a) (bit1 b) (bit1 c) H₁ H₂ := begin rewrite lt_bit1_bit1_eq_lt at *, apply lt_trans H₁ H₂ end theorem lt_antisymm : Π {a b : pos_num}, a < b → b ≮ a | one one H := rfl | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := begin rewrite lt_bit0_bit0_eq_lt at *, apply lt_antisymm H end | (bit0 a) (bit1 b) H := begin rewrite lt_bit1_bit0_eq_lt, rewrite lt_bit0_bit1_eq_lt_succ at H, have H₁ : succ b ≮ a, from lt_antisymm H, apply eq_ff_of_ne_tt, intro H₂, apply @by_cases (succ b = a), show succ b = a → empty, begin intro Hp, rewrite -Hp at H, apply absurd_of_eq_ff_of_eq_tt (lt_irrefl (succ b)) H end, show succ b ≠ a → empty, begin intro Hn, have H₃ : succ b < succ a, from lt_succ_succ H₂, have H₄ : succ b < a, from lt_of_lt_succ_of_ne H₃ Hn, apply absurd_of_eq_ff_of_eq_tt H₁ H₄ end, end | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite lt_bit0_bit1_eq_lt_succ, rewrite lt_bit1_bit0_eq_lt at H, have H₁ : lt b a = ff, from lt_antisymm H, apply eq_ff_of_ne_tt, intro H₂, apply @by_cases (b = a), show b = a → empty, begin intro Hp, rewrite -Hp at H, apply absurd_of_eq_ff_of_eq_tt (lt_irrefl b) H end, show b ≠ a → empty, begin intro Hn, have H₃ : b < a, from lt_of_lt_succ_of_ne H₂ Hn, apply absurd_of_eq_ff_of_eq_tt H₁ H₃ end, end | (bit1 a) (bit1 b) H := begin rewrite lt_bit1_bit1_eq_lt at *, apply lt_antisymm H end local notation a ≤ b := (le a b = tt) theorem le_refl : Π a : pos_num, a ≤ a := lt_base theorem le_eq_lt_succ {a b : pos_num} : le a b = lt a (succ b) := rfl theorem not_lt_of_le : Π {a b : pos_num}, a ≤ b → b < a → empty | one one H₁ H₂ := absurd H₂ ff_ne_tt | one (bit0 b) H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | one (bit1 b) H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | (bit0 a) one H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_one at H₁, lt_bit0_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit0 at H₁, lt_bit0_bit1_eq_lt_succ at H₁], rewrite [lt_bit0_bit0_eq_lt at H₂], apply not_lt_of_le H₁ H₂ end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit1 at H₁, lt_bit0_bit0_eq_lt at H₁], rewrite [lt_bit1_bit0_eq_lt at H₂], apply not_lt_of_le H₁ H₂ end | (bit1 a) one H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_one at H₁, lt_bit1_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit0 at H₁, lt_bit1_bit1_eq_lt at H₁], rewrite lt_bit0_bit1_eq_lt_succ at H₂, have H₃ : a < succ b, from lt_step H₁, apply @by_cases (b = a), begin intro Hba, rewrite -Hba at H₁, apply absurd_of_eq_ff_of_eq_tt (lt_irrefl b) H₁ end, begin intro Hnba, have H₄ : b < a, from lt_of_lt_succ_of_ne H₂ Hnba, apply not_lt_of_le H₃ H₄ end end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit1 at H₁, lt_bit1_bit0_eq_lt at H₁], rewrite [lt_bit1_bit1_eq_lt at H₂], apply not_lt_of_le H₁ H₂ end theorem le_antisymm : Π {a b : pos_num}, a ≤ b → b ≤ a → a = b | one one H₁ H₂ := rfl | one (bit0 b) H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff b) H₂ | one (bit1 b) H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff b) H₂ | (bit0 a) one H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H₁ | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit0 at *, lt_bit0_bit1_eq_lt_succ at *], have H : a = b, from le_antisymm H₁ H₂, rewrite H end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit1 at H₁, succ_bit0 at H₂], rewrite [lt_bit0_bit0_eq_lt at H₁, lt_bit1_bit1_eq_lt at H₂], apply empty.rec _ (not_lt_of_le H₁ H₂) end | (bit1 a) one H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H₁ | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit0 at H₁, succ_bit1 at H₂], rewrite [lt_bit1_bit1_eq_lt at H₁, lt_bit0_bit0_eq_lt at H₂], apply empty.rec _ (not_lt_of_le H₂ H₁) end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit1 at *, lt_bit1_bit0_eq_lt at *], have H : a = b, from le_antisymm H₁ H₂, rewrite H end theorem le_trans {a b c : pos_num} : a ≤ b → b ≤ c → a ≤ c := begin intro H₁ H₂, rewrite [le_eq_lt_succ at *], apply @by_cases (a = b), begin intro Hab, rewrite Hab, exact H₂ end, begin intro Hnab, have Haltb : a < b, from lt_of_lt_succ_of_ne H₁ Hnab, apply lt_trans Haltb H₂ end, end end pos_num namespace num open pos_num theorem decidable_eq [instance] : Π (a b : num), decidable (a = b) | zero zero := inl rfl | zero (pos b) := inr (by contradiction) | (pos a) zero := inr (by contradiction) | (pos a) (pos b) := if H : a = b then inl (by rewrite H) else inr (suppose pos a = pos b, begin injection this, contradiction end) end num
d28f21985a22b78d2c9a455fa50fdcf5f7ae1b18
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/is_alg_closed/classification.lean
77d72392bc026fe07a19e9588eb6329cd4a0956f
[ "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
8,669
lean
/- Copyright (c) 2022 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import ring_theory.algebraic_independent import field_theory.is_alg_closed.basic import data.polynomial.cardinal import data.mv_polynomial.cardinal import data.zmod.algebra /-! # Classification of Algebraically closed fields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains results related to classifying algebraically closed fields. ## Main statements * `is_alg_closed.equiv_of_transcendence_basis` Two fields with the same characteristic and the same cardinality of transcendence basis are isomorphic. * `is_alg_closed.ring_equiv_of_cardinal_eq_of_char_eq` Two uncountable algebraically closed fields are isomorphic if they have the same characteristic and the same cardinality. -/ universe u open_locale cardinal polynomial open cardinal section algebraic_closure namespace algebra.is_algebraic variables (R L : Type u) [comm_ring R] [comm_ring L] [is_domain L] [algebra R L] variables [no_zero_smul_divisors R L] (halg : algebra.is_algebraic R L) lemma cardinal_mk_le_sigma_polynomial : #L ≤ #(Σ p : R[X], { x : L // x ∈ (p.map (algebra_map R L)).roots }) := @mk_le_of_injective L (Σ p : R[X], { x : L | x ∈ (p.map (algebra_map R L)).roots }) (λ x : L, let p := classical.indefinite_description _ (halg x) in ⟨p.1, x, begin dsimp, have h : p.1.map (algebra_map R L) ≠ 0, { rw [ne.def, ← polynomial.degree_eq_bot, polynomial.degree_map_eq_of_injective (no_zero_smul_divisors.algebra_map_injective R L), polynomial.degree_eq_bot], exact p.2.1 }, erw [polynomial.mem_roots h, polynomial.is_root, polynomial.eval_map, ← polynomial.aeval_def, p.2.2], end⟩) (λ x y, begin intro h, simp only at h, refine (subtype.heq_iff_coe_eq _).1 h.2, simp only [h.1, iff_self, forall_true_iff] end) /--The cardinality of an algebraic extension is at most the maximum of the cardinality of the base ring or `ℵ₀` -/ lemma cardinal_mk_le_max : #L ≤ max (#R) ℵ₀ := calc #L ≤ #(Σ p : R[X], { x : L // x ∈ (p.map (algebra_map R L)).roots }) : cardinal_mk_le_sigma_polynomial R L halg ... = cardinal.sum (λ p : R[X], #{ x : L | x ∈ (p.map (algebra_map R L)).roots }) : by rw ← mk_sigma; refl ... ≤ cardinal.sum.{u u} (λ p : R[X], ℵ₀) : sum_le_sum _ _ $ λ p, (multiset.finite_to_set _).lt_aleph_0.le ... = #R[X] * ℵ₀ : sum_const' _ _ ... ≤ max (max (#R[X]) ℵ₀) ℵ₀ : mul_le_max _ _ ... ≤ max (max (max (#R) ℵ₀) ℵ₀) ℵ₀ : max_le_max (max_le_max polynomial.cardinal_mk_le_max le_rfl) le_rfl ... = max (#R) ℵ₀ : by simp only [max_assoc, max_comm ℵ₀, max_left_comm ℵ₀, max_self] end algebra.is_algebraic end algebraic_closure namespace is_alg_closed section classification noncomputable theory variables {R L K : Type*} [comm_ring R] variables [field K] [algebra R K] variables [field L] [algebra R L] variables {ι : Type*} (v : ι → K) variables {κ : Type*} (w : κ → L) variables (hv : algebraic_independent R v) lemma is_alg_closure_of_transcendence_basis [is_alg_closed K] (hv : is_transcendence_basis R v) : is_alg_closure (algebra.adjoin R (set.range v)) K := by letI := ring_hom.domain_nontrivial (algebra_map R K); exact { alg_closed := by apply_instance, algebraic := hv.is_algebraic } variables (hw : algebraic_independent R w) /-- setting `R` to be `zmod (ring_char R)` this result shows that if two algebraically closed fields have equipotent transcendence bases and the same characteristic then they are isomorphic. -/ def equiv_of_transcendence_basis [is_alg_closed K] [is_alg_closed L] (e : ι ≃ κ) (hv : is_transcendence_basis R v) (hw : is_transcendence_basis R w) : K ≃+* L := begin letI := is_alg_closure_of_transcendence_basis v hv; letI := is_alg_closure_of_transcendence_basis w hw; have e : algebra.adjoin R (set.range v) ≃+* algebra.adjoin R (set.range w), { refine hv.1.aeval_equiv.symm.to_ring_equiv.trans _, refine (alg_equiv.of_alg_hom (mv_polynomial.rename e) (mv_polynomial.rename e.symm) _ _).to_ring_equiv.trans _, { ext, simp }, { ext, simp }, exact hw.1.aeval_equiv.to_ring_equiv }, exact is_alg_closure.equiv_of_equiv K L e end end classification section cardinal variables {R L K : Type u} [comm_ring R] variables [field K] [algebra R K] [is_alg_closed K] variables {ι : Type u} (v : ι → K) variable (hv : is_transcendence_basis R v) lemma cardinal_le_max_transcendence_basis (hv : is_transcendence_basis R v) : #K ≤ max (max (#R) (#ι)) ℵ₀ := calc #K ≤ max (#(algebra.adjoin R (set.range v))) ℵ₀ : by letI := is_alg_closure_of_transcendence_basis v hv; exact algebra.is_algebraic.cardinal_mk_le_max _ _ is_alg_closure.algebraic ... = max (#(mv_polynomial ι R)) ℵ₀ : by rw [cardinal.eq.2 ⟨(hv.1.aeval_equiv).to_equiv⟩] ... ≤ max (max (max (#R) (#ι)) ℵ₀) ℵ₀ : max_le_max mv_polynomial.cardinal_mk_le_max le_rfl ... = _ : by simp [max_assoc] /-- If `K` is an uncountable algebraically closed field, then its cardinality is the same as that of a transcendence basis. -/ lemma cardinal_eq_cardinal_transcendence_basis_of_aleph_0_lt [nontrivial R] (hv : is_transcendence_basis R v) (hR : #R ≤ ℵ₀) (hK : ℵ₀ < #K) : #K = #ι := have ℵ₀ ≤ #ι, from le_of_not_lt (λ h, not_le_of_gt hK $ calc #K ≤ max (max (#R) (#ι)) ℵ₀ : cardinal_le_max_transcendence_basis v hv ... ≤ _ : max_le (max_le hR (le_of_lt h)) le_rfl), le_antisymm (calc #K ≤ max (max (#R) (#ι)) ℵ₀ : cardinal_le_max_transcendence_basis v hv ... = #ι : begin rw [max_eq_left, max_eq_right], { exact le_trans hR this }, { exact le_max_of_le_right this } end) (mk_le_of_injective (show function.injective v, from hv.1.injective)) end cardinal variables {K L : Type} [field K] [field L] [is_alg_closed K] [is_alg_closed L] /-- Two uncountable algebraically closed fields of characteristic zero are isomorphic if they have the same cardinality. -/ lemma ring_equiv_of_cardinal_eq_of_char_zero [char_zero K] [char_zero L] (hK : ℵ₀ < #K) (hKL : #K = #L) : nonempty (K ≃+* L) := begin cases exists_is_transcendence_basis ℤ (show function.injective (algebra_map ℤ K), from int.cast_injective) with s hs, cases exists_is_transcendence_basis ℤ (show function.injective (algebra_map ℤ L), from int.cast_injective) with t ht, have : #s = #t, { rw [← cardinal_eq_cardinal_transcendence_basis_of_aleph_0_lt _ hs (le_of_eq mk_int) hK, ← cardinal_eq_cardinal_transcendence_basis_of_aleph_0_lt _ ht (le_of_eq mk_int), hKL], rwa ← hKL }, cases cardinal.eq.1 this with e, exact ⟨equiv_of_transcendence_basis _ _ e hs ht⟩ end private lemma ring_equiv_of_cardinal_eq_of_char_p (p : ℕ) [fact p.prime] [char_p K p] [char_p L p] (hK : ℵ₀ < #K) (hKL : #K = #L) : nonempty (K ≃+* L) := begin letI : algebra (zmod p) K := zmod.algebra _ _, letI : algebra (zmod p) L := zmod.algebra _ _, cases exists_is_transcendence_basis (zmod p) (show function.injective (algebra_map (zmod p) K), from ring_hom.injective _) with s hs, cases exists_is_transcendence_basis (zmod p) (show function.injective (algebra_map (zmod p) L), from ring_hom.injective _) with t ht, have : #s = #t, { rw [← cardinal_eq_cardinal_transcendence_basis_of_aleph_0_lt _ hs (lt_aleph_0_of_finite (zmod p)).le hK, ← cardinal_eq_cardinal_transcendence_basis_of_aleph_0_lt _ ht (lt_aleph_0_of_finite (zmod p)).le, hKL], rwa ← hKL }, cases cardinal.eq.1 this with e, exact ⟨equiv_of_transcendence_basis _ _ e hs ht⟩ end /-- Two uncountable algebraically closed fields are isomorphic if they have the same cardinality and the same characteristic. -/ lemma ring_equiv_of_cardinal_eq_of_char_eq (p : ℕ) [char_p K p] [char_p L p] (hK : ℵ₀ < #K) (hKL : #K = #L) : nonempty (K ≃+* L) := begin rcases char_p.char_is_prime_or_zero K p with hp | hp, { haveI : fact p.prime := ⟨hp⟩, letI : algebra (zmod p) K := zmod.algebra _ _, letI : algebra (zmod p) L := zmod.algebra _ _, exact ring_equiv_of_cardinal_eq_of_char_p p hK hKL }, { rw [hp] at *, resetI, letI : char_zero K := char_p.char_p_to_char_zero K, letI : char_zero L := char_p.char_p_to_char_zero L, exact ring_equiv_of_cardinal_eq_of_char_zero hK hKL } end end is_alg_closed
e3ff7e3e1c36281918376aa6601498580e1f26e8
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Init/Data/Nat/Div.lean
6aaeca4fb3274e96aba50d4fad7cbd969cab7238
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,185
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.WF import Init.Data.Nat.Basic namespace Nat private def divRecLemma {x y : Nat} : 0 < y ∧ y ≤ x → x - y < x := fun ⟨ypos, ylex⟩ => subLt (Nat.ltOfLtOfLe ypos ylex) ypos private def div.F (x : Nat) (f : ∀ x₁, x₁ < x → Nat → Nat) (y : Nat) : Nat := if h : 0 < y ∧ y ≤ x then f (x - y) (divRecLemma h) y + 1 else zero @[extern "lean_nat_div"] protected def div (a b : @& Nat) : Nat := WellFounded.fix ltWf div.F a b instance : Div Nat := ⟨Nat.div⟩ private theorem divDefAux (x y : Nat) : x / y = if h : 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := congrFun (WellFounded.fixEq ltWf div.F x) y theorem divDef (x y : Nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := difEqIf (0 < y ∧ y ≤ x) ((x - y) / y + 1) 0 ▸ divDefAux x y private theorem div.induction.F.{u} (C : Nat → Nat → Sort u) (ind : ∀ x y, 0 < y ∧ y ≤ x → C (x - y) y → C x y) (base : ∀ x y, ¬(0 < y ∧ y ≤ x) → C x y) (x : Nat) (f : ∀ (x₁ : Nat), x₁ < x → ∀ (y : Nat), C x₁ y) (y : Nat) : C x y := if h : 0 < y ∧ y ≤ x then ind x y h (f (x - y) (divRecLemma h) y) else base x y h theorem div.inductionOn.{u} {motive : Nat → Nat → Sort u} (x y : Nat) (ind : ∀ x y, 0 < y ∧ y ≤ x → motive (x - y) y → motive x y) (base : ∀ x y, ¬(0 < y ∧ y ≤ x) → motive x y) : motive x y := WellFounded.fix Nat.ltWf (div.induction.F motive ind base) x y private def mod.F (x : Nat) (f : ∀ x₁, x₁ < x → Nat → Nat) (y : Nat) : Nat := if h : 0 < y ∧ y ≤ x then f (x - y) (divRecLemma h) y else x @[extern "lean_nat_mod"] protected def mod (a b : @& Nat) : Nat := WellFounded.fix ltWf mod.F a b instance : Mod Nat := ⟨Nat.mod⟩ private theorem modDefAux (x y : Nat) : x % y = if h : 0 < y ∧ y ≤ x then (x - y) % y else x := congrFun (WellFounded.fixEq ltWf mod.F x) y theorem modDef (x y : Nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x := difEqIf (0 < y ∧ y ≤ x) ((x - y) % y) x ▸ modDefAux x y theorem mod.inductionOn.{u} {motive : Nat → Nat → Sort u} (x y : Nat) (ind : ∀ x y, 0 < y ∧ y ≤ x → motive (x - y) y → motive x y) (base : ∀ x y, ¬(0 < y ∧ y ≤ x) → motive x y) : motive x y := div.inductionOn x y ind base theorem modZero (a : Nat) : a % 0 = a := have (if 0 < 0 ∧ 0 ≤ a then (a - 0) % 0 else a) = a from have h : ¬ (0 < 0 ∧ 0 ≤ a) from fun ⟨h₁, _⟩ => absurd h₁ (Nat.ltIrrefl _) ifNeg h (modDef a 0).symm ▸ this theorem modEqOfLt {a b : Nat} (h : a < b) : a % b = a := have (if 0 < b ∧ b ≤ a then (a - b) % b else a) = a from have h' : ¬(0 < b ∧ b ≤ a) from fun ⟨_, h₁⟩ => absurd h₁ (Nat.notLeOfGt h) ifNeg h' (modDef a b).symm ▸ this theorem modEqSubMod {a b : Nat} (h : a ≥ b) : a % b = (a - b) % b := match eqZeroOrPos b with | Or.inl h₁ => h₁.symm ▸ (Nat.subZero a).symm ▸ rfl | Or.inr h₁ => (modDef a b).symm ▸ ifPos ⟨h₁, h⟩ theorem modLt (x : Nat) {y : Nat} : y > 0 → x % y < y := by refine mod.inductionOn (motive := fun x y => y > 0 → x % y < y) x y ?k1 ?k2 case k1 => intro x y ⟨_, h₁⟩ h₂ h₃ rw [modEqSubMod h₁] exact h₂ h₃ case k2 => intro x y h₁ h₂ have h₁ : ¬ 0 < y ∨ ¬ y ≤ x from Iff.mp (Decidable.notAndIffOrNot _ _) h₁ match h₁ with | Or.inl h₁ => exact absurd h₂ h₁ | Or.inr h₁ => have hgt : y > x from gtOfNotLe h₁ have heq : x % y = x from modEqOfLt hgt rw [← heq] at hgt exact hgt theorem modLe (x y : Nat) : x % y ≤ x := by match Nat.ltOrGe x y with | Or.inl h₁ => rw [modEqOfLt h₁]; apply Nat.leRefl | Or.inr h₁ => match eqZeroOrPos y with | Or.inl h₂ => rw [h₂, Nat.modZero x]; apply Nat.leRefl | Or.inr h₂ => exact Nat.leTrans (Nat.leOfLt (Nat.modLt _ h₂)) h₁ end Nat
2d7a8239312210a20f0366289000166c409fe288
75c54c8946bb4203e0aaf196f918424a17b0de99
/src/zfc_expanded.lean
446a2b11ea14af0ca94b76849eb271bb2affb36f
[ "Apache-2.0" ]
permissive
urkud/flypitch
261e2a45f1038130178575406df8aea78255ba77
2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c
refs/heads/master
1,653,266,469,246
1,577,819,679,000
1,577,819,679,000
259,862,235
1
0
Apache-2.0
1,588,147,244,000
1,588,147,244,000
null
UTF-8
Lean
false
false
14,780
lean
/- Copyright (c) 2019 The Flypitch Project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jesse Han, Floris van Doorn -/ import .fol open fol namespace zfc inductive ZFC_rel : ℕ → Type | ϵ : ZFC_rel 2 def L_ZFC : Language := ⟨λ_, empty, ZFC_rel⟩ def ZFC_el : L_ZFC.relations 2 := ZFC_rel.ϵ local infix ` ∈' `:100 := bounded_formula_of_relation ZFC_el ---ugly but working (str_formula says it's not well-founded recursion, but it evaluates anyways) def str_preterm : ∀ n m : ℕ, ℕ → bounded_preterm L_ZFC n m → string | n m z &k := "x" ++ to_string(z - k) | _ _ _ _ := "h" def str_term: ∀ n : ℕ, ℕ → bounded_term L_ZFC n → string | n m &k := "x" ++ to_string(m - k.val) | _ _ _ := "n" def str_preformula : ∀ n m : ℕ, ℕ → bounded_preformula L_ZFC n m → string | _ _ _ (bd_falsum ) := "⊥" | n m z (bd_equal a b) := str_preterm n m z a ++ " = " ++ str_preterm n m z b | n m z (a ⟹ b) := str_preformula n m z a ++ " ⟹ " ++ str_preformula n m z b | n m z (bd_rel _) := "∈" | n m z (bd_apprel a b) := str_preformula n (m+1) z a ++ "(" ++ str_term n z b ++ ")" | n m z (∀' t) := "(∀x" ++ to_string(z+1) ++ "," ++ str_preformula (n+1) m (z+1) t ++ ")" def str_formula : ∀ {n : ℕ}, bounded_formula L_ZFC n → ℕ → string := λn f m, str_preformula n 0 m f def print_formula : ∀ {n : ℕ}, bounded_formula L_ZFC n → string := λ n f, str_formula f n -- section test -- /- ∀ x, ∀ y, x = y → ∀ z, z = x → z = y -/ -- def testsentence : sentence L_ZFC := ∀' ∀' (&1 ≃ &0 ⟹ ∀' (&0 ≃ &2 ⟹ &0 ≃ &1)) -- #eval print_formula testsentence --- it's alive!! -- end test ---------------------------------------------------------------------------- def Class : Type := bounded_formula L_ZFC 1 def small {n} (c : bounded_formula L_ZFC (n+1)) : bounded_formula L_ZFC n := ∃' ∀' (&0 ∈' &1 ⇔ (c ↑' 1 # 1)) def subclass (c₁ c₂ : Class) : sentence L_ZFC := ∀' (c₁ ⟹ c₂) def functional {n} (c : bounded_formula L_ZFC (n+2)) : bounded_formula L_ZFC n := -- ∀x ∃y ∀z, c z x ↔ z = y ∀' ∃' ∀' (c ↑' 1 # 1 ⇔ &0 ≃ &1) def subset : bounded_formula L_ZFC 2 := ∀' (&0 ∈' &1 ⟹ &0 ∈' &2) def is_emptyset : bounded_formula L_ZFC 1 := ∼ ∃' (&0 ∈' &1) def pair : bounded_formula L_ZFC 3 := bd_equal &0 &1 ⊔ bd_equal &0 &2 def singl : bounded_formula L_ZFC 2 := &0 ≃ &1 def binary_union : bounded_formula L_ZFC 3 := &0 ∈' &1 ⊔ &0 ∈' &2 def succ : bounded_formula L_ZFC 2 := bd_equal &0 &1 ⊔ &0 ∈' &1 --∀x∃y(x ∈ y ∧ ∀z(z ∈ y → ∃w(z ∈ w ∧ w ∈ y))) def ordered_pair : bounded_formula L_ZFC 3 := ∀' /-w-/ ((&0 ∈' &1) /-w ∈ z-/ ⇔ ( (bd_equal &0 &3) ⊔ /-w = x-/ ∀' /-v-/ ((&0 ∈' &1) ⇔ /-v ∈ w-/ (pair ↑' 1 # 1 ↑' 1 # 1 )))) /-v = {x,y}-/ -- &0 is an ordered pair of &2 and &1 (z = ⟨x, y⟩) def ordered_pair' : bounded_formula L_ZFC 3 := ∀' /-w-/ ((&0 ∈' &3) /-w ∈ x-/ ⇔ ( (bd_equal &0 &2) ⊔ /-w = y-/ ∀' /-v-/ ((&0 ∈' &1) ⇔ /-v ∈ w -/ (pair ↑' 1 # 1 ↑' 1 # 4)))) /-v = {y,z}-/ -- &2 is an ordered pair of &1 and &0 (x = ⟨y,z⟩) def is_ordered_pair : bounded_formula L_ZFC 1 := ∃' ∃' ordered_pair --&0 is an ordered pair of some two elements-- def relation : bounded_formula L_ZFC 1 := ∀' ((&0 ∈' &1) ⟹ is_ordered_pair ↑' 1 # 1) --&0 is a relation (is a set of ordered pairs) def function : bounded_formula L_ZFC 1 := bd_and relation ∀' /-x-/ ∀' /-y-/ ∀' /-z-/ ∀' /-p-/ ∀' /-q-/ ( ( ( (&1 ∈' &5) ⊓ /-p ∈ X-/ (ordered_pair ↑' 1 # 3 ↑' 1 # 1 ↑' 1 # 0) /-p = ⟨x,y⟩-/ ) ⊓ ( (&0 ∈' &5) ⊓ /-q ∈ X-/ (ordered_pair ↑' 1 # 3 ↑' 1 # 2 ↑' 1 # 1 ) /-q =⟨x,z⟩-/ ) ) ⟹ (bd_equal &3 &2) /-y = z-/ ) -- X is a function iff X is a relation and the following holds: -- ∀x ∀y ∀z ∀w ∀t, ((w ∈ X) ∧ (w = ⟨x, y⟩) ∧ (z ∈ X) ∧ (z = ⟨x, z⟩ ))) → y = z def fn_app : bounded_formula L_ZFC 3 := ∃' /-p-/ ( (&0 ∈' &3) ⊓ /-p ∈ x-/ (∀' /-w-/ ( (&0 ∈' &1) ⇔ /-w ∈ p-/ ( (bd_equal &0 &3) ⊔ /-w = y-/ (pair ↑' 1 # 1 ↑' 1 # 4) /-w = {y,z}-/ ) ) ) ) -- ⟨y, z⟩ ∈ x -- &0 = &2(&1) def fn_domain : bounded_formula L_ZFC 2 := ∀' /-a-/ ( (&0 ∈' &2) ⇔ /-a ∈ A-/ ∃' /-b-/ ∃' /-p-/ ( (ordered_pair ↑' 1 # 1 ↑' 1 # 1) ⊓ /-p = a,b-/ (&0 ∈' &3) /-p ∈ F-/ ) ) -- A = dom(F) -- &1 is the domain of &0 def fn_range : bounded_formula L_ZFC 2 := ∀' /-b-/ ( (&0 ∈' &2) ⇔ ∃' /-a-/ ∃' /-q-/ ( (∀' /-w-/ ( (&0 ∈' &1) ⇔ /-w ∈ q-/ ( (bd_equal &0 &2) ⊔ /-w = a-/ (pair ↑' 1 # 1 ↑' 1 # 4 ↑' 1 # 4) /-w = {a,b}-/ ) ) ) ⊓ (&0 ∈' &3) /-w ∈ F-/ ) ) -- B = Ran(F) --&1 is the range of &0 def inverse_relation : bounded_formula L_ZFC 2 := /-X := &0, Y := &1-/ ∀' /-x-/ ((&0 ∈' &1) ⇔ /- x ∈ X -/ ∃' /-u-/ ∃' /-v-/ ( (ordered_pair' ↑' 1 # 3 ↑' 1 # 3) ⊓ /-x = ⟨u,v⟩-/ ∃' /-y-/ ( (∀' /-w-/ ( (&0 ∈' &1) ⇔ /-w ∈ y-/ ( (bd_equal &0 &2) ⊔/-w = v-/ (pair ↑' 1 # 3 ↑' 1 # 3 ↑' 1 # 3 ↑' 1 # 1) ) ) ) ⊓ /-w = {v,u}-/ (&0 ∈' &5)))) /-y ∈ Y-/ -- &0 is the inverse relation of &1 def function_one_one : bounded_formula L_ZFC 1 := function ⊓ ∀' (inverse_relation ⟹ function ↑' 1 # 1) def irreflexive_relation : bounded_formula L_ZFC 2 := relation ↑' 1 # 1 ⊓ ∀' /-y-/ ( (&0 ∈' &2) /-y ∈ Y-/ ⟹ (∀' /-p-/ (∀' /-w-/ (&0 ∈' &1) ⇔ /-w ∈ p-/ (bd_or (bd_equal &0 &2) /-w = y-/ (∀' /-v-/ ( (&0 ∈' &1) ⇔ /-v ∈ w-/ (bd_equal &0 &3) /-v = y-/ ) ) ) ) ⟹ (∼(&0 ∈' &3)) ) ) -- &0 is an irreflexive relation on &1 def transitive_relation : bounded_formula L_ZFC 2 := /- X := &0, Y := &1 -/ bd_and (relation ↑' 1 # 1) ∀' /-u-/ ∀' /-v-/ ∀' /-w-/ (( ( ( bd_and ( bd_and (&2 ∈' &4) /-u ∈ Y -/ (&1 ∈' &4) ) /-v ∈ Y -/ (&0 ∈' &4)/-w ∈ Y -/ ) ⊓ (∃' /-p-/ ( (ordered_pair ↑' 1 # 1 ↑' 1 # 4 ↑' 1 # 4) ⊓ /-p = ⟨u,v⟩ -/ (&0 ∈' &4) ) ) ) ⊓ /- p ∈ X -/ ∃' /-q-/ ( (ordered_pair ↑' 1 # 3 ↑' 1 # 3 ↑' 1 # 3) ⊓ /-q = ⟨v,w⟩ -/ (&0 ∈' &4))) /-q ∈ X-/ ⟹ ∃' /-r-/ bd_and (ordered_pair ↑' 1 # 2 ↑' 1 # 4 ↑' 1 # 4 ) /-r = ⟨u,w⟩ -/ (&0 ∈' &4)) /-r ∈ X-/ --&0 is a transitive relation on &1 -- X Tr Y iff X is a relation and the following holds: -- ∀u ∀v ∀w, (u ∈ Y ∧ v ∈ Y ∧ w ∈ Y ∧ ⟨u, v⟩ ∈ X ∧ ⟨v,w⟩ ∈ X) → ⟨u,w⟩ ∈ X def partial_order_zfc : bounded_formula L_ZFC 2 := irreflexive_relation ⊓ transitive_relation def connected_relation : bounded_formula L_ZFC 2 := bd_and (relation ↑' 1 # 1) ∀' /-u-/ ∀' /-v-/ ((bd_and (bd_and (&0 ∈' &3) /-v ∈ y-/ (&1 ∈' &3)) /-u ∈ y-/ (∼ (bd_equal &0 &1))) /-v ≠ u-/ ⟹ ∃' /-p-/ bd_and (&0 ∈' &3) /-p ∈ X-/ (bd_or (ordered_pair ↑' 1 # 3 ↑' 1 # 3) /-p = ⟨u,v⟩-/ /-term below is "p = ⟨v,u⟩"-/ ∀' /-w-/ ((&0 ∈' &1) ⇔ /-w ∈ p-/ bd_or (bd_equal &0 &2) /-w = v-/ (pair ↑' 1 # 1 ↑' 1 # 4 ↑' 1 # 4)))) /-w = {u,v}-/ --&0 is a connected relation on &1 -- X Con Y iff Rel(X) and ∀u ∀v (u ∈ Y ∧ v ∈ Y ∧ u ≠ v) → ⟨u,v⟩ ∈ X ∨ ⟨v, u⟩ ∈ X def total_order : bounded_formula L_ZFC 2 := irreflexive_relation ⊓ transitive_relation ⊓ connected_relation def well_order : bounded_formula L_ZFC 2 := /-X := &0, Y := &1-/ bd_and (irreflexive_relation) ∀' /-Z-/ ( ( (subset ↑' 1 # 2) ⊓ /-Z ⊆ Y -/ ∃' (&0 ∈' &1) ) ⟹ ∃' /-y-/ ( (&0 ∈' &1) ⊓ /-y ∈ Z-/ (∀' /-v-/ ( (bd_and (&0 ∈' &2) /-v ∈ Z -/ ( ∼ (bd_equal &0 &1)) /-v ≠ y-/ ) ⟹ ( (∃' /-p-/ ( (ordered_pair ↑' 1 # 4 ↑' 1 # 4 ↑' 1 # 4) ⊓ /-p = ⟨y,v⟩-/ (&0 ∈' &4) /-p ∈ X -/ ) ) ⊓ (∼ (∃' /-q-/ /-first argument is q = ⟨v,y⟩-/ ( (∀' /-w-/ ( (&0 ∈' &1) ⇔ /-w ∈ q-/ ( (bd_equal &0 &2) ⊔ /-w = v-/ (pair ↑' 1 # 1 ↑' 1 # 4 ↑' 1 # 4 ↑' 1 # 4) ) ) ) ⊓ /-w = {v,y}-/ (&0 ∈' &4))))))))) /-q ∈ X-/ -- &0 well-orders &1 def membership_relation : bounded_formula L_ZFC 1 := relation ⊓ ∀' ( (&0 ∈' &1) ⇔ ∃' ∃' ∀' ( (&0 ∈' &3) ⇔ ( (bd_equal &0 &2 ⊔ pair ↑' 1 # 3 ↑' 1 # 3) ⊓ (&2 ∈' &1) ) ) ) -- &0 is E, the membership relation {⟨x,y⟩ | x ∈ y} def transitive_zfc : bounded_formula L_ZFC 1 := ∀' ((&0 ∈' &1) ⟹ subset) --&0 is transitive def fn_zfc_equiv : bounded_formula L_ZFC 3 := ( (function_one_one ↑' 1 # 1 ↑' 1 # 1) ⊓ (fn_domain ↑' 1 # 1)) ⊓ (fn_range ↑' 1 # 2) def zfc_equiv : bounded_formula L_ZFC 2 := ∃' fn_zfc_equiv --&0 ≃ &1, i.e. they are equinumerous def is_powerset : bounded_formula L_ZFC 2 := ∀' ((&0 ∈' &2) ⇔ subset ↑' 1 # 2) --&1 is P(&0) def is_suc_of : bounded_formula L_ZFC 2 := ∀' ((&0 ∈' &2) ⇔ ( (&0 ∈' &1) ⊔ (bd_equal &0 &1))) -- &1 = succ(&0) def is_ordinal : bounded_formula L_ZFC 1 := (∀' ((membership_relation ↑' 1 # 1) ⟹ well_order)) ⊓ transitive_zfc def is_suc_ordinal : bounded_formula L_ZFC 1 := is_ordinal ⊓ ∃' is_suc_of --&0 is a successor ordinal def ordinal_lt : bounded_formula L_ZFC 2 := (is_ordinal ↑' 1 # 1) ⊓ (is_ordinal ↑' 1 # 0) ⊓ (&0 ∈' &1) -- &0 < &1 def ordinal_le : bounded_formula L_ZFC 2 := ordinal_lt ⊔ (bd_equal &0 &1) -- &0 ≤ &1 def is_first_ordinal : bounded_formula L_ZFC 1 := ∀' ( (&0 ∈' &1) ⇔ ( ((is_emptyset ⊔ is_suc_ordinal)↑' 1 # 1) ⊓ ∀' ( (&0 ∈' &1) ⟹ ((is_emptyset ⊔ is_suc_ordinal) ↑' 1 # 1 ↑' 1 # 1) ) ) ) --&0 = ω def is_uncountable_ordinal : bounded_formula L_ZFC 1 := ∀' ((is_first_ordinal ↑' 1 # 1) ⟹ ∀' (subset ↑' 1 # 2 ⟹ (∼(zfc_equiv ↑' 1 # 1)))) --&0 ≥ ω₁ def is_first_uncountable_ordinal : bounded_formula L_ZFC 1 := is_uncountable_ordinal ⊓ (∀' ((is_uncountable_ordinal ↑' 1 # 1) ⟹ ordinal_le)) --&0 = ω₁ def continuum_hypothesis : sentence L_ZFC := ∀' ∀' (( (∃' ((is_first_ordinal ↑' 1 # 1 ↑' 1 # 1) ⊓ (is_powerset↑' 1 # 2))) ⊓ (is_first_uncountable_ordinal ↑' 1 #0)) ⟹ zfc_equiv) def axiom_of_extensionality : sentence L_ZFC := ∀' ∀' (∀' (&0 ∈' &1 ⇔ &0 ∈' &2) ⟹ &0 ≃ &1) def axiom_of_union : sentence L_ZFC := ∀' (small ∃' (&1 ∈' &0 ⊓ &0 ∈' &2)) -- todo: c can have free variables. Note that c y x is interpreted as y is the image of x def axiom_of_replacement (c : bounded_formula L_ZFC 2) : sentence L_ZFC := -- ∀α small (λy, ∃x, x ∈ α ∧ c y x) functional c ⟹ ∀' (small ∃' (&0 ∈' &2 ⊓ c.cast1)) def axiom_of_powerset : sentence L_ZFC := -- the class of all subsets of x is small ∀' small subset def axiom_of_infinity : sentence L_ZFC := --∀x∃y(x ∈ y ∧ ∀z(z ∈ y → ∃w(z ∈ w ∧ w ∈ y))) ∀' ∃' (&1 ∈' &0 ⊓ ∀'(&0 ∈' &1 ⟹ ∃' (bd_and (&1 ∈' &0) (&0 ∈' &2)))) def axiom_of_choice : sentence L_ZFC := -- for every E : A → B, there exists a function C on A such that for every a ∈ A, C a ∈ E a (if E a is nonempty). ∀' /-E-/ (∀' /-A-/ (fn_domain ⟹ (∃' /-C-/ (∀' /-a-/ ((&0 ∈' &2) ⟹ (∀' /-b-/ ( (fn_app ↑' 1 # 2 ↑' 1 # 2) ⟹ /-&0 = &4(&1) ; b = E(a)-/ ((∀' /-c-/ ( (fn_app ↑' 1 # 1 ↑' 1 # 4 ↑' 1 # 4) ⊓ /-&0 = &3(&2) ; c = C(a)-/ (∃' (&0 ∈' &2)) /- b is nonempty -/ ) ⟹ (&0 ∈' &1)))))))))) -- ∀E, function(E) ⇒ ∀ A, A = dom(E) ⇒ ∃ C, ∀ a, (a ∈ A ⇒ (∀ b, (fn_app E a b) ⇒ ∀ c, (fn_app C a c ∧ (∃'z, z ∈ b)) ⇒ c ∈ b)) -- the following axioms follow from the other axioms def axiom_of_emptyset : sentence L_ZFC := small ⊥ -- todo: c can have free variables def axiom_of_separation (c : Class) : sentence L_ZFC := ∀' (small $ &0 ∈' &1 ⊓ c.cast1) -- the class consisting of the unordered pair {x, y} def axiom_of_pairing : sentence L_ZFC := ∀' ∀' small pair --the class consisting of the ordered pair ⟨x, y⟩ def axiom_of_ordered_pairing : sentence L_ZFC := ∀' ∀' small ordered_pair --the class consisting of all ordered pairs def axiom_of_product : sentence L_ZFC := small is_ordered_pair def ZF : Theory L_ZFC := {axiom_of_extensionality, axiom_of_union, axiom_of_powerset, axiom_of_infinity} ∪ (λ(c : bounded_formula L_ZFC 2), axiom_of_replacement c) '' set.univ def ZFC : Theory L_ZFC := ZF ∪ {axiom_of_choice} end zfc
1933d382a824041bb26e0d84ad6f29eb23177925
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/ematch_partial_apps.lean
9c3b6bf7cd407a1867922e1f7231fa4dd92921d3
[ "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
778
lean
open tactic set_option trace.smt.ematch true example (a : list nat) (f : nat → nat) : a = [1, 2] → a^.map f = [f 1, f 2] := begin [smt] intros, ematch_using [list.map], ematch_using [list.map], ematch_using [list.map] end example (a : list nat) (f : nat → nat) : a = [1, 2] → a^.map f = [f 1, f 2] := begin [smt] intros, iterate {ematch_using [list.map], try { close }}, end attribute [ematch] list.map example (a : list nat) (f : nat → nat) : a = [1, 2] → a^.map f = [f 1, f 2] := begin [smt] intros, eblast end constant f : nat → nat → nat constant g : nat → nat → nat axiom fgx : ∀ x y, (: f x :) = (λ y, y) ∧ (: g y :) = λ x, 0 attribute [ematch] fgx example (a b c : nat) : f a b = b ∧ g b c = 0 := begin [smt] ematch end
49e60a953294858626c3f9e2b8b96426bc5e73bd
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/valid/mathd-algebra-11.lean
69b973b2dd006c3d0fe7267579488ab84ad598fe
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
558
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.real.basic example (a b : ℝ) (h₀ : a ≠ b) (h₁ : a ≠ 2*b) (h₂ : ( 4 * a + 3 * b ) / ( a - 2 * b ) = 5) : ( a + 11 * b ) / ( a - b ) = 2 := begin rw eq_comm, refine (eq_div_iff _).mpr _, exact sub_ne_zero_of_ne h₀, rw eq_comm at h₂, suffices : a = 13 * b, linarith, have key : 5 * (a - 2 * b) = (4 * a + 3 * b), rwa (eq_div_iff (sub_ne_zero_of_ne h₁)).mp, linarith, end
22e8794ec089e65da5160e4a22af52760fc318d1
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/ring_theory/power_series.lean
cdc1df3cf16a1458071bb9e20dda0480f89ff32d
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
57,892
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.mv_polynomial import ring_theory.ideal.operations import ring_theory.multiplicity import tactic.linarith /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as `φ`, for all `m ≤ n`, and `0` otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `le_order_add`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `R` as `mv_power_series σ R := (σ →₀ ℕ) → R`. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as `power_series R := mv_power_series unit R`. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by `unit →₀ ℕ`, which is of course canonically isomorphic to `ℕ`. We then build some glue to treat formal power series as if they are indexed by `ℕ`. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical big_operators /-- Multivariate formal power series, where `σ` is the index set of the variables and `R` is the coefficient ring.-/ def mv_power_series (σ : Type*) (R : Type*) := (σ →₀ ℕ) → R namespace mv_power_series open finsupp variables {σ R : Type*} instance [inhabited R] : inhabited (mv_power_series σ R) := ⟨λ _, default _⟩ instance [has_zero R] : has_zero (mv_power_series σ R) := pi.has_zero instance [add_monoid R] : add_monoid (mv_power_series σ R) := pi.add_monoid instance [add_group R] : add_group (mv_power_series σ R) := pi.add_group instance [add_comm_monoid R] : add_comm_monoid (mv_power_series σ R) := pi.add_comm_monoid instance [add_comm_group R] : add_comm_group (mv_power_series σ R) := pi.add_comm_group instance [nontrivial R] : nontrivial (mv_power_series σ R) := function.nontrivial section add_monoid variables (R) [add_monoid R] /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : R →+ mv_power_series σ R := { to_fun := λ a m, if m = n then a else 0, map_zero' := funext $ λ m, by { split_ifs; refl }, map_add' := λ a b, funext $ λ m, show (if m = n then a + b else 0) = (if m = n then a else 0) + (if m = n then b else 0), from if h : m = n then by simp only [if_pos h] else by simp only [if_neg h, add_zero] } /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ R) →+ R := { to_fun := λ φ, φ n, map_zero' := rfl, map_add' := λ _ _, rfl } variables {R} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ R} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) := ⟨λ h n, congr_arg (coeff R n) h, ext⟩ lemma coeff_monomial (m n : σ →₀ ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := rfl @[simp] lemma coeff_monomial' (n : σ →₀ ℕ) (a : R) : coeff R n (monomial R n a) = a := if_pos rfl @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff R n).comp (monomial R n) = add_monoid_hom.id R := add_monoid_hom.ext $ coeff_monomial' n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff R n (0 : mv_power_series σ R) = 0 := rfl end add_monoid section semiring variables [semiring R] (n : σ →₀ ℕ) (φ ψ : mv_power_series σ R) instance : has_one (mv_power_series σ R) := ⟨monomial R (0 : σ →₀ ℕ) 1⟩ lemma coeff_one : coeff R n (1 : mv_power_series σ R) = if n = 0 then 1 else 0 := rfl lemma coeff_zero_one : coeff R (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial' 0 1 instance : has_mul (mv_power_series σ R) := ⟨λ φ ψ n, ∑ p in (finsupp.antidiagonal n).support, φ p.1 * ψ p.2⟩ lemma coeff_mul : coeff R n (φ * ψ) = ∑ p in (finsupp.antidiagonal n).support, coeff R p.1 φ * coeff R p.2 ψ := rfl protected lemma zero_mul : (0 : mv_power_series σ R) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] protected lemma one_mul : (1 : mv_power_series σ R) * φ = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single ((0 : σ →₀ ℕ), n)]; simp [mem_antidiagonal_support, coeff_one], show ∀ (i j : σ →₀ ℕ), i + j = n → (i = 0 → j ≠ n) → (if i = 0 then coeff R j φ else 0) = 0, intros i j hij h, rw [if_neg], contrapose! h, simpa [h] using hij, end protected lemma mul_one : φ * 1 = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single (n, (0 : σ →₀ ℕ))], rotate, { rintros ⟨i, j⟩ hij h, rw [coeff_one, if_neg, mul_zero], rw mem_antidiagonal_support at hij, contrapose! h, simpa [h] using hij }, all_goals { simp [mem_antidiagonal_support, coeff_one] } end protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ R) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := ext $ λ n, begin simp only [coeff_mul], have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) R _ _ (antidiagonal n).support (λ p, (antidiagonal (p.1)).support) (λ x, coeff R x.2.1 φ₁ * coeff R x.2.2 φ₂ * coeff R x.1.2 φ₃), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, exact finset.sum_mul }, have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) R _ _ (antidiagonal n).support (λ p, (antidiagonal (p.2)).support) (λ x, coeff R x.1.1 φ₁ * (coeff R x.2.1 φ₂ * coeff R x.2.2 φ₃)), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, rw finset.mul_sum }, apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l+j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_antidiagonal_support, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i+k, l), (i, k)⟩, _, _⟩; { simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish } } end instance : semiring (mv_power_series σ R) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.has_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring R] : comm_semiring (mv_power_series σ R) := { mul_comm := λ φ ψ, ext $ λ n, finset.sum_bij (λ p hp, p.swap) (λ p hp, swap_mem_antidiagonal_support hp) (λ p hp, mul_comm _ _) (λ p q hp hq H, by simpa using congr_arg prod.swap H) (λ p hp, ⟨p.swap, swap_mem_antidiagonal_support hp, p.swap_swap.symm⟩), .. mv_power_series.semiring } instance [ring R] : ring (mv_power_series σ R) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring R] : comm_ring (mv_power_series σ R) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring R] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : R) : monomial R m a * monomial R n b = monomial R (m + n) (a * b) := begin ext k, rw [coeff_mul, coeff_monomial], split_ifs with h, { rw [h, finset.sum_eq_single (m,n)], { rw [coeff_monomial', coeff_monomial'] }, { rintros ⟨i,j⟩ hij hne, rw [ne.def, prod.mk.inj_iff, not_and] at hne, by_cases H : i = m, { rw [coeff_monomial j n b, if_neg (hne H), mul_zero] }, { rw [coeff_monomial, if_neg H, zero_mul] } }, { intro H, rw finsupp.mem_antidiagonal_support at H, exfalso, exact H rfl } }, { rw [finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, by_cases H : i = m, { subst i, have : j ≠ n, { rintro rfl, exact h hij.symm }, { rw [coeff_monomial j n b, if_neg this, mul_zero] } }, { rw [coeff_monomial, if_neg H, zero_mul] } } end variables (σ) (R) /-- The constant multivariate formal power series.-/ def C : R →+* mv_power_series σ R := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, .. monomial R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma monomial_zero_eq_C : monomial R (0 : σ →₀ ℕ) = C σ R := rfl lemma monomial_zero_eq_C_apply (a : R) : monomial R (0 : σ →₀ ℕ) a = C σ R a := rfl lemma coeff_C (n : σ →₀ ℕ) (a : R) : coeff R n (C σ R a) = if n = 0 then a else 0 := rfl lemma coeff_zero_C (a : R) : coeff R (0 : σ →₀ℕ) (C σ R a) = a := coeff_monomial' 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ R := monomial R (single s 1) 1 lemma coeff_X (n : σ →₀ ℕ) (s : σ) : coeff R n (X s : mv_power_series σ R) = if n = (single s 1) then 1 else 0 := rfl lemma coeff_index_single_X (s t : σ) : coeff R (single t 1) (X s : mv_power_series σ R) = if t = s then 1 else 0 := by { simp only [coeff_X, single_left_inj one_ne_zero], split_ifs; refl } @[simp] lemma coeff_index_single_self_X (s : σ) : coeff R (single s 1) (X s : mv_power_series σ R) = 1 := if_pos rfl lemma coeff_zero_X (s : σ) : coeff R (0 : σ →₀ ℕ) (X s : mv_power_series σ R) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma X_def (s : σ) : X s = monomial R (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ R)^n = monomial R (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero], refl }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff R m ((X s : mv_power_series σ R)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] @[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (φ * C σ R a) = coeff R n φ * a := begin rw [coeff_mul n φ], rw [finset.sum_eq_single (n,(0 : σ →₀ ℕ))], { rw [coeff_C, if_pos rfl] }, { rintro ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, by_cases hj : j = 0, { subst hj, simp at *, contradiction }, { rw [coeff_C, if_neg hj, mul_zero] } }, { intro h, exfalso, apply h, rw finsupp.mem_antidiagonal_support, apply add_zero } end @[simp] lemma coeff_C_mul (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (C σ R a * φ) = a * coeff R n φ := begin rw [coeff_mul n _ φ, finset.sum_eq_single ((0 : σ →₀ ℕ), _)], { rw [coeff_C, if_pos rfl] }, { rintro ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, by_cases hi : i = 0, { subst hi, simp at *, contradiction }, { rw [coeff_C, if_neg hi, zero_mul] } }, { intro h, exfalso, apply h, rw finsupp.mem_antidiagonal_support, apply zero_add } end lemma coeff_zero_mul_X (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (φ * X s) = 0 := begin rw [coeff_mul _ φ, finset.sum_eq_zero], rintro ⟨i,j⟩ hij, obtain ⟨rfl, rfl⟩ : i = 0 ∧ j = 0, { rw finsupp.mem_antidiagonal_support at hij, simpa using hij }, simp [coeff_zero_X] end variables (σ) (R) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ R) →+* R := { to_fun := coeff R (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], .. coeff R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma coeff_zero_eq_constant_coeff : coeff R (0 : σ →₀ ℕ) = constant_coeff σ R := rfl lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ R) : coeff R (0 : σ →₀ ℕ) φ = constant_coeff σ R φ := rfl @[simp] lemma constant_coeff_C (a : R) : constant_coeff σ R (C σ R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ R).comp (C σ R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ R 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ R (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ R) (h : is_unit φ) : is_unit (constant_coeff σ R φ) := h.map' (constant_coeff σ R) instance : semimodule R (mv_power_series σ R) := { smul := λ a φ, C σ R a * φ, one_smul := λ φ, one_mul _, mul_smul := λ a b φ, by simp [ring_hom.map_mul, mul_assoc], smul_add := λ a φ ψ, mul_add _ _ _, smul_zero := λ a, mul_zero _, add_smul := λ a b φ, by simp only [ring_hom.map_add, add_mul], zero_smul := λ φ, by simp only [zero_mul, ring_hom.map_zero] } @[simp] lemma coeff_smul (f : mv_power_series σ R) (n) (a : R) : coeff _ n (a • f) = a * coeff _ n f := coeff_C_mul _ _ _ lemma X_inj [nontrivial R] {s t : σ} : (X s : mv_power_series σ R) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff R (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end semiring instance [comm_ring R] : algebra R (mv_power_series σ R) := { commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, rfl, .. C σ R, .. mv_power_series.semimodule } section map variables {S T : Type*} [semiring R] [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ R →+* mv_power_series σ S := { to_fun := λ φ n, f $ coeff R n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff R n) 1) = (coeff S n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff R n) (φ + ψ)) = f ((coeff R n) φ) + f ((coeff R n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, ← finset.sum_hom _ f, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id R) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ R) : coeff S n (map σ f φ) = f (coeff R n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ R) : constant_coeff σ S (map σ f φ) = f (constant_coeff σ R φ) := rfl end map section trunc variables [comm_semiring R] (n : σ →₀ ℕ) /-- Auxiliary definition for the truncation function. -/ def trunc_fun (φ : mv_power_series σ R) : mv_polynomial σ R := { support := (n.antidiagonal.support.image prod.fst).filter (λ m, coeff R m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff R m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ finset.image prod.fst ((antidiagonal n).support) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩ s, rw finsupp.mem_antidiagonal_support at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finsupp.mem_antidiagonal_support, ext s, exact nat.add_sub_of_le (h s) } end } variable (R) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ R →+ mv_polynomial σ R := { to_fun := trunc_fun n, map_zero' := mv_polynomial.ext _ _ $ λ m, by { change ite _ _ _ = _, split_ifs; refl }, map_add' := λ φ ψ, mv_polynomial.ext _ _ $ λ m, begin rw mv_polynomial.coeff_add, change ite _ _ _ = ite _ _ _ + ite _ _ _, split_ifs with H, {refl}, {rw [zero_add]} end } variable {R} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ R) : mv_polynomial.coeff m (trunc R n φ) = if m ≤ n then coeff R m φ else 0 := rfl @[simp] lemma trunc_one : trunc R n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, erw mv_polynomial.coeff_C 0, simp }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg (ne.elim (ne.symm H')), }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg _, intro H', apply H, subst m, intro s, exact nat.zero_le _ } end @[simp] lemma trunc_C (a : R) : trunc R n (C σ R a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, intro s, exact nat.zero_le _ end end trunc section comm_semiring variable [comm_semiring R] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff R m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal_support at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff R (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff R m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.nat_sub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal_support, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext, simp, cc }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using nat.sub_add_cancel H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff R m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ R), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end comm_semiring section ring variables [ring R] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : R) (φ : mv_power_series σ R) : mv_power_series σ R | n := if n = 0 then a else - a * ∑ x in n.antidiagonal.support, if h : x.2 < n then coeff R x.1 φ * inv.aux x.2 else 0 using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux (n : σ →₀ ℕ) (a : R) (φ : mv_power_series σ R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in n.antidiagonal.support, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := show inv.aux a φ n = _, by { rw inv.aux, refl } /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ R) (u : units R) : mv_power_series σ R := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : units R) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in n.antidiagonal.support, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ R) (u : units R) : constant_coeff σ R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ R) (u : units R) (h : constant_coeff σ R φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal.support, { rw [finsupp.mem_antidiagonal_support, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal_support] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring R] /-- Multivariate formal power series over a local ring form a local ring. -/ instance is_local_ring [local_ring R] : local_ring (mv_power_series σ R) := { is_local := by { intro φ, rcases local_ring.is_local (constant_coeff σ R φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _), simpa using h.symm } } } -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] -- Thanks to the linter for informing us that this instance does -- not actually need R and S to be local rings! /-- The map `A[[X]] → B[[X]]` induced by a local ring hom `A → B` is local -/ instance map.is_local_ring_hom : is_local_ring_hom (map σ f) := ⟨begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ S) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ S ↑ψ) := @is_unit_constant_coeff σ S _ (↑ψ) (is_unit_unit ψ), rw h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm) end⟩ variables [local_ring R] [local_ring S] instance : local_ring (mv_power_series σ R) := { is_local := local_ring.is_local } end local_ring section field variables {k : Type*} [field k] /-- The inverse `1/f` of a multivariable power series `f` over a field -/ protected def inv (φ : mv_power_series σ k) : mv_power_series σ k := inv.aux (constant_coeff σ k φ)⁻¹ φ instance : has_inv (mv_power_series σ k) := ⟨mv_power_series.inv⟩ lemma coeff_inv (n : σ →₀ ℕ) (φ : mv_power_series σ k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff σ k φ)⁻¹ else - (constant_coeff σ k φ)⁻¹ * ∑ x in n.antidiagonal.support, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ k) : constant_coeff σ k (φ⁻¹) = (constant_coeff σ k φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ k} : φ⁻¹ = 0 ↔ constant_coeff σ k φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ k) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ k) (u : units k) (h : constant_coeff σ k φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv h] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ R) (mv_power_series σ R) := ⟨λ φ n, coeff n φ⟩ @[simp, norm_cast] lemma coeff_coe (φ : mv_polynomial σ R) (n : σ →₀ ℕ) : mv_power_series.coeff R n ↑φ = coeff n φ := rfl @[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : R) : (monomial n a : mv_power_series σ R) = mv_power_series.monomial R n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ R) : mv_power_series σ R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ R) : mv_power_series σ R) = 1 := coe_monomial _ _ @[simp, norm_cast] lemma coe_add (φ ψ : mv_polynomial σ R) : ((φ + ψ : mv_polynomial σ R) : mv_power_series σ R) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul (φ ψ : mv_polynomial σ R) : ((φ * ψ : mv_polynomial σ R) : mv_power_series σ R) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.C σ R a := coe_monomial _ _ @[simp, norm_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.X s := coe_monomial _ _ /-- The coercion from multivariable polynomials to multivariable power series as a ring homomorphism. -/ -- TODO as an algebra homomorphism? def coe_to_mv_power_series.ring_hom : mv_polynomial σ R →+* mv_power_series σ R := { to_fun := (coe : mv_polynomial σ R → mv_power_series σ R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } end mv_polynomial /-- Formal power series over the coefficient ring `R`.-/ def power_series (R : Type*) := mv_power_series unit R namespace power_series open finsupp (single) variable {R : Type*} section local attribute [reducible] power_series instance [inhabited R] : inhabited (power_series R) := by apply_instance instance [add_monoid R] : add_monoid (power_series R) := by apply_instance instance [add_group R] : add_group (power_series R) := by apply_instance instance [add_comm_monoid R] : add_comm_monoid (power_series R) := by apply_instance instance [add_comm_group R] : add_comm_group (power_series R) := by apply_instance instance [semiring R] : semiring (power_series R) := by apply_instance instance [comm_semiring R] : comm_semiring (power_series R) := by apply_instance instance [ring R] : ring (power_series R) := by apply_instance instance [comm_ring R] : comm_ring (power_series R) := by apply_instance instance [nontrivial R] : nontrivial (power_series R) := by apply_instance instance [semiring R] : semimodule R (power_series R) := by apply_instance instance [comm_ring R] : algebra R (power_series R) := by apply_instance end section add_monoid variables (R) [add_monoid R] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series R →+ R := mv_power_series.coeff R (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : R →+ power_series R := mv_power_series.monomial R (single () n) variables {R} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff R n = mv_power_series.coeff R s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series R} (h : ∀ n, coeff R n φ = coeff R n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series R} : φ = ψ ↔ (∀ n, coeff R n φ = coeff R n ψ) := ⟨λ h n, congr_arg (coeff R n) h, ext⟩ /-- Constructor for formal power series.-/ def mk {R} (f : ℕ → R) : power_series R := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → R) : coeff R n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := calc coeff R m (monomial R n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl } lemma monomial_eq_mk (n : ℕ) (a : R) : monomial R n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial' (n : ℕ) (a : R) : coeff R n (monomial R n a) = a := by convert if_pos rfl @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff R n).comp (monomial R n) = add_monoid_hom.id R := add_monoid_hom.ext $ coeff_monomial' n end add_monoid section semiring variable [semiring R] variable (R) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series R →+* R := mv_power_series.constant_coeff unit R /-- The constant formal power series.-/ def C : R →+* power_series R := mv_power_series.C unit R variable {R} /-- The variable of the formal power series ring.-/ def X : power_series R := mv_power_series.X () @[simp] lemma coeff_zero_eq_constant_coeff : coeff R 0 = constant_coeff R := begin rw [constant_coeff, ← mv_power_series.coeff_zero_eq_constant_coeff, coeff_def], refl end lemma coeff_zero_eq_constant_coeff_apply (φ : power_series R) : coeff R 0 φ = constant_coeff R φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : monomial R 0 = C R := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] lemma monomial_zero_eq_C_apply (a : R) : monomial R 0 a = C R a := by simp lemma coeff_C (n : ℕ) (a : R) : coeff R n (C R a : power_series R) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] lemma coeff_zero_C (a : R) : coeff R 0 (C R a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial' 0 a] lemma X_eq : (X : power_series R) = monomial R 1 1 := rfl lemma coeff_X (n : ℕ) : coeff R n (X : power_series R) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] lemma coeff_zero_X : coeff R 0 (X : power_series R) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff R 1 (X : power_series R) = 1 := by rw [coeff_X, if_pos rfl] lemma X_pow_eq (n : ℕ) : (X : power_series R)^n = monomial R n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff R m ((X : power_series R)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff R n ((X : power_series R)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff R n (1 : power_series R) = if n = 0 then 1 else 0 := calc coeff R n (1 : power_series R) = _ : mv_power_series.coeff_one _ ... = if n = 0 then 1 else 0 : by { simp only [finsupp.single_eq_zero], split_ifs; refl } lemma coeff_zero_one : coeff R 0 (1 : power_series R) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series R) : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series R) (a : R) : coeff R n (φ * C R a) = coeff R n φ * a := mv_power_series.coeff_mul_C _ φ a @[simp] lemma coeff_C_mul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (C R a * φ) = a * coeff R n φ := mv_power_series.coeff_C_mul _ φ a @[simp] lemma coeff_smul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (a • φ) = a * coeff R n φ := coeff_C_mul _ _ _ @[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series R) : coeff R (n+1) (φ * X) = coeff R n φ := begin rw [coeff_mul _ φ, finset.sum_eq_single (n,1)], { rw [coeff_X, if_pos rfl, mul_one] }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j = 1, { subst hj, simp at *, contradiction }, { simp [coeff_X, hj] } }, { intro h, exfalso, apply h, simp }, end @[simp] lemma constant_coeff_C (a : R) : constant_coeff R (C R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff R).comp (C R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff R 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff R X = 0 := mv_power_series.coeff_zero_X _ lemma coeff_zero_mul_X (φ : power_series R) : coeff R 0 (φ * X) = 0 := by simp /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series R) (h : is_unit φ) : is_unit (constant_coeff R φ) := mv_power_series.is_unit_constant_coeff φ h section map variables {S : Type*} {T : Type*} [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series R →+* power_series S := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id R) : power_series R → power_series R) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series R) : coeff S n (map f φ) = f (coeff R n φ) := rfl end map end semiring section comm_semiring variables [comm_semiring R] lemma X_pow_dvd_iff {n : ℕ} {φ : power_series R} : (X : power_series R)^n ∣ φ ↔ ∀ m, m < n → coeff R m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit R _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series R} : (X : power_series R) ∣ φ ↔ constant_coeff R φ = 0 := begin rw [← pow_one (X : power_series R), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series R) : polynomial R := { support := ((finset.nat.antidiagonal n).image prod.fst).filter (λ m, coeff R m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff R m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ ((finset.nat.antidiagonal n).image prod.fst) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩, rw finset.nat.mem_antidiagonal at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finset.nat.mem_antidiagonal, exact nat.add_sub_of_le h } end } lemma coeff_trunc (m) (n) (φ : power_series R) : polynomial.coeff (trunc n φ) m = if m ≤ n then coeff R m φ else 0 := rfl @[simp] lemma trunc_zero (n) : trunc n (0 : power_series R) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, add_monoid_hom.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc n (1 : power_series R) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, intro H', apply H, subst m, exact nat.zero_le _ } end @[simp] lemma trunc_C (n) (a : R) : trunc n (C R a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series R) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring R] /-- Auxiliary function used for computing inverse of a power series -/ protected def inv.aux : R → power_series R → power_series R := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : R) (φ : power_series R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series R) (u : units R) : power_series R := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series R) (u : units R) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series R) (u : units R) : constant_coeff R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series R) (u : units R) (h : constant_coeff R φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h end ring section integral_domain variable [integral_domain R] lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series R) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw or_iff_not_imp_left, intro H, have ex : ∃ m, coeff R m φ ≠ 0, { contrapose! H, exact ext H }, let P : ℕ → Prop := λ k, coeff R k φ ≠ 0, let m := nat.find ex, have hm₁ : coeff R m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff R k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff R n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff R (m + n)) h, rw [add_monoid_hom.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance : integral_domain (power_series R) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, .. power_series.nontrivial, .. power_series.comm_ring } /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series R))).is_prime := begin suffices : ideal.span ({X} : set (power_series R)) = (constant_coeff R).ker, { rw this, exact ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series R) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff R 1) h } end end integral_domain section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f variables [local_ring R] [local_ring S] instance : local_ring (power_series R) := mv_power_series.local_ring end local_ring section field variables {k : Type*} [field k] /-- The inverse 1/f of a power series f defined over a field -/ protected def inv : power_series k → power_series k := mv_power_series.inv instance : has_inv (power_series k) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series k) : φ⁻¹ = inv.aux (constant_coeff k φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff k φ)⁻¹ else - (constant_coeff k φ)⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff k φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series k) : constant_coeff k (φ⁻¹) = (constant_coeff k φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series k} : φ⁻¹ = 0 ↔ constant_coeff k φ = 0 := mv_power_series.inv_eq_zero @[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series k) (h : constant_coeff k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series k) (u : units k) (h : constant_coeff k φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv φ h @[simp] protected lemma inv_mul (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul φ h end field end power_series namespace power_series variable {R : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [comm_semiring R] /-- The order of a formal power series `φ` is the smallest `n : enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ @[reducible] def order (φ : power_series R) : enat := multiplicity X φ lemma order_finite_of_coeff_ne_zero (φ : power_series R) (h : ∃ n, coeff R n φ ≠ 0) : (order φ).dom := begin cases h with n h, refine ⟨n, _⟩, rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (φ : power_series R) (h : (order φ).dom) : coeff R (φ.order.get h) φ ≠ 0 := begin have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff, intros m hm, by_cases Hm : m < nat.find h, { have := nat.find_min h Hm, push_neg at this, rw X_pow_dvd_iff at this, exact this m (lt_add_one m) }, have : m = nat.find h, {linarith}, {rwa this} end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (φ : power_series R) (n : ℕ) (h : coeff R n φ ≠ 0) : order φ ≤ n := begin have h : ¬ X^(n+1) ∣ φ, { rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ }, have : (order φ).dom := ⟨n, h⟩, rw [← enat.coe_get this, enat.coe_le_coe], refine nat.find_min' this h end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (φ : power_series R) (n : ℕ) (h: ↑n < order φ) : coeff R n φ = 0 := by { contrapose! h, exact order_le _ _ h } /-- The `0` power series is the unique power series with infinite order.-/ lemma order_eq_top {φ : power_series R} : φ.order = ⊤ ↔ φ = 0 := begin rw multiplicity.eq_top_iff, split, { intro h, ext n, specialize h (n+1), rw X_pow_dvd_iff at h, exact h n (lt_add_one _) }, { rintros rfl n, exact dvd_zero _ } end /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series R) = ⊤ := multiplicity.zero _ /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma nat_le_order (φ : power_series R) (n : ℕ) (h : ∀ i < n, coeff R i φ = 0) : ↑n ≤ order φ := begin by_contra H, rw not_le at H, have : (order φ).dom := enat.dom_of_le_some (le_of_lt H), rw [← enat.coe_get this, enat.coe_lt_coe] at H, exact coeff_order _ this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma le_order (φ : power_series R) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff R i φ = 0) : n ≤ order φ := begin induction n using enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (enat.coe_lt_top i) }, { apply nat_le_order, simpa only [enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series R} {n : ℕ} : order φ = n ↔ (coeff R n φ ≠ 0) ∧ (∀ i, i < n → coeff R i φ = 0) := begin simp only [eq_some_iff, X_pow_dvd_iff], push_neg, split, { rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩, suffices : n = m, { rwa this }, suffices : m ≥ n, { linarith }, contrapose! hm₂, exact h₁ _ hm₂ }, { rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series R} {n : enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff R i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff R i φ = 0) := begin induction n using enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } }, { simpa [enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma le_order_add (φ ψ : power_series R) : min (order φ) (order ψ) ≤ order (φ + ψ) := multiplicity.min_le_multiplicity_add private lemma order_add_of_order_eq.aux (φ ψ : power_series R) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi, coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series R) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (le_order_add _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series R) : order φ + order ψ ≤ order (φ * ψ) := begin apply le_order, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order φ i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order ψ j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add hi hj), rw [← enat.coe_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : R) : order (monomial R n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, add_monoid_hom.map_zero] }, { rw [order_eq], split; intros i hi, { rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial'] }, { rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : R) (h : a ≠ 0) : order (monomial R n a) = n := by rw [order_monomial, if_neg h] end order_basic section order_zero_ne_one variables [comm_semiring R] [nontrivial R] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series R) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:R) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series R) = 1 := order_monomial_of_ne_zero 1 (1:R) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series R)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_integral_domain variables [integral_domain R] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series R) : order (φ * ψ) = order φ + order ψ := multiplicity.mul (X_prime) end order_integral_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe (polynomial R) (power_series R) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ @[simp, norm_cast] lemma coeff_coe (φ : polynomial R) (n) : power_series.coeff R n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : R) : (monomial n a : power_series R) = power_series.monomial R n a := power_series.ext $ λ m, begin rw [coeff_coe, power_series.coeff_monomial], simp only [@eq_comm _ m n], convert finsupp.single_apply, end @[simp, norm_cast] lemma coe_zero : ((0 : polynomial R) : power_series R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : polynomial R) : power_series R) = 1 := begin have := coe_monomial 0 (1:R), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_add (φ ψ : polynomial R) : ((φ + ψ : polynomial R) : power_series R) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul (φ ψ : polynomial R) : ((φ * ψ : polynomial R) : power_series R) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : polynomial R) : power_series R) = power_series.C R a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_X : ((X : polynomial R) : power_series R) = power_series.X := coe_monomial _ _ /-- The coercion from polynomials to power series as a ring homomorphism. -/ -- TODO as an algebra homomorphism? def coe_to_power_series.ring_hom : polynomial R →+* power_series R := { to_fun := (coe : polynomial R → power_series R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } end polynomial
b54193e727ad8e326c35cf3c4f360f311e852e8a
0d9b0a832bc57849732c5bd008a7a142f7e49656
/src/boxint.lean
88e95e137b92e78b8c16be2918d0e8358edc6e05
[]
no_license
mirefek/sokoban.lean
bb9414af67894e4d8ce75f8c8d7031df02d371d0
451c92308afb4d3f8e566594b9751286f93b899b
refs/heads/master
1,681,025,245,267
1,618,997,832,000
1,618,997,832,000
359,491,681
10
0
null
null
null
null
UTF-8
Lean
false
false
13,554
lean
import tactic import .direction import .list2d import .boolset2d import .component2d import .sokostate structure boxint := (subboxes : bset2d) (supboxes : bset2d) (sk_comp : bset2d) structure boxint.valid (avail : bset2d) (as : boxint) : Prop := (sub_sup : as.subboxes ⊆ as.supboxes) (sup_avail : as.supboxes ⊆ avail) (sub_disj : as.subboxes.disjoint as.sk_comp) (sk_comp_avail : as.sk_comp ⊆ avail) (sk_comp_closed : ∀ xy ∈ as.sk_comp, ∀ d : direction, d.shift xy ∈ avail → (d.shift xy ∈ as.sk_comp ∨ d.shift xy ∈ as.subboxes)) def boxint.mem (s : sokostate) (as : boxint) := s.storekeeper ∈ as.sk_comp ∧ as.subboxes ⊆ s.boxes ∧ s.boxes ⊆ as.supboxes instance : has_mem sokostate boxint := ⟨boxint.mem⟩ lemma boxint.mem.unfold {s : sokostate} {as : boxint} : s ∈ as = (s.storekeeper ∈ as.sk_comp ∧ as.subboxes ⊆ s.boxes ∧ s.boxes ⊆ as.supboxes) := rfl instance boxint.mem.decidable (s : sokostate) (as : boxint) : decidable (s ∈ as) := begin unfold has_mem.mem, unfold boxint.mem, apply_instance, end def boxint.disjoint (as1 : boxint) (as2 : boxes_only) : Prop := ¬ (as1.subboxes ⊆ as2.boxes ∧ as2.boxes ⊆ as1.supboxes) lemma boxint.disjoint_correct (as : boxint) (bs : boxes_only) (s : sokostate) : as.disjoint bs → s ∈ as → s ∈ bs → false := begin simp [boxint.mem.unfold, boxes_only.mem.unfold, boxint.disjoint], introv Hnsol Hsk Hsub Hsup Hsbs Hbss, exact Hnsol (bset2d.subset.trans Hsub Hsbs) (bset2d.subset.trans Hbss Hsup), end instance boxint.disjoint.decidable (as : boxint) (bs : boxes_only) : decidable (as.disjoint bs) := begin unfold boxint.disjoint, apply_instance, end def boxint.subset (as1 as2 : boxint) : Prop := as1.sk_comp ⊆ as2.sk_comp ∧ as2.subboxes ⊆ as1.subboxes ∧ as1.supboxes ⊆ as2.supboxes instance : has_subset boxint := ⟨boxint.subset⟩ lemma boxint.subset_correct (as1 as2 : boxint) : as1 ⊆ as2 → ∀ s : sokostate, s ∈ as1 → s ∈ as2 := begin intros H12 s H1, rcases H12 with ⟨H12sk,H12sub,H12sup⟩, rcases H1 with ⟨H1sk,H1sub,H1sup⟩, split, exact H12sk _ H1sk, split, exact bset2d.subset.trans H12sub H1sub, exact bset2d.subset.trans H1sup H12sup, end instance boxint.subset.decidable (as1 as2 : boxint) : decidable (as1 ⊆ as2) := begin unfold has_subset.subset, unfold boxint.subset, apply_instance, end def boxint.subset_g (as1 as2 : boxint) (goal : boxes_only) : Prop := as1.sk_comp ⊆ as2.sk_comp ∧ as2.subboxes ⊆ as1.subboxes ∧ ( as1.supboxes ⊆ as2.supboxes ∨ goal.boxes.count ≤ as1.subboxes.count ∧ as1.subboxes ⊆ as2.supboxes ) lemma boxint.subset_g_correct {avail : bset2d} {as1 as2 : boxint} {goal : boxes_only} : as1.subset_g as2 goal → ∀ s sg : sokostate, s ∈ as1 → sg ∈ goal → sg.reachable avail s → s ∈ as2 := begin intros H12 s sg H1 Hg Hr, rcases H12 with ⟨H12sk, H12sub, H12sup_cnt⟩, rcases H1 with ⟨H1sk,H1sub, H1sup⟩, split, exact H12sk _ H1sk, split, exact bset2d.subset.trans H12sub H1sub, cases H12sup_cnt with H12sup H12sup_cnt, exact bset2d.subset.trans H1sup H12sup, { cases H12sup_cnt with H_cnt H12sup, have : sg.boxes.count = s.boxes.count := sokostate.reachable_keep_box_count Hr, have : as1.subboxes.count ≤ s.boxes.count := bset2d.count_le_of_subset _ _ H1sub, have : sg.boxes.count ≤ goal.boxes.count := bset2d.count_le_of_subset _ _ Hg.1, have : as1.subboxes.count = s.boxes.count, by omega, have : s.boxes ⊆ as1.subboxes := bset2d.subset_eq_of_count_eq _ _ H1sub this, exact bset2d.subset.trans this H12sup, } end instance boxint.subset_g.decidable (as1 as2 : boxint) (goal : boxes_only) : decidable (as1.subset_g as2 goal) := begin unfold boxint.subset_g, apply_instance, end def boxint.generate (avail : bset2d) (subboxes supboxes : bset2d) (sk : ℕ × ℕ) : boxint := { subboxes := subboxes, supboxes := supboxes, sk_comp := component2d (avail \ subboxes) (bset2d.from_index sk), } theorem boxint.generate_valid {avail subboxes supboxes : bset2d} {sk : ℕ × ℕ} : subboxes ⊆ supboxes → supboxes ⊆ avail → (boxint.generate avail subboxes supboxes sk).valid avail := begin intros sub_sup sup_avail, split, exact sub_sup, exact sup_avail, { intros xy Hsub Hcomp, exact bset2d.nmem_of_mem_sdiff (component2d_subset_avail xy Hcomp) Hsub, }, { intros xy Hcomp, exact bset2d.mem_of_mem_sdiff (component2d_subset_avail xy Hcomp), }, { introv Hcomp Ha2, by_cases C : d.shift xy ∈ subboxes, { right, exact C, }, left, have Ha2 : d.shift xy ∈ avail \ subboxes := bset2d.mem_sdiff_of_mem_nmem Ha2 C, exact component2d_closed Hcomp Ha2, }, end def boxint.get_pushes (avail : bset2d) (s : boxint) : list (direction × (ℕ × ℕ)) := do box ← s.subboxes.to_indexes, d ← direction.luniv, if d.shift box ∈ avail ∧ d.shift box ∉ s.subboxes ∧ d.opposite.shift box ∈ s.sk_comp then return (d, box) else list.nil def boxint.get_appearances (avail : bset2d) (s : boxint) : list (direction × (ℕ × ℕ)) := do box ← (avail \ s.supboxes).to_indexes, d ← direction.luniv, if d.shift box ∈ s.supboxes ∧ d.shift box ∉ s.subboxes ∧ d.shift (d.shift box) ∈ s.sk_comp ∧ d.shift (d.shift box) ≠ d.shift box then return (d.opposite, d.shift box) else list.nil def boxint.get_moves (avail : bset2d) (as : boxint) : list (direction × (ℕ × ℕ)) := boxint.get_pushes avail as ++ boxint.get_appearances avail as lemma boxint.in_get_moves_iff (avail : bset2d) (s : boxint) (Hv : s.valid avail) : ∀ (d : direction) (box : ℕ×ℕ), (d,box) ∈ boxint.get_moves avail s ↔ ( d.opposite.shift box ∈ s.sk_comp ∧ d.opposite.shift box ≠ box ∧ d.shift box ∈ avail ∧ d.shift box ∉ s.subboxes ∧ box ∈ s.supboxes ∧ (d.shift box ∈ s.supboxes → box ∈ s.subboxes) ) := begin intros, unfold boxint.get_moves, rw list.mem_append, split, { rename box box', rename d d', intro H, cases H, { unfold boxint.get_pushes at H, simp [-prod.exists] at H, rcases H with ⟨box,Hbox,d,Huniv,H⟩, clear Huniv, have Hbox := (bset2d.to_indexes_iff _ _).mp Hbox, by_cases C : d.shift box ∈ avail ∧ d.shift box ∉ s.subboxes ∧ d.opposite.shift box ∈ s.sk_comp, { simp [C] at H, rw [H.1, H.2], clear H, rcases C with ⟨Ha2, Hnb2, Hsk⟩, split, exact Hsk, split, { -- disproving border case assume Heq, rw Heq at Hsk, exact Hv.sub_disj box Hbox Hsk, }, split, exact Ha2, split, exact Hnb2, split, exact Hv.sub_sup box Hbox, intro, exact Hbox, }, { simp [C] at H, exact false.elim H, }, }, { unfold boxint.get_appearances at H, simp [-prod.exists] at H, rcases H with ⟨box,Hbox,d,Huniv,H⟩, clear Huniv, have Hbox := (bset2d.to_indexes_iff _ box).mp Hbox, have Hba: box ∈ avail, from bset2d.mem_of_mem_sdiff Hbox, have Hbnsup: box ∉ s.supboxes, from bset2d.nmem_of_mem_sdiff Hbox, by_cases C : d.shift box ∈ s.supboxes ∧ d.shift box ∉ s.subboxes ∧ d.shift (d.shift box) ∈ s.sk_comp ∧ d.shift (d.shift box) ≠ d.shift box, { simp [C] at H, rw [H.1, H.2], clear H, rcases C with ⟨Hsup2, Hfree, Hcomp, Hnngen⟩, cases direction.opposite_shift d box with Heq Hop_simp, { -- border case d.shift box = box simp [Heq] at Hnngen, exact false.elim Hnngen, }, { rw [Hop_simp, direction.opposite_opposite], split, exact Hcomp, split, exact Hnngen, split, exact Hba, split, exact mt (Hv.sub_sup box) Hbnsup, split, exact Hsup2, assume Hbsup, exact false.elim (Hbnsup Hbsup), } }, { simp [C] at H, exact false.elim H, } } }, { rintros ⟨Hcomp, Hnngen, Hav, Hfree, Hsup, H⟩, by_cases C : box ∈ s.subboxes, { left, unfold boxint.get_pushes, simp [-prod.exists], existsi box, split, exact (bset2d.to_indexes_iff s.subboxes box).mpr C, existsi d, split, exact direction.luniv_complete, simp [Hfree, Hcomp, Hav], }, { right, unfold boxint.get_appearances, simp [-prod.exists], existsi d.shift box, split, { show d.shift box ∈ (avail \ s.supboxes).to_indexes, apply (bset2d.to_indexes_iff _ _).mpr, apply bset2d.mem_sdiff_of_mem_nmem, exact Hav, assume H2, exact C (H H2), }, existsi d.opposite, split, exact direction.luniv_complete, simp [direction.opposite_opposite], cases direction.opposite_shift d box with Heq Hop_simp, { -- border case, d.shift box = box rw Heq at H Hfree, exact false.elim (C (H Hsup)), }, { rw Hop_simp, simp! [Hsup, C, Hcomp, Hnngen], } }, } end def boxint.move (avail : bset2d) (s : boxint) (d : direction) (box : ℕ×ℕ) := boxint.generate avail ((s.subboxes.remove box).add (d.shift box)) ((s.supboxes.remove box).add (d.shift box)) box def boxint.next_states (avail : bset2d) (s : boxint) : list boxint := list.map (function.uncurry (boxint.move avail s)) (boxint.get_moves avail s) theorem boxint.next_valid (avail : bset2d) (as1 : boxint) : as1.valid avail → ∀ as2 : boxint, as2 ∈ as1.next_states avail → as2.valid avail := begin introv Hv H, simp [boxint.next_states, -prod.exists] at H, rcases H with ⟨⟨d, box⟩, H, Heq⟩, simp at Heq, rw ←Heq, clear Heq as2, rw (boxint.in_get_moves_iff avail as1 Hv) at H, rcases H with ⟨Hcomp, Hnng, Hav, Hnb, Hsp, Hextra⟩, apply boxint.generate_valid, { apply bset2d.subset_add_same, apply bset2d.subset_remove_same, exact Hv.sub_sup, }, { assume xy, assume H, cases bset2d.of_mem_add H with H H, rw H, exact Hav, have := bset2d.mem_of_mem_remove H, exact Hv.sup_avail xy this, } end theorem boxint.next_of_real_move (avail : bset2d) (as1 : boxint) : as1.valid avail → ∀ (s : sokostate) (d : direction), s ∈ as1 → s.move avail d ∈ as1 ∨ (∃ as2 : boxint, as2 ∈ as1.next_states avail ∧ s.move avail d ∈ as2) := begin intros Hv s d Hin, have := Hin, rcases this with ⟨Hsk,Hsub,Hsup⟩, let box := d.shift s.storekeeper, let box2 := d.shift box, by_cases C : box ∈ s.boxes ∧ box2 ∈ avail ∧ box2 ∉ s.boxes ∧ (box ∈ as1.subboxes ∨ box2 ∉ as1.supboxes), { right, -- we move to another abstract state existsi as1.move avail d box, rcases C with ⟨Hbb, Hb2a, Hb2nb, Has⟩, split, { -- in next_states simp [boxint.next_states, -prod.exists], existsi (d,box), split, { apply (boxint.in_get_moves_iff avail as1 Hv d box).mpr, have Hngen : box ≠ s.storekeeper, { assume Heq, simp [box] at Heq, simp only [box,box2,Heq] at Hbb Hb2nb, exact false.elim (Hb2nb Hbb), }, have : d.opposite.shift box = s.storekeeper := or.resolve_left (direction.opposite_shift d s.storekeeper) Hngen, rw this, split, exact Hsk, split, exact ne_comm.mp Hngen, split, exact Hb2a, split, exact mt (Hsub box2) Hb2nb, split, exact Hsup box Hbb, exact or.neg_resolve_right Has, }, refl, }, { -- emulates real move have Hba : box ∈ avail := Hv.sup_avail box (Hsup box Hbb), simp [boxint.move, boxint.generate], simp [sokostate.move, Hba, Hbb, Hb2a, Hb2nb], split, simp, { apply component2d_supset, { intros xy H, rw (bset2d.from_index_iff box xy).1 H, clear H xy, apply bset2d.mem_sdiff_of_mem_nmem Hba, apply bset2d.nmem_add_of_neq_nmem, { intro contra, rw contra at Hbb, exact Hb2nb Hbb, }, exact bset2d.nmem_remove, }, exact (bset2d.from_index_iff box box).2 rfl, }, simp, split, { apply bset2d.subset_add_same, apply bset2d.subset_remove_same, exact Hsub, }, apply bset2d.subset_add_same, apply bset2d.subset_remove_same, exact Hsup, } }, left, -- the abstract state remains the same simp at C, simp [sokostate.move], by_cases Cba : box ∈ avail, { simp [Cba], by_cases Cbb : box ∈ s.boxes, { simp [Cbb], by_cases Cb2a : box2 ∈ avail, { simp [Cb2a], by_cases Cb2b : box2 ∈ s.boxes, { simp [Cb2b], exact Hin, }, { simp [Cb2b], have C := C Cbb Cb2a Cb2b, cases not_or_distrib.mp C with C1 C2, have C2 := not_not.mp C2, rw boxint.mem.unfold, split, exact or.resolve_right (Hv.sk_comp_closed s.storekeeper Hsk d Cba) C1, split, { intros xy Hin, apply bset2d.mem_add_of_mem, apply bset2d.mem_remove_of_neq_mem, { intro contra, rw contra at Hin, exact C1 Hin, }, { exact Hsub xy Hin }, }, { intros xy Hin, cases bset2d.of_mem_add Hin with Heq Hin, { rw Heq, exact C2, }, { exact Hsup xy (bset2d.mem_of_mem_remove Hin), }, }, }, }, { simp [Cb2a], exact Hin, }, }, { simp [Cbb], split, exact or.resolve_right (Hv.sk_comp_closed s.storekeeper Hsk d Cba) (mt (Hsub box) Cbb), exact and.intro Hsub Hsup, }, }, { simp [Cba], exact Hin, }, end
c8074ea4c1881803689c62edcfcbd4b63c2c96ad
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/init/hedberg.hlean
77a830c67107f03a5b784bf12a144f2f109e6408
[ "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
1,508
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Hedberg's Theorem: every type with decidable equality is a set -/ prelude import init.trunc open eq eq.ops nat is_trunc sigma -- TODO(Leo): move const coll and path_coll to a different file? private definition const {A B : Type} (f : A → B) := ∀ x y, f x = f y private definition coll (A : Type) := Σ f : A → A, const f private definition path_coll (A : Type) := ∀ x y : A, coll (x = y) section parameter {A : Type} hypothesis [h : decidable_eq A] variables {x y : A} private definition pc [reducible] : path_coll A := λ a b, decidable.rec_on (h a b) (λ p : a = b, ⟨(λ q, p), λ q r, rfl⟩) (λ np : ¬ a = b, ⟨(λ q, q), λ q r, absurd q np⟩) private definition f [reducible] : x = y → x = y := sigma.rec_on (pc x y) (λ f c, f) private definition f_const (p q : x = y) : f p = f q := sigma.rec_on (pc x y) (λ f c, c p q) private definition aux (p : x = y) : p = (f (refl x))⁻¹ ⬝ (f p) := have aux : refl x = (f (refl x))⁻¹ ⬝ (f (refl x)), from eq.rec_on (f (refl x)) rfl, eq.rec_on p aux definition is_set_of_decidable_eq : is_set A := is_set.mk A (λ x y p q, calc p = (f (refl x))⁻¹ ⬝ (f p) : aux ... = (f (refl x))⁻¹ ⬝ (f q) : f_const ... = q : aux) end attribute is_set_of_decidable_eq [instance] [priority 600]
5c229cc29a810407367a867e6d6a25ad264a44bc
1a9d3677cccdaaccacb163507570e75d34043a38
/src/week_4/Part_C_topology.lean
1d999dee2919a91a392250f82962bd308aca6df2
[ "Apache-2.0" ]
permissive
alreadydone/formalising-mathematics
687d386a72065795e784e270f5c05ea3948b67dd
65869362cd7a2ac74dd1a97c7f9471835726570b
refs/heads/master
1,680,260,936,332
1,616,563,371,000
1,616,563,371,000
348,780,769
0
0
null
null
null
null
UTF-8
Lean
false
false
7,238
lean
import topology.subset_properties -- compactness of subsets of top spaces /-! # Topology, the traditional way Let's do some topology! In this file we prove that * the continuous image of a compact space is compact; * A closed subset of a compact space is compact. ## Details In fact we do a little more than this (but it's basically equivalent). We do not work with compact topological spaces, we work with compact subsets of topological spaces. What we will actually prove is this: * If `f : X → Y` is a continuous map, and `S : set X` is a compact subset (with the subspace topology), then `f '' S` (the image of `S` under `f`) is compact (with the subspace topology). * If `X` is a topological space, if `S` is a compact subset and if `C` is a closed subset, then `S ∩ C` is a compact subset. The original results are just the special case where `S` is `univ : set X`. -/ -- Let X and Y be topological spaces, and let `f : X → Y` be a map. variables (X Y : Type) [topological_space X] [topological_space Y] (f : X → Y) -- I don't want to be typing `set.this` and `set.that` so let's open -- the `set` namespace once and for all. open set /-! ## Compact subspaces `is_compact` is a predicate on `set X`, if `X` is a topological space. In other words, `is_compact X` doesn't make sense, but if `S : set X` then `is_compact S` does. The actual definition in mathlib involves filters! But it is a theorem in mathlib that `is_compact S` is true if and only if every collection of open subsets of `X` whose union contains `S` has a finite subcollection whose union contains `S`. Unfortunately, mathlib's version of this, `compact_iff_finite_subcover`, uses a slightly wacky notion of finite subcover involving `finset X`, the type of finite subsets of `X` (a completely different type to the type `set X`!). We prove an easier-to-use version involving `finite Z`, the predicate saying that `Z : set ι` is finite. You can ignore this proof. -/ lemma compact_iff_finite_subcover' {α : Type} [topological_space α] {S : set α} : is_compact S ↔ (∀ {ι : Type} (U : ι → (set α)), (∀ i, is_open (U i)) → S ⊆ (⋃ i, U i) → (∃ (t : set ι), t.finite ∧ S ⊆ (⋃ i ∈ t, U i))) := begin rw compact_iff_finite_subcover, split, { intros hs ι U hU hsU, cases hs U hU hsU with F hF, use [(↑F : set ι), finset.finite_to_set F], exact hF }, { intros hs ι U hU hsU, rcases hs U hU hsU with ⟨F, hFfin, hF⟩, use hFfin.to_finset, convert hF, ext, simp } end /-! ## Continuous image of compact is compact I would start with `rw compact_iff_finite_subcover' at hS ⊢,` The proof that I recommend formalising is this. Say `S` is a compact subset of `X`, and `f : X → Y` is continuous. We want to prove that every cover of `f '' S` by open subsets of `Y` has a finite subcover. So let's cover `f '' S` with opens `U i : set Y`, for `i : ι` and `ι` an index type. Pull these opens back to `V i : set X` and observe that they cover `S`. Choose a finite subcover corresponding to some `F : set ι` such that `F` is finite (Lean writes this `h : F.finite`) and then check that the corresponding cover of `f '' S` by the `U i` with `i ∈ F` is a finite subcover. Good luck! Please ask questions (or DM me on discord if you don't want to ask publically). Also feel free to DM me if you manage to do it! Useful theorems: `continuous.is_open_preimage` -- preimage of an open set under a continuous map is open. `is_open_compl_iff` -- complement `Sᶜ` of `S` is open iff `S` is closed. ## Some useful tactics: ### `specialize` `specialize` can be used with `_`. If you have a hypothesis `hS : ∀ {ι : Type} (U : ι → set X), (∀ (i : ι), is_open (U i)) → ...` and `U : ι → set X`, then `specialize hS U` will change `hS` to `hS : (∀ (i : ι), is_open (U i)) → ...` But what if you now want to prove `∀ i, is_open (U i)` so you can feed it into `hS` as an input? You can put `specialize hS _` and then that goal will pop out. Unfortunately it pops out _under_ the current goal! You can swap two goals with the `swap` tactic though :-) ### `change` If your goal is `⊢ P` and `P` is definitionally equal to `Q`, then you can write `change Q` and the goal will change to `Q`. Sometimes useful because rewriting works up to syntactic equality, which is stronger than definitional equality. ### `rwa` `rwa h` just means `rw h, assumption` ### `contradiction` If you have `h1 : P` and `h2 : ¬ P` as hypotheses, then you can prove any goal with the `contradiction` tactic, which just does `exfalso, apply h2, exact h1`. ### `set` Note : The `set` tactic is totally unrelated to the `set X` type of subsets of `X`! The `set` tactic can be used to define things. For example `set T := f '' S with hT_def,` will define `T` to be `f '' S` and will also define `hT_def : T = f '' S`. -/ lemma image_compact_of_compact (hf : continuous f) (S : set X) (hS : is_compact S) : is_compact (f '' S) := begin -- proof I recommend: -- (1) cover f''s with opens. Want finite subcover -- (2) pull back -- (3) finite subcover -- (4) push forward -- start by changing `is_compact` to something we can work with. rw compact_iff_finite_subcover' at hS ⊢, -- Define `T` to be `f '' S` -- why not? --set T := f '' S with hT_def, -- Now `T = f '' S` and `hT_def` tells us that. -- Note that `set T := ...` is about the *tactic* `set`. -- OK let's go. intros ι U ho hc, rcases hS (λi, f⁻¹'(U i)) _ _ with ⟨t,ht,hcf⟩, { use t, split, exact ht, rintros y ⟨x,hx,he⟩, rw ← he, specialize hcf hx, rwa mem_bUnion_iff at hcf ⊢ }, intro i, exact continuous.is_open_preimage hf _ (ho i), rwa [←preimage_Union, ←image_subset_iff] end /- ## Closed subset of a compact is compact. This is a little trickier because given `U : ι → set X` we need to produce `V : option ι → set X` at some point in the below proof. We can make it using `option.rec`. If `S` is compact and `C` is closed then we want to prove `S ∩ C` is compact. Start with `rw compact_iff_finite_subcover' at hS ⊢,`. Then given a cover `U : ι → set X`, define `V : option ι → set X` like this: `let V : option ι → set X := λ x, option.rec Cᶜ U x,` For finiteness, if you have `F : set (option ι)` and `hF : F.finite`, and you want `(some ⁻¹' F).finite`, then you can apply `set.finite.preimage` and use `option.some_inj` to deal with the injectivity. -/ lemma closed_of_compact (S : set X) (hS : is_compact S) (C : set X) (hC : is_closed C) : is_compact (S ∩ C) := begin rw compact_iff_finite_subcover' at hS ⊢, intros ι U ho hc, rcases hS (λi, option.rec Cᶜ U i) _ _ with ⟨t,ht,hcf⟩, { use function.embedding.some⁻¹' t, split, exact finite.preimage_embedding _ ht, intros x hx, specialize hcf hx.1, rw mem_bUnion_iff at hcf ⊢, rcases hcf with ⟨_|i,hi,h⟩, exact (h hx.2).elim, -- contradiction exact ⟨i,hi,h⟩ }, { rintro ⟨_|i⟩, exacts [hC, ho i] }, { intros x hx, rw mem_Union, by_cases h : x ∈ C, specialize hc ⟨hx,h⟩, rw mem_Union at hc, cases hc with i hi, exacts [⟨some i, hi⟩, ⟨none, h⟩] } end
49c413227bf0bee30177e979e5313ac471916570
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/char_p.lean
cd4cf2165c95085499b19698ba2bf399fa46ee1f
[ "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
9,111
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau, Joey van Langen, Casper Putz Characteristic of semirings. -/ import data.padics.padic_norm data.nat.choose data.fintype.basic import data.zmod.basic algebra.module universes u v /-- The generator of the kernel of the unique homomorphism ℕ → α for a semiring α -/ class char_p (α : Type u) [semiring α] (p : ℕ) : Prop := (cast_eq_zero_iff [] : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x) theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 := (char_p.cast_eq_zero_iff α p p).2 (dvd_refl p) theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q := nat.dvd_antisymm ((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _)) ((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _)) instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 := ⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩ theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p := by letI := classical.dec_eq α; exact classical.by_cases (assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0, ⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩) (λ H, ⟨nat.find (classical.not_forall.1 H), ⟨λ x, ⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2, nat.find_min (classical.not_forall.1 H) (nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)) (not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (classical.not_forall.1 H)), nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul, add_zero] at H1, H2⟩)), λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul]⟩⟩⟩) theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p := let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩ /-- Noncomuptable function that outputs the unique characteristic of a semiring. -/ noncomputable def ring_char (α : Type u) [semiring α] : ℕ := classical.some (char_p.exists_unique α) theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x := by letI := (classical.some_spec (char_p.exists_unique α)).1; unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α) theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α := (classical.some_spec (char_p.exists_unique α)).2 p C theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} (hp : nat.prime p) [char_p α p] (x y : α) : (x + y)^p = x^p + y^p := begin rw [add_pow, finset.sum_range_succ, nat.sub_self, pow_zero, nat.choose_self], rw [nat.cast_one, mul_one, mul_one, add_left_inj], transitivity, { refine finset.sum_eq_single 0 _ _, { intros b h1 h2, have := nat.prime.dvd_choose (nat.pos_of_ne_zero h2) (finset.mem_range.1 h1) hp, rw [← nat.div_mul_cancel this, nat.cast_mul, char_p.cast_eq_zero α p], simp only [mul_zero] }, { intro H, exfalso, apply H, exact finset.mem_range.2 hp.pos } }, rw [pow_zero, nat.sub_zero, one_mul, nat.choose_zero_right, nat.cast_one, mul_one] end section frobenius variables (R : Type u) [comm_ring R] {S : Type v} [comm_ring S] (f : R →* S) (g : R →+* S) (p : ℕ) [nat.prime p] [char_p R p] [char_p S p] (x y : R) /-- The frobenius map that sends x to x^p -/ def frobenius : R →+* R := { to_fun := λ x, x^p, map_one' := one_pow p, map_mul' := λ x y, mul_pow x y p, map_zero' := zero_pow (lt_trans zero_lt_one ‹nat.prime p›.one_lt), map_add' := add_pow_char R ‹nat.prime p› } variable {R} theorem frobenius_def : frobenius R p x = x ^ p := rfl theorem frobenius_mul : frobenius R p (x * y) = frobenius R p x * frobenius R p y := (frobenius R p).map_mul x y theorem frobenius_one : frobenius R p 1 = 1 := one_pow _ variable {R} theorem monoid_hom.map_frobenius : f (frobenius R p x) = frobenius S p (f x) := f.map_pow x p theorem ring_hom.map_frobenius : g (frobenius R p x) = frobenius S p (g x) := g.map_pow x p theorem monoid_hom.map_iterate_frobenius (n : ℕ) : f (frobenius R p^[n] x) = (frobenius S p^[n] (f x)) := (nat.iterate₁ $ λ x, (f.map_frobenius p x).symm).symm theorem ring_hom.map_iterate_frobenius (n : ℕ) : g (frobenius R p^[n] x) = (frobenius S p^[n] (g x)) := g.to_monoid_hom.map_iterate_frobenius p x n theorem monoid_hom.iterate_map_frobenius (f : R →* R) (p : ℕ) [nat.prime p] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ theorem ring_hom.iterate_map_frobenius (f : R →+* R) (p : ℕ) [nat.prime p] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ variable (R) theorem frobenius_zero : frobenius R p 0 = 0 := (frobenius R p).map_zero theorem frobenius_add : frobenius R p (x + y) = frobenius R p x + frobenius R p y := (frobenius R p).map_add x y theorem frobenius_neg : frobenius R p (-x) = -frobenius R p x := (frobenius R p).map_neg x theorem frobenius_sub : frobenius R p (x - y) = frobenius R p x - frobenius R p y := (frobenius R p).map_sub x y theorem frobenius_nat_cast (n : ℕ) : frobenius R p n = n := (frobenius R p).map_nat_cast n end frobenius theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [nat.prime p] [char_p α p] : function.injective (frobenius α p) := λ x h H, by { rw ← sub_eq_zero at H ⊢, rw ← frobenius_sub at H, exact pow_eq_zero H } namespace char_p section variables (α : Type u) [ring α] lemma char_p_to_char_zero [char_p α 0] : char_zero α := add_group.char_zero_of_inj_zero $ λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff α 0 n).mp h0) lemma cast_eq_mod (p : ℕ) [char_p α p] (k : ℕ) : (k : α) = (k % p : ℕ) := calc (k : α) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div] ... = ↑(k % p) : by simp[cast_eq_zero] theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p α p] [fintype α] : p ≠ 0 := assume h : p = 0, have char_zero α := @char_p_to_char_zero α _ (h ▸ hc), absurd (@nat.cast_injective α _ _ this) (not_injective_infinite_fintype coe) end section integral_domain open nat variables (α : Type u) [integral_domain α] theorem char_ne_one (p : ℕ) [hc : char_p α p] : p ≠ 1 := assume hp : p = 1, have ( 1 : α) = 0, by simpa using (cast_eq_zero_iff α p 1).mpr (hp ▸ dvd_refl p), absurd this one_ne_zero theorem char_is_prime_of_ge_two (p : ℕ) [hc : char_p α p] (hp : p ≥ 2) : nat.prime p := suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩, assume (d : ℕ) (hdvd : ∃ e, p = d * e), let ⟨e, hmul⟩ := hdvd in have (p : α) = 0, from (cast_eq_zero_iff α p p).mpr (dvd_refl p), have (d : α) * e = 0, from (@cast_mul α _ d e) ▸ (hmul ▸ this), or.elim (no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero (d : α) e this) (assume hd : (d : α) = 0, have p ∣ d, from (cast_eq_zero_iff α p d).mp hd, show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this)) (assume he : (e : α) = 0, have p ∣ e, from (cast_eq_zero_iff α p e).mp he, have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul), have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›, have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1), have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul, show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this)) theorem char_is_prime_or_zero (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 := match p, hc with | 0, _ := or.inr rfl | 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one α _ (1 : ℕ) hc) | (m+2), hc := or.inl (@char_is_prime_of_ge_two α _ (m+2) hc (nat.le_add_left 2 m)) end theorem char_is_prime [fintype α] (p : ℕ) [char_p α p] : nat.prime p := or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p) end integral_domain end char_p namespace zmod variables (α : Type u) [ring α] {n : ℕ+} /-- `zmod.cast : zmod n →+* α` as a ring homomorphism. -/ def cast_hom [char_p α n] : zmod n →+* α := { to_fun := cast, map_zero' := rfl, map_one' := by rw ←@nat.cast_one α _ _; exact eq.symm (char_p.cast_eq_mod α n 1), map_mul' := assume x y : zmod n, show ↑((x * y).val) = ↑(x.val) * ↑(y.val), by rw [zmod.mul_val, ←char_p.cast_eq_mod, nat.cast_mul], map_add' := assume x y : zmod n, show ↑((x + y).val) = ↑(x.val) + ↑(y.val), by rw [zmod.add_val, ←char_p.cast_eq_mod, nat.cast_add] } instance to_module [char_p α n] : module (zmod n) α := (cast_hom α).to_module instance to_module' {m : ℕ} {hm : m > 0} [hc : char_p α m] : module (zmod ⟨m, hm⟩) α := @zmod.to_module α _ ⟨m, hm⟩ hc end zmod
902895269331a1bb928701db3bf5ede32c5b6fe1
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/test/tactics.lean
d4787354e8dae018c7031281bda8dd1cfcbadbff
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
15,798
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Scott Morrison -/ import tactic.interactive import tactic.finish import tactic.ext import tactic.lift import tactic.apply import tactic.reassoc_axiom import tactic.tfae import tactic.elide import tactic.ring_exp import tactic.clear import tactic.simp_rw example (m n p q : nat) (h : m + n = p) : true := begin have : m + n = q, { generalize_hyp h' : m + n = x at h, guard_hyp h' := m + n = x, guard_hyp h := x = p, guard_target m + n = q, admit }, have : m + n = q, { generalize_hyp h' : m + n = x at h ⊢, guard_hyp h' := m + n = x, guard_hyp h := x = p, guard_target x = q, admit }, trivial end example (α : Sort*) (L₁ L₂ L₃ : list α) (H : L₁ ++ L₂ = L₃) : true := begin have : L₁ ++ L₂ = L₂, { generalize_hyp h : L₁ ++ L₂ = L at H, induction L with hd tl ih, case list.nil { tactic.cleanup, change list.nil = L₃ at H, admit }, case list.cons { change list.cons hd tl = L₃ at H, admit } }, trivial end example (x y : ℕ) (p q : Prop) (h : x = y) (h' : p ↔ q) : true := begin symmetry' at h, guard_hyp' h := y = x, guard_hyp' h' := p ↔ q, symmetry' at *, guard_hyp' h := x = y, guard_hyp' h' := q ↔ p, trivial end section h_generalize variables {α β γ φ ψ : Type} (f : α → α → α → φ → γ) (x y : α) (a b : β) (z : φ) (h₀ : β = α) (h₁ : β = α) (h₂ : φ = β) (hx : x == a) (hy : y == b) (hz : z == a) include f x y z a b hx hy hz example : f x y x z = f (eq.rec_on h₀ a) (cast h₀ b) (eq.mpr h₁.symm a) (eq.mpr h₂ a) := begin guard_hyp_nums 16, h_generalize hp : a == p with hh, guard_hyp_nums 19, guard_hyp' hh := β = α, guard_target f x y x z = f p (cast h₀ b) p (eq.mpr h₂ a), h_generalize hq : _ == q, guard_hyp_nums 21, guard_target f x y x z = f p q p (eq.mpr h₂ a), h_generalize _ : _ == r, guard_hyp_nums 23, guard_target f x y x z = f p q p r, casesm* [_ == _, _ = _], refl end end h_generalize section h_generalize variables {α β γ φ ψ : Type} (f : list α → list α → γ) (x : list α) (a : list β) (z : φ) (h₀ : β = α) (h₁ : list β = list α) (hx : x == a) include f x z a hx h₀ h₁ example : true := begin have : f x x = f (eq.rec_on h₀ a) (cast h₁ a), { guard_hyp_nums 11, h_generalize : a == p with _, guard_hyp_nums 13, guard_hyp' h := β = α, guard_target f x x = f p (cast h₁ a), h_generalize! : a == q , guard_hyp_nums 13, guard_target ∀ q, f x x = f p q, casesm* [_ == _, _ = _], success_if_fail { refl }, admit }, trivial end end h_generalize section tfae example (p q r s : Prop) (h₀ : p ↔ q) (h₁ : q ↔ r) (h₂ : r ↔ s) : p ↔ s := begin scc, end example (p' p q r r' s s' : Prop) (h₀ : p' → p) (h₀ : p → q) (h₁ : q → r) (h₁ : r' → r) (h₂ : r ↔ s) (h₂ : s → p) (h₂ : s → s') : p ↔ s := begin scc, end example (p' p q r r' s s' : Prop) (h₀ : p' → p) (h₀ : p → q) (h₁ : q → r) (h₁ : r' → r) (h₂ : r ↔ s) (h₂ : s → p) (h₂ : s → s') : p ↔ s := begin scc', assumption end example : tfae [true, ∀ n : ℕ, 0 ≤ n * n, true, true] := begin tfae_have : 3 → 1, { intro h, constructor }, tfae_have : 2 → 3, { intro h, constructor }, tfae_have : 2 ← 1, { intros h n, apply nat.zero_le }, tfae_have : 4 ↔ 2, { tauto }, tfae_finish, end example : tfae [] := begin tfae_finish, end variables P Q R : Prop example (pq : P → Q) (qr : Q → R) (rp : R → P) : tfae [P, Q, R] := begin tfae_finish end example (pq : P ↔ Q) (qr : Q ↔ R) : tfae [P, Q, R] := begin tfae_finish -- the success or failure of this tactic is nondeterministic! end example (p : unit → Prop) : tfae [p (), p ()] := begin tfae_have : 1 ↔ 2, from iff.rfl, tfae_finish end end tfae section clear_aux_decl example (n m : ℕ) (h₁ : n = m) (h₂ : ∃ a : ℕ, a = n ∧ a = m) : 2 * m = 2 * n := let ⟨a, ha⟩ := h₂ in begin clear_aux_decl, -- subst will fail without this line subst h₁ end example (x y : ℕ) (h₁ : ∃ n : ℕ, n * 1 = 2) (h₂ : 1 + 1 = 2 → x * 1 = y) : x = y := let ⟨n, hn⟩ := h₁ in begin clear_aux_decl, -- finish produces an error without this line finish end end clear_aux_decl section congr example (c : Prop → Prop → Prop → Prop) (x x' y z z' : Prop) (h₀ : x ↔ x') (h₁ : z ↔ z') : c x y z ↔ c x' y z' := begin congr', { guard_target x = x', ext, assumption }, { guard_target z = z', ext, assumption }, end end congr section convert_to example {a b c d : ℕ} (H : a = c) (H' : b = d) : a + b = d + c := by {convert_to c + d = _ using 2, from H, from H', rw[add_comm]} example {a b c d : ℕ} (H : a = c) (H' : b = d) : a + b = d + c := by {convert_to c + d = _ using 0, congr' 2, from H, from H', rw[add_comm]} example (a b c d e f g N : ℕ) : (a + b) + (c + d) + (e + f) + g ≤ a + d + e + f + c + g + b := by {ac_change a + d + e + f + c + g + b ≤ _, refl} end convert_to section swap example {α₁ α₂ α₃ : Type} : true := by {have : α₁, have : α₂, have : α₃, swap, swap, rotate, rotate, rotate, rotate 2, rotate 2, triv, recover} end swap section lift example (n m k x z u : ℤ) (hn : 0 < n) (hk : 0 ≤ k + n) (hu : 0 ≤ u) (h : k + n = 2 + x) (f : false) : k + n = m + x := begin lift n to ℕ using le_of_lt hn, guard_target (k + ↑n = m + x), guard_hyp hn := (0 : ℤ) < ↑n, lift m to ℕ, guard_target (k + ↑n = ↑m + x), tactic.swap, guard_target (0 ≤ m), tactic.swap, tactic.num_goals >>= λ n, guard (n = 2), lift (k + n) to ℕ using hk with l hl, guard_hyp l := ℕ, guard_hyp hl := ↑l = k + ↑n, guard_target (↑l = ↑m + x), tactic.success_if_fail (tactic.get_local `hk), lift x to ℕ with y hy, guard_hyp y := ℕ, guard_hyp hy := ↑y = x, guard_target (↑l = ↑m + x), lift z to ℕ with w, guard_hyp w := ℕ, tactic.success_if_fail (tactic.get_local `z), lift u to ℕ using hu with u rfl hu, guard_hyp hu := (0 : ℤ) ≤ ↑u, all_goals { exfalso, assumption }, end -- test lift of functions example (α : Type*) (f : α → ℤ) (hf : ∀ a, 0 ≤ f a) (hf' : ∀ a, f a < 1) (a : α) : 0 ≤ 2 * f a := begin lift f to α → ℕ using hf, guard_target ((0:ℤ) ≤ 2 * (λ i : α, (f i : ℤ)) a), guard_hyp hf' := ∀ a, ((λ i : α, (f i:ℤ)) a) < 1, trivial end instance can_lift_unit : can_lift unit unit := ⟨id, λ x, true, λ x _, ⟨x, rfl⟩⟩ /- test whether new instances of `can_lift` are added as simp lemmas -/ run_cmd do l ← can_lift_attr.get_cache, guard (`can_lift_unit ∈ l) /- test error messages -/ example (n : ℤ) (hn : 0 < n) : true := begin success_if_fail_with_msg {lift n to ℕ using hn} "lift tactic failed. The type of\n hn\nis 0 < n\nbut it is expected to be\n 0 ≤ n", success_if_fail_with_msg {lift (n : option ℤ) to ℕ} "Failed to find a lift from option ℤ to ℕ. Provide an instance of\n can_lift (option ℤ) ℕ", trivial end example (n : ℤ) : ℕ := begin success_if_fail_with_msg {lift n to ℕ} "lift tactic failed. Tactic is only applicable when the target is a proposition.", exact 0 end end lift private meta def get_exception_message (t : lean.parser unit) : lean.parser string | s := match t s with | result.success a s' := result.success "No exception" s | result.exception none pos s' := result.success "Exception no msg" s | result.exception (some msg) pos s' := result.success (msg ()).to_string s end @[user_command] meta def test_parser1_fail_cmd (_ : interactive.parse (lean.parser.tk "test_parser1")) : lean.parser unit := do let msg := "oh, no!", let t : lean.parser unit := tactic.fail msg, s ← get_exception_message t, if s = msg then tactic.skip else interaction_monad.fail "Message was corrupted while being passed through `lean.parser.of_tactic`" . -- Due to `lean.parser.of_tactic'` priority, the following *should not* fail with -- a VM check error, and instead catch the error gracefully and just -- run and succeed silently. test_parser1 section category_theory open category_theory variables {C : Type} [category.{1} C] example (X Y Z W : C) (x : X ⟶ Y) (y : Y ⟶ Z) (z z' : Z ⟶ W) (w : X ⟶ Z) (h : x ≫ y = w) (h' : y ≫ z = y ≫ z') : x ≫ y ≫ z = w ≫ z' := begin rw [h',reassoc_of h], end end category_theory section is_eta_expansion /- test the is_eta_expansion tactic -/ open function tactic structure my_equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) infix ` my≃ `:25 := my_equiv protected def my_rfl {α} : α my≃ α := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ def eta_expansion_test : ℕ × ℕ := ((1,0).1,(1,0).2) run_cmd do e ← get_env, x ← e.get `eta_expansion_test, let v := (x.value.get_app_args).drop 2, let nms := [`prod.fst, `prod.snd], guard $ expr.is_eta_expansion_test (nms.zip v) = some `((1, 0)) def eta_expansion_test2 : ℕ my≃ ℕ := ⟨my_rfl.to_fun, my_rfl.inv_fun, λ x, rfl, λ x, rfl⟩ run_cmd do e ← get_env, x ← e.get `eta_expansion_test2, let v := (x.value.get_app_args).drop 2, projs ← e.structure_fields_full `my_equiv, b ← expr.is_eta_expansion_aux x.value (projs.zip v), guard $ b = some `(@my_rfl ℕ) run_cmd do e ← get_env, x1 ← e.get `eta_expansion_test, x2 ← e.get `eta_expansion_test2, b1 ← expr.is_eta_expansion x1.value, b2 ← expr.is_eta_expansion x2.value, guard $ b1 = some `((1, 0)) ∧ b2 = some `(@my_rfl ℕ) structure my_str (n : ℕ) := (x y : ℕ) def dummy : my_str 3 := ⟨1, 1⟩ def wrong_param : my_str 2 := ⟨dummy.1, dummy.2⟩ def right_param : my_str 3 := ⟨dummy.1, dummy.2⟩ run_cmd do e ← get_env, x ← e.get `wrong_param, o ← x.value.is_eta_expansion, guard o.is_none, x ← e.get `right_param, o ← x.value.is_eta_expansion, guard $ o = some `(dummy) end is_eta_expansion section elide variables {x y z w : ℕ} variables (h : x + y + z ≤ w) (h' : x ≤ y + z + w) include h h' example : x + y + z ≤ w := begin elide 0 at h, elide 2 at h', guard_hyp h := @hidden _ (x + y + z ≤ w), guard_hyp h' := x ≤ @has_add.add (@hidden Type nat) (@hidden (has_add nat) nat.has_add) (@hidden ℕ (y + z)) (@hidden ℕ w), unelide at h, unelide at h', guard_hyp h' := x ≤ y + z + w, exact h, -- there was a universe problem in `elide`. `exact h` lets the kernel check -- the consistency of the universes end end elide section struct_eq @[ext] structure foo (α : Type*) := (x y : ℕ) (z : {z // z < x}) (k : α) (h : x < y) example {α : Type*} : Π (x y : foo α), x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y := foo.ext example {α : Type*} : Π (x y : foo α), x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k := foo.ext_iff example {α} (x y : foo α) (h : x = y) : y = x := begin ext, { guard_target' y.x = x.x, rw h }, { guard_target' y.y = x.y, rw h }, { guard_target' y.z == x.z, rw h }, { guard_target' y.k = x.k, rw h }, end end struct_eq section ring_exp example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + 2 * a * b + b^2) * (a + b)^n := by ring_exp end ring_exp section clear' example (a : ℕ) (b : fin a) : unit := begin success_if_fail { clear a b }, -- fails since `b` depends on `a` success_if_fail { clear' a }, -- fails since `b` depends on `a` clear' a b, guard_hyp_nums 0, exact () end example (a : ℕ) : fin a → unit := begin success_if_fail { clear' a }, -- fails since the target depends on `a` success_if_fail { clear_dependent a }, -- ditto exact λ _, () end example (a : unit) : unit := begin -- Check we fail with an error (but don't segfault) if hypotheses are repeated. success_if_fail { clear' a a }, success_if_fail { clear_dependent a a }, exact () end example (a a a : unit) : unit := begin -- If there are multiple hypotheses with the same name, -- `clear'`/`clear_dependent` currently clears only the last. clear' a, clear_dependent a, guard_hyp_nums 1, exact () end end clear' section clear_dependent example (a : ℕ) (b : fin a) : unit := begin success_if_fail { clear' a }, -- fails since `b` depends on `a` clear_dependent a, guard_hyp_nums 0, exact () end end clear_dependent section simp_rw example {α β : Type} {f : α → β} {t : set β} : (∀ s, f '' s ⊆ t) = ∀ s : set α, ∀ x ∈ s, x ∈ f ⁻¹' t := by simp_rw [set.image_subset_iff, set.subset_def] end simp_rw section local_definitions /- Some tactics about local definitions. Testing revert_deps, revert_after, generalize', clear_value. -/ open tactic example {A : ℕ → Type} {n : ℕ} : let k := n + 3, l := k + n, f : A k → A k := id in ∀(x : A k) (y : A (n + k)) (z : A n) (h : k = n + n), unit := begin intros, guard_target unit, do { e ← get_local `k, e1 ← tactic.local_def_value e, e2 ← to_expr ```(n + 3), guard $ e1 = e2 }, do { e ← get_local `n, success_if_fail_with_msg (tactic.local_def_value e) "Variable n is not a local definition." }, do { success_if_fail_with_msg (tactic.local_def_value `(1 + 2)) "No such hypothesis 1 + 2." }, revert_deps k, tactic.intron 5, guard_target unit, revert_after n, tactic.intron 7, guard_target unit, do { e ← get_local `k, tactic.revert_deps e, l ← local_context, guard $ e ∈ l, intros }, exact unit.star end example {A : ℕ → Type} {n : ℕ} : let k := n + 3, l := k + n, f : A k → A (n+3) := id in ∀(x : A k) (y : A (n + k)) (z : A n) (h : k = n + n), unit := begin intros, success_if_fail_with_msg {generalize : n + k = x} "generalize tactic failed, failed to find expression in the target", generalize' : n + k = x, generalize' h : n + k = y, exact unit.star end example {A : ℕ → Type} {n : ℕ} : let k := n + 3, l := k + n, f : A k → A (n+3) := id in ∀(x : A k) (y : A (n + k)) (z : A n) (h : k = n + n), unit := begin intros, tactic.to_expr ```(n + n) >>= λ e, tactic.generalize' e `xxx, success_if_fail_with_msg {clear_value n} "Cannot clear the body of n. It is not a local definition.", success_if_fail_with_msg {clear_value k} "Cannot clear the body of k. The resulting goal is not type correct.", clear_value k f, exact unit.star end example {A : ℕ → Type} {n : ℕ} : let k := n + 3, l := k + n, f : A k → A k := id in ∀(x : A k) (y : A (n + k)) (z : A n) (h : k = n + n), unit := begin intros, clear_value k f, exact unit.star end end local_definitions section set_attribute open tactic @[user_attribute] meta def my_user_attribute : user_attribute unit bool := { name := `my_attr, descr := "", parser := return ff } run_cmd do nm ← get_user_attribute_name `library_note, guard $ nm = `library_note_attr run_cmd do nm ← get_user_attribute_name `higher_order, guard $ nm = `tactic.higher_order_attr run_cmd do success_if_fail $ get_user_attribute_name `zxy.xzy run_cmd set_attribute `norm `prod.map tt run_cmd success_if_fail $ set_attribute `higher_order `prod.map tt run_cmd success_if_fail $ set_attribute `my_attr `prod.map run_cmd success_if_fail $ set_attribute `norm `xyz.zxy run_cmd success_if_fail $ set_attribute `zxy.xyz `prod.map end set_attribute
6254658d1bd3ef53a124f04f898850fe1dea08bf
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/algebra/infinite_sum.lean
6f2fb74a4c4777365dadc57541c188829696b19f
[ "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
40,313
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.big_operators.intervals import topology.instances.real import data.indicator_function import data.equiv.encodable.lattice import order.filter.at_top_bot /-! # Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ noncomputable theory open finset filter function classical open_locale topological_space classical big_operators variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset α` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is still invariant under reordering, and a absolute sum operator. This is based on Mario Carneiro's infinite sum in Metamath. For the definition or many statements, α does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/ @[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0 notation `∑'` binders `, ` r:(scoped f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : (∑'b, f b) = 0 := by simp [tsum, h] lemma has_sum.has_sum_of_sum_eq {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (hf : has_sum g a) : has_sum f a := le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf lemma has_sum_iff_has_sum {g : γ → α} (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) : has_sum f a ↔ has_sum g a := ⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩ lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf] lemma function.injective.summable_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr $ λ _, hg.has_sum_iff hf lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) : has_sum (f ∘ coe : s → α) a ↔ has_sum f a := subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf lemma has_sum_subtype_iff_indicator {s : set β} : has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a := by rw [← set.indicator_range_comp, subtype.range_coe, has_sum_subtype_iff_of_support_subset set.support_indicator] @[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset $ set.subset.refl _ lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) := order_top.tendsto_at_top_nhds _ protected lemma finset.has_sum (s : finset β) (f : β → α) : has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) := by { rw ← sum_attach, exact has_sum_fintype _ } protected lemma finset.summable (s : finset β) (f : β → α) : summable (f ∘ coe : (↑s : set β) → α) := (s.has_sum f).summable protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) : summable (f ∘ coe : s → α) := by convert hs.to_finset.summable f; simp only [hs.coe_to_finset] /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) := (has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := (has_sum_sum_of_ne_finset_zero hf).summable lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : has_sum f (f b) := suffices has_sum f (∑ b' in {b}, f b'), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : β) (a : α) : has_sum (λb', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma equiv.has_sum_iff (e : γ ≃ β) : has_sum (f ∘ e) a ↔ has_sum f a := e.injective.has_sum_iff $ by simp lemma equiv.summable_iff (e : γ ≃ β) : summable (f ∘ e) ↔ summable f := exists_congr $ λ a, e.has_sum_iff lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) := (equiv.prod_comm γ β).summable_iff.2 hf lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : has_sum f a ↔ has_sum g a := have (g ∘ coe) ∘ e = f ∘ coe, from funext he, by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support] lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : has_sum f a ↔ has_sum g a := iff.symm $ equiv.has_sum_iff_of_support (equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩) ⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h, λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩) hfg lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : summable f ↔ summable g := exists_congr $ λ _, e.has_sum_iff_of_support he protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a) (g : α →+ γ) (hg : continuous g) : has_sum (g ∘ f) (g a) := have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)), from funext $ g.map_sum _, show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)), from this ▸ (hg.tendsto a).comp hf protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f) (g : α →+ γ) (hg : continuous g) : summable (g ∘ f) := (hf.has_sum.map g hg).summable /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := h.comp tendsto_finset_range lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := begin refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩, rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat, exact hf.has_sum end lemma equiv.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) {f : β → α} {g : γ → α'} (he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : summable f ↔ summable g := ⟨λ ⟨a, ha⟩, ⟨e.symm a, he.1 $ by rwa [e.apply_symm_apply]⟩, λ ⟨a, ha⟩, ⟨e a, he.2 ha⟩⟩ variable [has_continuous_add α] lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp only [has_sum, sum_add_distrib]; exact hf.add hg lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := (hf.has_sum.add hg.has_sum).summable lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) := finset.induction_on s (by simp [has_sum_zero]) (by simp [has_sum.add] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, ∑ i in s, f i b) := (has_sum_sum $ assume i hi, (hf i hi).has_sum).summable lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : sᶜ → α) b) : has_sum f (a + b) := by simpa using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : summable f := (hs.has_sum.add_compl hsc.has_sum).summable lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a) (hb : has_sum (f ∘ coe : s → α) b) : has_sum f (a + b) := by simpa using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α)) (hsc : summable (f ∘ coe : s → α)) : summable f := (hs.has_sum.compl_add hsc.has_sum).summable lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a := begin refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _, rintros s ⟨hs, hsc⟩, rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩, use [u.image sigma.fst, trivial], intros bs hbs, simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu, have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p) at_top (𝓝 $ ∑ b in bs, g b), { simp only [← sigma_preimage_mk, sum_sigma], refine tendsto_finset_sum _ (λ b hb, _), change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)), exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) }, refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩), exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩ end /-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ` has sum `g b`, then the series `g` has sum `a`. -/ lemma has_sum.prod_fiberwise [regular_space α] {f : β × γ → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) : has_sum g a := has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) : summable (λb, ∑'c, f ⟨b, c⟩) := (ha.has_sum.sigma (assume b, (hf b).has_sum)).summable lemma has_sum.sigma_of_has_sum [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a := by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum end has_sum section tsum variables [add_comm_monoid α] [topological_space α] [t2_space α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.tsum_eq (ha : has_sum f a) : (∑'b, f b) = a := (summable.has_sum ⟨a, ha⟩).unique ha lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ (∑'b, f b) = a := iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum) @[simp] lemma tsum_zero : (∑'b:β, 0:α) = 0 := has_sum_zero.tsum_eq lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : (∑'b, f b) = ∑ b in s, f b := (has_sum_sum_of_ne_finset_zero hf).tsum_eq lemma tsum_fintype [fintype β] (f : β → α) : (∑'b, f b) = ∑ b, f b := (has_sum_fintype f).tsum_eq @[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) : (∑'x : {x // x ∈ s}, f x) = ∑ x in s, f x := (s.has_sum f).tsum_eq lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : (∑'b, f b) = f b := (has_sum_single b hf).tsum_eq @[simp] lemma tsum_ite_eq (b : β) (a : α) : (∑'b', if b' = b then a else 0) = a := (has_sum_ite_eq b a).tsum_eq lemma equiv.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) (h0 : e 0 = 0) {f : β → α} {g : γ → α'} (h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : (∑' b, f b) = e (∑' c, g c) := by_cases (assume : summable g, (h.mpr this.has_sum).tsum_eq) (assume hg : ¬ summable g, have hf : ¬ summable f, from mt (e.summable_iff_of_has_sum_iff @h).1 hg, by simp [tsum, hf, hg, h0]) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : (∑'b, f b) = (∑'c, g c) := (equiv.refl α).tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : (∑'c, f (j c)) = (∑'b, f b) := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g) (he : ∀ x, g (e x) = f x) : (∑' x, f x) = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : (∑' x, f x) = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg lemma tsum_subtype (s : set β) (f : β → α) : (∑' x : s, f x) = ∑' x, s.indicator f x := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator section has_continuous_add variable [has_continuous_add α] lemma tsum_add (hf : summable f) (hg : summable g) : (∑'b, f b + g b) = (∑'b, f b) + (∑'b, g b) := (hf.has_sum.add hg.has_sum).tsum_eq lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : (∑'b, ∑ i in s, f i b) = ∑ i in s, ∑'b, f i b := (has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq lemma tsum_sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : (∑'p, f p) = (∑'b c, f ⟨b, c⟩) := (h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_prod' [regular_space α] {f : β × γ → α} (h : summable f) (h₁ : ∀b, summable (λc, f (b, c))) : (∑'p, f p) = (∑'b c, f (b, c)) := (h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_comm' [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) (h₁ : ∀b, summable (f b)) (h₂ : ∀ c, summable (λ b, f b c)) : (∑' c b, f b c) = (∑' b c, f b c) := begin erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm β γ).tsum_eq], refl, assumption end end has_continuous_add section encodable open encodable variable [encodable γ] /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode2 [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (s : γ → β) : (∑' i : ℕ, m (⨆ b ∈ decode2 γ i, s b)) = (∑' b : γ, m (s b)) := begin have H : ∀ n, m (⨆ b ∈ decode2 γ n, s b) ≠ 0 → (decode2 γ n).is_some, { intros n h, cases decode2 γ n with b, { refine (h $ by simp [m0]).elim }, { exact rfl } }, symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _, { rintros ⟨m, hm⟩ ⟨n, hn⟩ e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨⟨encode b, _⟩, _⟩, { simp only [mem_support, encodek2] at h ⊢, convert h, simp [set.ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { rintros ⟨n, h⟩, dsimp only [subtype.coe_mk], transitivity, swap, rw [show decode2 γ n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end /-- `tsum_supr_decode2` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode2 (m : set β → α) (m0 : m ∅ = 0) (s : γ → set β) : (∑' i, m (⋃ b ∈ decode2 γ i, s b)) = (∑' b, m (s b)) := tsum_supr_decode2 m m0 s /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≤)` in all applications. -/ /-- If a function is countably sub-additive then it is sub-additive on encodable types -/ theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s : γ → β) : R (m (⨆ b : γ, s b)) (∑' b : γ, m (s b)) := by { rw [← supr_decode2, ← tsum_supr_decode2 _ m0 s], exact m_supr _ } /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s : δ → β) (t : finset δ) : R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) := by { cases t.nonempty_encodable, rw [supr_subtype'], convert rel_supr_tsum m m0 R m_supr _, rw [← finset.tsum_subtype], assumption } /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) := begin convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂), { simp only [supr_bool_eq, cond] }, { rw [tsum_fintype, fintype.sum_bool, cond, cond] } end end encodable end tsum section pi variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)] lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} : has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) := by simp [has_sum, tendsto_pi] lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) := by simp [summable, pi.has_sum, classical.skolem] lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) : (∑' i, f i) x = ∑' i, f i x := (pi.has_sum.mp hf.has_sum x).tsum_eq.symm end pi section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} -- `by simpa using` speeds up elaboration. Why? lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) := by simpa only using h.map (-add_monoid_hom.id α) continuous_neg lemma summable.neg (hf : summable f) : summable (λb, - f b) := hf.has_sum.neg.summable lemma summable.of_neg (hf : summable (λb, - f b)) : summable f := by simpa only [neg_neg] using hf.neg lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f := ⟨summable.of_neg, summable.neg⟩ lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by { simp [sub_eq_add_neg], exact hf.add hg.neg } lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := (hf.has_sum.sub hg.has_sum).summable lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) := begin refine ⟨λ h, hf.add_compl h, λ h, _⟩, rw [has_sum_subtype_iff_indicator] at hf ⊢, rw [set.indicator_compl], simpa only [add_sub_cancel'] using h.sub hf end lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) := iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right] lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) : summable (f ∘ coe : sᶜ → α) ↔ summable f := ⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable, λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩ protected lemma finset.has_sum_compl_iff (s : finset β) : has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) := (s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm] protected lemma finset.has_sum_iff_compl (s : finset β) : has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) := (s.has_sum f).has_sum_iff_compl protected lemma finset.summable_compl_iff (s : finset β) : summable (λ x : {x // x ∉ s}, f x) ↔ summable f := (s.summable f).summable_compl_iff lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) : summable (f ∘ coe : sᶜ → α) ↔ summable f := (hs.summable f).summable_compl_iff section tsum variables [t2_space α] lemma tsum_neg (hf : summable f) : (∑'b, - f b) = - (∑'b, f b) := hf.has_sum.neg.tsum_eq lemma tsum_sub (hf : summable f) (hg : summable g) : (∑'b, f b - g b) = (∑'b, f b) - (∑'b, g b) := (hf.has_sum.sub hg.has_sum).tsum_eq lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : (∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x := (hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm lemma sum_add_tsum_compl {s : finset β} (hf : summable f) : (∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x := ((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm end tsum /-! ### Sums on subtypes If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype `univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`. -/ section subtype variables {s : finset β} lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := begin refine iff.trans _ ((range k).has_sum_compl_iff), rw [← (not_mem_range_equiv k).symm.has_sum_iff], refl end lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f := iff.symm $ (equiv.add_right (∑ i in range k, f i)).summable_iff_of_has_sum_iff $ λ a, (has_sum_nat_add_iff k).symm lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a := by simp [has_sum_nat_add_iff] lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) : (∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i) := by simpa [add_comm] using ((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) : (∑'b, f b) = f 0 + (∑'b, f (b + 1)) := by simpa only [range_one, sum_singleton] using (sum_add_tsum_nat_add 1 hf).symm end subtype end topological_group section topological_semiring variables [semiring α] [topological_space α] [topological_semiring α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.mul_left (a₂) (h : has_sum f a₁) : has_sum (λb, a₂ * f b) (a₂ * a₁) := by simpa only using h.map (add_monoid_hom.mul_left a₂) (continuous_const.mul continuous_id) lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) := by simpa only using hf.map (add_monoid_hom.mul_right a₂) (continuous_id.mul continuous_const) lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) := (hf.has_sum.mul_left _).summable lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) := (hf.has_sum.mul_right _).summable section tsum variables [t2_space α] lemma tsum_mul_left (a) (hf : summable f) : (∑'b, a * f b) = a * (∑'b, f b) := (hf.has_sum.mul_left _).tsum_eq lemma tsum_mul_right (a) (hf : summable f) : (∑'b, f b * a) = (∑'b, f b) * a := (hf.has_sum.mul_right _).tsum_eq end tsum end topological_semiring section division_ring variables [division_ring α] [topological_space α] [topological_semiring α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) := ⟨has_sum.mul_left _, λ H, by simpa only [inv_mul_cancel_left' h] using H.mul_left a₂⁻¹⟩ lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) := ⟨has_sum.mul_right _, λ H, by simpa only [mul_inv_cancel_right' h] using H.mul_right a₂⁻¹⟩ lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) := ⟨λ H, H.mul_left _, λ H, by simpa only [inv_mul_cancel_left' h] using H.mul_left a⁻¹⟩ lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) := ⟨λ H, H.mul_right _, λ H, by simpa only [mul_inv_cancel_right' h] using H.mul_right a⁻¹⟩ end division_ring section order_topology variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' hf hg $ assume s, sum_le_sum $ assume b _, h b lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (i ∘ coe) _ _ _).2 hf, { exact assume c₁ c₂ eq, hi eq }, { intros c hc, rw [mem_support] at hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨⟨b, hc⟩, eq⟩ } }, { assume c, simp [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj i hi hs h hf.has_sum hg.has_sum lemma sum_le_has_sum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) : ∑ b in s, f b ≤ a := ge_of_tendsto hf (eventually_at_top.2 ⟨s, λ t hst, sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩) lemma le_has_sum (hf : has_sum f a) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ a := calc f b = ∑ b in {b}, f b : finset.sum_singleton.symm ... ≤ a : sum_le_has_sum _ (by { convert hb, simp }) hf lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) : ∑ b in s, f b ≤ tsum f := sum_le_has_sum s hs hf.has_sum lemma le_tsum (hf : summable f) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ ∑' b, f b := le_has_sum (summable.has_sum hf) b hb lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : (∑'b, f b) ≤ (∑'b, g b) := has_sum_le h hf.has_sum hg.has_sum lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ (∑'b, g b) := begin by_cases hg : summable g, { simpa using tsum_le_tsum h summable_zero hg }, { simp [tsum_eq_zero_of_not_summable hg] } end lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : (∑'b, f b) ≤ 0 := begin by_cases hf : summable f, { simpa using tsum_le_tsum h hf summable_zero}, { simp [tsum_eq_zero_of_not_summable hf] } end end order_topology section canonically_ordered variables [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] variables {f : β → α} {a : α} lemma le_has_sum' (hf : has_sum f a) (b : β) : f b ≤ a := le_has_sum hf b $ λ _ _, zero_le _ lemma le_tsum' (hf : summable f) (b : β) : f b ≤ ∑' b, f b := le_tsum hf b $ λ _ _, zero_le _ lemma has_sum_zero_iff : has_sum f 0 ↔ ∀ x, f x = 0 := begin refine ⟨_, λ h, _⟩, { contrapose!, exact λ ⟨x, hx⟩ h, irrefl _ (lt_of_lt_of_le (zero_lt_iff_ne_zero.2 hx) (le_has_sum' h x)) }, { convert has_sum_zero, exact funext h } end lemma tsum_eq_zero_iff (hf : summable f) : (∑' i, f i) = 0 ↔ ∀ x, f x = 0 := by rw [←has_sum_zero_iff, hf.has_sum_iff] end canonically_ordered section uniform_group variables [add_comm_group α] [uniform_space α] lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} : summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) := cauchy_map_iff_exists_tendsto.symm variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α} lemma cauchy_seq_finset_iff_vanishing : cauchy_seq (λ (s : finset β), ∑ b in s, f b) ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := begin simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top'], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_left_of_le le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) } end variable [complete_space α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing] /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := summable_iff_vanishing.2 $ assume e he, let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in ⟨s, assume t ht, have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b := calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = ∑ b in t, g b : begin refine finset.sum_subset (finset.filter_subset _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _) ht⟩ protected lemma summable.indicator (hf : summable f) (s : set β) : summable (s.indicator f) := hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _ lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := begin simpa only [set.indicator_range_comp] using (hi.summable_iff _).2 (hf.indicator (set.range i)), exact λ x hx, set.indicator_of_not_mem hx _ end lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) := hf.comp_injective subtype.coe_injective lemma summable_subtype_and_compl {s : set β} : summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f := ⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩ lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) := ha.comp_injective sigma_mk_injective lemma summable.sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) := ha.sigma' (λ b, ha.sigma_factor b) lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) : summable (λ c, f (b, c)) := h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2 lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : (∑'p, f p) = (∑'b c, f ⟨b, c⟩) := tsum_sigma' (λ b, ha.sigma_factor b) ha lemma tsum_prod [regular_space α] {f : β × γ → α} (h : summable f) : (∑'p, f p) = (∑'b c, f ⟨b, c⟩) := tsum_prod' h h.prod_factor lemma tsum_comm [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) : (∑' c b, f b c) = (∑' b c, f b c) := tsum_comm' h h.prod_factor h.prod_symm.prod_factor end uniform_group section topological_group variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) : ∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e := begin letI : uniform_space G := topological_add_group.to_uniform_space G, letI : uniform_add_group G := topological_add_group_is_uniform, rcases hf with ⟨y, hy⟩, exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he end /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) := begin intros e he, rw [filter.mem_map], rcases hf.vanishing he with ⟨s, hs⟩, refine s.eventually_cofinite_nmem.mono (λ x hx, _), by simpa using hs {x} (singleton_disjoint.2 hx) end end topological_group lemma summable_abs_iff [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : summable (λ x, abs (f x)) ↔ summable f := have h1 : ∀ x : {x | 0 ≤ f x}, abs (f x) = f x := λ x, abs_of_nonneg x.2, have h2 : ∀ x : {x | 0 ≤ f x}ᶜ, abs (f x) = -f x := λ x, abs_of_neg (not_le.1 x.2), calc summable (λ x, abs (f x)) ↔ summable (λ x : {x | 0 ≤ f x}, abs (f x)) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, abs (f x)) : summable_subtype_and_compl.symm ... ↔ summable (λ x : {x | 0 ≤ f x}, f x) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, -f x) : by simp only [h1, h2] ... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl] alias summable_abs_iff ↔ summable.of_abs summable.abs section cauchy_seq open finset.Ico filter /-- If the extended distance between consequent points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_edist_le_of_summable [emetric_space α] {f : ℕ → α} (d : ℕ → nnreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _), -- Actually we need partial sums of `d` to be a Cauchy sequence replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, -- Now we take the same `N` as in one of the definitions of a Cauchy sequence refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _), have hsum := hN n hn, -- We simplify the known inequality rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, nnreal.add_sub_cancel'] at hsum, norm_cast at hsum, replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum, rw edist_comm, -- Then use `hf` to simplify the goal to the same form apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)), assumption_mod_cast end /-- If the distance between consequent points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_dist_le_of_summable [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine metric.cauchy_seq_iff'.2 (λε εpos, _), replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _), have hsum := hN n hn, rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum, calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _ ... ≤ ∑ x in Ico N n, d x : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k) ... ≤ abs (∑ x in Ico N n, d x) : le_abs_self _ ... < ε : hsum end lemma cauchy_seq_of_summable_dist [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ (λ _, le_refl _) h lemma dist_le_tsum_of_dist_le_of_tendsto [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.dist ha) (eventually_at_top.2 ⟨n, λ m hnm, _⟩), refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _, rw [sum_Ico_eq_sum_range], refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _, exact hd.comp_injective (add_right_injective n) end lemma dist_le_tsum_of_dist_le_of_tendsto₀ [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 lemma dist_le_tsum_dist_of_tendsto [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) : dist (f n) a ≤ ∑' m, dist (f (n+m)) (f (n+m).succ) := show dist (f n) a ≤ ∑' m, (λx, dist (f x) (f x.succ)) (n + m), from dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_refl _) h ha n lemma dist_le_tsum_dist_of_tendsto₀ [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 end cauchy_seq
b60e1501d5cd9a5c3fa7ac03581d4df1e1feefdd
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/constructions/epi_mono_auto.lean
52210f19ebd41fce2fb214d8c3521bb18b731ad6
[]
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,314
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.shapes.pullbacks import Mathlib.category_theory.limits.shapes.binary_products import Mathlib.category_theory.limits.preserves.shapes.pullbacks import Mathlib.PostPort universes v u₁ u₂ namespace Mathlib /-! # Relating monomorphisms and epimorphisms to limits and colimits If `F` preserves (resp. reflects) pullbacks, then it preserves (resp. reflects) monomorphisms. ## TODO Dualise and apply to functor categories. -/ namespace category_theory /-- If `F` preserves pullbacks, then it preserves monomorphisms. -/ protected instance preserves_mono {C : Type u₁} {D : Type u₂} [category C] [category D] (F : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) [limits.preserves_limit (limits.cospan f f) F] [mono f] : mono (functor.map F f) := sorry /-- If `F` reflects pullbacks, then it reflects monomorphisms. -/ theorem reflects_mono {C : Type u₁} {D : Type u₂} [category C] [category D] (F : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) [limits.reflects_limit (limits.cospan f f) F] [mono (functor.map F f)] : mono f := sorry end Mathlib
9a19768b17279c9c7741b8bda02b3950fea936c8
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/metric_space/completion.lean
49f313ab15d248c2e9fbe61b39b7678904f46ba0
[ "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,655
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.uniform_space.completion import topology.metric_space.isometry import topology.instances.real /-! # The completion of a metric space Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show here that the uniform space completion of a metric space inherits a metric space structure, by extending the distance to the completion and checking that it is indeed a distance, and that it defines the same uniformity as the already defined uniform structure on the completion -/ open set filter uniform_space uniform_space.completion open_locale filter noncomputable theory universes u variables {α : Type u} [pseudo_metric_space α] namespace metric /-- The distance on the completion is obtained by extending the distance on the original space, by uniform continuity. -/ instance : has_dist (completion α) := ⟨completion.extension₂ dist⟩ /-- The new distance is uniformly continuous. -/ protected lemma completion.uniform_continuous_dist : uniform_continuous (λp:completion α × completion α, dist p.1 p.2) := uniform_continuous_extension₂ dist /-- The new distance is an extension of the original distance. -/ protected lemma completion.dist_eq (x y : α) : dist (x : completion α) y = dist x y := completion.extension₂_coe_coe uniform_continuous_dist _ _ /- Let us check that the new distance satisfies the axioms of a distance, by starting from the properties on α and extending them to `completion α` by continuity. -/ protected lemma completion.dist_self (x : completion α) : dist x x = 0 := begin apply induction_on x, { refine is_closed_eq _ continuous_const, exact (completion.uniform_continuous_dist.continuous.comp (continuous.prod_mk continuous_id continuous_id : _) : _) }, { assume a, rw [completion.dist_eq, dist_self] } end protected lemma completion.dist_comm (x y : completion α) : dist x y = dist y x := begin apply induction_on₂ x y, { refine is_closed_eq completion.uniform_continuous_dist.continuous _, exact completion.uniform_continuous_dist.continuous.comp (@continuous_swap (completion α) (completion α) _ _) }, { assume a b, rw [completion.dist_eq, completion.dist_eq, dist_comm] } end protected lemma completion.dist_triangle (x y z : completion α) : dist x z ≤ dist x y + dist y z := begin apply induction_on₃ x y z, { refine is_closed_le _ (continuous.add _ _), { have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.2)) := continuous.prod_mk continuous_fst (continuous.comp continuous_snd continuous_snd), exact (completion.uniform_continuous_dist.continuous.comp this : _) }, { have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.1)) := continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd), exact (completion.uniform_continuous_dist.continuous.comp this : _) }, { have : continuous (λp : completion α × completion α × completion α, (p.2.1, p.2.2)) := continuous.prod_mk (continuous_fst.comp continuous_snd) (continuous.comp continuous_snd continuous_snd), exact (continuous.comp completion.uniform_continuous_dist.continuous this : _) } }, { assume a b c, rw [completion.dist_eq, completion.dist_eq, completion.dist_eq], exact dist_triangle a b c } end /-- Elements of the uniformity (defined generally for completions) can be characterized in terms of the distance. -/ protected lemma completion.mem_uniformity_dist (s : set (completion α × completion α)) : s ∈ uniformity (completion α) ↔ (∃ε>0, ∀{a b}, dist a b < ε → (a, b) ∈ s) := begin split, { /- Start from an entourage `s`. It contains a closed entourage `t`. Its pullback in α is an entourage, so it contains an ε-neighborhood of the diagonal by definition of the entourages in metric spaces. Then `t` contains an ε-neighborhood of the diagonal in `completion α`, as closed properties pass to the completion. -/ assume hs, rcases mem_uniformity_is_closed hs with ⟨t, ht, ⟨tclosed, ts⟩⟩, have A : {x : α × α | (coe (x.1), coe (x.2)) ∈ t} ∈ uniformity α := uniform_continuous_def.1 (uniform_continuous_coe α) t ht, rcases mem_uniformity_dist.1 A with ⟨ε, εpos, hε⟩, refine ⟨ε, εpos, λx y hxy, _⟩, have : ε ≤ dist x y ∨ (x, y) ∈ t, { apply induction_on₂ x y, { have : {x : completion α × completion α | ε ≤ dist (x.fst) (x.snd) ∨ (x.fst, x.snd) ∈ t} = {p : completion α × completion α | ε ≤ dist p.1 p.2} ∪ t, by ext; simp, rw this, apply is_closed.union _ tclosed, exact is_closed_le continuous_const completion.uniform_continuous_dist.continuous }, { assume x y, rw completion.dist_eq, by_cases h : ε ≤ dist x y, { exact or.inl h }, { have Z := hε (not_le.1 h), simp only [set.mem_set_of_eq] at Z, exact or.inr Z }}}, simp only [not_le.mpr hxy, false_or, not_le] at this, exact ts this }, { /- Start from a set `s` containing an ε-neighborhood of the diagonal in `completion α`. To show that it is an entourage, we use the fact that `dist` is uniformly continuous on `completion α × completion α` (this is a general property of the extension of uniformly continuous functions). Therefore, the preimage of the ε-neighborhood of the diagonal in ℝ is an entourage in `completion α × completion α`. Massaging this property, it follows that the ε-neighborhood of the diagonal is an entourage in `completion α`, and therefore this is also the case of `s`. -/ rintros ⟨ε, εpos, hε⟩, let r : set (ℝ × ℝ) := {p | dist p.1 p.2 < ε}, have : r ∈ uniformity ℝ := metric.dist_mem_uniformity εpos, have T := uniform_continuous_def.1 (@completion.uniform_continuous_dist α _) r this, simp only [uniformity_prod_eq_prod, mem_prod_iff, exists_prop, filter.mem_map, set.mem_set_of_eq] at T, rcases T with ⟨t1, ht1, t2, ht2, ht⟩, refine mem_of_superset ht1 _, have A : ∀a b : completion α, (a, b) ∈ t1 → dist a b < ε, { assume a b hab, have : ((a, b), (a, a)) ∈ set.prod t1 t2 := ⟨hab, refl_mem_uniformity ht2⟩, have I := ht this, simp [completion.dist_self, real.dist_eq, completion.dist_comm] at I, exact lt_of_le_of_lt (le_abs_self _) I }, show t1 ⊆ s, { rintros ⟨a, b⟩ hp, have : dist a b < ε := A a b hp, exact hε this }} end /-- If two points are at distance 0, then they coincide. -/ protected lemma completion.eq_of_dist_eq_zero (x y : completion α) (h : dist x y = 0) : x = y := begin /- This follows from the separation of `completion α` and from the description of entourages in terms of the distance. -/ have : separated_space (completion α) := by apply_instance, refine separated_def.1 this x y (λs hs, _), rcases (completion.mem_uniformity_dist s).1 hs with ⟨ε, εpos, hε⟩, rw ← h at εpos, exact hε εpos end /-- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition of the metric space structure. -/ protected lemma completion.uniformity_dist' : uniformity (completion α) = (⨅ε:{ε : ℝ // 0 < ε}, 𝓟 {p | dist p.1 p.2 < ε.val}) := begin ext s, rw mem_infi_of_directed, { simp [completion.mem_uniformity_dist, subset_def] }, { rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩, simp [lt_min_iff, (≥)] {contextual := tt} } end protected lemma completion.uniformity_dist : uniformity (completion α) = (⨅ ε>0, 𝓟 {p | dist p.1 p.2 < ε}) := by simpa [infi_subtype] using @completion.uniformity_dist' α _ /-- Metric space structure on the completion of a pseudo_metric space. -/ instance completion.metric_space : metric_space (completion α) := { dist_self := completion.dist_self, eq_of_dist_eq_zero := completion.eq_of_dist_eq_zero, dist_comm := completion.dist_comm, dist_triangle := completion.dist_triangle, to_uniform_space := by apply_instance, uniformity_dist := completion.uniformity_dist } /-- The embedding of a metric space in its completion is an isometry. -/ lemma completion.coe_isometry : isometry (coe : α → completion α) := isometry_emetric_iff_metric.2 completion.dist_eq end metric
a3fc34ec094af83cc3fd79df067a021c2f38b671
54b389c64167c70f046b08bae8e0de8b39b0bf4f
/problem147.lean
3bed5005b1031b66218be386158c6135c667f0b0
[]
no_license
Mercerenies/eulers-melting-pot
4340b55b0c05f2cf8da2a80649971a26315cff18
1a2ea7e8ed33f8c027e08207852b50d6f2767a2c
refs/heads/master
1,693,602,792,233
1,692,838,742,000
1,692,838,742,000
62,594,871
11
0
null
null
null
null
UTF-8
Lean
false
false
1,521
lean
import data.nat.basic import algebra.parity variables {α : Type*} def clamp [linear_order α] (x a b: α): α := linear_order.min (linear_order.max x a) b def sum_zero_up_to [has_zero α] [has_add α] (limit: nat) (f: nat → α): α := nat.rec 0 (λ n acc, f n + acc) limit -- Note: We re-order some terms from the Rust code so that the monus -- operator doesn't lose information. Specifically, we always do -- subtraction last, after adding everything together. def count_dia_rectangles_at (w h x y: nat): nat := if (x + y) % 2 = 1 then 0 else let upper := linear_order.min y (w - x) in let mid_bound := clamp (1 + w + y - x - h) 1 (1 + upper) in (h - y) * (mid_bound - 1) + (w - x) * (1 + upper - mid_bound) - (upper * (1 + upper) - mid_bound * (mid_bound - 1)) / 2 def count_dia_rectangles_y (w h x: nat): nat := sum_zero_up_to h.succ (count_dia_rectangles_at w h x) def count_dia_rectangles (w h: nat): nat := sum_zero_up_to w.succ (count_dia_rectangles_y w h) def count_aa_rectangles (w h: nat): nat := (w * w + w) * (h * h + h) / 4 def count_total_rectangles (w h: nat): nat := count_dia_rectangles (2 * w) (2 * h) + count_aa_rectangles w h -- Returns 0 if either arg is 0. def count_total_rectangles_checked (w h: nat): nat := if w = 0 ∨ h = 0 then 0 else count_total_rectangles w h def count_all_given_i (i: nat): nat := sum_zero_up_to 44 (count_total_rectangles_checked i) def count_all: nat := sum_zero_up_to 48 count_all_given_i #eval count_all
e6127032e320c3318c58aa77a4e7b2383cbffda8
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Lean/Util/CollectMVars.lean
b9c6211a69b2cfb7eaf7ebb7f19669fb47542722
[ "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
1,215
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.Expr namespace Lean namespace CollectMVars structure State := (visitedExpr : ExprSet := {}) (result : Array MVarId := #[]) instance State.inhabited : Inhabited State := ⟨{}⟩ abbrev Visitor := State → State @[inline] def visit (f : Expr → Visitor) (e : Expr) : Visitor := fun s => if !e.hasMVar || s.visitedExpr.contains e then s else f e { s with visitedExpr := s.visitedExpr.insert e } partial def main : Expr → Visitor | Expr.proj _ _ e _ => visit main e | Expr.forallE _ d b _ => visit main b ∘ visit main d | Expr.lam _ d b _ => visit main b ∘ visit main d | Expr.letE _ t v b _ => visit main b ∘ visit main v ∘ visit main t | Expr.app f a _ => visit main a ∘ visit main f | Expr.mdata _ b _ => visit main b | Expr.mvar mvarId _ => fun s => { s with result := s.result.push mvarId } | _ => id end CollectMVars def collectMVars (s : CollectMVars.State) (e : Expr) : CollectMVars.State := CollectMVars.visit CollectMVars.main e s end Lean
325d469d4e2f697089cf5d1544ec80471137ec61
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/topology/algebra/monoid.lean
370d25e7453145fa47b1ea059db304ed452c7d4b
[ "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
5,143
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 Theory of topological monoids. TODO: generalize `topological_monoid` and `topological_add_monoid` to semigroups, or add a type class `topological_operator α (*)`. -/ import topology.constructions open classical set lattice filter topological_space local attribute [instance] classical.prop_decidable universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section topological_monoid /-- A topological monoid is a monoid in which the multiplication is continuous as a function `α × α → α`. -/ class topological_monoid (α : Type u) [topological_space α] [monoid α] : Prop := (continuous_mul : continuous (λp:α×α, p.1 * p.2)) /-- A topological (additive) monoid is a monoid in which the addition is continuous as a function `α × α → α`. -/ class topological_add_monoid (α : Type u) [topological_space α] [add_monoid α] : Prop := (continuous_add : continuous (λp:α×α, p.1 + p.2)) attribute [to_additive topological_add_monoid] topological_monoid attribute [to_additive topological_add_monoid.mk] topological_monoid.mk attribute [to_additive topological_add_monoid.continuous_add] topological_monoid.continuous_mul section variables [topological_space α] [monoid α] [topological_monoid α] @[to_additive continuous_add'] lemma continuous_mul' : continuous (λp:α×α, p.1 * p.2) := topological_monoid.continuous_mul α @[to_additive continuous_add] lemma continuous_mul [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := (hf.prod_mk hg).comp continuous_mul' -- @[to_additive continuous_smul] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : α, a ^ n) | 0 := by simpa using continuous_const | (k+1) := show continuous (λ (a : α), a * a ^ k), from continuous_mul continuous_id (continuous_pow _) @[to_additive tendsto_add'] lemma tendsto_mul' {a b : α} : tendsto (λp:α×α, p.fst * p.snd) (nhds (a, b)) (nhds (a * b)) := continuous_iff_continuous_at.mp (topological_monoid.continuous_mul α) (a, b) @[to_additive tendsto_add] lemma tendsto_mul {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (λx, f x * g x) x (nhds (a * b)) := (hf.prod_mk hg).comp (by rw [←nhds_prod_eq]; exact tendsto_mul') @[to_additive tendsto_list_sum] lemma tendsto_list_prod {f : γ → β → α} {x : filter β} {a : γ → α} : ∀l:list γ, (∀c∈l, tendsto (f c) x (nhds (a c))) → tendsto (λb, (l.map (λc, f c b)).prod) x (nhds ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp, exact tendsto_mul (h f (list.mem_cons_self _ _)) (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive continuous_list_sum] lemma continuous_list_prod [topological_space β] {f : γ → β → α} (l : list γ) (h : ∀c∈l, continuous (f c)) : continuous (λa, (l.map (λc, f c a)).prod) := continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_continuous_at.1 (h c hc) x @[to_additive prod.topological_add_monoid] instance [topological_space β] [monoid β] [topological_monoid β] : topological_monoid (α × β) := ⟨continuous.prod_mk (continuous_mul (continuous_fst.comp continuous_fst) (continuous_snd.comp continuous_fst)) (continuous_mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)) ⟩ attribute [instance] prod.topological_add_monoid end section variables [topological_space α] [comm_monoid α] [topological_monoid α] @[to_additive tendsto_multiset_sum] lemma tendsto_multiset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : multiset γ) : (∀c∈s, tendsto (f c) x (nhds (a c))) → tendsto (λb, (s.map (λc, f c b)).prod) x (nhds ((s.map a).prod)) := by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l } @[to_additive tendsto_finset_sum] lemma tendsto_finset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : finset γ) : (∀c∈s, tendsto (f c) x (nhds (a c))) → tendsto (λb, s.prod (λc, f c b)) x (nhds (s.prod a)) := tendsto_multiset_prod _ @[to_additive continuous_multiset_sum] lemma continuous_multiset_prod [topological_space β] {f : γ → β → α} (s : multiset γ) : (∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) := by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l } @[to_additive continuous_finset_sum] lemma continuous_finset_prod [topological_space β] {f : γ → β → α} (s : finset γ) : (∀c∈s, continuous (f c)) → continuous (λa, s.prod (λc, f c a)) := continuous_multiset_prod _ @[to_additive is_add_submonoid.mem_nhds_zero] lemma is_submonoid.mem_nhds_one (β : set α) [is_submonoid β] (oβ : is_open β) : β ∈ nhds (1 : α) := mem_nhds_sets_iff.2 ⟨β, (by refl), oβ, is_submonoid.one_mem _⟩ end end topological_monoid
9fabb900271cce2cc13151ae6fda3aa5d39af271
52b9f0379b3b0200088f3b2ec594d4dd3d3e6128
/factor.lean
5ae20a8c81cc06bc67f582a6b7ebb05096835d15
[]
no_license
minchaowu/mathematica_examples
f83fdf092a136f157dde8119b8a75c2cd4d91aae
fcc65b0b9fcb854f8671c0ebbca77bb3c1a9ecc1
refs/heads/master
1,610,729,580,720
1,498,331,049,000
1,498,331,049,000
99,731,631
0
0
null
1,502,222,706,000
1,502,222,706,000
null
UTF-8
Lean
false
false
1,265
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import init.meta.mathematica datatypes open expr tactic nat local attribute [simp] left_distrib right_distrib open mmexpr nat -- this will be unnecessary when the arithmetic simplifier is finished @[simp] lemma {u} n2a {α : Type u} [comm_ring α] (x : α) : -(x*2) = (-1)*x + (-1)*x := begin rw (mul_comm x 2), change -((1+1)*x) = -1*x + -1*x, simp end meta def factor (e : expr) (nm : option name) : tactic unit := do t ← mathematica.run_command_on (λ s, s ++" // LeanForm // Activate // Factor") e, ts ← to_expr t, pf ← eq_by_simp e ts, match nm with | some n := note n none pf >> skip | none := do n ← get_unused_name `h none, note n none pf, skip end namespace tactic namespace interactive section open interactive.types interactive meta def factor (e : parse texpr) (nm : parse using_ident) : tactic unit := do e' ← i_to_expr e, _root_.factor e' nm end end interactive end tactic example (x : ℝ) : x^2-2*x+1 ≥ 0 := begin factor x^2-2*x+1 using q, rewrite q, apply sq_nonneg end example (x y : ℝ) : true := begin factor x^10-y^10, trace_state, triv end
bbab8cd97b9bb8b26b374245ec0d1b3f3c76181f
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/category_theory/opposites.lean
e86d5ec02bcc0938b366f3c6e995be21db5c6131
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
10,060
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison -/ import category_theory.types import category_theory.equivalence import data.opposite universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open opposite variables {C : Type u₁} section has_hom variables [has_hom.{v₁} C] /-- The hom types of the opposite of a category (or graph). As with the objects, we'll make this irreducible below. Use `f.op` and `f.unop` to convert between morphisms of C and morphisms of Cᵒᵖ. -/ instance has_hom.opposite : has_hom Cᵒᵖ := { hom := λ X Y, unop Y ⟶ unop X } def has_hom.hom.op {X Y : C} (f : X ⟶ Y) : op Y ⟶ op X := f def has_hom.hom.unop {X Y : Cᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := f attribute [irreducible] has_hom.opposite lemma has_hom.hom.op_inj {X Y : C} : function.injective (has_hom.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) := λ _ _ H, congr_arg has_hom.hom.unop H lemma has_hom.hom.unop_inj {X Y : Cᵒᵖ} : function.injective (has_hom.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) := λ _ _ H, congr_arg has_hom.hom.op H @[simp] lemma has_hom.hom.unop_op {X Y : C} {f : X ⟶ Y} : f.op.unop = f := rfl @[simp] lemma has_hom.hom.op_unop {X Y : Cᵒᵖ} {f : X ⟶ Y} : f.unop.op = f := rfl end has_hom variables [category.{v₁} C] /-- The opposite category. See https://stacks.math.columbia.edu/tag/001M. -/ instance category.opposite : category.{v₁} Cᵒᵖ := { comp := λ _ _ _ f g, (g.unop ≫ f.unop).op, id := λ X, (𝟙 (unop X)).op } @[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).op = g.op ≫ f.op := rfl @[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl @[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).unop = g.unop ≫ f.unop := rfl @[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl @[simp] lemma unop_id_op {X : C} : (𝟙 (op X)).unop = 𝟙 X := rfl @[simp] lemma op_id_unop {X : Cᵒᵖ} : (𝟙 (unop X)).op = 𝟙 X := rfl /-- The functor from the double-opposite of a category to the underlying category. -/ @[simps] def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C := { obj := λ X, unop (unop X), map := λ X Y f, f.unop.unop } /-- The functor from a category to its double-opposite. -/ @[simps] def unop_unop : C ⥤ Cᵒᵖᵒᵖ := { obj := λ X, op (op X), map := λ X Y f, f.op.op } /-- The double opposite category is equivalent to the original. -/ @[simps] def op_op_equivalence : Cᵒᵖᵒᵖ ≌ C := { functor := op_op, inverse := unop_unop, unit_iso := iso.refl (𝟭 Cᵒᵖᵒᵖ), counit_iso := iso.refl (unop_unop ⋙ op_op) } def is_iso_of_op {X Y : C} (f : X ⟶ Y) [is_iso f.op] : is_iso f := { inv := (inv (f.op)).unop, hom_inv_id' := has_hom.hom.op_inj (by simp), inv_hom_id' := has_hom.hom.op_inj (by simp) } namespace functor section variables {D : Type u₂} [category.{v₂} D] variables {C D} @[simps] protected definition op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (unop X)), map := λ X Y f, (F.map f.unop).op } @[simps] protected definition unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D := { obj := λ X, unop (F.obj (op X)), map := λ X Y f, (F.map f.op).unop } /-- The isomorphism between `F.op.unop` and `F`. -/ def op_unop_iso (F : C ⥤ D) : F.op.unop ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) /-- The isomorphism between `F.unop.op` and `F`. -/ def unop_op_iso (F : Cᵒᵖ ⥤ Dᵒᵖ) : F.unop.op ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) variables (C D) @[simps] definition op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) := { obj := λ F, (unop F).op, map := λ F G α, { app := λ X, (α.unop.app (unop X)).op, naturality' := λ X Y f, has_hom.hom.unop_inj (α.unop.naturality f.unop).symm } } @[simps] definition op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ := { obj := λ F, op F.unop, map := λ F G α, has_hom.hom.op { app := λ X, (α.app (op X)).unop, naturality' := λ X Y f, has_hom.hom.op_inj $ (α.naturality f.op).symm } } -- TODO show these form an equivalence variables {C D} @[simps] protected definition left_op (F : C ⥤ Dᵒᵖ) : Cᵒᵖ ⥤ D := { obj := λ X, unop (F.obj (unop X)), map := λ X Y f, (F.map f.unop).unop } @[simps] protected definition right_op (F : Cᵒᵖ ⥤ D) : C ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (op X)), map := λ X Y f, (F.map f.op).op } -- TODO show these form an equivalence instance {F : C ⥤ D} [full F] : full F.op := { preimage := λ X Y f, (F.preimage f.unop).op } instance {F : C ⥤ D} [faithful F] : faithful F.op := { map_injective' := λ X Y f g h, has_hom.hom.unop_inj $ by simpa using map_injective F (has_hom.hom.op_inj h) } /-- If F is faithful then the right_op of F is also faithful. -/ instance right_op_faithful {F : Cᵒᵖ ⥤ D} [faithful F] : faithful F.right_op := { map_injective' := λ X Y f g h, has_hom.hom.op_inj (map_injective F (has_hom.hom.op_inj h)) } /-- If F is faithful then the left_op of F is also faithful. -/ instance left_op_faithful {F : C ⥤ Dᵒᵖ} [faithful F] : faithful F.left_op := { map_injective' := λ X Y f g h, has_hom.hom.unop_inj (map_injective F (has_hom.hom.unop_inj h)) } end end functor namespace nat_trans variables {D : Type u₂} [category.{v₂} D] section variables {F G : C ⥤ D} local attribute [semireducible] has_hom.opposite @[simps] protected definition op (α : F ⟶ G) : G.op ⟶ F.op := { app := λ X, (α.app (unop X)).op, naturality' := begin tidy, erw α.naturality, refl, end } @[simp] lemma op_id (F : C ⥤ D) : nat_trans.op (𝟙 F) = 𝟙 (F.op) := rfl @[simps] protected definition unop (α : F.op ⟶ G.op) : G ⟶ F := { app := λ X, (α.app (op X)).unop, naturality' := begin intros X Y f, have := congr_arg has_hom.hom.op (α.naturality f.op), dsimp at this, erw this, refl, end } @[simp] lemma unop_id (F : C ⥤ D) : nat_trans.unop (𝟙 F.op) = 𝟙 F := rfl end section variables {F G : C ⥤ Dᵒᵖ} local attribute [semireducible] has_hom.opposite protected definition left_op (α : F ⟶ G) : G.left_op ⟶ F.left_op := { app := λ X, (α.app (unop X)).unop, naturality' := begin tidy, erw α.naturality, refl, end } @[simp] lemma left_op_app (α : F ⟶ G) (X) : (nat_trans.left_op α).app X = (α.app (unop X)).unop := rfl protected definition right_op (α : F.left_op ⟶ G.left_op) : G ⟶ F := { app := λ X, (α.app (op X)).op, naturality' := begin intros X Y f, have := congr_arg has_hom.hom.op (α.naturality f.op), dsimp at this, erw this end } @[simp] lemma right_op_app (α : F.left_op ⟶ G.left_op) (X) : (nat_trans.right_op α).app X = (α.app (op X)).op := rfl end end nat_trans namespace iso variables {X Y : C} protected definition op (α : X ≅ Y) : op Y ≅ op X := { hom := α.hom.op, inv := α.inv.op, hom_inv_id' := has_hom.hom.unop_inj α.inv_hom_id, inv_hom_id' := has_hom.hom.unop_inj α.hom_inv_id } @[simp] lemma op_hom {α : X ≅ Y} : α.op.hom = α.hom.op := rfl @[simp] lemma op_inv {α : X ≅ Y} : α.op.inv = α.inv.op := rfl end iso namespace nat_iso variables {D : Type u₂} [category.{v₂} D] variables {F G : C ⥤ D} /-- The natural isomorphism between opposite functors `G.op ≅ F.op` induced by a natural isomorphism between the original functors `F ≅ G`. -/ protected definition op (α : F ≅ G) : G.op ≅ F.op := { hom := nat_trans.op α.hom, inv := nat_trans.op α.inv, hom_inv_id' := begin ext, dsimp, rw ←op_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←op_comp, rw α.hom_inv_id_app, refl, end } @[simp] lemma op_hom (α : F ≅ G) : (nat_iso.op α).hom = nat_trans.op α.hom := rfl @[simp] lemma op_inv (α : F ≅ G) : (nat_iso.op α).inv = nat_trans.op α.inv := rfl /-- The natural isomorphism between functors `G ≅ F` induced by a natural isomorphism between the opposite functors `F.op ≅ G.op`. -/ protected definition unop (α : F.op ≅ G.op) : G ≅ F := { hom := nat_trans.unop α.hom, inv := nat_trans.unop α.inv, hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw α.hom_inv_id_app, refl, end } @[simp] lemma unop_hom (α : F.op ≅ G.op) : (nat_iso.unop α).hom = nat_trans.unop α.hom := rfl @[simp] lemma unop_inv (α : F.op ≅ G.op) : (nat_iso.unop α).inv = nat_trans.unop α.inv := rfl end nat_iso /-- The equivalence between arrows of the form `A ⟶ B` and `B.unop ⟶ A.unop`. Useful for building adjunctions. Note that this (definitionally) gives variants ``` def op_equiv' (A : C) (B : Cᵒᵖ) : (opposite.op A ⟶ B) ≃ (B.unop ⟶ A) := op_equiv _ _ def op_equiv'' (A : Cᵒᵖ) (B : C) : (A ⟶ opposite.op B) ≃ (B ⟶ A.unop) := op_equiv _ _ def op_equiv''' (A B : C) : (opposite.op A ⟶ opposite.op B) ≃ (B ⟶ A) := op_equiv _ _ ``` -/ def op_equiv (A B : Cᵒᵖ) : (A ⟶ B) ≃ (B.unop ⟶ A.unop) := { to_fun := λ f, f.unop, inv_fun := λ g, g.op, left_inv := λ _, rfl, right_inv := λ _, rfl } -- These two are made by hand rather than by simps because simps generates -- `(op_equiv _ _).to_fun f = ...` rather than the coercion version. @[simp] lemma op_equiv_apply (A B : Cᵒᵖ) (f : A ⟶ B) : op_equiv _ _ f = f.unop := rfl @[simp] lemma op_equiv_symm_apply (A B : Cᵒᵖ) (f : B.unop ⟶ A.unop) : (op_equiv _ _).symm f = f.op := rfl universes v variables {α : Type v} [preorder α] /-- Construct a morphism in the opposite of a preorder category from an inequality. -/ def op_hom_of_le {U V : αᵒᵖ} (h : unop V ≤ unop U) : U ⟶ V := has_hom.hom.op (hom_of_le h) lemma le_of_op_hom {U V : αᵒᵖ} (h : U ⟶ V) : unop V ≤ unop U := le_of_hom (h.unop) end category_theory
8834ea8e8b46afea80890b8d7cf595505949a9f6
3bdd27ffdff3ffa22d4bb010eba695afcc96bc4a
/src/combinatorics/simplicial_complex/star.lean
661b2de3a83692b783423074bb32c4a5a483d536
[]
no_license
mmasdeu/brouwerfixedpoint
684d712c982c6a8b258b4e2c6b2eab923f2f1289
548270f79ecf12d7e20a256806ccb9fcf57b87e2
refs/heads/main
1,690,539,793,996
1,631,801,831,000
1,631,801,831,000
368,139,809
4
3
null
1,624,453,250,000
1,621,246,034,000
Lean
UTF-8
Lean
false
false
5,587
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import combinatorics.simplicial_complex.basic import combinatorics.simplicial_complex.closure namespace affine open set variables {m n : ℕ} {E : Type*} [normed_group E] [normed_space ℝ E] {S : simplicial_complex E} {X Y : finset E} {A B : set (finset E)} /-- The open star of a set of faces is the union of their surfaces. Note that the star is all of the original complex as soon as A contains the empty set. -/ def simplicial_complex.star (S : simplicial_complex E) : set (finset E) → set (finset E) := λ A, {X | X ∈ S.faces ∧ ∃ {Y}, Y ∈ A ∧ Y ⊆ X} lemma star_empty : S.star ∅ = ∅ := begin unfold simplicial_complex.star, simp, end lemma star_singleton_empty : S.star {∅} = S.faces := begin unfold simplicial_complex.star, simp, end lemma mem_star_singleton_iff : Y ∈ S.star {X} ↔ Y ∈ S.faces ∧ X ⊆ Y := begin unfold simplicial_complex.star, simp, end lemma mem_star_iff : X ∈ S.star A ↔ X ∈ S.faces ∩ ⋃ (Y ∈ A), {Z | Y ⊆ Z} := begin unfold simplicial_complex.star, simp, end lemma star_subset : S.star A ⊆ S.faces := λ X hX, hX.1 lemma subset_star : S.faces ∩ A ⊆ S.star A := λ X hX, ⟨hX.1, X, hX.2, subset.refl X⟩ lemma star_mono (hAB : A ⊆ B) : S.star A ⊆ S.star B := λ X ⟨hX, Y, hY, hYX⟩, ⟨hX, Y, hAB hY, hYX⟩ lemma star_up_closed : X ∈ S.faces → Y ∈ S.star A → Y ⊆ X → X ∈ S.star A := λ hX ⟨hY, Z, hZ, hZY⟩ hYX, ⟨hX, Z, hZ, subset.trans hZY hYX⟩ lemma Union_star_eq_star : (⋃ (X ∈ A), S.star {X}) = S.star A := begin ext X, rw mem_bUnion_iff, split, { rintro ⟨Y', hY, hX, Y, (hYY' : Y = Y'), hYX⟩, subst hYY', exact ⟨hX, Y, hY, hYX⟩, }, { rintro ⟨hX, Y, hY, hYX⟩, exact ⟨Y, hY, hX, Y, mem_singleton Y, hYX⟩, } end --Can maybe get rid of hX? lemma star_singleton_eq_Inter_star_singleton (hX : X ∈ S.faces) : S.star {X} = ⋂ x ∈ X, S.star {{x}} := begin ext Y, split, { rintro ⟨hY, Z, (hZ : Z = X), hXY⟩, rw hZ at hXY, exact mem_bInter (λ x (hx : x ∈ X), ⟨hY, {x}, mem_singleton {x}, finset.singleton_subset_iff.2 (hXY hx)⟩) }, { rintro h, rw mem_star_singleton_iff, split, { simp only [mem_Inter] at h, sorry }, rintro x hx, obtain ⟨hY, Z, (hZ : Z = {x}), hxY⟩ := mem_bInter_iff.1 h x hx, rw hZ at hxY, exact finset.singleton_subset_iff.1 hxY } end /-- The closed star of a complex S and a set A is the complex whose faces are in S and share a surface with some face in A -/ def simplicial_complex.Star (S : simplicial_complex E) (A : set (finset E)) : simplicial_complex E := simplicial_complex.of_surcomplex {X | ∃ {Y Z}, Y ∈ A ∧ Z ∈ S.faces ∧ X ⊆ Z ∧ Y ⊆ Z} (λ X ⟨_, Z, _, hZ, hXZ, _⟩, S.down_closed hZ hXZ) (λ X W ⟨Y, Z, hY, hZ, hXZ, hYZ⟩ hWX, ⟨Y, Z, hY, hZ, subset.trans hWX hXZ, hYZ⟩) lemma Star_empty : (S.Star ∅).faces = ∅ := begin unfold simplicial_complex.Star, simp, end lemma Star_singleton_empty : S.Star {∅} = S := begin ext X, split, { rintro ⟨Y, Z, (hY : Y = ∅), hZ, hXZ, hYZ⟩, exact S.down_closed hZ hXZ, }, { rintro hX, exact ⟨∅, X, rfl, hX, subset.refl _, empty_subset X⟩, } end lemma mem_Star_singleton_iff : Y ∈ (S.Star {X}).faces ↔ ∃ {Z}, Z ∈ S.faces ∧ Y ⊆ Z ∧ X ⊆ Z := begin unfold simplicial_complex.Star, simp, end /-- The closed star of a set is the closure of its open star. -/ lemma Star_eq_closure_star : S.Star A = S.closure (S.star A) := begin ext X, split, { rintro ⟨Y, Z, hY, hZ, hXZ, hYZ⟩, exact ⟨S.down_closed hZ hXZ, Z, ⟨hZ, Y, hY, hYZ⟩, hXZ⟩, }, { rintro ⟨hX, Z, ⟨hZ, Y, hY, hYZ⟩, hXZ⟩, exact ⟨Y, Z, hY, hZ, hXZ, hYZ⟩, } end lemma Star_subset : (S.Star A).faces ⊆ S.faces := λ X ⟨_, Z, _, hZ, hXZ, _⟩, S.down_closed hZ hXZ lemma subset_Star : S.faces ∩ A ⊆ (S.Star A).faces := λ X ⟨hXS, hXA⟩, ⟨X, X, hXA, hXS, subset.refl X, subset.refl X⟩ lemma star_subset_Star : S.star A ⊆ (S.Star A).faces := λ X ⟨hX, Y, hY, hYX⟩, ⟨Y, X, hY, hX, subset.refl X, hYX⟩ lemma Star_mono (hAB : A ⊆ B) : (S.Star A).faces ⊆ (S.Star B).faces := begin rw [Star_eq_closure_star, Star_eq_closure_star], exact closure_faces_subset_of_subset (star_mono hAB), end lemma Star_facet_iff : X ∈ (S.Star A).facets ↔ X ∈ S.facets ∧ ∃ {Y}, Y ∈ A ∧ Y ⊆ X := begin split, { rintro ⟨⟨Y, Z, hY, hZ, hXZ, hYZ⟩, hXmax⟩, have := hXmax ⟨Y, Z, hY, hZ, subset.refl Z, hYZ⟩ hXZ, subst this, split, { use hZ, rintro W hW hXW, exact hXmax (star_subset_Star ⟨hW, Y, hY, subset.trans hYZ hXW⟩) hXW, }, { exact ⟨Y, hY, hYZ⟩, } }, { rintro ⟨hX, Y, hY, hYX⟩, split, exact ⟨Y, X, hY, hX.1, subset.refl X, hYX⟩, rintro Z hZ, exact hX.2 (Star_subset hZ), } end lemma pure_Star_of_pure (hS : S.pure_of n) : (S.Star A).pure_of n := λ X hX, hS (Star_facet_iff.1 hX).1 lemma Star_pureness_eq_pureness [finite_dimensional ℝ E] (hS : S.pure) (hSA : (S.Star A).faces.nonempty) : (S.Star A).pureness = S.pureness := begin obtain ⟨n, hS⟩ := hS, obtain ⟨X, hX⟩ := id hSA, rw [pureness_def' hSA (pure_Star_of_pure hS), pureness_def' (hSA.mono Star_subset) hS], end end affine
be97e2d003715bc75be0a79c9c3cc281c911c32f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/quadratic_form/isometry.lean
7c97543e99937c4b164783f18f52d34bb7faa03e
[ "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
5,647
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Eric Wieser -/ import linear_algebra.quadratic_form.basic /-! # Isometries with respect to quadratic forms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions * `quadratic_form.isometry`: `linear_equiv`s which map between two different quadratic forms * `quadratic_form.equvialent`: propositional version of the above ## Main results * `equivalent_weighted_sum_squares`: in finite dimensions, any quadratic form is equivalent to a parametrization of `quadratic_form.weighted_sum_squares`. -/ variables {ι R K M M₁ M₂ M₃ V : Type*} namespace quadratic_form variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₁] [module R M₂] [module R M₃] /-- An isometry between two quadratic spaces `M₁, Q₁` and `M₂, Q₂` over a ring `R`, is a linear equivalence between `M₁` and `M₂` that commutes with the quadratic forms. -/ @[nolint has_nonempty_instance] structure isometry (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) extends M₁ ≃ₗ[R] M₂ := (map_app' : ∀ m, Q₂ (to_fun m) = Q₁ m) /-- Two quadratic forms over a ring `R` are equivalent if there exists an isometry between them: a linear equivalence that transforms one quadratic form into the other. -/ def equivalent (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) := nonempty (Q₁.isometry Q₂) namespace isometry variables {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} instance : has_coe (Q₁.isometry Q₂) (M₁ ≃ₗ[R] M₂) := ⟨isometry.to_linear_equiv⟩ @[simp] lemma to_linear_equiv_eq_coe (f : Q₁.isometry Q₂) : f.to_linear_equiv = f := rfl instance : has_coe_to_fun (Q₁.isometry Q₂) (λ _, M₁ → M₂) := ⟨λ f, ⇑(f : M₁ ≃ₗ[R] M₂)⟩ @[simp] lemma coe_to_linear_equiv (f : Q₁.isometry Q₂) : ⇑(f : M₁ ≃ₗ[R] M₂) = f := rfl @[simp] lemma map_app (f : Q₁.isometry Q₂) (m : M₁) : Q₂ (f m) = Q₁ m := f.map_app' m /-- The identity isometry from a quadratic form to itself. -/ @[refl] def refl (Q : quadratic_form R M) : Q.isometry Q := { map_app' := λ m, rfl, .. linear_equiv.refl R M } /-- The inverse isometry of an isometry between two quadratic forms. -/ @[symm] def symm (f : Q₁.isometry Q₂) : Q₂.isometry Q₁ := { map_app' := by { intro m, rw ← f.map_app, congr, exact f.to_linear_equiv.apply_symm_apply m }, .. (f : M₁ ≃ₗ[R] M₂).symm } /-- The composition of two isometries between quadratic forms. -/ @[trans] def trans (f : Q₁.isometry Q₂) (g : Q₂.isometry Q₃) : Q₁.isometry Q₃ := { map_app' := by { intro m, rw [← f.map_app, ← g.map_app], refl }, .. (f : M₁ ≃ₗ[R] M₂).trans (g : M₂ ≃ₗ[R] M₃) } end isometry namespace equivalent variables {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} @[refl] lemma refl (Q : quadratic_form R M) : Q.equivalent Q := ⟨isometry.refl Q⟩ @[symm] lemma symm (h : Q₁.equivalent Q₂) : Q₂.equivalent Q₁ := h.elim $ λ f, ⟨f.symm⟩ @[trans] lemma trans (h : Q₁.equivalent Q₂) (h' : Q₂.equivalent Q₃) : Q₁.equivalent Q₃ := h'.elim $ h.elim $ λ f g, ⟨f.trans g⟩ end equivalent variables [fintype ι] {v : basis ι R M} /-- A quadratic form composed with a `linear_equiv` is isometric to itself. -/ def isometry_of_comp_linear_equiv (Q : quadratic_form R M) (f : M₁ ≃ₗ[R] M) : Q.isometry (Q.comp (f : M₁ →ₗ[R] M)) := { map_app' := begin intro, simp only [comp_apply, linear_equiv.coe_coe, linear_equiv.to_fun_eq_coe, linear_equiv.apply_symm_apply, f.apply_symm_apply], end, .. f.symm } /-- A quadratic form is isometric to its bases representations. -/ noncomputable def isometry_basis_repr (Q : quadratic_form R M) (v : basis ι R M) : isometry Q (Q.basis_repr v) := isometry_of_comp_linear_equiv Q v.equiv_fun.symm variables [field K] [invertible (2 : K)] [add_comm_group V] [module K V] /-- Given an orthogonal basis, a quadratic form is isometric with a weighted sum of squares. -/ noncomputable def isometry_weighted_sum_squares (Q : quadratic_form K V) (v : basis (fin (finite_dimensional.finrank K V)) K V) (hv₁ : (associated Q).is_Ortho v) : Q.isometry (weighted_sum_squares K (λ i, Q (v i))) := begin let iso := Q.isometry_basis_repr v, refine ⟨iso, λ m, _⟩, convert iso.map_app m, rw basis_repr_eq_of_is_Ortho _ _ hv₁, end variables [finite_dimensional K V] open bilin_form lemma equivalent_weighted_sum_squares (Q : quadratic_form K V) : ∃ w : fin (finite_dimensional.finrank K V) → K, equivalent Q (weighted_sum_squares K w) := let ⟨v, hv₁⟩ := exists_orthogonal_basis (associated_is_symm _ Q) in ⟨_, ⟨Q.isometry_weighted_sum_squares v hv₁⟩⟩ lemma equivalent_weighted_sum_squares_units_of_nondegenerate' (Q : quadratic_form K V) (hQ : (associated Q).nondegenerate) : ∃ w : fin (finite_dimensional.finrank K V) → Kˣ, equivalent Q (weighted_sum_squares K w) := begin obtain ⟨v, hv₁⟩ := exists_orthogonal_basis (associated_is_symm _ Q), have hv₂ := hv₁.not_is_ortho_basis_self_of_nondegenerate hQ, simp_rw [is_ortho, associated_eq_self_apply] at hv₂, exact ⟨λ i, units.mk0 _ (hv₂ i), ⟨Q.isometry_weighted_sum_squares v hv₁⟩⟩, end end quadratic_form
de87a7359f992ae956f64f05f8341a010ce739de
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/prod.lean
90f2736c294bca3ee5950211e4a78fe248d1a7c3
[ "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
27,517
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Patrick Massot -/ import data.set.image /-! # Sets in product and pi types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the product of sets in `α × β` and in `Π i, α i` along with the diagonal of a type. ## Main declarations * `set.prod`: Binary product of sets. For `s : set α`, `t : set β`, we have `s.prod t : set (α × β)`. * `set.diagonal`: Diagonal of a type. `set.diagonal α = {(x, x) | x : α}`. * `set.off_diag`: Off-diagonal. `s ×ˢ s` without the diagonal. * `set.pi`: Arbitrary product of sets. -/ open function namespace set /-! ### Cartesian binary product of sets -/ section prod variables {α β γ δ : Type*} {s s₁ s₂ : set α} {t t₁ t₂ : set β} {a : α} {b : β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} /- This notation binds more strongly than (pre)images, unions and intersections. -/ infixr (name := set.prod) ` ×ˢ `:82 := set.prod lemma prod_eq (s : set α) (t : set β) : s ×ˢ t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl lemma mem_prod_eq {p : α × β} : p ∈ s ×ˢ t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp, mfld_simps] lemma mem_prod {p : α × β} : p ∈ s ×ˢ t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[simp, mfld_simps] lemma prod_mk_mem_set_prod_eq : (a, b) ∈ s ×ˢ t = (a ∈ s ∧ b ∈ t) := rfl lemma mk_mem_prod (ha : a ∈ s) (hb : b ∈ t) : (a, b) ∈ s ×ˢ t := ⟨ha, hb⟩ instance decidable_mem_prod [hs : decidable_pred (∈ s)] [ht : decidable_pred (∈ t)] : decidable_pred (∈ (s ×ˢ t)) := λ _, and.decidable lemma prod_mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁ ×ˢ t₁ ⊆ s₂ ×ˢ t₂ := λ x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ lemma prod_mono_left (hs : s₁ ⊆ s₂) : s₁ ×ˢ t ⊆ s₂ ×ˢ t := prod_mono hs subset.rfl lemma prod_mono_right (ht : t₁ ⊆ t₂) : s ×ˢ t₁ ⊆ s ×ˢ t₂ := prod_mono subset.rfl ht @[simp] lemma prod_self_subset_prod_self : s₁ ×ˢ s₁ ⊆ s₂ ×ˢ s₂ ↔ s₁ ⊆ s₂ := ⟨λ h x hx, (h (mk_mem_prod hx hx)).1, λ h x hx, ⟨h hx.1, h hx.2⟩⟩ @[simp] lemma prod_self_ssubset_prod_self : s₁ ×ˢ s₁ ⊂ s₂ ×ˢ s₂ ↔ s₁ ⊂ s₂ := and_congr prod_self_subset_prod_self $ not_congr prod_self_subset_prod_self lemma prod_subset_iff {P : set (α × β)} : s ×ˢ t ⊆ P ↔ ∀ (x ∈ s) (y ∈ t), (x, y) ∈ P := ⟨λ h _ hx _ hy, h (mk_mem_prod hx hy), λ h ⟨_, _⟩ hp, h _ hp.1 _ hp.2⟩ lemma forall_prod_set {p : α × β → Prop} : (∀ x ∈ s ×ˢ t, p x) ↔ ∀ (x ∈ s) (y ∈ t), p (x, y) := prod_subset_iff lemma exists_prod_set {p : α × β → Prop} : (∃ x ∈ s ×ˢ t, p x) ↔ ∃ (x ∈ s) (y ∈ t), p (x, y) := by simp [and_assoc] @[simp] lemma prod_empty : s ×ˢ (∅ : set β) = ∅ := by { ext, exact and_false _ } @[simp] lemma empty_prod : (∅ : set α) ×ˢ t = ∅ := by { ext, exact false_and _ } @[simp, mfld_simps] lemma univ_prod_univ : @univ α ×ˢ @univ β = univ := by { ext, exact true_and _ } lemma univ_prod {t : set β} : (univ : set α) ×ˢ t = prod.snd ⁻¹' t := by simp [prod_eq] lemma prod_univ {s : set α} : s ×ˢ (univ : set β) = prod.fst ⁻¹' s := by simp [prod_eq] @[simp] lemma singleton_prod : ({a} : set α) ×ˢ t = prod.mk a '' t := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } @[simp] lemma prod_singleton : s ×ˢ ({b} : set β) = (λ a, (a, b)) '' s := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } lemma singleton_prod_singleton : ({a} : set α) ×ˢ ({b} : set β) = {(a, b)} :=by simp @[simp] lemma union_prod : (s₁ ∪ s₂) ×ˢ t = s₁ ×ˢ t ∪ s₂ ×ˢ t := by { ext ⟨x, y⟩, simp [or_and_distrib_right] } @[simp] lemma prod_union : s ×ˢ (t₁ ∪ t₂) = s ×ˢ t₁ ∪ s ×ˢ t₂ := by { ext ⟨x, y⟩, simp [and_or_distrib_left] } lemma inter_prod : (s₁ ∩ s₂) ×ˢ t = s₁ ×ˢ t ∩ s₂ ×ˢ t := by { ext ⟨x, y⟩, simp only [←and_and_distrib_right, mem_inter_iff, mem_prod] } lemma prod_inter : s ×ˢ (t₁ ∩ t₂) = s ×ˢ t₁ ∩ s ×ˢ t₂ := by { ext ⟨x, y⟩, simp only [←and_and_distrib_left, mem_inter_iff, mem_prod] } @[mfld_simps] lemma prod_inter_prod : s₁ ×ˢ t₁ ∩ s₂ ×ˢ t₂ = (s₁ ∩ s₂) ×ˢ (t₁ ∩ t₂) := by { ext ⟨x, y⟩, simp [and_assoc, and.left_comm] } @[simp] lemma disjoint_prod : disjoint (s₁ ×ˢ t₁) (s₂ ×ˢ t₂) ↔ disjoint s₁ s₂ ∨ disjoint t₁ t₂ := begin simp_rw [disjoint_left, mem_prod, not_and_distrib, prod.forall, and_imp, ←@forall_or_distrib_right α, ←@forall_or_distrib_left β, ←@forall_or_distrib_right (_ ∈ s₁), ←@forall_or_distrib_left (_ ∈ t₁)], end lemma _root_.disjoint.set_prod_left (hs : disjoint s₁ s₂) (t₁ t₂ : set β) : disjoint (s₁ ×ˢ t₁) (s₂ ×ˢ t₂) := disjoint_left.2 $ λ ⟨a, b⟩ ⟨ha₁, hb₁⟩ ⟨ha₂, hb₂⟩, disjoint_left.1 hs ha₁ ha₂ lemma _root_.disjoint.set_prod_right (ht : disjoint t₁ t₂) (s₁ s₂ : set α) : disjoint (s₁ ×ˢ t₁) (s₂ ×ˢ t₂) := disjoint_left.2 $ λ ⟨a, b⟩ ⟨ha₁, hb₁⟩ ⟨ha₂, hb₂⟩, disjoint_left.1 ht hb₁ hb₂ lemma insert_prod : insert a s ×ˢ t = (prod.mk a '' t) ∪ s ×ˢ t := by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} } lemma prod_insert : s ×ˢ (insert b t) = ((λa, (a, b)) '' s) ∪ s ×ˢ t := by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} } lemma prod_preimage_eq {f : γ → α} {g : δ → β} : (f ⁻¹' s) ×ˢ (g ⁻¹' t) = (λ p : γ × δ, (f p.1, g p.2)) ⁻¹' s ×ˢ t := rfl lemma prod_preimage_left {f : γ → α} : (f ⁻¹' s) ×ˢ t = (λ p : γ × β, (f p.1, p.2)) ⁻¹' s ×ˢ t := rfl lemma prod_preimage_right {g : δ → β} : s ×ˢ (g ⁻¹' t) = (λ p : α × δ, (p.1, g p.2)) ⁻¹' s ×ˢ t := rfl lemma preimage_prod_map_prod (f : α → β) (g : γ → δ) (s : set β) (t : set δ) : prod.map f g ⁻¹' s ×ˢ t = (f ⁻¹' s) ×ˢ (g ⁻¹' t) := rfl lemma mk_preimage_prod (f : γ → α) (g : γ → β) : (λ x, (f x, g x)) ⁻¹' s ×ˢ t = f ⁻¹' s ∩ g ⁻¹' t := rfl @[simp] lemma mk_preimage_prod_left (hb : b ∈ t) : (λ a, (a, b)) ⁻¹' s ×ˢ t = s := by { ext a, simp [hb] } @[simp] lemma mk_preimage_prod_right (ha : a ∈ s) : prod.mk a ⁻¹' s ×ˢ t = t := by { ext b, simp [ha] } @[simp] lemma mk_preimage_prod_left_eq_empty (hb : b ∉ t) : (λ a, (a, b)) ⁻¹' s ×ˢ t = ∅ := by { ext a, simp [hb] } @[simp] lemma mk_preimage_prod_right_eq_empty (ha : a ∉ s) : prod.mk a ⁻¹' s ×ˢ t = ∅ := by { ext b, simp [ha] } lemma mk_preimage_prod_left_eq_if [decidable_pred (∈ t)] : (λ a, (a, b)) ⁻¹' s ×ˢ t = if b ∈ t then s else ∅ := by split_ifs; simp [h] lemma mk_preimage_prod_right_eq_if [decidable_pred (∈ s)] : prod.mk a ⁻¹' s ×ˢ t = if a ∈ s then t else ∅ := by split_ifs; simp [h] lemma mk_preimage_prod_left_fn_eq_if [decidable_pred (∈ t)] (f : γ → α) : (λ a, (f a, b)) ⁻¹' s ×ˢ t = if b ∈ t then f ⁻¹' s else ∅ := by rw [← mk_preimage_prod_left_eq_if, prod_preimage_left, preimage_preimage] lemma mk_preimage_prod_right_fn_eq_if [decidable_pred (∈ s)] (g : δ → β) : (λ b, (a, g b)) ⁻¹' s ×ˢ t = if a ∈ s then g ⁻¹' t else ∅ := by rw [← mk_preimage_prod_right_eq_if, prod_preimage_right, preimage_preimage] @[simp] lemma preimage_swap_prod (s : set α) (t : set β) : prod.swap ⁻¹' s ×ˢ t = t ×ˢ s := by { ext ⟨x, y⟩, simp [and_comm] } @[simp] lemma image_swap_prod (s : set α) (t : set β) : prod.swap '' s ×ˢ t = t ×ˢ s := by rw [image_swap_eq_preimage_swap, preimage_swap_prod] lemma prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : (m₁ '' s) ×ˢ (m₂ '' t) = (λ p : α × β, (m₁ p.1, m₂ p.2)) '' s ×ˢ t := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] lemma prod_range_range_eq {m₁ : α → γ} {m₂ : β → δ} : (range m₁) ×ˢ (range m₂) = range (λ p : α × β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] @[simp, mfld_simps] lemma range_prod_map {m₁ : α → γ} {m₂ : β → δ} : range (prod.map m₁ m₂) = (range m₁) ×ˢ (range m₂) := prod_range_range_eq.symm lemma prod_range_univ_eq {m₁ : α → γ} : (range m₁) ×ˢ (univ : set β) = range (λ p : α × β, (m₁ p.1, p.2)) := ext $ by simp [range] lemma prod_univ_range_eq {m₂ : β → δ} : (univ : set α) ×ˢ (range m₂) = range (λ p : α × β, (p.1, m₂ p.2)) := ext $ by simp [range] lemma range_pair_subset (f : α → β) (g : α → γ) : range (λ x, (f x, g x)) ⊆ (range f) ×ˢ (range g) := have (λ x, (f x, g x)) = prod.map f g ∘ (λ x, (x, x)), from funext (λ x, rfl), by { rw [this, ← range_prod_map], apply range_comp_subset_range } lemma nonempty.prod : s.nonempty → t.nonempty → (s ×ˢ t).nonempty := λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨(x, y), ⟨hx, hy⟩⟩ lemma nonempty.fst : (s ×ˢ t).nonempty → s.nonempty := λ ⟨x, hx⟩, ⟨x.1, hx.1⟩ lemma nonempty.snd : (s ×ˢ t).nonempty → t.nonempty := λ ⟨x, hx⟩, ⟨x.2, hx.2⟩ lemma prod_nonempty_iff : (s ×ˢ t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, h.1.prod h.2⟩ lemma prod_eq_empty_iff : s ×ˢ t = ∅ ↔ s = ∅ ∨ t = ∅ := by simp only [not_nonempty_iff_eq_empty.symm, prod_nonempty_iff, not_and_distrib] lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : s ×ˢ t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] lemma image_prod_mk_subset_prod {f : α → β} {g : α → γ} {s : set α} : (λ x, (f x, g x)) '' s ⊆ (f '' s) ×ˢ (g '' s) := by { rintros _ ⟨x, hx, rfl⟩, exact mk_mem_prod (mem_image_of_mem f hx) (mem_image_of_mem g hx) } lemma image_prod_mk_subset_prod_left (hb : b ∈ t) : (λ a, (a, b)) '' s ⊆ s ×ˢ t := by { rintro _ ⟨a, ha, rfl⟩, exact ⟨ha, hb⟩ } lemma image_prod_mk_subset_prod_right (ha : a ∈ s) : prod.mk a '' t ⊆ s ×ˢ t := by { rintro _ ⟨b, hb, rfl⟩, exact ⟨ha, hb⟩ } lemma prod_subset_preimage_fst (s : set α) (t : set β) : s ×ˢ t ⊆ prod.fst ⁻¹' s := inter_subset_left _ _ lemma fst_image_prod_subset (s : set α) (t : set β) : prod.fst '' s ×ˢ t ⊆ s := image_subset_iff.2 $ prod_subset_preimage_fst s t lemma fst_image_prod (s : set β) {t : set α} (ht : t.nonempty) : prod.fst '' s ×ˢ t = s := (fst_image_prod_subset _ _).antisymm $ λ y hy, let ⟨x, hx⟩ := ht in ⟨(y, x), ⟨hy, hx⟩, rfl⟩ lemma prod_subset_preimage_snd (s : set α) (t : set β) : s ×ˢ t ⊆ prod.snd ⁻¹' t := inter_subset_right _ _ lemma snd_image_prod_subset (s : set α) (t : set β) : prod.snd '' s ×ˢ t ⊆ t := image_subset_iff.2 $ prod_subset_preimage_snd s t lemma snd_image_prod {s : set α} (hs : s.nonempty) (t : set β) : prod.snd '' s ×ˢ t = t := (snd_image_prod_subset _ _).antisymm $ λ y y_in, let ⟨x, x_in⟩ := hs in ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩ lemma prod_diff_prod : s ×ˢ t \ s₁ ×ˢ t₁ = s ×ˢ (t \ t₁) ∪ (s \ s₁) ×ˢ t := by { ext x, by_cases h₁ : x.1 ∈ s₁; by_cases h₂ : x.2 ∈ t₁; simp * } /-- A product set is included in a product set if and only factors are included, or a factor of the first set is empty. -/ lemma prod_subset_prod_iff : s ×ˢ t ⊆ s₁ ×ˢ t₁ ↔ s ⊆ s₁ ∧ t ⊆ t₁ ∨ s = ∅ ∨ t = ∅ := begin cases (s ×ˢ t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, have st : s.nonempty ∧ t.nonempty, by rwa [prod_nonempty_iff] at h, refine ⟨λ H, or.inl ⟨_, _⟩, _⟩, { have := image_subset (prod.fst : α × β → α) H, rwa [fst_image_prod _ st.2, fst_image_prod _ (h.mono H).snd] at this }, { have := image_subset (prod.snd : α × β → β) H, rwa [snd_image_prod st.1, snd_image_prod (h.mono H).fst] at this }, { intro H, simp only [st.1.ne_empty, st.2.ne_empty, or_false] at H, exact prod_mono H.1 H.2 } end lemma prod_eq_prod_iff_of_nonempty (h : (s ×ˢ t).nonempty) : s ×ˢ t = s₁ ×ˢ t₁ ↔ s = s₁ ∧ t = t₁ := begin split, { intro heq, have h₁ : (s₁ ×ˢ t₁ : set _).nonempty, { rwa [← heq] }, rw [prod_nonempty_iff] at h h₁, rw [← fst_image_prod s h.2, ← fst_image_prod s₁ h₁.2, heq, eq_self_iff_true, true_and, ← snd_image_prod h.1 t, ← snd_image_prod h₁.1 t₁, heq] }, { rintro ⟨rfl, rfl⟩, refl } end lemma prod_eq_prod_iff : s ×ˢ t = s₁ ×ˢ t₁ ↔ s = s₁ ∧ t = t₁ ∨ (s = ∅ ∨ t = ∅) ∧ (s₁ = ∅ ∨ t₁ = ∅) := begin symmetry, cases eq_empty_or_nonempty (s ×ˢ t) with h h, { simp_rw [h, @eq_comm _ ∅, prod_eq_empty_iff, prod_eq_empty_iff.mp h, true_and, or_iff_right_iff_imp], rintro ⟨rfl, rfl⟩, exact prod_eq_empty_iff.mp h }, rw [prod_eq_prod_iff_of_nonempty h], rw [nonempty_iff_ne_empty, ne.def, prod_eq_empty_iff] at h, simp_rw [h, false_and, or_false], end @[simp] lemma prod_eq_iff_eq (ht : t.nonempty) : s ×ˢ t = s₁ ×ˢ t ↔ s = s₁ := begin simp_rw [prod_eq_prod_iff, ht.ne_empty, eq_self_iff_true, and_true, or_iff_left_iff_imp, or_false], rintro ⟨rfl, rfl⟩, refl, end section mono variables [preorder α] {f : α → set β} {g : α → set γ} theorem _root_.monotone.set_prod (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ×ˢ g x) := λ a b h, prod_mono (hf h) (hg h) theorem _root_.antitone.set_prod (hf : antitone f) (hg : antitone g) : antitone (λ x, f x ×ˢ g x) := λ a b h, prod_mono (hf h) (hg h) theorem _root_.monotone_on.set_prod (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, f x ×ˢ g x) s := λ a ha b hb h, prod_mono (hf ha hb h) (hg ha hb h) theorem _root_.antitone_on.set_prod (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, f x ×ˢ g x) s := λ a ha b hb h, prod_mono (hf ha hb h) (hg ha hb h) end mono end prod /-! ### Diagonal In this section we prove some lemmas about the diagonal set `{p | p.1 = p.2}` and the diagonal map `λ x, (x, x)`. -/ section diagonal variables {α : Type*} {s t : set α} /-- `diagonal α` is the set of `α × α` consisting of all pairs of the form `(a, a)`. -/ def diagonal (α : Type*) : set (α × α) := {p | p.1 = p.2} lemma mem_diagonal (x : α) : (x, x) ∈ diagonal α := by simp [diagonal] @[simp] lemma mem_diagonal_iff {x : α × α} : x ∈ diagonal α ↔ x.1 = x.2 := iff.rfl lemma diagonal_nonempty [nonempty α] : (diagonal α).nonempty := nonempty.elim ‹_› $ λ x, ⟨_, mem_diagonal x⟩ instance decidable_mem_diagonal [h : decidable_eq α] (x : α × α) : decidable (x ∈ diagonal α) := h x.1 x.2 lemma preimage_coe_coe_diagonal (s : set α) : (prod.map coe coe) ⁻¹' (diagonal α) = diagonal s := by { ext ⟨⟨x, hx⟩, ⟨y, hy⟩⟩, simp [set.diagonal] } @[simp] lemma range_diag : range (λ x, (x, x)) = diagonal α := by { ext ⟨x, y⟩, simp [diagonal, eq_comm] } lemma diagonal_subset_iff {s} : diagonal α ⊆ s ↔ ∀ x, (x, x) ∈ s := by rw [← range_diag, range_subset_iff] @[simp] lemma prod_subset_compl_diagonal_iff_disjoint : s ×ˢ t ⊆ (diagonal α)ᶜ ↔ disjoint s t := prod_subset_iff.trans disjoint_iff_forall_ne.symm @[simp] lemma diag_preimage_prod (s t : set α) : (λ x, (x, x)) ⁻¹' (s ×ˢ t) = s ∩ t := rfl lemma diag_preimage_prod_self (s : set α) : (λ x, (x, x)) ⁻¹' (s ×ˢ s) = s := inter_self s lemma diag_image (s : set α) : (λ x, (x, x)) '' s = diagonal α ∩ (s ×ˢ s) := begin ext x, split, { rintro ⟨x, hx, rfl⟩, exact ⟨rfl, hx, hx⟩ }, { obtain ⟨x, y⟩ := x, rintro ⟨rfl : x = y, h2x⟩, exact mem_image_of_mem _ h2x.1 } end end diagonal section off_diag variables {α : Type*} {s t : set α} {x : α × α} {a : α} /-- The off-diagonal of a set `s` is the set of pairs `(a, b)` with `a, b ∈ s` and `a ≠ b`. -/ def off_diag (s : set α) : set (α × α) := {x | x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2} @[simp] lemma mem_off_diag : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := iff.rfl lemma off_diag_mono : monotone (off_diag : set α → set (α × α)) := λ s t h x, and.imp (@h _) $ and.imp_left $ @h _ @[simp] lemma off_diag_nonempty : s.off_diag.nonempty ↔ s.nontrivial := by simp [off_diag, set.nonempty, set.nontrivial] @[simp] lemma off_diag_eq_empty : s.off_diag = ∅ ↔ s.subsingleton := by rw [←not_nonempty_iff_eq_empty, ←not_nontrivial_iff, off_diag_nonempty.not] alias off_diag_nonempty ↔ _ nontrivial.off_diag_nonempty alias off_diag_nonempty ↔ _ subsingleton.off_diag_eq_empty variables (s t) lemma off_diag_subset_prod : s.off_diag ⊆ s ×ˢ s := λ x hx, ⟨hx.1, hx.2.1⟩ lemma off_diag_eq_sep_prod : s.off_diag = {x ∈ s ×ˢ s | x.1 ≠ x.2} := ext $ λ _, and.assoc.symm @[simp] lemma off_diag_empty : (∅ : set α).off_diag = ∅ := by simp @[simp] lemma off_diag_singleton (a : α) : ({a} : set α).off_diag = ∅ := by simp @[simp] lemma off_diag_univ : (univ : set α).off_diag = (diagonal α)ᶜ := ext $ by simp @[simp] lemma prod_sdiff_diagonal : s ×ˢ s \ diagonal α = s.off_diag := ext $ λ _, and.assoc @[simp] lemma disjoint_diagonal_off_diag : disjoint (diagonal α) s.off_diag := disjoint_left.mpr $ λ x hd ho, ho.2.2 hd lemma off_diag_inter : (s ∩ t).off_diag = s.off_diag ∩ t.off_diag := ext $ λ x, by { simp only [mem_off_diag, mem_inter_iff], tauto } variables {s t} lemma off_diag_union (h : disjoint s t) : (s ∪ t).off_diag = s.off_diag ∪ t.off_diag ∪ s ×ˢ t ∪ t ×ˢ s := begin rw [off_diag_eq_sep_prod, union_prod, prod_union, prod_union, union_comm _ (t ×ˢ t), union_assoc, union_left_comm (s ×ˢ t), ←union_assoc, sep_union, sep_union, ←off_diag_eq_sep_prod, ←off_diag_eq_sep_prod, sep_eq_self_iff_mem_true.2, ←union_assoc], simp only [mem_union, mem_prod, ne.def, prod.forall], rintro i j (⟨hi, hj⟩ | ⟨hi, hj⟩) rfl; exact h.le_bot ⟨‹_›, ‹_›⟩, end lemma off_diag_insert (ha : a ∉ s) : (insert a s).off_diag = s.off_diag ∪ {a} ×ˢ s ∪ s ×ˢ {a} := begin rw [insert_eq, union_comm, off_diag_union, off_diag_singleton, union_empty, union_right_comm], rw disjoint_left, rintro b hb (rfl : b = a), exact ha hb end end off_diag /-! ### Cartesian set-indexed product of sets -/ section pi variables {ι : Type*} {α β : ι → Type*} {s s₁ s₂ : set ι} {t t₁ t₂ : Π i, set (α i)} {i : ι} /-- Given an index set `ι` and a family of sets `t : Π i, set (α i)`, `pi s t` is the set of dependent functions `f : Πa, π a` such that `f a` belongs to `t a` whenever `a ∈ s`. -/ def pi (s : set ι) (t : Π i, set (α i)) : set (Π i, α i) := {f | ∀ i ∈ s, f i ∈ t i} @[simp] lemma mem_pi {f : Π i, α i} : f ∈ s.pi t ↔ ∀ i ∈ s, f i ∈ t i := iff.rfl @[simp] lemma mem_univ_pi {f : Π i, α i} : f ∈ pi univ t ↔ ∀ i, f i ∈ t i := by simp @[simp] lemma empty_pi (s : Π i, set (α i)) : pi ∅ s = univ := by { ext, simp [pi] } @[simp] lemma pi_univ (s : set ι) : pi s (λ i, (univ : set (α i))) = univ := eq_univ_of_forall $ λ f i hi, mem_univ _ lemma pi_mono (h : ∀ i ∈ s, t₁ i ⊆ t₂ i) : pi s t₁ ⊆ pi s t₂ := λ x hx i hi, (h i hi $ hx i hi) lemma pi_inter_distrib : s.pi (λ i, t i ∩ t₁ i) = s.pi t ∩ s.pi t₁ := ext $ λ x, by simp only [forall_and_distrib, mem_pi, mem_inter_iff] lemma pi_congr (h : s₁ = s₂) (h' : ∀ i ∈ s₁, t₁ i = t₂ i) : s₁.pi t₁ = s₂.pi t₂ := h ▸ (ext $ λ x, forall₂_congr $ λ i hi, h' i hi ▸ iff.rfl) lemma pi_eq_empty (hs : i ∈ s) (ht : t i = ∅) : s.pi t = ∅ := by { ext f, simp only [mem_empty_iff_false, not_forall, iff_false, mem_pi, not_imp], exact ⟨i, hs, by simp [ht]⟩ } lemma univ_pi_eq_empty (ht : t i = ∅) : pi univ t = ∅ := pi_eq_empty (mem_univ i) ht lemma pi_nonempty_iff : (s.pi t).nonempty ↔ ∀ i, ∃ x, i ∈ s → x ∈ t i := by simp [classical.skolem, set.nonempty] lemma univ_pi_nonempty_iff : (pi univ t).nonempty ↔ ∀ i, (t i).nonempty := by simp [classical.skolem, set.nonempty] lemma pi_eq_empty_iff : s.pi t = ∅ ↔ ∃ i, is_empty (α i) ∨ i ∈ s ∧ t i = ∅ := begin rw [← not_nonempty_iff_eq_empty, pi_nonempty_iff], push_neg, refine exists_congr (λ i, _), casesI is_empty_or_nonempty (α i); simp [*, forall_and_distrib, eq_empty_iff_forall_not_mem], end @[simp] lemma univ_pi_eq_empty_iff : pi univ t = ∅ ↔ ∃ i, t i = ∅ := by simp [← not_nonempty_iff_eq_empty, univ_pi_nonempty_iff] @[simp] lemma univ_pi_empty [h : nonempty ι] : pi univ (λ i, ∅ : Π i, set (α i)) = ∅ := univ_pi_eq_empty_iff.2 $ h.elim $ λ x, ⟨x, rfl⟩ @[simp] lemma disjoint_univ_pi : disjoint (pi univ t₁) (pi univ t₂) ↔ ∃ i, disjoint (t₁ i) (t₂ i) := by simp only [disjoint_iff_inter_eq_empty, ← pi_inter_distrib, univ_pi_eq_empty_iff] lemma _root_.disjoint.set_pi (hi : i ∈ s) (ht : disjoint (t₁ i) (t₂ i)) : disjoint (s.pi t₁) (s.pi t₂) := disjoint_left.2 $ λ h h₁ h₂, disjoint_left.1 ht (h₁ _ hi) (h₂ _ hi) section nonempty variables [Π i, nonempty (α i)] lemma pi_eq_empty_iff' : s.pi t = ∅ ↔ ∃ i ∈ s, t i = ∅ := by simp [pi_eq_empty_iff] @[simp] lemma disjoint_pi : disjoint (s.pi t₁) (s.pi t₂) ↔ ∃ i ∈ s, disjoint (t₁ i) (t₂ i) := by simp only [disjoint_iff_inter_eq_empty, ← pi_inter_distrib, pi_eq_empty_iff'] end nonempty @[simp] lemma range_dcomp (f : Π i, α i → β i) : range (λ (g : Π i, α i), (λ i, f i (g i))) = pi univ (λ i, range (f i)) := begin apply subset.antisymm _ (λ x hx, _), { rintro _ ⟨x, rfl⟩ i -, exact ⟨x i, rfl⟩ }, { choose y hy using hx, exact ⟨λ i, y i trivial, funext $ λ i, hy i trivial⟩ } end @[simp] lemma insert_pi (i : ι) (s : set ι) (t : Π i, set (α i)) : pi (insert i s) t = (eval i ⁻¹' t i) ∩ pi s t := by { ext, simp [pi, or_imp_distrib, forall_and_distrib] } @[simp] lemma singleton_pi (i : ι) (t : Π i, set (α i)) : pi {i} t = (eval i ⁻¹' t i) := by { ext, simp [pi] } lemma singleton_pi' (i : ι) (t : Π i, set (α i)) : pi {i} t = {x | x i ∈ t i} := singleton_pi i t lemma univ_pi_singleton (f : Π i, α i) : pi univ (λ i, {f i}) = ({f} : set (Π i, α i)) := ext $ λ g, by simp [funext_iff] lemma preimage_pi (s : set ι) (t : Π i, set (β i)) (f : Π i, α i → β i) : (λ (g : Π i, α i) i, f _ (g i)) ⁻¹' s.pi t = s.pi (λ i, f i ⁻¹' t i) := rfl lemma pi_if {p : ι → Prop} [h : decidable_pred p] (s : set ι) (t₁ t₂ : Π i, set (α i)) : pi s (λ i, if p i then t₁ i else t₂ i) = pi {i ∈ s | p i} t₁ ∩ pi {i ∈ s | ¬ p i} t₂ := begin ext f, refine ⟨λ h, _, _⟩, { split; { rintro i ⟨his, hpi⟩, simpa [*] using h i } }, { rintro ⟨ht₁, ht₂⟩ i his, by_cases p i; simp * at * } end lemma union_pi : (s₁ ∪ s₂).pi t = s₁.pi t ∩ s₂.pi t := by simp [pi, or_imp_distrib, forall_and_distrib, set_of_and] @[simp] lemma pi_inter_compl (s : set ι) : pi s t ∩ pi sᶜ t = pi univ t := by rw [← union_pi, union_compl_self] lemma pi_update_of_not_mem [decidable_eq ι] (hi : i ∉ s) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : s.pi (λ j, t j (update f i a j)) = s.pi (λ j, t j (f j)) := pi_congr rfl $ λ j hj, by { rw update_noteq, exact λ h, hi (h ▸ hj) } lemma pi_update_of_mem [decidable_eq ι] (hi : i ∈ s) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : s.pi (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) := calc s.pi (λ j, t j (update f i a j)) = ({i} ∪ s \ {i}).pi (λ j, t j (update f i a j)) : by rw [union_diff_self, union_eq_self_of_subset_left (singleton_subset_iff.2 hi)] ... = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) : by { rw [union_pi, singleton_pi', update_same, pi_update_of_not_mem], simp } lemma univ_pi_update [decidable_eq ι] {β : Π i, Type*} (i : ι) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : pi univ (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ pi {i}ᶜ (λ j, t j (f j)) := by rw [compl_eq_univ_diff, ← pi_update_of_mem (mem_univ _)] lemma univ_pi_update_univ [decidable_eq ι] (i : ι) (s : set (α i)) : pi univ (update (λ j : ι, (univ : set (α j))) i s) = eval i ⁻¹' s := by rw [univ_pi_update i (λ j, (univ : set (α j))) s (λ j t, t), pi_univ, inter_univ, preimage] lemma eval_image_pi_subset (hs : i ∈ s) : eval i '' s.pi t ⊆ t i := image_subset_iff.2 $ λ f hf, hf i hs lemma eval_image_univ_pi_subset : eval i '' pi univ t ⊆ t i := eval_image_pi_subset (mem_univ i) lemma subset_eval_image_pi (ht : (s.pi t).nonempty) (i : ι) : t i ⊆ eval i '' s.pi t := begin classical, obtain ⟨f, hf⟩ := ht, refine λ y hy, ⟨update f i y, λ j hj, _, update_same _ _ _⟩, obtain rfl | hji := eq_or_ne j i; simp [*, hf _ hj] end lemma eval_image_pi (hs : i ∈ s) (ht : (s.pi t).nonempty) : eval i '' s.pi t = t i := (eval_image_pi_subset hs).antisymm (subset_eval_image_pi ht i) @[simp] lemma eval_image_univ_pi (ht : (pi univ t).nonempty) : (λ f : Π i, α i, f i) '' pi univ t = t i := eval_image_pi (mem_univ i) ht lemma pi_subset_pi_iff : pi s t₁ ⊆ pi s t₂ ↔ (∀ i ∈ s, t₁ i ⊆ t₂ i) ∨ pi s t₁ = ∅ := begin refine ⟨λ h, or_iff_not_imp_right.2 _, λ h, h.elim pi_mono (λ h', h'.symm ▸ empty_subset _)⟩, rw [← ne.def, ←nonempty_iff_ne_empty], intros hne i hi, simpa only [eval_image_pi hi hne, eval_image_pi hi (hne.mono h)] using image_subset (λ f : Π i, α i, f i) h end lemma univ_pi_subset_univ_pi_iff : pi univ t₁ ⊆ pi univ t₂ ↔ (∀ i, t₁ i ⊆ t₂ i) ∨ ∃ i, t₁ i = ∅ := by simp [pi_subset_pi_iff] lemma eval_preimage [decidable_eq ι] {s : set (α i)} : eval i ⁻¹' s = pi univ (update (λ i, univ) i s) := by { ext x, simp [@forall_update_iff _ (λ i, set (α i)) _ _ _ _ (λ i' y, x i' ∈ y)] } lemma eval_preimage' [decidable_eq ι] {s : set (α i)} : eval i ⁻¹' s = pi {i} (update (λ i, univ) i s) := by { ext, simp } lemma update_preimage_pi [decidable_eq ι] {f : Π i, α i} (hi : i ∈ s) (hf : ∀ j ∈ s, j ≠ i → f j ∈ t j) : (update f i) ⁻¹' s.pi t = t i := begin ext x, refine ⟨λ h, _, λ hx j hj, _⟩, { convert h i hi, simp }, { obtain rfl | h := eq_or_ne j i, { simpa }, { rw update_noteq h, exact hf j hj h } } end lemma update_preimage_univ_pi [decidable_eq ι] {f : Π i, α i} (hf : ∀ j ≠ i, f j ∈ t j) : (update f i) ⁻¹' pi univ t = t i := update_preimage_pi (mem_univ i) (λ j _, hf j) lemma subset_pi_eval_image (s : set ι) (u : set (Π i, α i)) : u ⊆ pi s (λ i, eval i '' u) := λ f hf i hi, ⟨f, hf, rfl⟩ lemma univ_pi_ite (s : set ι) [decidable_pred (∈ s)] (t : Π i, set (α i)) : pi univ (λ i, if i ∈ s then t i else univ) = s.pi t := by { ext, simp_rw [mem_univ_pi], refine forall_congr (λ i, _), split_ifs; simp [h] } end pi end set
86bceedaaa2610c64d294f6b041200788fc0dbd0
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Meta/Tactic/Cases.lean
ad2ba19a4713e41e1df8b36b8040405b7204f85b
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
14,855
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Injection import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Subst namespace Lean.Meta private def throwInductiveTypeExpected {α} (type : Expr) : MetaM α := do throwError "failed to compile pattern matching, inductive type expected{indentExpr type}" def getInductiveUniverseAndParams (type : Expr) : MetaM (List Level × Array Expr) := do let type ← whnfD type matchConstInduct type.getAppFn (fun _ => throwInductiveTypeExpected type) fun val us => let I := type.getAppFn let Iargs := type.getAppArgs let params := Iargs.extract 0 val.numParams pure (us, params) private def mkEqAndProof (lhs rhs : Expr) : MetaM (Expr × Expr) := do let lhsType ← inferType lhs let rhsType ← inferType rhs let u ← getLevel lhsType if (← isDefEq lhsType rhsType) then pure (mkApp3 (mkConst `Eq [u]) lhsType lhs rhs, mkApp2 (mkConst `Eq.refl [u]) lhsType lhs) else pure (mkApp4 (mkConst `HEq [u]) lhsType lhs rhsType rhs, mkApp2 (mkConst `HEq.refl [u]) lhsType lhs) private partial def withNewEqs {α} (targets targetsNew : Array Expr) (k : Array Expr → Array Expr → MetaM α) : MetaM α := let rec loop (i : Nat) (newEqs : Array Expr) (newRefls : Array Expr) := do if h : i < targets.size then let (newEqType, newRefl) ← mkEqAndProof targets[i] targetsNew[i] withLocalDeclD `h newEqType fun newEq => do loop (i+1) (newEqs.push newEq) (newRefls.push newRefl) else k newEqs newRefls loop 0 #[] #[] def generalizeTargets (mvarId : MVarId) (motiveType : Expr) (targets : Array Expr) : MetaM MVarId := withMVarContext mvarId do checkNotAssigned mvarId `generalizeTargets let (typeNew, eqRefls) ← forallTelescopeReducing motiveType fun targetsNew _ => do unless targetsNew.size == targets.size do throwError "invalid number of targets #{targets.size}, motive expects #{targetsNew.size}" withNewEqs targets targetsNew fun eqs eqRefls => do let type ← getMVarType mvarId let typeNew ← mkForallFVars eqs type let typeNew ← mkForallFVars targetsNew typeNew pure (typeNew, eqRefls) let mvarNew ← mkFreshExprSyntheticOpaqueMVar typeNew (← getMVarTag mvarId) assignExprMVar mvarId (mkAppN (mkAppN mvarNew targets) eqRefls) pure mvarNew.mvarId! structure GeneralizeIndicesSubgoal where mvarId : MVarId indicesFVarIds : Array FVarId fvarId : FVarId numEqs : Nat /-- Similar to `generalizeTargets` but customized for the `casesOn` motive. Given a metavariable `mvarId` representing the ``` Ctx, h : I A j, D |- T ``` where `fvarId` is `h`s id, and the type `I A j` is an inductive datatype where `A` are parameters, and `j` the indices. Generate the goal ``` Ctx, h : I A j, D, j' : J, h' : I A j' |- j == j' -> h == h' -> T ``` Remark: `(j == j' -> h == h')` is a "telescopic" equality. Remark: `j` is sequence of terms, and `j'` a sequence of free variables. The result contains the fields - `mvarId`: the new goal - `indicesFVarIds`: `j'` ids - `fvarId`: `h'` id - `numEqs`: number of equations in the target -/ def generalizeIndices (mvarId : MVarId) (fvarId : FVarId) : MetaM GeneralizeIndicesSubgoal := withMVarContext mvarId do let lctx ← getLCtx let localInsts ← getLocalInstances checkNotAssigned mvarId `generalizeIndices let fvarDecl ← getLocalDecl fvarId let type ← whnf fvarDecl.type type.withApp fun f args => matchConstInduct f (fun _ => throwTacticEx `generalizeIndices mvarId "inductive type expected") fun val _ => do unless val.numIndices > 0 do throwTacticEx `generalizeIndices mvarId "indexed inductive type expected" unless args.size == val.numIndices + val.numParams do throwTacticEx `generalizeIndices mvarId "ill-formed inductive datatype" let indices := args.extract (args.size - val.numIndices) args.size let IA := mkAppN f (args.extract 0 val.numParams) -- `I A` let IAType ← inferType IA forallTelescopeReducing IAType fun newIndices _ => do let newType := mkAppN IA newIndices withLocalDeclD fvarDecl.userName newType fun h' => withNewEqs indices newIndices fun newEqs newRefls => do let (newEqType, newRefl) ← mkEqAndProof fvarDecl.toExpr h' let newRefls := newRefls.push newRefl withLocalDeclD `h newEqType fun newEq => do let newEqs := newEqs.push newEq /- auxType `forall (j' : J) (h' : I A j'), j == j' -> h == h' -> target -/ let target ← getMVarType mvarId let tag ← getMVarTag mvarId let auxType ← mkForallFVars newEqs target let auxType ← mkForallFVars #[h'] auxType let auxType ← mkForallFVars newIndices auxType let newMVar ← mkFreshExprMVarAt lctx localInsts auxType MetavarKind.syntheticOpaque tag /- assign mvarId := newMVar indices h refls -/ assignExprMVar mvarId (mkAppN (mkApp (mkAppN newMVar indices) fvarDecl.toExpr) newRefls) let (indicesFVarIds, newMVarId) ← introNP newMVar.mvarId! newIndices.size let (fvarId, newMVarId) ← intro1P newMVarId pure { mvarId := newMVarId, indicesFVarIds := indicesFVarIds, fvarId := fvarId, numEqs := newEqs.size } structure CasesSubgoal extends InductionSubgoal where ctorName : Name namespace Cases structure Context where inductiveVal : InductiveVal casesOnVal : DefinitionVal nminors : Nat := inductiveVal.ctors.length majorDecl : LocalDecl majorTypeFn : Expr majorTypeArgs : Array Expr majorTypeIndices : Array Expr := majorTypeArgs.extract (majorTypeArgs.size - inductiveVal.numIndices) majorTypeArgs.size private def mkCasesContext? (majorFVarId : FVarId) : MetaM (Option Context) := do let env ← getEnv if !env.contains `Eq || !env.contains `HEq then pure none else let majorDecl ← getLocalDecl majorFVarId let majorType ← whnf majorDecl.type majorType.withApp fun f args => matchConstInduct f (fun _ => pure none) fun ival _ => if args.size != ival.numIndices + ival.numParams then pure none else match env.find? (Name.mkStr ival.name "casesOn") with | ConstantInfo.defnInfo cval => pure $ some { inductiveVal := ival, casesOnVal := cval, majorDecl := majorDecl, majorTypeFn := f, majorTypeArgs := args } | _ => pure none /- We say the major premise has independent indices IF 1- its type is *not* an indexed inductive family, OR 2- its type is an indexed inductive family, but all indices are distinct free variables, and all local declarations different from the major and its indices do not depend on the indices. -/ private def hasIndepIndices (ctx : Context) : MetaM Bool := do if ctx.majorTypeIndices.isEmpty then pure true else if ctx.majorTypeIndices.any $ fun idx => !idx.isFVar then /- One of the indices is not a free variable. -/ pure false else if ctx.majorTypeIndices.size.any fun i => i.any fun j => ctx.majorTypeIndices[i] == ctx.majorTypeIndices[j] then /- An index ocurrs more than once -/ pure false else let lctx ← getLCtx let mctx ← getMCtx pure $ lctx.all fun decl => decl.fvarId == ctx.majorDecl.fvarId || -- decl is the major ctx.majorTypeIndices.any (fun index => decl.fvarId == index.fvarId!) || -- decl is one of the indices mctx.findLocalDeclDependsOn decl (fun fvarId => ctx.majorTypeIndices.all $ fun idx => idx.fvarId! != fvarId) -- or does not depend on any index private def elimAuxIndices (s₁ : GeneralizeIndicesSubgoal) (s₂ : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := let indicesFVarIds := s₁.indicesFVarIds s₂.mapM fun s => do indicesFVarIds.foldlM (init := s) fun s indexFVarId => match s.subst.get indexFVarId with | Expr.fvar indexFVarId' _ => (do let mvarId ← clear s.mvarId indexFVarId'; pure { s with mvarId := mvarId, subst := s.subst.erase indexFVarId }) <|> (pure s) | _ => pure s /- Convert `s` into an array of `CasesSubgoal`, by attaching the corresponding constructor name, and adding the substitution `majorFVarId -> ctor_i us params fields` into each subgoal. -/ private def toCasesSubgoals (s : Array InductionSubgoal) (ctorNames : Array Name) (majorFVarId : FVarId) (us : List Level) (params : Array Expr) : Array CasesSubgoal := s.mapIdx fun i s => let ctorName := ctorNames[i] let ctorApp := mkAppN (mkAppN (mkConst ctorName us) params) s.fields let s := { s with subst := s.subst.insert majorFVarId ctorApp } { ctorName := ctorName, toInductionSubgoal := s } /- Convert heterogeneous equality into a homegeneous one -/ private def heqToEq (mvarId : MVarId) (eqDecl : LocalDecl) : MetaM MVarId := do /- Convert heterogeneous equality into a homegeneous one -/ let prf ← mkEqOfHEq (mkFVar eqDecl.fvarId) let aEqb ← whnf (← inferType prf) let mvarId ← assert mvarId eqDecl.userName aEqb prf clear mvarId eqDecl.fvarId partial def unifyEqs (numEqs : Nat) (mvarId : MVarId) (subst : FVarSubst) (caseName? : Option Name := none): MetaM (Option (MVarId × FVarSubst)) := do if numEqs == 0 then pure (some (mvarId, subst)) else let (eqFVarId, mvarId) ← intro1 mvarId withMVarContext mvarId do let eqDecl ← getLocalDecl eqFVarId if eqDecl.type.isHEq then let mvarId ← heqToEq mvarId eqDecl unifyEqs numEqs mvarId subst caseName? else match eqDecl.type.eq? with | none => throwError "equality expected{indentExpr eqDecl.type}" | some (α, a, b) => if (← isDefEq a b) then /- Skip equality -/ unifyEqs (numEqs - 1) (← clear mvarId eqFVarId) subst caseName? else -- Remark: we use `let rec` here because otherwise the compiler would generate an insane amount of code. -- We can remove the `rec` after we fix the eagerly inlining issue in the compiler. let rec substEq (symm : Bool) := do /- TODO: support for acyclicity (e.g., `xs ≠ x :: xs`) -/ let (substNew, mvarId) ← substCore mvarId eqFVarId symm subst unifyEqs (numEqs - 1) mvarId substNew caseName? let rec injection (a b : Expr) := do let env ← getEnv if a.isConstructorApp env && b.isConstructorApp env then /- ctor_i ... = ctor_j ... -/ match (← injectionCore mvarId eqFVarId) with | InjectionResultCore.solved => pure none -- this alternative has been solved | InjectionResultCore.subgoal mvarId numEqsNew => unifyEqs (numEqs - 1 + numEqsNew) mvarId subst caseName? else let a' ← whnf a let b' ← whnf b if a' != a || b' != b then /- Reduced lhs/rhs of current equality -/ let prf := mkFVar eqFVarId let aEqb' ← mkEq a' b' let mvarId ← assert mvarId eqDecl.userName aEqb' prf let mvarId ← clear mvarId eqFVarId unifyEqs numEqs mvarId subst caseName? else match caseName? with | none => throwError "dependent elimination failed, failed to solve equation{indentExpr eqDecl.type}" | some caseName => throwError "dependent elimination failed, failed to solve equation{indentExpr eqDecl.type}\nat case {mkConst caseName}" let a ← instantiateMVars a let b ← instantiateMVars b match a, b with | Expr.fvar aFVarId _, Expr.fvar bFVarId _ => /- x = y -/ let aDecl ← getLocalDecl aFVarId let bDecl ← getLocalDecl bFVarId substEq (aDecl.index < bDecl.index) | Expr.fvar .., _ => /- x = t -/ substEq (symm := false) | _, Expr.fvar .. => /- t = x -/ substEq (symm := true) | a, b => injection a b private def unifyCasesEqs (numEqs : Nat) (subgoals : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := subgoals.foldlM (init := #[]) fun subgoals s => do match (← unifyEqs numEqs s.mvarId s.subst s.ctorName) with | none => pure subgoals | some (mvarId, subst) => pure $ subgoals.push { s with mvarId := mvarId, subst := subst, fields := s.fields.map (subst.apply ·) } private def inductionCasesOn (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames) (ctx : Context) : MetaM (Array CasesSubgoal) := do withMVarContext mvarId do let majorType ← inferType (mkFVar majorFVarId) let (us, params) ← getInductiveUniverseAndParams majorType let casesOn := mkCasesOnName ctx.inductiveVal.name let ctors := ctx.inductiveVal.ctors.toArray let s ← induction mvarId majorFVarId casesOn givenNames return toCasesSubgoals s ctors majorFVarId us params def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames := #[]) : MetaM (Array CasesSubgoal) := withMVarContext mvarId do checkNotAssigned mvarId `cases let context? ← mkCasesContext? majorFVarId match context? with | none => throwTacticEx `cases mvarId "not applicable to the given hypothesis" | some ctx => /- Remark: if caller does not need a `FVarSubst` (variable substitution), and `hasIndepIndices ctx` is true, then we can also use the simple case. This is a minor optimization, and we currently do not even allow callers to specify whether they want the `FVarSubst` or not. -/ if ctx.inductiveVal.numIndices == 0 then -- Simple case inductionCasesOn mvarId majorFVarId givenNames ctx else let s₁ ← generalizeIndices mvarId majorFVarId trace[Meta.Tactic.cases] "after generalizeIndices\n{MessageData.ofGoal s₁.mvarId}" let s₂ ← inductionCasesOn s₁.mvarId s₁.fvarId givenNames ctx let s₂ ← elimAuxIndices s₁ s₂ unifyCasesEqs s₁.numEqs s₂ end Cases def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames := #[]) : MetaM (Array CasesSubgoal) := Cases.cases mvarId majorFVarId givenNames builtin_initialize registerTraceClass `Meta.Tactic.cases end Lean.Meta
efe15d7071787fabe4d5f76a73c599c3583d7ee8
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/triangulated/pretriangulated.lean
74477154a1df68cd4175a3356d9733e494845905
[ "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,579
lean
/- Copyright (c) 2021 Luke Kershaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Kershaw -/ import category_theory.additive.basic import category_theory.shift import category_theory.preadditive.additive_functor import category_theory.triangulated.rotate /-! # Pretriangulated Categories This file contains the definition of pretriangulated categories and triangulated functors between them. ## Implementation Notes We work under the assumption that pretriangulated categories are preadditive categories, but not necessarily additive categories, as is assumed in some sources. TODO: generalise this to n-angulated categories as in https://arxiv.org/abs/1006.4592 -/ noncomputable theory open category_theory open category_theory.preadditive open category_theory.limits universes v v₀ v₁ v₂ u u₀ u₁ u₂ namespace category_theory.triangulated open category_theory.category /- We work in an preadditive category `C` equipped with an additive shift. -/ variables (C : Type u) [category.{v} C] [has_zero_object C] [has_shift C] [preadditive C] [functor.additive (shift C).functor] /-- A preadditive category `C` with an additive shift, and a class of "distinguished triangles" relative to that shift is called pretriangulated if the following hold: * Any triangle that is isomorphic to a distinguished triangle is also distinguished. * Any triangle of the form `(X,X,0,id,0,0)` is distinguished. * For any morphism `f : X ⟶ Y` there exists a distinguished triangle of the form `(X,Y,Z,f,g,h)`. * The triangle `(X,Y,Z,f,g,h)` is distinguished if and only if `(Y,Z,X⟦1⟧,g,h,-f⟦1⟧)` is. * Given a diagram: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │a │b │a⟦1⟧' V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` where the left square commutes, and whose rows are distinguished triangles, there exists a morphism `c : Z ⟶ Z'` such that `(a,b,c)` is a triangle morphism. See https://stacks.math.columbia.edu/tag/0145 -/ class pretriangulated := (distinguished_triangles [] : set (triangle C)) (isomorphic_distinguished : Π (T₁ ∈ distinguished_triangles) (T₂ : triangle C) (T₁ ≅ T₂), T₂ ∈ distinguished_triangles) (contractible_distinguished : Π (X : C), (contractible_triangle C X) ∈ distinguished_triangles) (distinguished_cocone_triangle : Π (X Y : C) (f: X ⟶ Y), (∃ (Z : C) (g : Y ⟶ Z) (h : Z ⟶ X⟦1⟧), triangle.mk _ f g h ∈ distinguished_triangles)) (rotate_distinguished_triangle : Π (T : triangle C), T ∈ distinguished_triangles ↔ T.rotate ∈ distinguished_triangles) (complete_distinguished_triangle_morphism : Π (T₁ T₂ : triangle C) (h₁ : T₁ ∈ distinguished_triangles) (h₂ : T₂ ∈ distinguished_triangles) (a : T₁.obj₁ ⟶ T₂.obj₁) (b : T₁.obj₂ ⟶ T₂.obj₂) (comm₁ : T₁.mor₁ ≫ b = a ≫ T₂.mor₁), (∃ (c : T₁.obj₃ ⟶ T₂.obj₃), (T₁.mor₂ ≫ c = b ≫ T₂.mor₂) ∧ (T₁.mor₃ ≫ a⟦1⟧' = c ≫ T₂.mor₃) )) namespace pretriangulated variables [pretriangulated C] notation `dist_triang`:20 C := distinguished_triangles C /-- Given any distinguished triangle `T`, then we know `T.rotate` is also distinguished. -/ lemma rot_of_dist_triangle (T ∈ dist_triang C) : (T.rotate ∈ dist_triang C) := (rotate_distinguished_triangle T).mp H /-- Given any distinguished triangle `T`, then we know `T.inv_rotate` is also distinguished. -/ lemma inv_rot_of_dist_triangle (T ∈ dist_triang C) : (T.inv_rotate ∈ dist_triang C) := (rotate_distinguished_triangle (T.inv_rotate)).mpr (isomorphic_distinguished T H (T.inv_rotate.rotate) T (inv_rot_comp_rot.symm.app T)) /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `f ≫ g = 0`. See https://stacks.math.columbia.edu/tag/0146 -/ lemma comp_dist_triangle_mor_zero₁₂ (T ∈ dist_triang C) : T.mor₁ ≫ T.mor₂ = 0 := begin have h := contractible_distinguished T.obj₁, have f := complete_distinguished_triangle_morphism, specialize f (contractible_triangle C T.obj₁) T h H (𝟙 T.obj₁) T.mor₁, have t : (contractible_triangle C T.obj₁).mor₁ ≫ T.mor₁ = 𝟙 T.obj₁ ≫ T.mor₁, by refl, specialize f t, cases f with c f, rw ← f.left, simp only [limits.zero_comp, contractible_triangle_mor₂], end -- TODO : tidy this proof up /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `g ≫ h = 0`. See https://stacks.math.columbia.edu/tag/0146 -/ lemma comp_dist_triangle_mor_zero₂₃ (T ∈ dist_triang C) : T.mor₂ ≫ T.mor₃ = 0 := comp_dist_triangle_mor_zero₁₂ C T.rotate (rot_of_dist_triangle C T H) /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `h ≫ f⟦1⟧ = 0`. See https://stacks.math.columbia.edu/tag/0146 -/ lemma comp_dist_triangle_mor_zero₃₁ (T ∈ dist_triang C) : T.mor₃ ≫ ((shift C).functor.map T.mor₁) = 0 := have H₂ : _ := rot_of_dist_triangle C T.rotate (rot_of_dist_triangle C T H), by simpa using comp_dist_triangle_mor_zero₁₂ C (T.rotate.rotate) H₂ /- TODO: If `C` is pretriangulated with respect to a shift, then `Cᵒᵖ` is pretriangulated with respect to the inverse shift. -/ end pretriangulated end category_theory.triangulated namespace category_theory.triangulated namespace pretriangulated variables (C : Type u₁) [category.{v₁} C] [has_zero_object C] [has_shift C] [preadditive C] [functor.additive (shift C).functor] [functor.additive (shift C).inverse] variables (D : Type u₂) [category.{v₂} D] [has_zero_object D] [has_shift D] [preadditive D] [functor.additive (shift D).functor] [functor.additive (shift D).inverse] /-- The underlying structure of a triangulated functor between pretriangulated categories `C` and `D` is a functor `F : C ⥤ D` together with given functorial isomorphisms `ξ X : F(X⟦1⟧) ⟶ F(X)⟦1⟧`. -/ structure triangulated_functor_struct extends (C ⥤ D) := (comm_shift : (shift C).functor ⋙ to_functor ≅ to_functor ⋙ (shift D).functor) instance : inhabited (triangulated_functor_struct C C) := ⟨{ obj := λ X, X, map := λ _ _ f, f, comm_shift := by refl }⟩ variables {C D} /-- Given a `triangulated_functor_struct` we can define a function from triangles of `C` to triangles of `D`. -/ @[simp] def triangulated_functor_struct.map_triangle (F : triangulated_functor_struct C D) (T : triangle C) : triangle D := triangle.mk _ (F.map T.mor₁) (F.map T.mor₂) (F.map T.mor₃ ≫ F.comm_shift.hom.app T.obj₁) variables (C D) /-- A triangulated functor between pretriangulated categories `C` and `D` is a functor `F : C ⥤ D` together with given functorial isomorphisms `ξ X : F(X⟦1⟧) ⟶ F(X)⟦1⟧` such that for every distinguished triangle `(X,Y,Z,f,g,h)` of `C`, the triangle `(F(X), F(Y), F(Z), F(f), F(g), F(h) ≫ (ξ X))` is a distinguished triangle of `D`. See https://stacks.math.columbia.edu/tag/014V -/ structure triangulated_functor [pretriangulated C] [pretriangulated D] extends triangulated_functor_struct C D := (map_distinguished' : Π (T: triangle C), (T ∈ dist_triang C) → (to_triangulated_functor_struct.map_triangle T ∈ dist_triang D) ) instance [pretriangulated C] : inhabited (triangulated_functor C C) := ⟨{obj := λ X, X, map := λ _ _ f, f, comm_shift := by refl , map_distinguished' := begin rintros ⟨_,_,_,_⟩ Tdt, dsimp at *, rwa category.comp_id, end }⟩ variables {C D} [pretriangulated C] [pretriangulated D] /-- Given a `triangulated_functor` we can define a function from triangles of `C` to triangles of `D`. -/ @[simp] def triangulated_functor.map_triangle (F : triangulated_functor C D) (T : triangle C) : triangle D := triangle.mk _ (F.map T.mor₁) (F.map T.mor₂) (F.map T.mor₃ ≫ F.comm_shift.hom.app T.obj₁) /-- Given a `triangulated_functor` and a distinguished triangle `T` of `C`, then the triangle it maps onto in `D` is also distinguished. -/ lemma triangulated_functor.map_distinguished (F : triangulated_functor C D) (T : triangle C) (h : T ∈ dist_triang C) : (F.map_triangle T) ∈ dist_triang D := F.map_distinguished' T h end pretriangulated end category_theory.triangulated
d4d961dd84dbf88e9e512f8f2683e09625f63e99
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/casePrime.lean
f0cb4335ec3c08fcd990db1f532688b5fd0c13d9
[ "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
443
lean
example (hp : p) (hq : p → q) (hr : p → r) : (s ∨ q) ∧ (r ∨ s) := by constructor case' left => apply Or.inr case' right => apply Or.inl case' left => apply hq case' right => apply hr all_goals assumption example (hp : p) (hq : p → q) (hr : p → r) : (p ∧ q) ∧ (r ∧ p) := by constructor case' left | right => constructor case' right.left => apply hr case' left.right => apply hq all_goals assumption
f95fe1efa191a89a78df9d2831c33ac319598768
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/field_power.lean
cb94312989cac60b4c57e66ab85274b02b4caece
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,711
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 -/ import algebra.group_with_zero.power import tactic.linarith import data.equiv.ring /-! # Integer power operation on fields and division rings This file collects basic facts about the operation of raising an element of a `division_ring` to an integer power. More specialised results are provided in the case of a linearly ordered field. -/ universe u @[simp] lemma ring_hom.map_fpow {K L : Type*} [division_ring K] [division_ring L] (f : K →+* L) : ∀ (a : K) (n : ℤ), f (a ^ n) = f a ^ n := f.to_monoid_with_zero_hom.map_fpow @[simp] lemma ring_equiv.map_fpow {K L : Type*} [division_ring K] [division_ring L] (f : K ≃+* L) : ∀ (a : K) (n : ℤ), f (a ^ n) = f a ^ n := f.to_ring_hom.map_fpow @[simp] lemma fpow_bit0_neg {K : Type*} [division_ring K] (x : K) (n : ℤ) : (-x) ^ (bit0 n) = x ^ bit0 n := by rw [fpow_bit0', fpow_bit0', neg_mul_neg] lemma even.fpow_neg {K : Type*} [division_ring K] {n : ℤ} (h : even n) (a : K) : (-a) ^ n = a ^ n := begin obtain ⟨k, rfl⟩ := h, rw [←bit0_eq_two_mul, fpow_bit0_neg], end @[simp] lemma fpow_bit1_neg {K : Type*} [division_ring K] (x : K) (n : ℤ) : (-x) ^ (bit1 n) = - x ^ bit1 n := by rw [fpow_bit1', fpow_bit1', neg_mul_neg, neg_mul_eq_mul_neg] section ordered_field_power open int variables {K : Type u} [linear_ordered_field K] {a : K} {n : ℤ} lemma fpow_eq_zero_iff (hn : 0 < n) : a ^ n = 0 ↔ a = 0 := begin refine ⟨fpow_eq_zero, _⟩, rintros rfl, exact zero_fpow _ hn.ne' end lemma fpow_nonneg {a : K} (ha : 0 ≤ a) : ∀ (z : ℤ), 0 ≤ a ^ z | (n : ℕ) := by { rw gpow_coe_nat, exact pow_nonneg ha _ } | -[1+n] := by { rw gpow_neg_succ_of_nat, exact inv_nonneg.2 (pow_nonneg ha _) } lemma fpow_pos_of_pos {a : K} (ha : 0 < a) : ∀ (z : ℤ), 0 < a ^ z | (n : ℕ) := by { rw gpow_coe_nat, exact pow_pos ha _ } | -[1+n] := by { rw gpow_neg_succ_of_nat, exact inv_pos.2 (pow_pos ha _) } lemma fpow_le_of_le {x : K} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b := begin induction a with a a; induction b with b b, { simp only [of_nat_eq_coe, gpow_coe_nat], apply pow_le_pow hx, apply le_of_coe_nat_le_coe_nat h }, { apply absurd h, apply not_le_of_gt, exact lt_of_lt_of_le (neg_succ_lt_zero _) (of_nat_nonneg _) }, { simp only [gpow_neg_succ_of_nat, one_div, of_nat_eq_coe, gpow_coe_nat], apply le_trans (inv_le_one _); apply one_le_pow_of_one_le hx }, { simp only [gpow_neg_succ_of_nat], apply (inv_le_inv _ _).2, { apply pow_le_pow hx, have : -(↑(a+1) : ℤ) ≤ -(↑(b+1) : ℤ), from h, have h' := le_of_neg_le_neg this, apply le_of_coe_nat_le_coe_nat h' }, repeat { apply pow_pos (lt_of_lt_of_le zero_lt_one hx) } } end lemma pow_le_max_of_min_le {x : K} (hx : 1 ≤ x) {a b c : ℤ} (h : min a b ≤ c) : x ^ (-c) ≤ max (x ^ (-a)) (x ^ (-b)) := begin wlog hle : a ≤ b, have hnle : -b ≤ -a, from neg_le_neg hle, have hfle : x ^ (-b) ≤ x ^ (-a), from fpow_le_of_le hx hnle, have : x ^ (-c) ≤ x ^ (-a), { apply fpow_le_of_le hx, simpa only [min_eq_left hle, neg_le_neg_iff] using h }, simpa only [max_eq_left hfle] end lemma fpow_le_one_of_nonpos {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : z ≤ 0) : p ^ z ≤ 1 := calc p ^ z ≤ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp lemma one_le_fpow_of_nonneg {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : 0 ≤ z) : 1 ≤ p ^ z := calc p ^ z ≥ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp theorem fpow_bit0_nonneg (a : K) (n : ℤ) : 0 ≤ a ^ bit0 n := by { rw fpow_bit0, exact mul_self_nonneg _ } theorem fpow_two_nonneg (a : K) : 0 ≤ a ^ 2 := pow_bit0_nonneg a 1 theorem fpow_bit0_pos {a : K} (h : a ≠ 0) (n : ℤ) : 0 < a ^ bit0 n := (fpow_bit0_nonneg a n).lt_of_ne (fpow_ne_zero _ h).symm theorem fpow_two_pos_of_ne_zero (a : K) (h : a ≠ 0) : 0 < a ^ 2 := pow_bit0_pos h 1 @[simp] theorem fpow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ fpow_nonneg h' _, λ h, by rw [bit1, fpow_add_one h.ne]; exact mul_neg_of_pos_of_neg (fpow_bit0_pos h.ne _) h⟩ @[simp] theorem fpow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 fpow_bit1_neg_iff @[simp] theorem fpow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := begin rw [le_iff_lt_or_eq, fpow_bit1_neg_iff], split, { rintro (h | h), { exact h.le }, { exact (fpow_eq_zero h).le } }, { intro h, rcases eq_or_lt_of_le h with rfl|h, { exact or.inr (zero_fpow _ (bit1_ne_zero n)) }, { exact or.inl h } } end @[simp] theorem fpow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le fpow_bit1_nonpos_iff lemma even.fpow_nonneg {n : ℤ} (hn : even n) (a : K) : 0 ≤ a ^ n := begin cases le_or_lt 0 a with h h, { exact fpow_nonneg h _ }, { exact (hn.fpow_neg a).subst (fpow_nonneg (neg_nonneg_of_nonpos h.le) _) } end theorem even.fpow_pos (hn : even n) (ha : a ≠ 0) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit0_pos ha k theorem odd.fpow_nonneg (hn : odd n) (ha : 0 ≤ a) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_nonneg_iff.mpr ha theorem odd.fpow_pos (hn : odd n) (ha : 0 < a) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_pos_iff.mpr ha theorem odd.fpow_nonpos (hn : odd n) (ha : a ≤ 0) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_nonpos_iff.mpr ha theorem odd.fpow_neg (hn : odd n) (ha : a < 0) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_neg_iff.mpr ha lemma even.fpow_abs {p : ℤ} (hp : even p) (a : K) : |a| ^ p = a ^ p := begin cases abs_choice a with h h; simp only [h, hp.fpow_neg _], end @[simp] lemma fpow_bit0_abs (a : K) (p : ℤ) : |a| ^ bit0 p = a ^ bit0 p := (even_bit0 _).fpow_abs _ lemma even.abs_fpow {p : ℤ} (hp : even p) (a : K) : |a ^ p| = a ^ p := begin rw [abs_eq_self], exact hp.fpow_nonneg _ end @[simp] lemma abs_fpow_bit0 (a : K) (p : ℤ) : |a ^ bit0 p| = a ^ bit0 p := (even_bit0 _).abs_fpow _ end ordered_field_power lemma one_lt_fpow {K} [linear_ordered_field K] {p : K} (hp : 1 < p) : ∀ z : ℤ, 0 < z → 1 < p ^ z | (n : ℕ) h := (gpow_coe_nat p n).symm.subst (one_lt_pow hp $ int.coe_nat_ne_zero.mp h.ne') | -[1+ n] h := ((int.neg_succ_not_pos _).mp h).elim section ordered variables {K : Type*} [linear_ordered_field K] lemma nat.fpow_pos_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : 0 < (p:K)^n := by { apply fpow_pos_of_pos, exact_mod_cast h } lemma nat.fpow_ne_zero_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : (p:K)^n ≠ 0 := ne_of_gt (nat.fpow_pos_of_pos h n) lemma fpow_strict_mono {x : K} (hx : 1 < x) : strict_mono (λ n:ℤ, x ^ n) := λ m n h, show x ^ m < x ^ n, begin have xpos : 0 < x := zero_lt_one.trans hx, have h₀ : x ≠ 0 := xpos.ne', have hxm : 0 < x^m := fpow_pos_of_pos xpos m, have h : 1 < x ^ (n - m) := one_lt_fpow hx _ (sub_pos_of_lt h), replace h := mul_lt_mul_of_pos_right h hxm, rwa [sub_eq_add_neg, fpow_add h₀, mul_assoc, fpow_neg_mul_fpow_self _ h₀, one_mul, mul_one] at h, end @[simp] lemma fpow_lt_iff_lt {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m < x ^ n ↔ m < n := (fpow_strict_mono hx).lt_iff_lt @[simp] lemma fpow_le_iff_le {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m ≤ x ^ n ↔ m ≤ n := (fpow_strict_mono hx).le_iff_le @[simp] lemma pos_div_pow_pos {a b : K} (ha : 0 < a) (hb : 0 < b) (k : ℕ) : 0 < a/b^k := div_pos ha (pow_pos hb k) @[simp] lemma div_pow_le {a b : K} (ha : 0 < a) (hb : 1 ≤ b) (k : ℕ) : a/b^k ≤ a := (div_le_iff $ pow_pos (lt_of_lt_of_le zero_lt_one hb) k).mpr (calc a = a * 1 : (mul_one a).symm ... ≤ a*b^k : (mul_le_mul_left ha).mpr $ one_le_pow_of_one_le hb _) lemma fpow_injective {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) : function.injective ((^) x : ℤ → K) := begin intros m n h, rcases h₁.lt_or_lt with H|H, { apply (fpow_strict_mono (one_lt_inv h₀ H)).injective, show x⁻¹ ^ m = x⁻¹ ^ n, rw [← fpow_neg_one, ← fpow_mul, ← fpow_mul, mul_comm _ m, mul_comm _ n, fpow_mul, fpow_mul, h], }, { exact (fpow_strict_mono H).injective h, }, end @[simp] lemma fpow_inj {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) {m n : ℤ} : x ^ m = x ^ n ↔ m = n := (fpow_injective h₀ h₁).eq_iff end ordered section variables {K : Type*} [field K] @[simp, norm_cast] theorem rat.cast_fpow [char_zero K] (q : ℚ) (n : ℤ) : ((q ^ n : ℚ) : K) = q ^ n := (rat.cast_hom K).map_fpow q n end
0eef5207e3e7a12625cac0e941039f365047e964
f47872278edfa65030d6cd0604480581b09ae4b5
/src/extra.lean
52e794b9eb54755b544a64aa0b44b54cb3702bb3
[ "MIT" ]
permissive
ocornoc/geodude
c822c494d9ed5d6dd2efa434cbaa5e0e42c22691
e63c87db67f1686c902e9bcd1863e74e1a29457f
refs/heads/master
1,681,951,483,388
1,620,592,363,000
1,620,595,412,000
287,442,904
0
0
null
null
null
null
UTF-8
Lean
false
false
41
lean
-- This page is intentionally left blank.
ae943d97ef065905ef27fb0db0badfdea7756dd9
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/bundle.lean
7eaad1912e26db22e0b32fbb2c051f588b6c3c33
[ "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
2,978
lean
/- Copyright © 2021 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import tactic.basic import algebra.module.basic /-! # Bundle Basic data structure to implement fiber bundles, vector bundles (maybe fibrations?), etc. This file should contain all possible results that do not involve any topology. We provide a type synonym of `Σ x, E x` as `bundle.total_space E`, to be able to endow it with a topology which is not the disjoint union topology `sigma.topological_space`. In general, the constructions of fiber bundles we will make will be of this form. ## References - https://en.wikipedia.org/wiki/Bundle_(mathematics) -/ namespace bundle variables {B : Type*} (E : B → Type*) /-- `total_space E` is the total space of the bundle `Σ x, E x`. This type synonym is used to avoid conflicts with general sigma types. -/ def total_space := Σ x, E x instance [inhabited B] [inhabited (E (default B))] : inhabited (total_space E) := ⟨⟨default B, default (E (default B))⟩⟩ /-- `bundle.proj E` is the canonical projection `total_space E → B` on the base space. -/ @[simp] def proj : total_space E → B := sigma.fst /-- Constructor for the total space of a `topological_fiber_bundle_core`. -/ @[simp, reducible] def total_space_mk (E : B → Type*) (b : B) (a : E b) : bundle.total_space E := ⟨b, a⟩ instance {x : B} : has_coe_t (E x) (total_space E) := ⟨sigma.mk x⟩ @[simp] lemma coe_fst (x : B) (v : E x) : (v : total_space E).fst = x := rfl lemma to_total_space_coe {x : B} (v : E x) : (v : total_space E) = ⟨x, v⟩ := rfl /-- `bundle.trivial B F` is the trivial bundle over `B` of fiber `F`. -/ def trivial (B : Type*) (F : Type*) : B → Type* := function.const B F instance {F : Type*} [inhabited F] {b : B} : inhabited (bundle.trivial B F b) := ⟨(default F : F)⟩ /-- The trivial bundle, unlike other bundles, has a canonical projection on the fiber. -/ def trivial.proj_snd (B : Type*) (F : Type*) : (total_space (bundle.trivial B F)) → F := sigma.snd section fiber_structures variable [∀ x, add_comm_monoid (E x)] @[simp] lemma coe_snd_map_apply (x : B) (v w : E x) : (↑(v + w) : total_space E).snd = (v : total_space E).snd + (w : total_space E).snd := rfl variables (R : Type*) [semiring R] [∀ x, module R (E x)] @[simp] lemma coe_snd_map_smul (x : B) (r : R) (v : E x) : (↑(r • v) : total_space E).snd = r • (v : total_space E).snd := rfl end fiber_structures section trivial_instances local attribute [reducible] bundle.trivial variables {F : Type*} {R : Type*} [semiring R] (b : B) instance [add_comm_monoid F] : add_comm_monoid (bundle.trivial B F b) := ‹add_comm_monoid F› instance [add_comm_group F] : add_comm_group (bundle.trivial B F b) := ‹add_comm_group F› instance [add_comm_monoid F] [module R F] : module R (bundle.trivial B F b) := ‹module R F› end trivial_instances end bundle
cfb68ef5ab03cb0f720af9f87e68bb3fb95ac12e
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/nat/basic.lean
e1429e1aeddd37964714a9e77f84e611ee787724
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
59,857
lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import algebra.ordered_ring import algebra.ordered_sub /-! # Basic operations on the natural numbers This file contains: - instances on the natural numbers - some basic lemmas about natural numbers - extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers * `decreasing_induction`: recursion growing downwards * `le_rec_on'`, `decreasing_induction'`: versions with slightly weaker assumptions * `strong_rec'`: recursion based on strong inequalities - decidability instances on predicates about the natural numbers -/ universes u v /-! ### instances -/ instance : nontrivial ℕ := ⟨⟨0, 1, nat.zero_ne_one⟩⟩ instance : comm_semiring nat := { add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm, nsmul := λ m n, m * n, nsmul_zero' := nat.zero_mul, nsmul_succ' := λ n x, by rw [nat.succ_eq_add_one, nat.add_comm, nat.right_distrib, nat.one_mul] } instance : linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, lt := nat.lt, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_le_one := nat.le_of_lt (nat.zero_lt_succ 0), mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_eq := nat.decidable_eq, exists_pair_ne := ⟨0, 1, ne_of_lt nat.zero_lt_one⟩, ..nat.comm_semiring, ..nat.linear_order } -- all the fields are already included in the linear_ordered_semiring instance instance : linear_ordered_cancel_add_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.linear_ordered_semiring } instance : linear_ordered_comm_monoid_with_zero ℕ := { mul_le_mul_left := λ a b h c, nat.mul_le_mul_left c h, ..nat.linear_ordered_semiring, ..(infer_instance : comm_monoid_with_zero ℕ)} instance : ordered_comm_semiring ℕ := { .. nat.comm_semiring, .. nat.linear_ordered_semiring } /-! Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid nat := by apply_instance instance : add_monoid nat := by apply_instance instance : monoid nat := by apply_instance instance : comm_monoid nat := by apply_instance instance : comm_semigroup nat := by apply_instance instance : semigroup nat := by apply_instance instance : add_comm_semigroup nat := by apply_instance instance : add_semigroup nat := by apply_instance instance : distrib nat := by apply_instance instance : semiring nat := by apply_instance instance : ordered_semiring nat := by apply_instance instance : canonically_ordered_comm_semiring ℕ := { le_iff_exists_add := assume a b, ⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩, assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩, eq_zero_or_eq_zero_of_mul_eq_zero := assume a b, nat.eq_zero_of_mul_eq_zero, bot := 0, bot_le := nat.zero_le, .. nat.nontrivial, .. (infer_instance : ordered_add_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } instance : canonically_linear_ordered_add_monoid ℕ := { .. (infer_instance : canonically_ordered_add_monoid ℕ), .. nat.linear_order } instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred (∈ s)] [h : nonempty s] : semilattice_sup_bot s := { bot := ⟨nat.find (nonempty_subtype.1 h), nat.find_spec (nonempty_subtype.1 h)⟩, bot_le := λ x, nat.find_min' _ x.2, ..subtype.linear_order s, ..lattice_of_linear_order } theorem nat.nsmul_eq_mul (m n : ℕ) : m • n = m * n := rfl theorem nat.eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : 0 < m) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact nat.eq_of_mul_eq_mul_left Hm H instance nat.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero ℕ := { mul_left_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_left (nat.pos_of_ne_zero h1) h2, mul_right_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_right (nat.pos_of_ne_zero h1) h2, .. (infer_instance : comm_monoid_with_zero ℕ) } attribute [simp] nat.not_lt_zero nat.succ_ne_zero nat.succ_ne_self nat.zero_ne_one nat.one_ne_zero nat.zero_ne_bit1 nat.bit1_ne_zero nat.bit0_ne_one nat.one_ne_bit0 nat.bit0_ne_bit1 nat.bit1_ne_bit0 /-! Inject some simple facts into the type class system. This `fact` should not be confused with the factorial function `nat.fact`! -/ section facts instance succ_pos'' (n : ℕ) : fact (0 < n.succ) := ⟨n.succ_pos⟩ instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) := ⟨lt_trans zero_lt_one h.1⟩ end facts variables {m n k : ℕ} namespace nat /-! ### Recursion and `set.range` -/ section set open set theorem zero_union_range_succ : {0} ∪ range succ = univ := by { ext n, cases n; simp } variables {α : Type*} theorem range_of_succ (f : ℕ → α) : {f 0} ∪ range (f ∘ succ) = range f := by rw [← image_singleton, range_comp, ← image_union, zero_union_range_succ, image_univ] theorem range_rec {α : Type*} (x : α) (f : ℕ → α → α) : (set.range (λ n, nat.rec x f n) : set α) = {x} ∪ set.range (λ n, nat.rec (f 0 x) (f ∘ succ) n) := begin convert (range_of_succ _).symm, ext n, induction n with n ihn, { refl }, { dsimp at ihn ⊢, rw ihn } end theorem range_cases_on {α : Type*} (x : α) (f : ℕ → α) : (set.range (λ n, nat.cases_on n x f) : set α) = {x} ∪ set.range f := (range_of_succ _).symm end set /-! ### The units of the natural numbers as a `monoid` and `add_monoid` -/ theorem units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ theorem add_units_eq_zero (u : add_units ℕ) : u = 0 := add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1 @[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) instance unique_units : unique (units ℕ) := { default := 1, uniq := nat.units_eq_one } instance unique_add_units : unique (add_units ℕ) := { default := 0, uniq := nat.add_units_eq_zero } /-! ### Equalities and inequalities involving zero and one -/ lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ lemma zero_max {m : ℕ} : max 0 m = m := max_eq_right (zero_le _) @[simp] lemma min_eq_zero_iff {m n : ℕ} : min m n = 0 ↔ m = 0 ∨ n = 0 := begin split, { intro h, cases le_total n m with H H, { simpa [H] using or.inr h }, { simpa [H] using or.inl h } }, { rintro (rfl|rfl); simp } end @[simp] lemma max_eq_zero_iff {m n : ℕ} : max m n = 0 ↔ m = 0 ∧ n = 0 := begin split, { intro h, cases le_total n m with H H, { simp only [H, max_eq_left] at h, exact ⟨h, le_antisymm (H.trans h.le) (zero_le _)⟩ }, { simp only [H, max_eq_right] at h, exact ⟨le_antisymm (H.trans h.le) (zero_le _), h⟩ } }, { rintro ⟨rfl, rfl⟩, simp } end lemma add_eq_max_iff {n m : ℕ} : n + m = max n m ↔ n = 0 ∨ m = 0 := begin rw ←min_eq_zero_iff, cases le_total n m with H H; simp [H] end lemma add_eq_min_iff {n m : ℕ} : n + m = min n m ↔ n = 0 ∧ m = 0 := begin rw ←max_eq_zero_iff, cases le_total n m with H H; simp [H] end lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h theorem eq_one_of_mul_eq_one_right {m n : ℕ} (H : m * n = 1) : m = 1 := eq_one_of_dvd_one ⟨n, H.symm⟩ theorem eq_one_of_mul_eq_one_left {m n : ℕ} (H : m * n = 1) : n = 1 := eq_one_of_mul_eq_one_right (by rwa mul_comm) /-! ### `succ` -/ lemma succ_eq_one_add (n : ℕ) : n.succ = 1 + n := by rw [nat.succ_eq_add_one, nat.add_comm] theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) lemma eq_of_le_of_lt_succ {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n + 1) : m = n := nat.le_antisymm (le_of_succ_le_succ h₂) h₁ theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] @[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ.inj, congr_arg _⟩ theorem succ_injective : function.injective nat.succ := λ x y, succ.inj lemma succ_ne_succ {n m : ℕ} : succ n ≠ succ m ↔ n ≠ m := succ_injective.ne_iff @[simp] lemma succ_succ_ne_one (n : ℕ) : n.succ.succ ≠ 1 := succ_ne_succ.mpr n.succ_ne_zero @[simp] lemma one_lt_succ_succ (n : ℕ) : 1 < n.succ.succ := succ_lt_succ $ succ_pos n theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := ⟨le_of_lt_succ, lt_succ_of_le⟩ lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff -- Just a restatement of `nat.lt_succ_iff` using `+1`. lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b := by simp only [add_comm, lt_succ_iff] -- This is true reflexively, by the definition of `≤` on ℕ, -- but it's still useful to have, to convince Lean to change the syntactic type. lemma add_one_le_iff {a b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl _ lemma one_add_le_iff {a b : ℕ} : 1 + a ≤ b ↔ a < b := by simp only [add_comm, add_one_le_iff] theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := H.lt_or_eq_dec.imp le_of_lt_succ id lemma succ_lt_succ_iff {m n : ℕ} : succ m < succ n ↔ m < n := ⟨lt_of_succ_lt_succ, succ_lt_succ⟩ @[simp] lemma lt_one_iff {n : ℕ} : n < 1 ↔ n = 0 := lt_succ_iff.trans le_zero_iff lemma div_le_iff_le_mul_add_pred {m n k : ℕ} (n0 : 0 < n) : m / n ≤ k ↔ m ≤ n * k + (n - 1) := begin rw [← lt_succ_iff, div_lt_iff_lt_mul _ _ n0, succ_mul, mul_comm], cases n, {cases n0}, exact lt_succ_iff, end /-! ### `add` -/ -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left attribute [simp] nat.sub_self lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk, add_comm, add_left_comm]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ lemma add_succ_lt_add {a b c d : ℕ} (hab : a < b) (hcd : c < d) : a + c + 1 < b + d := begin rw add_assoc, exact add_lt_add_of_lt_of_le hab (nat.succ_le_iff.2 hcd) end -- TODO: generalize to some ordered add_monoids, based on #6145 lemma le_of_add_le_left {a b c : ℕ} (h : a + b ≤ c) : a ≤ c := by { refine le_trans _ h, simp } lemma le_of_add_le_right {a b c : ℕ} (h : a + b ≤ c) : b ≤ c := by { refine le_trans _ h, simp } /-! ### `pred` -/ @[simp] lemma add_succ_sub_one (n m : ℕ) : (n + succ m) - 1 = n + m := by rw [add_succ, succ_sub_one] @[simp] lemma succ_add_sub_one (n m : ℕ) : (succ n + m) - 1 = n + m := by rw [succ_add, succ_sub_one] lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 := by cases n; split; rintro ⟨⟩; refl theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← nat.sub_one, nat.sub_sub, one_add]; refl lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 lemma le_of_pred_lt {m n : ℕ} : pred m < n → m ≤ n := match m with | 0 := le_of_lt | m+1 := id end /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := ⟨le_succ_of_pred_le, by { cases n, { exact λ h, zero_le m }, exact le_of_succ_le_succ }⟩ /-! ### `sub` Todo: remove lemmas that are proven in general for `has_ordered_sub`. -/ protected theorem sub_le_iff_right : m - n ≤ k ↔ m ≤ k + n := begin induction n with n ih generalizing k, { simp }, { simp only [sub_succ, add_succ, succ_add, ih, pred_le_iff] } end instance : has_ordered_sub ℕ := ⟨λ n m k, nat.sub_le_iff_right⟩ protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := le_sub_add protected theorem add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n := add_sub_cancel_of_le h protected theorem sub_add_sub_cancel {a b c : ℕ} (hab : b ≤ a) (hbc : c ≤ b) : (a - b) + (b - c) = a - c := sub_add_sub_cancel'' hab hbc protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := sub_eq_of_eq_add'' $ by rw [add_comm, h] theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := sub_inj_left h₁ h₂ w lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b := sub_sub_sub_cancel_right' h₂ protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b := sub_add_eq_add_sub' h theorem sub_sub_assoc {a b c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := sub_sub_assoc h₁ h₂ protected theorem lt_of_sub_pos (h : 0 < n - m) : m < n := sub_pos_iff_lt.mp h protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := lt_of_sub_lt_sub_right protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_of_sub_lt_sub_left protected theorem sub_lt_self (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m := sub_lt_self' h₁ h₂ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := le_sub_of_add_le_right' h protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := le_sub_of_add_le_left' h protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_sub_iff_right.mpr h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := lt_sub_iff_left.mpr h protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := lt_sub_iff_right.mp h protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := lt_sub_iff_left.mp h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := sub_le_iff_right.mp protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := sub_le_iff_left.mp protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_add_of_sub_lt_right' protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_add_of_sub_lt_left' protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := sub_le_iff_left.mpr protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := sub_le_iff_right.mpr protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := sub_lt_iff_left H protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_sub_iff_left H protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := le_sub_iff_right H protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k := lt_sub_iff_left protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := lt_sub_iff_right theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := sub_le_iff_left theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := sub_le_iff_right protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := sub_lt_iff_right H protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := sub_le_sub_iff_left' H protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := sub_lt_sub_iff_right' H protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := sub_lt_sub_iff_left_of_le H protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := sub_le_iff_sub_le protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := sub_le_self' protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := sub_lt_iff_sub_lt h₁ h₂ lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (lt_pred_iff.1 h) lemma le_or_le_of_add_eq_add_pred {a b c d : ℕ} (h : c + d = a + b - 1) : a ≤ c ∨ b ≤ d := begin cases le_or_lt a c with h' h'; [left, right], { exact h', }, { replace h' := add_lt_add_right h' d, rw h at h', cases b.eq_zero_or_pos with hb hb, { rw hb, exact zero_le d, }, rw [a.add_sub_assoc hb, add_lt_add_iff_left] at h', exact nat.le_of_pred_lt h', }, end @[simp] lemma add_sub_sub_cancel {a c : ℕ} (h : c ≤ a) (b : ℕ) : a + b - (a - c) = b + c := by rw [add_comm, nat.add_sub_assoc (nat.sub_le_self _ _), nat.sub_sub_self h] /-! ### `mul` -/ lemma succ_mul_pos (m : ℕ) (hn : 0 < n) : 0 < (succ m) * n := mul_pos (succ_pos m) hn theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := decidable.mul_le_mul h h (zero_le _) (zero_le _) theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m | 0 m h := mul_pos h h | (succ n) m h := decidable.mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _) theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m := ⟨mul_self_le_mul_self, le_imp_le_of_lt_imp_lt mul_self_lt_mul_self⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := le_iff_le_iff_lt_iff_lt.1 mul_self_le_mul_self_iff theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_refl _ | (n+1) := let t := nat.mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact decidable.mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact decidable.mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by { rw [add_comm, add_mul_mod_self_left, mul_mod_right, mod_eq_of_lt]; simp }) lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨ λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], λ h, by simp only [h, mul_one]⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ lemma mul_left_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, x * a) := λ _ _, eq_of_mul_eq_mul_right ha lemma mul_right_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, a * x) := λ _ _, nat.eq_of_mul_eq_mul_left ha lemma mul_ne_mul_left {a b c : ℕ} (ha : 0 < a) : b * a ≠ c * a ↔ b ≠ c := (mul_left_injective ha).ne_iff lemma mul_ne_mul_right {a b c : ℕ} (ha : 0 < a) : a * b ≠ a * c ↔ b ≠ c := (mul_right_injective ha).ne_iff lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_right_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans decidable.le_iff_lt_or_eq theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ @[simp] lemma rec_zero {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) : (nat.rec h0 h : Π n, C n) 0 = h0 := rfl @[simp] lemma rec_add_one {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) (n : ℕ) : (nat.rec h0 h : Π n, C n) (n + 1) = h n ((nat.rec h0 h : Π n, C n) n) := rfl /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`, there is a map from `C n` to each `C m`, `n ≤ m`. For a version where the assumption is only made when `k ≥ n`, see `le_rec_on'`. -/ @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (nat.eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end /-- Recursion principle based on `<`. -/ @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_eliminator] def strong_rec_on' {P : ℕ → Sort*} (n : ℕ) (h : ∀ n, (∀ m, m < n → P m) → P n) : P n := nat.strong_rec' h n theorem strong_rec_on_beta' {P : ℕ → Sort*} {h} {n : ℕ} : (strong_rec_on' n h : P n) = h n (λ m hmn, (strong_rec_on' m h : P m)) := by { simp only [strong_rec_on'], rw nat.strong_rec' } /-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/ @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) : ∀ n, m ≤ n → P n := by apply nat.less_than_or_equal.rec h0; exact h1 /-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`. Also works for functions to `Sort*`. For a version assuming only the assumption for `k < n`, see `decreasing_induction'`. -/ @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k ≥ n`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ @[elab_as_eliminator] def le_rec_on' {C : ℕ → Sort*} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π ⦃k⦄, n ≤ k → C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (nat.eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next h $ le_rec_on' h next x) (λ h : n = m + 1, eq.rec_on h x) /-- Decreasing induction: if `P (k+1)` implies `P k` for all `m ≤ k < n`, then `P n` implies `P m`. Also works for functions to `Sort*`. Weakens the assumptions of `decreasing_induction`. -/ @[elab_as_eliminator] def decreasing_induction' {P : ℕ → Sort*} {m n : ℕ} (h : ∀ k < n, m ≤ k → P (k+1) → P k) (mn : m ≤ n) (hP : P n) : P m := begin -- induction mn using nat.le_rec_on' generalizing h hP -- this doesn't work unfortunately refine le_rec_on' mn _ _ h hP; clear h hP mn n, { intros n mn ih h hP, apply ih, { exact λ k hk, h k hk.step }, { exact h n (lt_succ_self n) mn hP } }, { intros h hP, exact hP } end /-! ### `div` -/ attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (nat.eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (_root_.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (nat.eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : nat.mul_le_mul_right _ n0) /-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (n b : ℕ) : (n+1)/(b+2) < n+1 := nat.div_lt_self (nat.succ_pos n) (nat.succ_lt_succ (nat.succ_pos _)) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := le_div_iff_mul_le x y k0 theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self _ _) h lemma lt_of_div_lt_div {m n k : ℕ} : m / k < n / k → m < n := lt_imp_lt_of_le_imp_le $ λ h, nat.div_le_div_right h protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_right_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ protected lemma div_eq_zero {a b : ℕ} (hb : a < b) : a / b = 0 := (nat.div_eq_zero_iff $ (zero_le a).trans_lt hb).mpr hb lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma mul_div_le_mul_div_assoc (a b c : ℕ) : a * (b / c) ≤ (a * b) / c := if hc0 : c = 0 then by simp [hc0] else (nat.le_div_iff_mul_le _ _ (nat.pos_of_ne_zero hc0)).2 (by rw [mul_assoc]; exact nat.mul_le_mul_left _ (nat.div_mul_le_self _ _)) lemma div_mul_div_le_div (a b c : ℕ) : ((a / c) * b) / a ≤ b / c := if ha0 : a = 0 then by simp [ha0] else calc a / c * b / a ≤ b * a / c / a : nat.div_le_div_right (by rw [mul_comm]; exact mul_div_le_mul_div_assoc _ _ _) ... = b / c : by rw [nat.div_div_eq_div_mul, mul_comm b, mul_comm c, nat.mul_div_mul _ _ (nat.pos_of_ne_zero ha0)] lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] /-- Alias of `nat.mul_div_mul` -/ --TODO: Update `nat.mul_div_mul` in the core? protected lemma mul_div_mul_left (a b : ℕ) {c : ℕ} (hc : 0 < c) : c * a / (c * b) = a / b := nat.mul_div_mul a b hc protected lemma mul_div_mul_right (a b : ℕ) {c : ℕ} (hc : 0 < c) : a * c / (b * c) = a / b := by rw [mul_comm, mul_comm b, a.mul_div_mul_left b hc] /-! ### `mod`, `dvd` -/ lemma div_add_mod (m k : ℕ) : k * (m / k) + m % k = m := (nat.add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℕ) : m % k + (m / k) * k = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℕ) : (m / k) * k + m % k = m := by { rw mul_comm, exact div_add_mod _ _ } protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw [eq_zero_of_zero_dvd h₁, nat.div_zero, nat.div_zero] | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_left_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := begin rcases nat.eq_zero_or_pos b with rfl|hb, { simp }, rcases nat.eq_zero_or_pos c with rfl|hc, { simp }, conv_rhs { rw ← mod_add_div a (b * c) }, rw [mul_assoc, nat.add_mul_div_left _ _ hb, add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos hb hc)))] end lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_rfl⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm @[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬ 2 ∣ bit1 n := by { rw [bit1, nat.dvd_add_right two_dvd_bit0, nat.dvd_one], cc } /-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_left {m n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number `m` divides the sum `n + m` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) -- TODO: update `nat.dvd_sub` in core lemma dvd_sub' {k m n : ℕ} (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n := begin cases le_total n m with H H, { exact dvd_sub H h₁ h₂ }, { rw nat.sub_eq_zero_of_le H, exact dvd_zero k }, end lemma not_dvd_of_pos_of_lt {a b : ℕ} (h1 : 0 < b) (h2 : b < a) : ¬ a ∣ b := begin rintros ⟨c, rfl⟩, rcases nat.eq_zero_or_pos c with (rfl | hc), { exact lt_irrefl 0 h1 }, { exact not_lt.2 (le_mul_of_pos_right hc) h2 }, end protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_right_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_left_inj hc] lemma succ_div : ∀ (a b : ℕ), (a + 1) / b = a / b + if b ∣ a + 1 then 1 else 0 | a 0 := by simp | 0 1 := by simp | 0 (b+2) := have hb2 : b + 2 > 1, from dec_trivial, by simp [ne_of_gt hb2, div_eq_of_lt hb2] | (a+1) (b+1) := begin rw [nat.div_def], conv_rhs { rw nat.div_def }, by_cases hb_eq_a : b = a + 1, { simp [hb_eq_a, le_refl] }, by_cases hb_le_a1 : b ≤ a + 1, { have hb_le_a : b ≤ a, from le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a), have h₁ : (0 < b + 1 ∧ b + 1 ≤ a + 1 + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a1⟩, have h₂ : (0 < b + 1 ∧ b + 1 ≤ a + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a⟩, have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1, { rw [nat.dvd_add_iff_left (dvd_refl (b + 1)), ← nat.add_sub_add_right a 1 b, add_comm (_ - _), add_assoc, nat.sub_add_cancel (succ_le_succ hb_le_a), add_comm 1] }, have wf : a - b < a + 1, from lt_succ_of_le (nat.sub_le_self _ _), rw [if_pos h₁, if_pos h₂, nat.add_sub_add_right, nat.sub_add_comm hb_le_a, by exact have _ := wf, succ_div (a - b), nat.add_sub_add_right], simp [dvd_iff, succ_eq_add_one, add_comm 1, add_assoc] }, { have hba : ¬ b ≤ a, from not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)), have hb_dvd_a : ¬ b + 1 ∣ a + 2, from λ h, hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)), simp [hba, hb_le_a1, hb_dvd_a], } end lemma succ_div_of_dvd {a b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := by rw [succ_div, if_pos hba] lemma succ_div_of_not_dvd {a b : ℕ} (hba : ¬ b ∣ a + 1) : (a + 1) / b = a / b := by rw [succ_div, if_neg hba, add_zero] @[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (nat.eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) /-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/ lemma sub_mod_eq_zero_of_mod_eq {a b c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 := by rw [←nat.mod_add_div a c, ←nat.mod_add_div b c, ←h, ←nat.sub_sub, nat.add_sub_cancel_left, ←nat.mul_sub_left_distrib, nat.mul_mod_right] @[simp] lemma one_mod (n : ℕ) : 1 % (n + 2) = 1 := nat.mod_eq_of_lt (add_lt_add_right n.succ_pos 1) lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) := ⟨k / n, nat.sub_eq_of_eq_add (nat.mod_add_div k n).symm⟩ @[simp] theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℕ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] lemma add_mod_eq_ite {a b n : ℕ} : (a + b) % n = if n ≤ a % n + b % n then a % n + b % n - n else a % n + b % n := begin cases n, { simp }, rw nat.add_mod, split_ifs with h, { rw [nat.mod_eq_sub_mod h, nat.mod_eq_of_lt], exact (nat.sub_lt_right_iff_lt_add h).mpr (nat.add_lt_add (a.mod_lt n.zero_lt_succ) (b.mod_lt n.zero_lt_succ)) }, { exact nat.mod_eq_of_lt (lt_of_not_ge h) } end lemma mul_mod (a b n : ℕ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc, add_mul_mod_self_right] } end lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ @[simp] lemma dvd_div_iff {a b c : ℕ} (hbc : c ∣ b) : a ∣ b / c ↔ c * a ∣ b := ⟨λ h, mul_dvd_of_dvd_div hbc h, λ h, dvd_div_of_mul_dvd h⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have 0 < b, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have 0 < d, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end @[simp] lemma div_div_div_eq_div : ∀ {a b c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c), (c / (a / b)) / b = c / a | 0 _ := by simp | (a + 1) 0 := λ _ dvd _, by simpa using dvd | (a + 1) (c + 1) := have a_split : a + 1 ≠ 0 := succ_ne_zero a, have c_split : c + 1 ≠ 0 := succ_ne_zero c, λ b dvd dvd2, begin rcases dvd2 with ⟨k, rfl⟩, rcases dvd with ⟨k2, pr⟩, have k2_nonzero : k2 ≠ 0 := λ k2_zero, by simpa [k2_zero] using pr, rw [nat.mul_div_cancel_left k (nat.pos_of_ne_zero a_split), pr, nat.mul_div_cancel_left k2 (nat.pos_of_ne_zero c_split), nat.mul_comm ((c + 1) * k2) k, ←nat.mul_assoc k (c + 1) k2, nat.mul_div_cancel _ (nat.pos_of_ne_zero k2_nonzero), nat.mul_div_cancel _ (nat.pos_of_ne_zero c_split)], end lemma eq_of_dvd_of_div_eq_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := by rw [←nat.div_mul_cancel w, h, one_mul] lemma eq_zero_of_dvd_of_div_eq_zero {a b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 := by rw [←nat.div_mul_cancel w, h, zero_mul] /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ lemma eq_zero_of_dvd_of_lt {a b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 := nat.eq_zero_of_dvd_of_div_eq_zero w ((nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).elim_right h) lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (nat.mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end lemma lt_iff_le_pred : ∀ {m n : ℕ}, 0 < n → (m < n ↔ m ≤ n - 1) | m (n+1) _ := lt_succ_iff lemma div_eq_sub_mod_div {m n : ℕ} : m / n = (m - m % n) / n := begin by_cases n0 : n = 0, { rw [n0, nat.div_zero, nat.div_zero] }, { rw [← mod_add_div m n] { occs := occurrences.pos [2] }, rw [nat.add_sub_cancel_left, mul_div_right _ (nat.pos_of_ne_zero n0)] } end lemma mul_div_le (m n : ℕ) : n * (m / n) ≤ m := begin cases nat.eq_zero_or_pos n with n0 h, { rw [n0, zero_mul], exact m.zero_le }, { rw [mul_comm, ← nat.le_div_iff_mul_le' h] }, end lemma lt_mul_div_succ (m : ℕ) {n : ℕ} (n0 : 0 < n) : m < n * ((m / n) + 1) := begin rw [mul_comm, ← nat.div_lt_iff_lt_mul' n0], exact lt_succ_self _ end @[simp] lemma mod_div_self (m n : ℕ) : m % n / n = 0 := begin cases n, { exact (m % 0).div_zero }, { exact nat.div_eq_zero (m.mod_lt n.succ_pos) } end /-- `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℕ) {n : ℕ} (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m := begin split, { rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k, rw [lt_succ_iff, ← not_lt] at h2k, exact h2k h1k }, { intro h, rw [dvd_iff_mod_eq_zero, ← ne.def, ← pos_iff_ne_zero] at h, simp only [← mod_add_div m n] {single_pass := tt}, refine ⟨m / n, lt_add_of_pos_left _ h, _⟩, rw [add_comm _ 1, left_distrib, mul_one], exact add_lt_add_right (mod_lt _ hn) _ } end /-- Two natural numbers are equal if and only if the have the same multiples. -/ lemma dvd_right_iff_eq {m n : ℕ} : (∀ a : ℕ, m ∣ a ↔ n ∣ a) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mpr dvd_rfl) ((h _).mp dvd_rfl), λ h n, by rw h⟩ /-- Two natural numbers are equal if and only if the have the same divisors. -/ lemma dvd_left_iff_eq {m n : ℕ} : (∀ a : ℕ, a ∣ m ↔ a ∣ n) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mp dvd_rfl) ((h _).mpr dvd_rfl), λ h n, by rw h⟩ /-- `dvd` is injective in the left argument -/ lemma dvd_left_injective : function.injective ((∣) : ℕ → ℕ → Prop) := λ m n h, dvd_right_iff_eq.mp $ λ a, iff_of_eq (congr_fun h a) /-! ### `find` -/ section find variables {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q] lemma find_eq_iff (h : ∃ n : ℕ, p n) : nat.find h = m ↔ p m ∧ ∀ n < m, ¬ p n := begin split, { rintro rfl, exact ⟨nat.find_spec h, λ _, nat.find_min h⟩ }, { rintro ⟨hm, hlt⟩, exact le_antisymm (nat.find_min' h hm) (not_lt.1 $ imp_not_comm.1 (hlt _) $ nat.find_spec h) } end @[simp] lemma find_lt_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h < n ↔ ∃ m < n, p m := ⟨λ h2, ⟨nat.find h, h2, nat.find_spec h⟩, λ ⟨m, hmn, hm⟩, (nat.find_min' h hm).trans_lt hmn⟩ @[simp] lemma find_le_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h ≤ n ↔ ∃ m ≤ n, p m := by simp only [exists_prop, ← lt_succ_iff, find_lt_iff] @[simp] lemma le_find_iff (h : ∃ (n : ℕ), p n) (n : ℕ) : n ≤ nat.find h ↔ ∀ m < n, ¬ p m := by simp_rw [← not_lt, find_lt_iff, not_exists] @[simp] lemma lt_find_iff (h : ∃ n : ℕ, p n) (n : ℕ) : n < nat.find h ↔ ∀ m ≤ n, ¬ p m := by simp only [← succ_le_iff, le_find_iff, succ_le_succ_iff] @[simp] lemma find_eq_zero (h : ∃ n : ℕ, p n) : nat.find h = 0 ↔ p 0 := by simp [find_eq_iff] @[simp] lemma find_pos (h : ∃ n : ℕ, p n) : 0 < nat.find h ↔ ¬ p 0 := by rw [pos_iff_ne_zero, ne, nat.find_eq_zero] theorem find_le (h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) : nat.find hp ≤ nat.find hq := nat.find_min' _ (h _ (nat.find_spec hq)) lemma find_comp_succ (h₁ : ∃ n, p n) (h₂ : ∃ n, p (n + 1)) (h0 : ¬ p 0) : nat.find h₁ = nat.find h₂ + 1 := begin refine (find_eq_iff _).2 ⟨nat.find_spec h₂, λ n hn, _⟩, cases n with n, exacts [h0, @nat.find_min (λ n, p (n + 1)) _ h₂ _ (succ_lt_succ_iff.1 hn)] end end find /-! ### `find_greatest` -/ section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_eq_iff {b m} : nat.find_greatest P b = m ↔ m ≤ b ∧ (m ≠ 0 → P m) ∧ (∀ ⦃n⦄, m < n → n ≤ b → ¬P n) := begin induction b with b ihb generalizing m, { rw [eq_comm, iff.comm], simp only [nonpos_iff_eq_zero, ne.def, and_iff_left_iff_imp, find_greatest_zero], rintro rfl, exact ⟨λ h, (h rfl).elim, λ n hlt heq, (hlt.ne heq.symm).elim⟩ }, { by_cases hb : P (b + 1), { rw [find_greatest_eq hb], split, { rintro rfl, exact ⟨le_refl _, λ _, hb, λ n hlt hle, (hlt.not_le hle).elim⟩ }, { rintros ⟨hle, h0, hm⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt, exacts [rfl, (hm hlt (le_refl _) hb).elim] } }, { rw [find_greatest_of_not hb, ihb], split, { rintros ⟨hle, hP, hm⟩, refine ⟨hle.trans b.le_succ, hP, λ n hlt hle, _⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt', exacts [hb, hm hlt $ lt_succ_iff.1 hlt'] }, { rintros ⟨hle, hP, hm⟩, refine ⟨lt_succ_iff.1 (hle.lt_of_ne _), hP, λ n hlt hle, hm hlt (hle.trans b.le_succ)⟩, rintro rfl, exact hb (hP b.succ_ne_zero) } } } end lemma find_greatest_eq_zero_iff {b} : nat.find_greatest P b = 0 ↔ ∀ ⦃n⦄, 0 < n → n ≤ b → ¬P n := by simp [find_greatest_eq_iff] lemma find_greatest_spec {b} (h : ∃m, m ≤ b ∧ P m) : P (nat.find_greatest P b) := begin rcases h with ⟨m, hmb, hm⟩, by_cases h : nat.find_greatest P b = 0, { cases m, { rwa h }, exact ((find_greatest_eq_zero_iff.1 h) m.zero_lt_succ hmb hm).elim }, { exact (find_greatest_eq_iff.1 rfl).2.1 h } end lemma find_greatest_le {b} : nat.find_greatest P b ≤ b := (find_greatest_eq_iff.1 rfl).1 lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := le_of_not_lt $ λ hlt, (find_greatest_eq_iff.1 rfl).2.2 hlt hmb hm lemma find_greatest_is_greatest {b k} (hk : nat.find_greatest P b < k) (hkb : k ≤ b) : ¬ P k := (find_greatest_eq_iff.1 rfl).2.2 hk hkb lemma find_greatest_of_ne_zero {b m} (h : nat.find_greatest P b = m) (h0 : m ≠ 0) : P m := (find_greatest_eq_iff.1 h).2.1 h0 end find_greatest /-! ### `bodd_div2` and `bodd` -/ @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /-! ### `bit0` and `bit1` -/ -- There is no need to prove `bit0_eq_zero : bit0 n = 0 ↔ n = 0` -- as this is true for any `[semiring R] [no_zero_divisors R] [char_zero R]` -- However the lemmas `bit0_eq_bit0`, `bit1_eq_bit1`, `bit1_eq_one`, `one_eq_bit1` -- need `[ring R] [no_zero_divisors R] [char_zero R]` in general, -- so we prove `ℕ` specialized versions here. @[simp] lemma bit0_eq_bit0 {m n : ℕ} : bit0 m = bit0 n ↔ m = n := ⟨nat.bit0_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_bit1 {m n : ℕ} : bit1 m = bit1 n ↔ m = n := ⟨nat.bit1_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_one {n : ℕ} : bit1 n = 1 ↔ n = 0 := ⟨@nat.bit1_inj n 0, λ h, by subst h⟩ @[simp] lemma one_eq_bit1 {n : ℕ} : 1 = bit1 n ↔ n = 0 := ⟨λ h, (@nat.bit1_inj 0 n h).symm, λ h, by subst h⟩ protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) @[simp] lemma bit0_le_bit1_iff : bit0 k ≤ bit1 n ↔ k ≤ n := ⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq, bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩ @[simp] lemma bit0_lt_bit1_iff : bit0 k < bit1 n ↔ k ≤ n := ⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩ @[simp] lemma bit1_le_bit0_iff : bit1 k ≤ bit0 n ↔ k < n := ⟨λ h, by rwa [k.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h, λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩ @[simp] lemma bit1_lt_bit0_iff : bit1 k < bit0 n ↔ k < n := ⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩ @[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n := by { convert bit1_le_bit0_iff, refl, } @[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n := by { convert bit1_lt_bit0_iff, refl, } @[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b k ≤ bit b n ↔ k ≤ n | ff := bit0_le_bit0 | tt := bit1_le_bit1 @[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b k < bit b n ↔ k < n | ff := bit0_lt_bit0 | tt := bit1_lt_bit1 @[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b k ≤ bit1 n ↔ k ≤ n | ff := bit0_le_bit1_iff | tt := bit1_le_bit1 @[simp] lemma bit0_mod_two : bit0 n % 2 = 0 := by { rw nat.mod_two_of_bodd, simp } @[simp] lemma bit1_mod_two : bit1 n % 2 = 1 := by { rw nat.mod_two_of_bodd, simp } lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } /-- Define a function on `ℕ` depending on parity of the argument. -/ @[elab_as_eliminator] def bit_cases {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : C n := eq.rec_on n.bit_decomp (H (bodd n) (div2 n)) /-! ### decidability of predicates -/ instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (le_of_lt_succ h').lt_or_eq_dec.elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl instance decidable_exists_lt {P : ℕ → Prop} [h : decidable_pred P] : decidable_pred (λ n, ∃ (m : ℕ), m < n ∧ P m) | 0 := is_false (by simp) | (n + 1) := decidable_of_decidable_of_iff (@or.decidable _ _ (decidable_exists_lt n) (h n)) (by simp only [lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, exists_eq_left]) end nat
ef3c449dbb43e82b207afe4f48043a3f643e9f50
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/mathlibetaissue.lean
978d143b4c8d7919d96033e392d1418f48e2db3d
[ "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
5,941
lean
/-! # An etaExperiment timeout The purpose of this file is to demonstrate a typeclass search that * times out with `etaExperiment` * is fast on `lean-toolchain` `gebner/lean4:reenableeta230506` * is realistic, i.e. is a minimisation of something appearing in mathlib. I've taken the example Matthew Ballard showed me: ``` import Mathlib #synth Zero ℤ ``` and minimised it. I've used `sorry` liberally, but not changed the typeclass inheritance structure at all relative to mathlib4. (It could probably be minimized further, but I think this is not the point?) This file is minimised in the sense that: * removing any command should either cause a new error, or remove the timeout. * removing any field of a structure, and sorrying a field of an instance, should do the same. Section titles correspond to the files the material came from the mathlib4/std4. -/ section Std.Classes.Cast class NatCast (R : Type u) where class IntCast (R : Type u) where end Std.Classes.Cast section Std.Data.Int.Lemmas namespace Int theorem add_zero : ∀ a : Int, a + 0 = a := sorry theorem mul_one (a : Int) : a * 1 = a := sorry end Int end Std.Data.Int.Lemmas section Std.Classes.RatCast class RatCast (K : Type u) where end Std.Classes.RatCast section Mathlib.Init.ZeroOne class Zero.{u} (α : Type u) where zero : α instance Zero.toOfNat0 {α} [Zero α] : OfNat α (nat_lit 0) where ofNat := ‹Zero α›.1 class One (α : Type u) where one : α instance One.toOfNat1 {α} [One α] : OfNat α (nat_lit 1) where ofNat := ‹One α›.1 end Mathlib.Init.ZeroOne section Mathlib.Algebra.Group.Defs class Inv (α : Type u) where class Semigroup (G : Type u) extends Mul G where class AddSemigroup (G : Type u) extends Add G where class CommSemigroup (G : Type u) extends Semigroup G where mul_comm : ∀ a b : G, a * b = b * a class AddCommSemigroup (G : Type u) extends AddSemigroup G where class MulOneClass (M : Type u) extends One M, Mul M where mul_one : ∀ a : M, a * 1 = a class AddZeroClass (M : Type u) extends Zero M, Add M where add_zero : ∀ a : M, a + 0 = a class AddMonoid (M : Type u) extends AddSemigroup M, AddZeroClass M where class Monoid (M : Type u) extends Semigroup M, MulOneClass M where class AddCommMonoid (M : Type u) extends AddMonoid M, AddCommSemigroup M class CommMonoid (M : Type u) extends Monoid M, CommSemigroup M class DivInvMonoid (G : Type u) extends Monoid G, Inv G, Div G where class SubNegMonoid (G : Type u) extends AddMonoid G, Neg G, Sub G where class Group (G : Type u) extends DivInvMonoid G where class AddGroup (A : Type u) extends SubNegMonoid A where class AddCommGroup (G : Type u) extends AddGroup G, AddCommMonoid G end Mathlib.Algebra.Group.Defs section Mathlib.Logic.Nontrivial class Nontrivial (α : Type _) : Prop where end Mathlib.Logic.Nontrivial section Mathlib.Algebra.GroupWithZero.Defs class MulZeroClass (M₀ : Type u) extends Mul M₀, Zero M₀ where class IsLeftCancelMulZero (M₀ : Type u) [Mul M₀] [Zero M₀] : Prop where class IsRightCancelMulZero (M₀ : Type u) [Mul M₀] [Zero M₀] : Prop where class IsCancelMulZero (M₀ : Type u) [Mul M₀] [Zero M₀] extends IsLeftCancelMulZero M₀, IsRightCancelMulZero M₀ : Prop class NoZeroDivisors (M₀ : Type _) [Mul M₀] [Zero M₀] : Prop where class SemigroupWithZero (S₀ : Type u) extends Semigroup S₀, MulZeroClass S₀ class MulZeroOneClass (M₀ : Type u) extends MulOneClass M₀, MulZeroClass M₀ class MonoidWithZero (M₀ : Type u) extends Monoid M₀, MulZeroOneClass M₀, SemigroupWithZero M₀ class CommMonoidWithZero (M₀ : Type _) extends CommMonoid M₀, MonoidWithZero M₀ class CancelCommMonoidWithZero (M₀ : Type _) extends CommMonoidWithZero M₀, IsLeftCancelMulZero M₀ end Mathlib.Algebra.GroupWithZero.Defs section Mathlib.Data.Nat.Cast.Defs class AddMonoidWithOne (R : Type u) extends NatCast R, AddMonoid R, One R where class AddCommMonoidWithOne (R : Type _) extends AddMonoidWithOne R, AddCommMonoid R end Mathlib.Data.Nat.Cast.Defs section Mathlib.Data.Int.Cast.Defs class AddGroupWithOne (R : Type u) extends IntCast R, AddMonoidWithOne R, AddGroup R where end Mathlib.Data.Int.Cast.Defs section Mathlib.Algebra.Ring.Defs class NonUnitalNonAssocSemiring (α : Type u) extends AddCommMonoid α, MulZeroClass α class NonUnitalSemiring (α : Type u) extends NonUnitalNonAssocSemiring α, SemigroupWithZero α class NonAssocSemiring (α : Type u) extends NonUnitalNonAssocSemiring α, MulZeroOneClass α, AddCommMonoidWithOne α class Semiring (α : Type u) extends NonUnitalSemiring α, NonAssocSemiring α, MonoidWithZero α class Ring (R : Type u) extends Semiring R, AddCommGroup R, AddGroupWithOne R class CommSemiring (R : Type u) extends Semiring R, CommMonoid R class CommRing (α : Type u) extends Ring α, CommMonoid α instance CommRing.toCommSemiring [s : CommRing α] : CommSemiring α := { s with } class IsDomain (α : Type u) [Semiring α] extends IsCancelMulZero α, Nontrivial α : Prop end Mathlib.Algebra.Ring.Defs section Mathlib.Data.Int.Basic instance : CommRing Int where mul_comm := sorry mul_one := Int.mul_one -- Replacing this with `sorry` makes the timeout go away! add_zero := Int.add_zero -- Similarly here. end Mathlib.Data.Int.Basic section Mathlib.Algebra.Ring.Regular section IsDomain instance IsDomain.toCancelCommMonoidWithZero [CommSemiring α] [IsDomain α] : CancelCommMonoidWithZero α := { } end IsDomain end Mathlib.Algebra.Ring.Regular section Mathlib.Algebra.Field.Defs class DivisionRing (K : Type u) extends Ring K, DivInvMonoid K, Nontrivial K, RatCast K where class Field (K : Type u) extends CommRing K, DivisionRing K end Mathlib.Algebra.Field.Defs section Mathlib.Algebra.Field.Basic instance Field.isDomain [Field K] : IsDomain K := sorry end Mathlib.Algebra.Field.Basic set_option synthInstance.maxHeartbeats 200 in #synth Zero Int -- works fine
1e61602f2ed9a8108f4dfed2afabc7e47f135c4e
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/subtype.lean
7adb787c7f81ed4bf43bf9c0226543d7aa61879c
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
342
lean
/- This defines subtype lemmas -/ universe variable u namespace subtype variable {α : Type u} variable {P : α → Prop} @[simp] theorem mk_eq_mk (x : α) (p : P x) (y : α) (q : P y) : mk x p = mk y q ↔ x = y := begin apply iff.intro, { intro g, injection g with h }, { intro p, simp [p], } end end subtype
ba8d44eccbd74358aa8a58c44e8274acde799bb7
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Meta/Tactic/Cases.lean
fb37d6eb2f452ff2779e592abd0534ff07561e70
[ "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
11,311
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.Meta.AppBuilder import Init.Lean.Meta.Tactic.Induction import Init.Lean.Meta.Tactic.Injection import Init.Lean.Meta.Tactic.Assert import Init.Lean.Meta.Tactic.Subst namespace Lean namespace Meta private def mkEqAndProof (lhs rhs : Expr) : MetaM (Expr × Expr) := do lhsType ← inferType lhs; rhsType ← inferType rhs; u ← getLevel lhsType; condM (isDefEq lhsType rhsType) (pure (mkApp3 (mkConst `Eq [u]) lhsType lhs rhs, mkApp2 (mkConst `Eq.refl [u]) lhsType lhs)) (pure (mkApp4 (mkConst `HEq [u]) lhsType lhs rhsType rhs, mkApp2 (mkConst `HEq.refl [u]) lhsType lhs)) private partial def withNewIndexEqsAux {α} (indices newIndices : Array Expr) (k : Array Expr → Array Expr → MetaM α) : Nat → Array Expr → Array Expr → MetaM α | i, newEqs, newRefls => if h : i < indices.size then do let index := indices.get! i; let newIndex := newIndices.get! i; (newEqType, newRefl) ← mkEqAndProof index newIndex; withLocalDecl `h newEqType BinderInfo.default $ fun newEq => do withNewIndexEqsAux (i+1) (newEqs.push newEq) (newRefls.push newRefl) else k newEqs newRefls private def withNewIndexEqs {α} (indices newIndices : Array Expr) (k : Array Expr → Array Expr → MetaM α) : MetaM α := withNewIndexEqsAux indices newIndices k 0 #[] #[] structure GeneralizeIndicesSubgoal := (mvarId : MVarId) (indicesFVarIds : Array FVarId) (fvarId : FVarId) (numEqs : Nat) /-- Given a metavariable `mvarId` representing the ``` Ctx, h : I A j, D |- T ``` where `fvarId` is `h`s id, and the type `I A j` is an inductive datatype where `A` are parameters, and `j` the indices. Generate the goal ``` Ctx, h : I A j, D, j' : J, h' : I A j' |- j == j' -> h == h' -> T ``` Remark: `(j == j' -> h == h')` is a "telescopic" equality. Remark: `j` is sequence of terms, and `j'` a sequence of free variables. The result contains the fields - `mvarId`: the new goal - `indicesFVarIds`: `j'` ids - `fvarId`: `h'` id - `numEqs`: number of equations in the target -/ def generalizeIndices (mvarId : MVarId) (fvarId : FVarId) : MetaM GeneralizeIndicesSubgoal := do withMVarContext mvarId $ do lctx ← getLCtx; localInsts ← getLocalInstances; env ← getEnv; checkNotAssigned mvarId `generalizeIndices; fvarDecl ← getLocalDecl fvarId; type ← whnf fvarDecl.type; type.withApp $ fun f args => matchConst env f (fun _ => throwTacticEx `generalizeIndices mvarId "inductive type expected") $ fun cinfo _ => match cinfo with | ConstantInfo.inductInfo val => do unless (val.nindices > 0) $ throwTacticEx `generalizeIndices mvarId "indexed inductive type expected"; unless (args.size == val.nindices + val.nparams) $ throwTacticEx `generalizeIndices mvarId "ill-formed inductive datatype"; let indices := args.extract (args.size - val.nindices) args.size; let IA := mkAppN f (args.extract 0 val.nparams); -- `I A` IAType ← inferType IA; forallTelescopeReducing IAType $ fun newIndices _ => do let newType := mkAppN IA newIndices; withLocalDecl fvarDecl.userName newType BinderInfo.default $ fun h' => withNewIndexEqs indices newIndices $ fun newEqs newRefls => do (newEqType, newRefl) ← mkEqAndProof fvarDecl.toExpr h'; let newRefls := newRefls.push newRefl; withLocalDecl `h newEqType BinderInfo.default $ fun newEq => do let newEqs := newEqs.push newEq; /- auxType `forall (j' : J) (h' : I A j'), j == j' -> h == h' -> target -/ target ← getMVarType mvarId; tag ← getMVarTag mvarId; auxType ← mkForall newEqs target; auxType ← mkForall #[h'] auxType; auxType ← mkForall newIndices auxType; newMVar ← mkFreshExprMVarAt lctx localInsts auxType tag MetavarKind.syntheticOpaque; /- assign mvarId := newMVar indices h refls -/ assignExprMVar mvarId (mkAppN (mkApp (mkAppN newMVar indices) fvarDecl.toExpr) newRefls); (indicesFVarIds, newMVarId) ← introN newMVar.mvarId! newIndices.size [] false; (fvarId, newMVarId) ← intro1 newMVarId false; pure { mvarId := newMVarId, indicesFVarIds := indicesFVarIds, fvarId := fvarId, numEqs := newEqs.size } | _ => throwTacticEx `generalizeIndices mvarId "inductive type expected" structure CasesSubgoal extends InductionSubgoal := (ctorName : Name) namespace Cases structure Context := (inductiveVal : InductiveVal) (casesOnVal : DefinitionVal) (nminors : Nat := inductiveVal.ctors.length) (majorDecl : LocalDecl) (majorTypeFn : Expr) (majorTypeArgs : Array Expr) (majorTypeIndices : Array Expr := majorTypeArgs.extract (majorTypeArgs.size - inductiveVal.nindices) majorTypeArgs.size) private def mkCasesContext? (majorFVarId : FVarId) : MetaM (Option Context) := do env ← getEnv; if !env.contains `Eq || !env.contains `HEq then pure none else do majorDecl ← getLocalDecl majorFVarId; majorType ← whnf majorDecl.type; majorType.withApp $ fun f args => matchConst env f (fun _ => pure none) $ fun cinfo _ => do match cinfo with | ConstantInfo.inductInfo ival => if args.size != ival.nindices + ival.nparams then pure none else match env.find? (mkNameStr ival.name "casesOn") with | ConstantInfo.defnInfo cval => pure $ some { inductiveVal := ival, casesOnVal := cval, majorDecl := majorDecl, majorTypeFn := f, majorTypeArgs := args } | _ => pure none | _ => pure none /- We say the major premise has independent indices IF 1- its type is *not* an indexed inductive family, OR 2- its type is an indexed inductive family, but all indices are distinct free variables, and all local declarations different from the major and its indices do not depend on the indices. -/ private def hasIndepIndices (ctx : Context) : MetaM Bool := if ctx.majorTypeIndices.isEmpty then pure true else if ctx.majorTypeIndices.any $ fun idx => !idx.isFVar then /- One of the indices is not a free variable. -/ pure false else if ctx.majorTypeIndices.size.any $ fun i => i.any $ fun j => ctx.majorTypeIndices.get! i == ctx.majorTypeIndices.get! j then /- An index ocurrs more than once -/ pure false else do lctx ← getLCtx; mctx ← getMCtx; pure $ lctx.all $ fun decl => decl.fvarId == ctx.majorDecl.fvarId || -- decl is the major ctx.majorTypeIndices.any (fun index => decl.fvarId == index.fvarId!) || -- decl is one of the indices mctx.findLocalDeclDependsOn decl (fun fvarId => ctx.majorTypeIndices.all $ fun idx => idx.fvarId! != fvarId) -- or does not depend on any index private def elimAuxIndices (s₁ : GeneralizeIndicesSubgoal) (s₂ : Array InductionSubgoal) : MetaM (Array InductionSubgoal) := let indicesFVarIds := s₁.indicesFVarIds; s₂.mapM $ fun s => do indicesFVarIds.foldlM (fun s indexFVarId => let indexFVarId' := s.subst.get indexFVarId; (do mvarId ← clear s.mvarId indexFVarId'; pure { s with mvarId := mvarId, subst := s.subst.erase indexFVarId }) <|> (pure s)) s private def toCasesSubgoals (s : Array InductionSubgoal) (ctorNames : Array Name) : Array CasesSubgoal := s.mapIdx $ fun i s => { ctorName := ctorNames.get! i, toInductionSubgoal := s } private partial def unifyEqsAux : Nat → CasesSubgoal → MetaM (Option CasesSubgoal) | 0, s => do trace! `Meta.cases ("unifyEqs " ++ MessageData.ofGoal s.mvarId); pure (some s) | n+1, s => do trace! `Meta.cases ("unifyEqs [" ++ toString (n+1) ++ "] " ++ MessageData.ofGoal s.mvarId); (eqFVarId, mvarId) ← intro1 s.mvarId; withMVarContext mvarId $ do eqDecl ← getLocalDecl eqFVarId; match eqDecl.type.heq? with | some (α, a, β, b) => do prf ← mkEqOfHEq (mkFVar eqFVarId); aEqb ← mkEq a b; mvarId ← assert mvarId eqDecl.userName aEqb prf; mvarId ← clear mvarId eqFVarId; unifyEqsAux (n+1) { s with mvarId := mvarId } | none => match eqDecl.type.eq? with | some (α, a, b) => let skip : Unit → MetaM (Option CasesSubgoal) := fun _ => do { mvarId ← clear mvarId eqFVarId; unifyEqsAux n { s with mvarId := mvarId } }; let substEq (symm : Bool) : MetaM (Option CasesSubgoal) := do { (newSubst, mvarId) ← substCore mvarId eqFVarId false true; unifyEqsAux n { s with mvarId := mvarId, subst := newSubst.compose s.subst, fields := s.fields.map $ fun fvarId => newSubst.get fvarId } }; let inj : Unit → MetaM (Option CasesSubgoal) := fun _ => do { r ← injectionCore mvarId eqFVarId; match r with | InjectionResultCore.solved => pure none -- this alternative has been solved | InjectionResultCore.subgoal mvarId numEqs => unifyEqsAux (n+numEqs) { s with mvarId := mvarId } }; condM (isDefEq a b) (skip ()) $ do a ← whnf a; b ← whnf b; match a, b with | Expr.fvar aFVarId _, Expr.fvar bFVarId _ => do aDecl ← getLocalDecl aFVarId; bDecl ← getLocalDecl bFVarId; substEq (aDecl.index < bDecl.index) | Expr.fvar _ _, _ => substEq false | _, Expr.fvar _ _ => substEq true | _, _ => inj () | none => throwTacticEx `cases mvarId "equality expected" private def unifyEqs (numEqs : Nat) (subgoals : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := subgoals.foldlM (fun subgoals s => do s? ← unifyEqsAux numEqs s; match s? with | none => pure $ subgoals | some s => pure $ subgoals.push s) #[] def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name) := #[]) (useUnusedNames := false) : MetaM (Array CasesSubgoal) := withMVarContext mvarId $ do checkNotAssigned mvarId `cases; context? ← mkCasesContext? majorFVarId; match context? with | none => throwTacticEx `cases mvarId "not applicable to the given hypothesis" | some ctx => let ctors := ctx.inductiveVal.ctors.toArray; let casesOn := mkCasesOnFor ctx.inductiveVal.name; condM (hasIndepIndices ctx) (do s ← induction mvarId majorFVarId casesOn givenNames useUnusedNames; pure $ toCasesSubgoals s ctors) (do s₁ ← generalizeIndices mvarId majorFVarId; trace! `Meta.cases ("after generalizeIndices" ++ Format.line ++ MessageData.ofGoal s₁.mvarId); s₂ ← induction s₁.mvarId s₁.fvarId casesOn givenNames useUnusedNames; s₂ ← elimAuxIndices s₁ s₂; let s₂ := toCasesSubgoals s₂ ctors; unifyEqs s₁.numEqs s₂) end Cases def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name) := #[]) (useUnusedNames := false) : MetaM (Array CasesSubgoal) := Cases.cases mvarId majorFVarId givenNames useUnusedNames end Meta end Lean
dbfd0bbc88ad3ee4d7f2951b60cfcd3f91cc516a
83bd63fd58ebbb33f769cbf6d6a67463ba1bc637
/src/day_3/groups.lean
d9ec6d797a7cf1517a9183bf67e59a552e808677
[]
no_license
Wornbard/mbl_lean_workshop
6ebdafebac74f1b1148f67a528242a3687af17e1
6b68ce25fdc49043fd5ab409de8e4a2987def22e
refs/heads/main
1,690,205,591,845
1,630,953,271,000
1,630,953,271,000
403,417,180
0
0
null
null
null
null
UTF-8
Lean
false
false
8,454
lean
import tactic namespace mbl /- # Groups ## Definition of a group The `group` class will extend `has_mul`, `has_one` and `has_inv`. `has_mul G` means that `G` has a multiplication `* : G → G → G` `has_one G` means that `G` has a `1 : G` `has_inv G` means that `G` has an `⁻¹ : G → G` All of `*`, `1` and `⁻¹` are notation for functions -- no axioms yet. A `group` has all of this notation, and the group axioms too. Let's now define the group class. A `group` structure on a type `G` is multiplication, identity and inverse, plus the usual axioms -/ class group (G : Type) extends has_mul G, has_one G, has_inv G := (mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)) (one_mul : ∀ (a : G), 1 * a = a) (mul_left_inv : ∀ (a : G), a⁻¹ * a = 1) /- Formally, a term of type `group G` is now the following data: a multiplication, 1, and inverse function, and proofs that the group axioms are satisfied. The way to say "let G be a group" is now `(G : Type) [group G]` The square bracket notation is the notation used for classes. Formally, it means "put a term of type `group G` into the type class inference system". In practice this just means "you can use group notation and axioms in proofs, and Lean will figure out why they're true" We have been extremely mean with our axioms. Some authors also add the axioms `mul_one : ∀ (a : G), a * 1 = a` and `mul_right_inv : ∀ (a : G), a * a⁻¹ = 1`. But these follow from the three axioms we used. Our first job is to prove them. As you might imagine, mathematically this is pretty much the trickiest part, because we have to be careful not to accidentally assume these axioms when we're proving them. Here are the four lemmas we will prove next. `mul_left_cancel : ∀ (a b c : G), a * b = a * c → b = c` `mul_eq_of_eq_inv_mul {a x y : G} : x = a⁻¹ * y → a * x = y` `mul_one (a : G) : a * 1 = a` `mul_right_inv (a : G) : a * a⁻¹ = 1` -/ namespace group -- let `G` be a group. variables {G : Type} [group G] /- This proof could be done using rewrites, but I will take this opportunity to introduce the `calc` tactic. The math is already done. All you need to do is apply correct axioms/assumptions -/ lemma mul_left_cancel (a b c : G) (Habac : a * b = a * c) : b = c := begin calc b = 1 * b : by sorry ... = (a⁻¹ * a) * b : by sorry ... = a⁻¹ * (a * b) : by sorry ... = a⁻¹ * (a * c) : by sorry ... = (a⁻¹ * a) * c : by sorry ... = 1 * c : by sorry ... = c : by sorry end /-! Next we prove that if `x = a⁻¹ * y` then `a * x = y`. Remember we are still missing `mul_one` and `mul_right_inv`. A proof that avoids them is the following: we want `a * x = y`. Now `apply`ing the previous lemma, it suffices to prove that `a⁻¹ * (a * x) = a⁻¹ * y.` Now use associativity and left cancellation on on the left, to reduce to `h`. Note that `mul_left_cancel` is a function, and its first input is called `a`, but you had better give it `a⁻¹` instead. -/ lemma mul_eq_of_eq_inv_mul {a x y : G} (h : x = a⁻¹ * y) : a * x = y := begin sorry, end -- Let `a,b,c,x,y` be elements of `G`. variables (a b c x y : G) --From now on we don't need to redefine all the variables in our theorems /- We can use `mul_eq_of_eq_inv_mul` to prove the two "missing" axioms `mul_one` and `mul_right_inv`, and then our lives will be much easier. Try `apply`ing it in the theorems below. -/ @[simp] theorem mul_one : a * 1 = a := begin sorry, end @[simp] theorem mul_right_inv : a * a⁻¹ = 1 := begin sorry, end /- ## Lean's simplifier A human sees `a * a⁻¹` in group theory, and instantly replaces it with `1`. We are going to train a simple AI called `simp` to do the same thing. Lean's simplifier `simp` is a "term rewriting system". This means that if you teach it a bunch of theorems of the form `A = B` or `P ↔ Q` (by tagging them with the `@[simp]` attribute) and then give it a complicated goal, like `example : (a * b) * 1⁻¹⁻¹ * b⁻¹ * (a⁻¹ * a⁻¹⁻¹⁻¹) * a = 1` then it will try to use the `rw` tactic as much as it can, using the lemmas it has been taught, in an attempt to simplify the goal. If it manages to solve it completely, then great! If it does not, but you feel like it should have done, you might want to tag more lemmas with `@[simp]`. `simp` should only be used to completely close goals. We are now going to train the simplifier to solve the example above (indeed, we are going to train it to reduce an arbitrary element of a free group into a unique normal form, so it will solve any equalities which are true for all groups, like the example above). ## Important note Lean's simplifier does a series of rewrites, each one replacing something with something else. But the simplifier will always rewrite from left to right! If you tell it that `A = B` is a `simp` lemma then it will replace `A`s with `B`s, but it will never replace `B`s with `A`s. If you tag a proof of `A = B` with `@[simp]` and you also tag a proof of `B = A` with `@[simp]`, then the simplifier will get stuck in an infinite loop when it runs into an `A`! Equality should not be thought of as symmetric here. Because the simplifier works from left to right, an important rule of thumb is that if `A = B` is a `simp` lemma, then `B` should probably be simpler than `A`! In particular, equality should not be thought of as symmetric here. It is not a coincidence that in the theorems below `@[simp] theorem mul_one (a : G) : a * 1 = a` `@[simp] theorem mul_right_inv (a : G) : a * a⁻¹ = 1` the right hand side is simpler than the left hand side. It would be a > disaster to tag `a = a * 1` with the `@[simp]` tag -- can you see why? Let's train Lean's simplifier! Let's teach it the axioms of a `group` next. We have already done the axioms, so we have to retrospectively tag them with the `@[simp]` attribute. -/ attribute [simp] one_mul mul_left_inv mul_assoc /- Now let's teach the simplifier the following five lemmas: `inv_mul_cancel_left : a⁻¹ * (a * b) = b` `mul_inv_cancel_left : a * (a⁻¹ * b) = b` `inv_mul : (a * b)⁻¹ = b⁻¹ * a⁻¹` `one_inv : (1 : G)⁻¹ = 1` `inv_inv : (a⁻¹)⁻¹ = a` Note that in each case, the right hand side is simpler than the left hand side. Try using the simplifier in your proofs! I will do the first one for you. -/ @[simp] lemma inv_mul_cancel_left : a⁻¹ * (a * b) = b := begin rw ← mul_assoc, -- the simplifier wouldn't do it that way -- so we have to do it manually simp, -- simplifier takes it from here, -- rewriting a⁻¹ * a to 1 and then 1 * b to b end @[simp] lemma mul_inv_cancel_left : a * (a⁻¹ * b) = b := begin sorry, end @[simp] lemma inv_mul : (a * b)⁻¹ = b⁻¹ * a⁻¹ := begin sorry, end @[simp] lemma one_inv : (1 : G)⁻¹ = 1 := begin sorry, end @[simp] lemma inv_inv : a ⁻¹ ⁻¹ = a := begin sorry, end --Once we prove those, simp can solve things such as this example : (a * b) * 1⁻¹⁻¹ * b⁻¹ * (a⁻¹ * a⁻¹⁻¹⁻¹) * a = 1 := by simp -- short for begin simp end --Even more exercises. We probably won't look at them but you are welcome to try them in your own time lemma eq_mul_inv_of_mul_eq {a b c : G} (h : a * c = b) : a = b * c⁻¹ := begin sorry, end lemma eq_inv_mul_of_mul_eq {a b c : G} (h : b * a = c) : a = b⁻¹ * c := begin sorry end lemma mul_left_eq_self {a b : G} : a * b = b ↔ a = 1 := begin sorry end lemma mul_right_eq_self {a b : G} : a * b = a ↔ b = 1 := begin sorry end lemma eq_inv_of_mul_eq_one {a b : G} (h : a * b = 1) : a = b⁻¹ := begin sorry end lemma inv_eq_of_mul_eq_one {a b : G} (h : a * b = 1) : a⁻¹ = b := begin sorry, end lemma unique_left_id {e : G} (h : ∀ x : G, e * x = x) : e = 1 := begin sorry end lemma unique_right_inv {a b : G} (h : a * b = 1) : b = a⁻¹ := begin sorry end lemma mul_left_cancel_iff (a x y : G) : a * x = a * y ↔ x = y := begin sorry, end -- You don't even need to go into tactic mode (begin/end) to use `calc`: lemma mul_right_cancel (a x y : G) (Habac : x * a = y * a) : x = y := calc x = x * 1 : by rw mul_one -- missing arguments here ... = y : by sorry -- `↔` lemmas are good simp lemmas too. @[simp] theorem inv_inj_iff {a b : G}: a⁻¹ = b⁻¹ ↔ a = b := begin sorry end theorem inv_eq {a b : G}: a⁻¹ = b ↔ b⁻¹ = a := begin sorry end end group end mbl
51e5a6b57525427170482d5e0ec5aa2094645d3b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/instances/add_circle.lean
88ac997cbf3ebf93cda7b67cbb6906db6f0b30dc
[ "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
24,039
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import data.nat.totient import algebra.ring.add_aut import group_theory.divisible import group_theory.order_of_element import algebra.order.floor import algebra.order.to_interval_mod import topology.instances.real /-! # The additive circle > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the additive circle `add_circle p` as the quotient `𝕜 ⧸ (ℤ ∙ p)` for some period `p : 𝕜`. See also `circle` and `real.angle`. For the normed group structure on `add_circle`, see `add_circle.normed_add_comm_group` in a later file. ## Main definitions and results: * `add_circle`: the additive circle `𝕜 ⧸ (ℤ ∙ p)` for some period `p : 𝕜` * `unit_add_circle`: the special case `ℝ ⧸ ℤ` * `add_circle.equiv_add_circle`: the rescaling equivalence `add_circle p ≃+ add_circle q` * `add_circle.equiv_Ico`: the natural equivalence `add_circle p ≃ Ico a (a + p)` * `add_circle.add_order_of_div_of_gcd_eq_one`: rational points have finite order * `add_circle.exists_gcd_eq_one_of_is_of_fin_add_order`: finite-order points are rational * `add_circle.homeo_Icc_quot`: the natural topological equivalence between `add_circle p` and `Icc a (a + p)` with its endpoints identified. * `add_circle.lift_Ico_continuous`: if `f : ℝ → B` is continuous, and `f a = f (a + p)` for some `a`, then there is a continuous function `add_circle p → B` which agrees with `f` on `Icc a (a + p)`. ## Implementation notes: Although the most important case is `𝕜 = ℝ` we wish to support other types of scalars, such as the rational circle `add_circle (1 : ℚ)`, and so we set things up more generally. ## TODO * Link with periodicity * Lie group structure * Exponential equivalence to `circle` -/ noncomputable theory open add_comm_group set function add_subgroup topological_space open_locale topology variables {𝕜 B : Type*} section continuity variables [linear_ordered_add_comm_group 𝕜] [archimedean 𝕜] [topological_space 𝕜] [order_topology 𝕜] {p : 𝕜} (hp : 0 < p) (a x : 𝕜) lemma continuous_right_to_Ico_mod : continuous_within_at (to_Ico_mod hp a) (Ici x) x := begin intros s h, rw [filter.mem_map, mem_nhds_within_iff_exists_mem_nhds_inter], haveI : nontrivial 𝕜 := ⟨⟨0, p, hp.ne⟩⟩, simp_rw mem_nhds_iff_exists_Ioo_subset at h ⊢, obtain ⟨l, u, hxI, hIs⟩ := h, let d := to_Ico_div hp a x • p, have hd := to_Ico_mod_mem_Ico hp a x, simp_rw [subset_def, mem_inter_iff], refine ⟨_, ⟨l + d, min (a + p) u + d, _, λ x, id⟩, λ y, _⟩; simp_rw [← sub_mem_Ioo_iff_left, mem_Ioo, lt_min_iff], { exact ⟨hxI.1, hd.2, hxI.2⟩ }, { rintro ⟨h, h'⟩, apply hIs, rw [← to_Ico_mod_sub_zsmul, (to_Ico_mod_eq_self _).2], exacts [⟨h.1, h.2.2⟩, ⟨hd.1.trans (sub_le_sub_right h' _), h.2.1⟩] }, end lemma continuous_left_to_Ioc_mod : continuous_within_at (to_Ioc_mod hp a) (Iic x) x := begin rw (funext (λ y, eq.trans (by rw neg_neg) $ to_Ioc_mod_neg _ _ _) : to_Ioc_mod hp a = (λ x, p - x) ∘ to_Ico_mod hp (-a) ∘ has_neg.neg), exact ((continuous_sub_left _).continuous_at.comp_continuous_within_at $ (continuous_right_to_Ico_mod _ _ _).comp continuous_neg.continuous_within_at $ λ y, neg_le_neg), end variables {x} (hx : (x : 𝕜 ⧸ zmultiples p) ≠ a) lemma to_Ico_mod_eventually_eq_to_Ioc_mod : to_Ico_mod hp a =ᶠ[𝓝 x] to_Ioc_mod hp a := is_open.mem_nhds (by {rw Ico_eq_locus_Ioc_eq_Union_Ioo, exact is_open_Union (λ i, is_open_Ioo)}) $ (not_modeq_iff_to_Ico_mod_eq_to_Ioc_mod hp).1 $ not_modeq_iff_ne_mod_zmultiples.2 hx lemma continuous_at_to_Ico_mod : continuous_at (to_Ico_mod hp a) x := let h := to_Ico_mod_eventually_eq_to_Ioc_mod hp a hx in continuous_at_iff_continuous_left_right.2 $ ⟨(continuous_left_to_Ioc_mod hp a x).congr_of_eventually_eq (h.filter_mono nhds_within_le_nhds) h.eq_of_nhds, continuous_right_to_Ico_mod hp a x⟩ lemma continuous_at_to_Ioc_mod : continuous_at (to_Ioc_mod hp a) x := let h := to_Ico_mod_eventually_eq_to_Ioc_mod hp a hx in continuous_at_iff_continuous_left_right.2 $ ⟨continuous_left_to_Ioc_mod hp a x, (continuous_right_to_Ico_mod hp a x).congr_of_eventually_eq (h.symm.filter_mono nhds_within_le_nhds) h.symm.eq_of_nhds⟩ end continuity /-- The "additive circle": `𝕜 ⧸ (ℤ ∙ p)`. See also `circle` and `real.angle`. -/ @[derive [add_comm_group, topological_space, topological_add_group, inhabited, has_coe_t 𝕜], nolint unused_arguments] def add_circle [linear_ordered_add_comm_group 𝕜] [topological_space 𝕜] [order_topology 𝕜] (p : 𝕜) := 𝕜 ⧸ zmultiples p namespace add_circle section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group 𝕜] [topological_space 𝕜] [order_topology 𝕜] (p : 𝕜) lemma coe_nsmul {n : ℕ} {x : 𝕜} : (↑(n • x) : add_circle p) = n • (x : add_circle p) := rfl lemma coe_zsmul {n : ℤ} {x : 𝕜} : (↑(n • x) : add_circle p) = n • (x : add_circle p) := rfl lemma coe_add (x y : 𝕜) : (↑(x + y) : add_circle p) = (x : add_circle p) + (y : add_circle p) := rfl lemma coe_sub (x y : 𝕜) : (↑(x - y) : add_circle p) = (x : add_circle p) - (y : add_circle p) := rfl lemma coe_neg {x : 𝕜} : (↑(-x) : add_circle p) = -(x : add_circle p) := rfl lemma coe_eq_zero_iff {x : 𝕜} : (x : add_circle p) = 0 ↔ ∃ (n : ℤ), n • p = x := by simp [add_subgroup.mem_zmultiples_iff] lemma coe_eq_zero_of_pos_iff (hp : 0 < p) {x : 𝕜} (hx : 0 < x) : (x : add_circle p) = 0 ↔ ∃ (n : ℕ), n • p = x := begin rw coe_eq_zero_iff, split; rintros ⟨n, rfl⟩, { replace hx : 0 < n, { contrapose! hx, simpa only [←neg_nonneg, ←zsmul_neg, zsmul_neg'] using zsmul_nonneg hp.le (neg_nonneg.2 hx) }, exact ⟨n.to_nat, by rw [← coe_nat_zsmul, int.to_nat_of_nonneg hx.le]⟩, }, { exact ⟨(n : ℤ), by simp⟩, }, end lemma coe_period : (p : add_circle p) = 0 := (quotient_add_group.eq_zero_iff p).2 $ mem_zmultiples p @[simp] lemma coe_add_period (x : 𝕜) : ((x + p : 𝕜) : add_circle p) = x := by rw [coe_add, ←eq_sub_iff_add_eq', sub_self, coe_period] @[continuity, nolint unused_arguments] protected lemma continuous_mk' : continuous (quotient_add_group.mk' (zmultiples p) : 𝕜 → add_circle p) := continuous_coinduced_rng variables [hp : fact (0 < p)] include hp variables (a : 𝕜) [archimedean 𝕜] instance : circular_order (add_circle p) := quotient_add_group.circular_order /-- The equivalence between `add_circle p` and the half-open interval `[a, a + p)`, whose inverse is the natural quotient map. -/ def equiv_Ico : add_circle p ≃ Ico a (a + p) := quotient_add_group.equiv_Ico_mod hp.out a /-- The equivalence between `add_circle p` and the half-open interval `(a, a + p]`, whose inverse is the natural quotient map. -/ def equiv_Ioc : add_circle p ≃ Ioc a (a + p) := quotient_add_group.equiv_Ioc_mod hp.out a /-- Given a function on `𝕜`, return the unique function on `add_circle p` agreeing with `f` on `[a, a + p)`. -/ def lift_Ico (f : 𝕜 → B) : add_circle p → B := restrict _ f ∘ add_circle.equiv_Ico p a /-- Given a function on `𝕜`, return the unique function on `add_circle p` agreeing with `f` on `(a, a + p]`. -/ def lift_Ioc (f : 𝕜 → B) : add_circle p → B := restrict _ f ∘ add_circle.equiv_Ioc p a variables {p a} lemma coe_eq_coe_iff_of_mem_Ico {x y : 𝕜} (hx : x ∈ Ico a (a + p)) (hy : y ∈ Ico a (a + p)) : (x : add_circle p) = y ↔ x = y := begin refine ⟨λ h, _, by tauto⟩, suffices : (⟨x, hx⟩ : Ico a (a + p)) = ⟨y, hy⟩, by exact subtype.mk.inj this, apply_fun equiv_Ico p a at h, rw [←(equiv_Ico p a).right_inv ⟨x, hx⟩, ←(equiv_Ico p a).right_inv ⟨y, hy⟩], exact h end lemma lift_Ico_coe_apply {f : 𝕜 → B} {x : 𝕜} (hx : x ∈ Ico a (a + p)) : lift_Ico p a f ↑x = f x := begin have : (equiv_Ico p a) x = ⟨x, hx⟩, { rw equiv.apply_eq_iff_eq_symm_apply, refl, }, rw [lift_Ico, comp_apply, this], refl, end lemma lift_Ioc_coe_apply {f : 𝕜 → B} {x : 𝕜} (hx : x ∈ Ioc a (a + p)) : lift_Ioc p a f ↑x = f x := begin have : (equiv_Ioc p a) x = ⟨x, hx⟩, { rw equiv.apply_eq_iff_eq_symm_apply, refl, }, rw [lift_Ioc, comp_apply, this], refl, end variables (p a) section continuity @[continuity] lemma continuous_equiv_Ico_symm : continuous (equiv_Ico p a).symm := continuous_quotient_mk.comp continuous_subtype_coe @[continuity] lemma continuous_equiv_Ioc_symm : continuous (equiv_Ioc p a).symm := continuous_quotient_mk.comp continuous_subtype_coe variables {x : add_circle p} (hx : x ≠ a) include hx lemma continuous_at_equiv_Ico : continuous_at (equiv_Ico p a) x := begin induction x using quotient_add_group.induction_on', rw [continuous_at, filter.tendsto, quotient_add_group.nhds_eq, filter.map_map], exact (continuous_at_to_Ico_mod hp.out a hx).cod_restrict _, end lemma continuous_at_equiv_Ioc : continuous_at (equiv_Ioc p a) x := begin induction x using quotient_add_group.induction_on', rw [continuous_at, filter.tendsto, quotient_add_group.nhds_eq, filter.map_map], exact (continuous_at_to_Ioc_mod hp.out a hx).cod_restrict _, end end continuity /-- The image of the closed-open interval `[a, a + p)` under the quotient map `𝕜 → add_circle p` is the entire space. -/ @[simp] lemma coe_image_Ico_eq : (coe : 𝕜 → add_circle p) '' Ico a (a + p) = univ := by { rw image_eq_range, exact (equiv_Ico p a).symm.range_eq_univ } /-- The image of the closed-open interval `[a, a + p)` under the quotient map `𝕜 → add_circle p` is the entire space. -/ @[simp] lemma coe_image_Ioc_eq : (coe : 𝕜 → add_circle p) '' Ioc a (a + p) = univ := by { rw image_eq_range, exact (equiv_Ioc p a).symm.range_eq_univ } /-- The image of the closed interval `[0, p]` under the quotient map `𝕜 → add_circle p` is the entire space. -/ @[simp] lemma coe_image_Icc_eq : (coe : 𝕜 → add_circle p) '' Icc a (a + p) = univ := eq_top_mono (image_subset _ Ico_subset_Icc_self) $ coe_image_Ico_eq _ _ end linear_ordered_add_comm_group section linear_ordered_field variables [linear_ordered_field 𝕜] [topological_space 𝕜] [order_topology 𝕜] (p q : 𝕜) /-- The rescaling equivalence between additive circles with different periods. -/ def equiv_add_circle (hp : p ≠ 0) (hq : q ≠ 0) : add_circle p ≃+ add_circle q := quotient_add_group.congr _ _ (add_aut.mul_right $ (units.mk0 p hp)⁻¹ * units.mk0 q hq) $ by rw [add_monoid_hom.map_zmultiples, add_monoid_hom.coe_coe, add_aut.mul_right_apply, units.coe_mul, units.coe_mk0, units.coe_inv, units.coe_mk0, mul_inv_cancel_left₀ hp] @[simp] lemma equiv_add_circle_apply_mk (hp : p ≠ 0) (hq : q ≠ 0) (x : 𝕜) : equiv_add_circle p q hp hq (x : 𝕜) = (x * (p⁻¹ * q) : 𝕜) := rfl @[simp] lemma equiv_add_circle_symm_apply_mk (hp : p ≠ 0) (hq : q ≠ 0) (x : 𝕜) : (equiv_add_circle p q hp hq).symm (x : 𝕜) = (x * (q⁻¹ * p) : 𝕜) := rfl variables [hp : fact (0 < p)] include hp section floor_ring variables [floor_ring 𝕜] @[simp] lemma coe_equiv_Ico_mk_apply (x : 𝕜) : (equiv_Ico p 0 $ quotient_add_group.mk x : 𝕜) = int.fract (x / p) * p := to_Ico_mod_eq_fract_mul _ x instance : divisible_by (add_circle p) ℤ := { div := λ x n, (↑(((n : 𝕜)⁻¹) * (equiv_Ico p 0 x : 𝕜)) : add_circle p), div_zero := λ x, by simp only [algebra_map.coe_zero, quotient_add_group.coe_zero, inv_zero, zero_mul], div_cancel := λ n x hn, begin replace hn : (n : 𝕜) ≠ 0, { norm_cast, assumption, }, change n • quotient_add_group.mk' _ ((n : 𝕜)⁻¹ * ↑(equiv_Ico p 0 x)) = x, rw [← map_zsmul, ← smul_mul_assoc, zsmul_eq_mul, mul_inv_cancel hn, one_mul], exact (equiv_Ico p 0).symm_apply_apply x, end, } end floor_ring section finite_order_points variables {p} lemma add_order_of_period_div {n : ℕ} (h : 0 < n) : add_order_of ((p / n : 𝕜) : add_circle p) = n := begin rw [add_order_of_eq_iff h], replace h : 0 < (n : 𝕜) := nat.cast_pos.2 h, refine ⟨_, λ m hn h0, _⟩; simp only [ne, ← coe_nsmul, nsmul_eq_mul], { rw [mul_div_cancel' _ h.ne', coe_period] }, rw coe_eq_zero_of_pos_iff p hp.out (mul_pos (nat.cast_pos.2 h0) $ div_pos hp.out h), rintro ⟨k, hk⟩, rw [mul_div, eq_div_iff h.ne', nsmul_eq_mul, mul_right_comm, ← nat.cast_mul, (mul_left_injective₀ hp.out.ne').eq_iff, nat.cast_inj, mul_comm] at hk, exact (nat.le_of_dvd h0 ⟨_, hk.symm⟩).not_lt hn, end variables (p) lemma gcd_mul_add_order_of_div_eq {n : ℕ} (m : ℕ) (hn : 0 < n) : m.gcd n * add_order_of (↑(↑m / ↑n * p) : add_circle p) = n := begin rw [mul_comm_div, ← nsmul_eq_mul, coe_nsmul, add_order_of_nsmul''], { rw [add_order_of_period_div hn, nat.gcd_comm, nat.mul_div_cancel'], exacts [n.gcd_dvd_left m, hp] }, { rw [← add_order_of_pos_iff, add_order_of_period_div hn], exacts [hn, hp] }, end variable {p} lemma add_order_of_div_of_gcd_eq_one {m n : ℕ} (hn : 0 < n) (h : m.gcd n = 1) : add_order_of (↑(↑m / ↑n * p) : add_circle p) = n := by { convert gcd_mul_add_order_of_div_eq p m hn, rw [h, one_mul] } lemma add_order_of_div_of_gcd_eq_one' {m : ℤ} {n : ℕ} (hn : 0 < n) (h : m.nat_abs.gcd n = 1) : add_order_of (↑(↑m / ↑n * p) : add_circle p) = n := begin induction m, { simp only [int.of_nat_eq_coe, int.cast_coe_nat, int.nat_abs_of_nat] at h ⊢, exact add_order_of_div_of_gcd_eq_one hn h, }, { simp only [int.cast_neg_succ_of_nat, neg_div, neg_mul, coe_neg, order_of_neg], exact add_order_of_div_of_gcd_eq_one hn h, }, end lemma add_order_of_coe_rat {q : ℚ} : add_order_of (↑(↑q * p) : add_circle p) = q.denom := begin have : (↑(q.denom : ℤ) : 𝕜) ≠ 0, { norm_cast, exact q.pos.ne.symm, }, rw [← @rat.num_denom q, rat.cast_mk_of_ne_zero _ _ this, int.cast_coe_nat, rat.num_denom, add_order_of_div_of_gcd_eq_one' q.pos q.cop], apply_instance, end lemma add_order_of_eq_pos_iff {u : add_circle p} {n : ℕ} (h : 0 < n) : add_order_of u = n ↔ ∃ m < n, m.gcd n = 1 ∧ ↑(↑m / ↑n * p) = u := begin refine ⟨quotient_add_group.induction_on' u (λ k hk, _), _⟩, swap, { rintros ⟨m, h₀, h₁, rfl⟩, exact add_order_of_div_of_gcd_eq_one h h₁ }, have h0 := add_order_of_nsmul_eq_zero (k : add_circle p), rw [hk, ← coe_nsmul, coe_eq_zero_iff] at h0, obtain ⟨a, ha⟩ := h0, have h0 : (_ : 𝕜) ≠ 0 := nat.cast_ne_zero.2 h.ne', rw [nsmul_eq_mul, mul_comm, ← div_eq_iff h0, ← a.div_add_mod' n, add_smul, add_div, zsmul_eq_mul, int.cast_mul, int.cast_coe_nat, mul_assoc, ← mul_div, mul_comm _ p, mul_div_cancel p h0] at ha, have han : _ = a % n := int.to_nat_of_nonneg (int.mod_nonneg _ $ by exact_mod_cast h.ne'), have he := _, refine ⟨(a % n).to_nat, _, _, he⟩, { rw [← int.coe_nat_lt, han], exact int.mod_lt_of_pos _ (int.coe_nat_lt.2 h) }, { have := (gcd_mul_add_order_of_div_eq p _ h).trans ((congr_arg add_order_of he).trans hk).symm, rw [he, nat.mul_left_eq_self_iff] at this, { exact this }, { rwa hk } }, convert congr_arg coe ha using 1, rw [coe_add, ← int.cast_coe_nat, han, zsmul_eq_mul, mul_div_right_comm, eq_comm, add_left_eq_self, ← zsmul_eq_mul, coe_zsmul, coe_period, smul_zero], end lemma exists_gcd_eq_one_of_is_of_fin_add_order {u : add_circle p} (h : is_of_fin_add_order u) : ∃ m : ℕ, m.gcd (add_order_of u) = 1 ∧ m < (add_order_of u) ∧ ↑(((m : 𝕜) / add_order_of u) * p) = u := let ⟨m, hl, hg, he⟩ := (add_order_of_eq_pos_iff $ add_order_of_pos' h).1 rfl in ⟨m, hg, hl, he⟩ variables (p) /-- The natural bijection between points of order `n` and natural numbers less than and coprime to `n`. The inverse of the map sends `m ↦ (m/n * p : add_circle p)` where `m` is coprime to `n` and satisfies `0 ≤ m < n`. -/ def set_add_order_of_equiv {n : ℕ} (hn : 0 < n) : {u : add_circle p | add_order_of u = n} ≃ {m | m < n ∧ m.gcd n = 1} := equiv.symm $ equiv.of_bijective (λ m, ⟨↑((m : 𝕜) / n * p), add_order_of_div_of_gcd_eq_one hn (m.prop.2)⟩) begin refine ⟨λ m₁ m₂ h, subtype.ext _, λ u, _⟩, { simp_rw [subtype.ext_iff, subtype.coe_mk] at h, rw [← sub_eq_zero, ← coe_sub, ← sub_mul, ← sub_div, coe_coe, coe_coe, ← int.cast_coe_nat m₁, ← int.cast_coe_nat m₂, ← int.cast_sub, coe_eq_zero_iff] at h, obtain ⟨m, hm⟩ := h, rw [← mul_div_right_comm, eq_div_iff, mul_comm, ← zsmul_eq_mul, mul_smul_comm, ← nsmul_eq_mul, ← coe_nat_zsmul, smul_smul, (zsmul_strict_mono_left hp.out).injective.eq_iff, mul_comm] at hm, swap, { exact nat.cast_ne_zero.2 hn.ne' }, rw [← @nat.cast_inj ℤ, ← sub_eq_zero], refine int.eq_zero_of_abs_lt_dvd ⟨_, hm.symm⟩ (abs_sub_lt_iff.2 ⟨_, _⟩); apply (int.sub_le_self _ $ nat.cast_nonneg _).trans_lt (nat.cast_lt.2 _), exacts [m₁.2.1, m₂.2.1] }, obtain ⟨m, hmn, hg, he⟩ := (add_order_of_eq_pos_iff hn).mp u.2, exact ⟨⟨m, hmn, hg⟩, subtype.ext he⟩, end @[simp] lemma card_add_order_of_eq_totient {n : ℕ} : nat.card {u : add_circle p // add_order_of u = n} = n.totient := begin rcases n.eq_zero_or_pos with rfl | hn, { simp only [nat.totient_zero, add_order_of_eq_zero_iff], rcases em (∃ (u : add_circle p), ¬ is_of_fin_add_order u) with ⟨u, hu⟩ | h, { haveI : infinite {u : add_circle p // ¬is_of_fin_add_order u}, { erw infinite_coe_iff, exact infinite_not_is_of_fin_add_order hu, }, exact nat.card_eq_zero_of_infinite, }, { haveI : is_empty {u : add_circle p // ¬is_of_fin_add_order u}, { simpa using h, }, exact nat.card_of_is_empty, }, }, { rw [← coe_set_of, nat.card_congr (set_add_order_of_equiv p hn), n.totient_eq_card_lt_and_coprime], simp only [nat.gcd_comm], }, end lemma finite_set_of_add_order_eq {n : ℕ} (hn : 0 < n) : {u : add_circle p | add_order_of u = n}.finite := finite_coe_iff.mp $ nat.finite_of_card_ne_zero $ by simpa only [coe_set_of, card_add_order_of_eq_totient p] using (nat.totient_pos hn).ne' end finite_order_points end linear_ordered_field variables (p : ℝ) /-- The "additive circle" `ℝ ⧸ (ℤ ∙ p)` is compact. -/ instance compact_space [fact (0 < p)] : compact_space $ add_circle p := begin rw [← is_compact_univ_iff, ← coe_image_Icc_eq p 0], exact is_compact_Icc.image (add_circle.continuous_mk' p), end /-- The action on `ℝ` by right multiplication of its the subgroup `zmultiples p` (the multiples of `p:ℝ`) is properly discontinuous. -/ instance : properly_discontinuous_vadd (zmultiples p).opposite ℝ := (zmultiples p).properly_discontinuous_vadd_opposite_of_tendsto_cofinite (add_subgroup.tendsto_zmultiples_subtype_cofinite p) /-- The "additive circle" `ℝ ⧸ (ℤ ∙ p)` is Hausdorff. -/ instance : t2_space (add_circle p) := t2_space_of_properly_discontinuous_vadd_of_t2_space /-- The "additive circle" `ℝ ⧸ (ℤ ∙ p)` is normal. -/ instance [fact (0 < p)] : normal_space (add_circle p) := normal_of_compact_t2 /-- The "additive circle" `ℝ ⧸ (ℤ ∙ p)` is second-countable. -/ instance : second_countable_topology (add_circle p) := quotient_add_group.second_countable_topology end add_circle local attribute [instance] real.fact_zero_lt_one /-- The unit circle `ℝ ⧸ ℤ`. -/ @[derive [compact_space, normal_space, second_countable_topology]] abbreviation unit_add_circle := add_circle (1 : ℝ) section identify_Icc_ends /-! This section proves that for any `a`, the natural map from `[a, a + p] ⊂ 𝕜` to `add_circle p` gives an identification of `add_circle p`, as a topological space, with the quotient of `[a, a + p]` by the equivalence relation identifying the endpoints. -/ namespace add_circle variables [linear_ordered_add_comm_group 𝕜] [topological_space 𝕜] [order_topology 𝕜] (p a : 𝕜) [hp : fact (0 < p)] include hp local notation `𝕋` := add_circle p /-- The relation identifying the endpoints of `Icc a (a + p)`. -/ inductive endpoint_ident : Icc a (a + p) → Icc a (a + p) → Prop | mk : endpoint_ident ⟨a, left_mem_Icc.mpr $ le_add_of_nonneg_right hp.out.le⟩ ⟨a + p, right_mem_Icc.mpr $ le_add_of_nonneg_right hp.out.le⟩ variables [archimedean 𝕜] /-- The equivalence between `add_circle p` and the quotient of `[a, a + p]` by the relation identifying the endpoints. -/ def equiv_Icc_quot : 𝕋 ≃ quot (endpoint_ident p a) := { to_fun := λ x, quot.mk _ $ inclusion Ico_subset_Icc_self (equiv_Ico _ _ x), inv_fun := λ x, quot.lift_on x coe $ by { rintro _ _ ⟨_⟩, exact (coe_add_period p a).symm }, left_inv := (equiv_Ico p a).symm_apply_apply, right_inv := quot.ind $ by { rintro ⟨x, hx⟩, have := _, rcases ne_or_eq x (a + p) with h | rfl, { revert x, exact this }, { rw ← quot.sound endpoint_ident.mk, exact this _ _ (lt_add_of_pos_right a hp.out).ne }, intros x hx h, congr, ext1, apply congr_arg subtype.val ((equiv_Ico p a).right_inv ⟨x, hx.1, hx.2.lt_of_ne h⟩) } } lemma equiv_Icc_quot_comp_mk_eq_to_Ico_mod : equiv_Icc_quot p a ∘ quotient.mk' = λ x, quot.mk _ ⟨to_Ico_mod hp.out a x, Ico_subset_Icc_self $ to_Ico_mod_mem_Ico _ _ x⟩ := rfl lemma equiv_Icc_quot_comp_mk_eq_to_Ioc_mod : equiv_Icc_quot p a ∘ quotient.mk' = λ x, quot.mk _ ⟨to_Ioc_mod hp.out a x, Ioc_subset_Icc_self $ to_Ioc_mod_mem_Ioc _ _ x⟩ := begin rw equiv_Icc_quot_comp_mk_eq_to_Ico_mod, funext, by_cases a ≡ x [PMOD p], { simp_rw [(modeq_iff_to_Ico_mod_eq_left hp.out).1 h, (modeq_iff_to_Ioc_mod_eq_right hp.out).1 h], exact quot.sound endpoint_ident.mk }, { simp_rw (not_modeq_iff_to_Ico_mod_eq_to_Ioc_mod hp.out).1 h } end /-- The natural map from `[a, a + p] ⊂ 𝕜` with endpoints identified to `𝕜 / ℤ • p`, as a homeomorphism of topological spaces. -/ def homeo_Icc_quot : 𝕋 ≃ₜ quot (endpoint_ident p a) := { to_equiv := equiv_Icc_quot p a, continuous_to_fun := begin simp_rw [quotient_map_quotient_mk.continuous_iff, continuous_iff_continuous_at, continuous_at_iff_continuous_left_right], intro x, split, work_on_goal 1 { erw equiv_Icc_quot_comp_mk_eq_to_Ioc_mod }, work_on_goal 2 { erw equiv_Icc_quot_comp_mk_eq_to_Ico_mod }, all_goals { apply continuous_quot_mk.continuous_at.comp_continuous_within_at, rw inducing_coe.continuous_within_at_iff }, { apply continuous_left_to_Ioc_mod }, { apply continuous_right_to_Ico_mod }, end, continuous_inv_fun := continuous_quot_lift _ ((add_circle.continuous_mk' p).comp continuous_subtype_coe) } /-! We now show that a continuous function on `[a, a + p]` satisfying `f a = f (a + p)` is the pullback of a continuous function on `add_circle p`. -/ variables {p a} lemma lift_Ico_eq_lift_Icc {f : 𝕜 → B} (h : f a = f (a + p)) : lift_Ico p a f = quot.lift (restrict (Icc a $ a + p) f) (by { rintro _ _ ⟨_⟩, exact h }) ∘ equiv_Icc_quot p a := rfl lemma lift_Ico_continuous [topological_space B] {f : 𝕜 → B} (hf : f a = f (a + p)) (hc : continuous_on f $ Icc a (a + p)) : continuous (lift_Ico p a f) := begin rw lift_Ico_eq_lift_Icc hf, refine continuous.comp _ (homeo_Icc_quot p a).continuous_to_fun, exact continuous_coinduced_dom.mpr (continuous_on_iff_continuous_restrict.mp hc), end section zero_based lemma lift_Ico_zero_coe_apply {f : 𝕜 → B} {x : 𝕜} (hx : x ∈ Ico 0 p) : lift_Ico p 0 f ↑x = f x := lift_Ico_coe_apply (by rwa zero_add) lemma lift_Ico_zero_continuous [topological_space B] {f : 𝕜 → B} (hf : f 0 = f p) (hc : continuous_on f $ Icc 0 p) : continuous (lift_Ico p 0 f) := lift_Ico_continuous (by rwa zero_add : f 0 = f (0 + p)) (by rwa zero_add) end zero_based end add_circle end identify_Icc_ends
594af493ccf56ff595dc9f6b8df8d9884205154d
b186c784450e8bcbcf835ab3f10fa7e73f27bc2e
/chapter_4.lean
3f25ecd0bd560db721be60b21019b31218a7a3fe
[]
no_license
esclear/Learning-Lean
9780a0efe769e275992cf3ab4ebf55809ec53b48
d81d5c4743b94c96d8f1bb135e1f13a1d99b3154
refs/heads/master
1,593,312,896,806
1,565,904,243,000
1,565,904,243,000
200,125,941
0
0
null
null
null
null
UTF-8
Lean
false
false
4,501
lean
open classical variables (α : Type) (p q : α → Prop) variable r : Prop -- Exercise 1 example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro (assume h : ∀ x, p x ∧ q x, and.intro (assume x, (h x).left) (assume x, (h x).right)) (assume h : (∀ x, p x) ∧ (∀ x, q x), assume x, show p x ∧ q x, from and.intro (h.left x) (h.right x)) example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := assume hi : ∀ x, p x → q x, assume hp : ∀ x, p x, assume x, have hp : p x, from hp x, (hi x) hp example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := assume h : (∀ x, p x) ∨ (∀ x, q x), h.elim (assume hp : ∀ x, p x, assume x, or.inl (hp x)) (assume hq : ∀ x, q x, assume x, or.inr (hq x)) -- Exercise 2 example : α → ((∀ x : α, r) ↔ r) := assume hα, iff.intro (assume h : ∀ x : α, r, h hα) (assume hr : r, assume x : α, hr) example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := iff.intro (assume h : (∀ x, p x ∨ r), by_cases (assume hr : r, or.inr hr) (assume hnr : ¬r, have hfpx : ∀ x, p x, from ( assume x, have ho : p x ∨ r, from h x, have hpx : p x, from ((h x).elim (assume hpx : p x, hpx) (assume hr : r, absurd hr hnr)), hpx), or.inl hfpx)) (assume h : (∀ x, p x) ∨ r, h.elim (assume hf : ∀ x, p x, assume x, show p x ∨ r, from or.inl (hf x)) (assume hr : r, assume x, show p x ∨ r, from or.inr hr)) example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := iff.intro (assume h : ∀ x, r → p x, assume hr : r, assume x, (h x) hr) (assume h : r → ∀ x, p x, assume x, assume hr : r, (h hr) x) -- Exercise 3 variables (men : Type) (barber : men) variable (shaves : men → men → Prop) example (h : ∀ x : men, shaves barber x ↔ ¬ shaves x x) : false := have hab : shaves barber barber ↔ ¬ shaves barber barber, from h barber, have hnsbb : ¬ shaves barber barber, from ( assume hsbb : shaves barber barber, absurd hsbb (hab.elim_left hsbb) ), absurd (hab.elim_right hnsbb) hnsbb -- Exercise 4 namespace hidden def divides (m n : ℕ) : Prop := ∃ k, m * k = n instance : has_dvd nat := ⟨divides⟩ def even (n : ℕ) : Prop := 2 ∣ n section variables m n : ℕ def prime (n : ℕ) : Prop := ∀ r : ℕ, (r ∣ n) → (r = 1 ∨ r = n) def infinitely_many_primes : Prop := ∀ n : ℕ, ∃ q : ℕ, q > n ∧ prime q def Fermat_prime (n : ℕ) : Prop := prime n ∧ ∃ k : ℕ, n = 2 ^ (2 ^ k) def infinitely_many_Fermat_primes : Prop := ∀ n : ℕ, ∃ q : ℕ, q > n ∧ Fermat_prime q def goldbach_conjecture : Prop := ∀ k : ℕ, even k → ∃ (m n : ℕ), prime m ∧ prime n ∧ k = m + n def Goldbach's_weak_conjecture : Prop := ∀ k : ℕ, k > 5 ∧ ¬(even k) → ∃ (l m n : ℕ), prime l ∧ prime m ∧ prime n ∧ k = l + m + n def Fermat's_last_theorem : Prop := ¬ (∃ (a b c n : ℕ), a > 0 ∧ b > 0 ∧ c > 0 ∧ n > 2 ∧ a^n + b^n = c^n) end end hidden -- Exercise 5 -- see existential_quantifier.lean -- Exercise 6 variables (real : Type) [ordered_ring real] variables (log exp : real → real) variable log_exp_eq : ∀ x, log (exp x) = x variable exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x variable exp_pos : ∀ x, exp x > 0 variable exp_add : ∀ x y, exp (x + y) = exp x * exp y -- this ensures the assumptions are available in tactic proofs include log_exp_eq exp_log_eq exp_pos exp_add theorem log_mul {x y : real} (hx : x > 0) (hy : y > 0) : log (x * y) = log x + log y := calc log(x * y) = log(exp (log x) * exp (log y)) : by rw [←eq.symm (exp_log_eq hx), ←eq.symm (exp_log_eq hy)] ... = log(exp (log x + log y)) : by rw [exp_add (log x) (log y)] ... = log x + log y : by rw [log_exp_eq] -- Exercise 7 example (x : ℤ) : x * 0 = 0 := calc x * 0 = x * (1 - 1) : by rw sub_self ... = x * 1 - x * 1 : by rw mul_sub ... = x - x : by rw mul_one -- Could be skipped ... = 0 : by rw sub_self
6eb7359bfdffaba82e614fd5b79b824f4c0195ee
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/category_theory/action.lean
adb99c81d2c849bdcabcc66d583c45eaa8b3f4c8
[ "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
3,195
lean
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import category_theory.elements import category_theory.single_obj import group_theory.group_action.basic /-! # Actions as functors and as categories From a multiplicative action M ↻ X, we can construct a functor from M to the category of types, mapping the single object of M to X and an element `m : M` to map `X → X` given by multiplication by `m`. This functor induces a category structure on X -- a special case of the category of elements. A morphism `x ⟶ y` in this category is simply a scalar `m : M` such that `m • x = y`. In the case where M is a group, this category is a groupoid -- the `action groupoid'. -/ open mul_action namespace category_theory universes u variables (M : Type*) [monoid M] (X : Type u) [mul_action M X] /-- A multiplicative action M ↻ X viewed as a functor mapping the single object of M to X and an element `m : M` to the map `X → X` given by multiplication by `m`. -/ @[simps] def action_as_functor : single_obj M ⥤ Type u := { obj := λ _, X, map := λ _ _, (•), map_id' := λ _, funext $ mul_action.one_smul, map_comp' := λ _ _ _ f g, funext $ λ x, (smul_smul g f x).symm } /-- A multiplicative action M ↻ X induces a category strucure on X, where a morphism from x to y is a scalar taking x to y. Due to implementation details, the object type of this category is not equal to X, but is in bijection with X. -/ @[derive category] def action_category := (action_as_functor M X).elements namespace action_category noncomputable instance (G : Type*) [group G] [mul_action G X] : groupoid (action_category G X) := category_theory.groupoid_of_elements _ /-- The projection from the action category to the monoid, mapping a morphism to its label. -/ def π : action_category M X ⥤ single_obj M := category_of_elements.π _ @[simp] lemma π_map (p q : action_category M X) (f : p ⟶ q) : (π M X).map f = f.val := rfl @[simp] lemma π_obj (p : action_category M X) : (π M X).obj p = single_obj.star M := @subsingleton.elim unit _ _ _ /-- An object of the action category given by M ↻ X corresponds to an element of X. -/ def obj_equiv : X ≃ action_category M X := { to_fun := λ x, ⟨single_obj.star M, x⟩, inv_fun := λ p, p.2, left_inv := by tidy, right_inv := by tidy } lemma hom_as_subtype (p q : action_category M X) : (p ⟶ q) = { m : M // m • (obj_equiv M X).symm p = (obj_equiv M X).symm q } := rfl instance [inhabited X] : inhabited (action_category M X) := { default := obj_equiv M X (default X) } variables {X} (x : X) /-- The stabilizer of a point is isomorphic to the endomorphism monoid at the corresponding point. In fact they are definitionally equivalent. -/ def stabilizer_iso_End : stabilizer.submonoid M x ≃* End (obj_equiv M X x) := mul_equiv.refl _ @[simp] lemma stabilizer_iso_End_apply (f : stabilizer.submonoid M x) : (stabilizer_iso_End M x).to_fun f = f := rfl @[simp] lemma stabilizer_iso_End_symm_apply (f : End _) : (stabilizer_iso_End M x).inv_fun f = f := rfl end action_category end category_theory
38c4ed31e398c0db5b386688d0fab22cf5074fe5
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/topology/algebra/module.lean
87b55ce5bbcbb3afc3d6b41a1df9e16f154f09c7
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
9,731
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo Theory of topological modules and continuous linear maps. -/ import topology.algebra.ring linear_algebra.basic ring_theory.algebra open topological_space universes u v w u' /-- A topological semimodule, over a semiring which is also a topological space, is a semimodule in which scalar multiplication is continuous. In applications, α will be a topological semiring and β a topological additive semigroup, but this is not needed for the definition -/ class topological_semimodule (α : Type u) (β : Type v) [semiring α] [topological_space α] [topological_space β] [add_comm_monoid β] [semimodule α β] : Prop := (continuous_smul : continuous (λp : α × β, p.1 • p.2)) section variables {α : Type u} {β : Type v} [semiring α] [topological_space α] [topological_space β] [add_comm_monoid β] [semimodule α β] [topological_semimodule α β] lemma continuous_smul' : continuous (λp:α×β, p.1 • p.2) := topological_semimodule.continuous_smul α β lemma continuous_smul {γ : Type*} [topological_space γ] {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λp, f p • g p) := continuous_smul'.comp (hf.prod_mk hg) end /-- A topological module, over a ring which is also a topological space, is a module in which scalar multiplication is continuous. In applications, α will be a topological ring and β a topological additive group, but this is not needed for the definition -/ class topological_module (α : Type u) (β : Type v) [ring α] [topological_space α] [topological_space β] [add_comm_group β] [module α β] extends topological_semimodule α β : Prop /-- A topological vector space is a topological module over a field. -/ class topological_vector_space (α : Type u) (β : Type v) [discrete_field α] [topological_space α] [topological_space β] [add_comm_group β] [vector_space α β] extends topological_module α β /-- Continuous linear maps between modules. We only put the type classes that are necessary for the definition, although in applications β and γ will be topological modules over the topological ring α -/ structure continuous_linear_map (α : Type*) [ring α] (β : Type*) [topological_space β] [add_comm_group β] (γ : Type*) [topological_space γ] [add_comm_group γ] [module α β] [module α γ] extends linear_map α β γ := (cont : continuous to_fun) notation β ` →L[`:25 α `] ` γ := continuous_linear_map α β γ namespace continuous_linear_map section general_ring /- Properties that hold for non-necessarily commutative rings. -/ variables {α : Type*} [ring α] {β : Type*} [topological_space β] [add_comm_group β] {γ : Type*} [topological_space γ] [add_comm_group γ] {δ : Type*} [topological_space δ] [add_comm_group δ] [module α β] [module α γ] [module α δ] /-- Coerce continuous linear maps to linear maps. -/ instance : has_coe (β →L[α] γ) (β →ₗ[α] γ) := ⟨to_linear_map⟩ protected lemma continuous (f : β →L[α] γ) : continuous f := f.2 /-- Coerce continuous linear maps to functions. -/ instance to_fun : has_coe_to_fun $ β →L[α] γ := ⟨_, λ f, f.to_fun⟩ @[extensionality] theorem ext {f g : β →L[α] γ} (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr' 1; ext x; apply h theorem ext_iff {f g : β →L[α] γ} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, by rw h, by ext⟩ variables (c : α) (f g : β →L[α] γ) (h : γ →L[α] δ) (x y z : β) -- make some straightforward lemmas available to `simp`. @[simp] lemma map_zero : f (0 : β) = 0 := (to_linear_map _).map_zero @[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _ @[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _ @[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _ @[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _ @[simp, squash_cast] lemma coe_coe : ((f : β →ₗ[α] γ) : (β → γ)) = (f : β → γ) := rfl /-- The continuous map that is constantly zero. -/ def zero : β →L[α] γ := ⟨0, by exact continuous_const⟩ instance: has_zero (β →L[α] γ) := ⟨zero⟩ @[simp] lemma zero_apply : (0 : β →L[α] γ) x = 0 := rfl @[simp, elim_cast] lemma coe_zero : ((0 : β →L[α] γ) : β →ₗ[α] γ) = 0 := rfl /- no simp attribute on the next line as simp does not always simplify 0 x to x when 0 is the zero function, while it does for the zero continuous linear map, and this is the most important property we care about. -/ @[elim_cast] lemma coe_zero' : ((0 : β →L[α] γ) : β → γ) = 0 := rfl /-- the identity map as a continuous linear map. -/ def id : β →L[α] β := ⟨linear_map.id, continuous_id⟩ instance : has_one (β →L[α] β) := ⟨id⟩ @[simp] lemma id_apply : (id : β →L[α] β) x = x := rfl @[simp, elim_cast] lemma coe_id : ((id : β →L[α] β) : β →ₗ[α] β) = linear_map.id := rfl @[simp, elim_cast] lemma coe_id' : ((id : β →L[α] β) : β → β) = _root_.id := rfl section add variables [topological_add_group γ] instance : has_add (β →L[α] γ) := ⟨λ f g, ⟨f + g, continuous_add f.2 g.2⟩⟩ @[simp] lemma add_apply : (f + g) x = f x + g x := rfl @[simp, move_cast] lemma coe_add : (((f + g) : β →L[α] γ) : β →ₗ[α] γ) = (f : β →ₗ[α] γ) + g := rfl @[move_cast] lemma coe_add' : (((f + g) : β →L[α] γ) : β → γ) = (f : β → γ) + g := rfl instance : has_neg (β →L[α] γ) := ⟨λ f, ⟨-f, continuous_neg f.2⟩⟩ @[simp] lemma neg_apply : (-f) x = - (f x) := rfl @[simp, move_cast] lemma coe_neg : (((-f) : β →L[α] γ) : β →ₗ[α] γ) = -(f : β →ₗ[α] γ) := rfl @[move_cast] lemma coe_neg' : (((-f) : β →L[α] γ) : β → γ) = -(f : β → γ) := rfl instance : add_comm_group (β →L[α] γ) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp @[simp] lemma sub_apply (x : β) : (f - g) x = f x - g x := rfl @[simp, move_cast] lemma coe_sub : (((f - g) : β →L[α] γ) : β →ₗ[α] γ) = (f : β →ₗ[α] γ) - g := rfl @[simp, move_cast] lemma coe_sub' : (((f - g) : β →L[α] γ) : β → γ) = (f : β → γ) - g := rfl end add /-- Composition of bounded linear maps. -/ def comp (g : γ →L[α] δ) (f : β →L[α] γ) : β →L[α] δ := ⟨linear_map.comp g.to_linear_map f.to_linear_map, g.2.comp f.2⟩ @[simp, move_cast] lemma coe_comp : ((h.comp f) : (β →ₗ[α] δ)) = (h : γ →ₗ[α] δ).comp f := rfl @[simp, move_cast] lemma coe_comp' : ((h.comp f) : (β → δ)) = (h : γ → δ) ∘ f := rfl instance : has_mul (β →L[α] β) := ⟨comp⟩ instance [topological_add_group β] : ring (β →L[α] β) := { mul := (*), one := 1, mul_one := λ _, ext $ λ _, rfl, one_mul := λ _, ext $ λ _, rfl, mul_assoc := λ _ _ _, ext $ λ _, rfl, left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _, right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _, ..continuous_linear_map.add_comm_group } /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ def prod (f₁ : β →L[α] γ) (f₂ : β →L[α] δ) : β →L[α] (γ × δ) := { cont := continuous.prod_mk f₁.2 f₂.2, ..f₁.to_linear_map.prod f₂.to_linear_map } end general_ring section comm_ring variables {α : Type*} [comm_ring α] [topological_space α] {β : Type*} [topological_space β] [add_comm_group β] {γ : Type*} [topological_space γ] [add_comm_group γ] [module α β] [module α γ] [topological_module α γ] instance : has_scalar α (β →L[α] γ) := ⟨λ c f, ⟨c • f, continuous_smul continuous_const f.2⟩⟩ variables (c : α) (f g : β →L[α] γ) (x y z : β) @[simp] lemma smul_apply : (c • f) x = c • (f x) := rfl @[simp, move_cast] lemma coe_apply : (((c • f) : β →L[α] γ) : β →ₗ[α] γ) = c • (f : β →ₗ[α] γ) := rfl @[move_cast] lemma coe_apply' : (((c • f) : β →L[α] γ) : β → γ) = c • (f : β → γ) := rfl /-- Associating to a scalar-valued linear map and an element of `γ` the `γ`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `γ`) -/ def smul_right (c : β →L[α] α) (f : γ) : β →L[α] γ := { cont := continuous_smul c.2 continuous_const, ..c.to_linear_map.smul_right f } variable [topological_add_group γ] instance : module α (β →L[α] γ) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } set_option class.instance_max_depth 55 instance : is_ring_hom (λ c : α, c • (1 : γ →L[α] γ)) := { map_one := one_smul _ _, map_add := λ _ _, ext $ λ _, add_smul _ _ _, map_mul := λ _ _, ext $ λ _, mul_smul _ _ _ } instance : algebra α (γ →L[α] γ) := { to_fun := λ c, c • 1, smul_def' := λ _ _, rfl, commutes' := λ _ _, ext $ λ _, map_smul _ _ _ } end comm_ring section field variables {α : Type*} [discrete_field α] [topological_space α] {β : Type*} [topological_space β] [add_comm_group β] {γ : Type*} [topological_space γ] [add_comm_group γ] [topological_add_group γ] [vector_space α β] [vector_space α γ] [topological_vector_space α γ] instance : vector_space α (β →L[α] γ) := { ..continuous_linear_map.module } end field end continuous_linear_map
76c07cb3cd97a7e9c168090e931ebe17a2765b0b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Data/Name.lean
b97a9599695812caf211981473edd4636f71f5ca
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
4,257
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ namespace Lean instance : Coe String Name := ⟨Name.mkSimple⟩ namespace Name -- Remark: we export the `Name.hash` to make sure it matches the hash implemented in C++ @[export lean_name_hash_exported] def hashEx : Name → UInt64 := Name.hash def getPrefix : Name → Name | anonymous => anonymous | str p _ => p | num p _ => p def getString! : Name → String | str _ s => s | _ => unreachable! def getNumParts : Name → Nat | anonymous => 0 | str p _ => getNumParts p + 1 | num p _ => getNumParts p + 1 def updatePrefix : Name → Name → Name | anonymous, _ => anonymous | str _ s, newP => Name.mkStr newP s | num _ s, newP => Name.mkNum newP s def componentsRev : Name → List Name | anonymous => [] | str n s => Name.mkStr anonymous s :: componentsRev n | num n v => Name.mkNum anonymous v :: componentsRev n def components (n : Name) : List Name := n.componentsRev.reverse def eqStr : Name → String → Bool | str anonymous s, s' => s == s' | _, _ => false def isPrefixOf : Name → Name → Bool | p, anonymous => p == anonymous | p, n@(num p' _) => p == n || isPrefixOf p p' | p, n@(str p' _) => p == n || isPrefixOf p p' def isSuffixOf : Name → Name → Bool | anonymous, _ => true | str p₁ s₁, str p₂ s₂ => s₁ == s₂ && isSuffixOf p₁ p₂ | num p₁ n₁, num p₂ n₂ => n₁ == n₂ && isSuffixOf p₁ p₂ | _, _ => false def cmp : Name → Name → Ordering | anonymous, anonymous => Ordering.eq | anonymous, _ => Ordering.lt | _, anonymous => Ordering.gt | num p₁ i₁, num p₂ i₂ => match cmp p₁ p₂ with | Ordering.eq => compare i₁ i₂ | ord => ord | num _ _, str _ _ => Ordering.lt | str _ _, num _ _ => Ordering.gt | str p₁ n₁, str p₂ n₂ => match cmp p₁ p₂ with | Ordering.eq => compare n₁ n₂ | ord => ord def lt (x y : Name) : Bool := cmp x y == Ordering.lt def quickCmpAux : Name → Name → Ordering | anonymous, anonymous => Ordering.eq | anonymous, _ => Ordering.lt | _, anonymous => Ordering.gt | num n v, num n' v' => match compare v v' with | Ordering.eq => n.quickCmpAux n' | ord => ord | num _ _, str _ _ => Ordering.lt | str _ _, num _ _ => Ordering.gt | str n s, str n' s' => match compare s s' with | Ordering.eq => n.quickCmpAux n' | ord => ord def quickCmp (n₁ n₂ : Name) : Ordering := match compare n₁.hash n₂.hash with | Ordering.eq => quickCmpAux n₁ n₂ | ord => ord def quickLt (n₁ n₂ : Name) : Bool := quickCmp n₁ n₂ == Ordering.lt /-- The frontend does not allow user declarations to start with `_` in any of its parts. We use name parts starting with `_` internally to create auxiliary names (e.g., `_private`). -/ def isInternal : Name → Bool | str p s => s.get 0 == '_' || isInternal p | num p _ => isInternal p | _ => false /-- Checks whether the name is an implementation-detail hypothesis name. Implementation-detail hypothesis names start with a double underscore. -/ def isImplementationDetail : Name → Bool | str anonymous s => s.startsWith "__" | num p _ => p.isImplementationDetail | str p _ => p.isImplementationDetail | anonymous => false def isAtomic : Name → Bool | anonymous => true | str anonymous _ => true | num anonymous _ => true | _ => false def isAnonymous : Name → Bool | anonymous => true | _ => false def isStr : Name → Bool | str .. => true | _ => false def isNum : Name → Bool | num .. => true | _ => false /-- Return `true` if `n` contains a string part `s` that satifies `f`. Examples: ``` #eval (`foo.bla).anyS (·.startsWith "fo") -- true #eval (`foo.bla).anyS (·.startsWith "boo") -- false ``` -/ def anyS (n : Name) (f : String → Bool) : Bool := match n with | .str p s => f s || p.anyS f | .num p _ => p.anyS f | _ => false end Name end Lean open Lean
6c602d9eea7e366796bdb9ff9b2fb5f4b9f22856
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/closed/monoidal.lean
4982d2700a805f93bc387a3334784114f7a0d4f6
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
1,662
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.category import category_theory.adjunction.basic /-! # Closed monoidal categories Define (right) closed objects and (right) closed monoidal categories. ## TODO Some of the theorems proved about cartesian closed categories should be generalised and moved to this file. -/ universes v u u₂ namespace category_theory open category monoidal_category /-- An object `X` is (right) closed if `(X ⊗ -)` is a left adjoint. -/ class closed {C : Type u} [category.{v} C] [monoidal_category.{v} C] (X : C) := (is_adj : is_left_adjoint (tensor_left X)) /-- A monoidal category `C` is (right) monoidal closed if every object is (right) closed. -/ class monoidal_closed (C : Type u) [category.{v} C] [monoidal_category.{v} C] := (closed : Π (X : C), closed X) attribute [instance, priority 100] monoidal_closed.closed /-- The unit object is always closed. This isn't an instance because most of the time we'll prove closedness for all objects at once, rather than just for this one. -/ def unit_closed {C : Type u} [category.{v} C] [monoidal_category.{v} C] : closed (𝟙_ C) := { is_adj := { right := 𝟭 C, adj := adjunction.mk_of_hom_equiv { hom_equiv := λ X _, { to_fun := λ a, (left_unitor X).inv ≫ a, inv_fun := λ a, (left_unitor X).hom ≫ a, left_inv := by tidy, right_inv := by tidy }, hom_equiv_naturality_left_symm' := λ X' X Y f g, by { dsimp, rw left_unitor_naturality_assoc } } } } end category_theory
0deaadedc71b01c81043d0a28156597f07f4e53b
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20170201-universes-problem.lean
4cb28e2b31f9b7f218e54343e2019009aeb13af1
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
3,091
lean
universe variables u v u1 u2 v1 v2 set_option pp.universes true open smt_tactic meta def blast : tactic unit := using_smt $ intros >> add_lemmas_from_facts >> repeat_at_most 3 ematch notation `♮` := by blast structure semigroup_morphism { α β : Type u } ( s : semigroup α ) ( t: semigroup β ) := (map: α → β) (multiplicative : ∀ x y : α, map(x * y) = map(x) * map(y)) attribute [simp] semigroup_morphism.multiplicative instance semigroup_morphism_to_map { α β : Type u } { s : semigroup α } { t: semigroup β } : has_coe_to_fun (semigroup_morphism s t) := { F := λ f, Π x : α, β, coe := semigroup_morphism.map } @[reducible] definition semigroup_identity { α : Type u } ( s: semigroup α ) : semigroup_morphism s s := ⟨ id, ♮ ⟩ @[reducible] definition semigroup_morphism_composition { α β γ : Type u } { s: semigroup α } { t: semigroup β } { u: semigroup γ} ( f: semigroup_morphism s t ) ( g: semigroup_morphism t u ) : semigroup_morphism s u := { map := λ x, g (f x), multiplicative := begin blast, simp end } @[reducible] definition semigroup_product { α β : Type u } ( s : semigroup α ) ( t: semigroup β ) : semigroup (α × β) := { mul := λ p q, (p^.fst * q^.fst, p^.snd * q^.snd), mul_assoc := begin intros, simp [@mul.equations._eqn_1 (α × β)], dsimp, simp end } definition semigroup_morphism_product { α β γ δ : Type u } { s_f : semigroup α } { s_g: semigroup β } { t_f : semigroup γ } { t_g: semigroup δ } ( f : semigroup_morphism s_f t_f ) ( g : semigroup_morphism s_g t_g ) : semigroup_morphism (semigroup_product s_f s_g) (semigroup_product t_f t_g) := { map := λ p, (f p.1, g p.2), multiplicative := begin -- cf https://groups.google.com/d/msg/lean-user/bVs5FdjClp4/tfHiVjLIBAAJ intros, unfold mul has_mul.mul, dsimp, simp end } structure Category := (Obj : Type u) (Hom : Obj → Obj → Type v) structure Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) := (onObjects : C^.Obj → D^.Obj) (onMorphisms : Π { X Y : C^.Obj }, C^.Hom X Y → D^.Hom (onObjects X) (onObjects Y)) @[reducible] definition ProductCategory (C : Category) (D : Category) : Category := { Obj := C^.Obj × D^.Obj, Hom := (λ X Y : C^.Obj × D^.Obj, C^.Hom (X^.fst) (Y^.fst) × D^.Hom (X^.snd) (Y^.snd)) } namespace ProductCategory notation C `×` D := ProductCategory C D end ProductCategory structure PreMonoidalCategory extends carrier : Category := (tensor : Functor (carrier × carrier) carrier) definition CategoryOfSemigroups : Category := { Obj := Σ α : Type u, semigroup α, Hom := λ s t, semigroup_morphism s.2 t.2 } definition PreMonoidalCategoryOfSemigroups : PreMonoidalCategory := { CategoryOfSemigroups.{u} with tensor := { onObjects := λ p, sigma.mk (p.1.1 × p.2.1) (semigroup_product p.1.2 p.2.2), onMorphisms := λ s t f, semigroup_morphism_product f.1 f.2 } }
e1f64b5a7230cb968072625ce50d336f7cc58826
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/hello/Hello.lean
99415d9d9fc72e540b7fc4f2e1242b9cfd06814d
[ "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
21
lean
def hello := "world"
bd207bda950ef37ec35235e2b354a84324ca7838
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/group/units.lean
c4b5ed6ce9f9278652057b9006552a9093e6e8a1
[ "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
13,257
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker -/ import algebra.group.basic import logic.nontrivial /-! # Units (i.e., invertible elements) of a multiplicative monoid -/ universe u variable {α : Type u} /-- Units of a monoid, bundled version. An element of a `monoid` is a unit if it has a two-sided inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_unit`. -/ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) /-- Units of an add_monoid, bundled version. An element of an add_monoid is a unit if it has a two-sided additive inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_add_unit`. -/ structure add_units (α : Type u) [add_monoid α] := (val : α) (neg : α) (val_neg : val + neg = 0) (neg_val : neg + val = 0) attribute [to_additive add_units] units namespace units variables [monoid α] @[to_additive] instance : has_coe (units α) α := ⟨val⟩ @[simp, to_additive] lemma coe_mk (a : α) (b h₁ h₂) : ↑(units.mk a b h₁ h₂) = a := rfl @[ext, to_additive] theorem ext : function.injective (coe : units α → α) | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ @[norm_cast, to_additive] theorem eq_iff {a b : units α} : (a : α) = b ↔ a = b := ext.eq_iff @[to_additive] theorem ext_iff {a b : units α} : a = b ↔ (a : α) = b := eq_iff.symm @[to_additive] instance [decidable_eq α] : decidable_eq (units α) := λ a b, decidable_of_iff' _ ext_iff @[simp, to_additive] theorem mk_coe (u : units α) (y h₁ h₂) : mk (u : α) y h₁ h₂ = u := ext rfl /-- Units of a monoid form a group. -/ @[to_additive] instance : group (units α) := { mul := λ u₁ u₂, ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, by rw [mul_assoc, ← mul_assoc u₂.val, val_inv, one_mul, val_inv], by rw [mul_assoc, ← mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩, one := ⟨1, 1, one_mul 1, one_mul 1⟩, mul_one := λ u, ext $ mul_one u, one_mul := λ u, ext $ one_mul u, mul_assoc := λ u₁ u₂ u₃, ext $ mul_assoc u₁ u₂ u₃, inv := λ u, ⟨u.2, u.1, u.4, u.3⟩, mul_left_inv := λ u, ext u.inv_val } variables (a b : units α) {c : units α} @[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : α) = a * b := rfl attribute [norm_cast] add_units.coe_add @[simp, norm_cast, to_additive] lemma coe_one : ((1 : units α) : α) = 1 := rfl attribute [norm_cast] add_units.coe_zero @[simp, norm_cast, to_additive] lemma coe_eq_one {a : units α} : (a : α) = 1 ↔ a = 1 := by rw [←units.coe_one, eq_iff] @[simp, to_additive] lemma inv_mk (x y : α) (h₁ h₂) : (mk x y h₁ h₂)⁻¹ = mk y x h₂ h₁ := rfl @[to_additive] lemma val_coe : (↑a : α) = a.val := rfl @[norm_cast, to_additive] lemma coe_inv : ((a⁻¹ : units α) : α) = a.inv := rfl attribute [norm_cast] add_units.coe_neg @[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[to_additive] lemma inv_mul_of_eq {u : units α} {a : α} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by { rw [←h, u.inv_mul], } @[to_additive] lemma mul_inv_of_eq {u : units α} {a : α} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by { rw [←h, u.mul_inv], } @[simp, to_additive] lemma mul_inv_cancel_left (a : units α) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp, to_additive] lemma inv_mul_cancel_left (a : units α) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp, to_additive] lemma mul_inv_cancel_right (a : α) (b : units α) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp, to_additive] lemma inv_mul_cancel_right (a : α) (b : units α) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] @[to_additive] instance : inhabited (units α) := ⟨1⟩ @[to_additive] instance {α} [comm_monoid α] : comm_group (units α) := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } @[to_additive] instance [has_repr α] : has_repr (units α) := ⟨repr ∘ val⟩ @[simp, to_additive] theorem mul_right_inj (a : units α) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[simp, to_additive] theorem mul_left_inj (a : units α) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : α} : a = b * ↑c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq {a c : α} : a = ↑b⁻¹ * c ↔ ↑b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul {b c : α} : ↑a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul {a c : α} : a * ↑b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ lemma inv_eq_of_mul_eq_one {u : units α} {a : α} (h : ↑u * a = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one ... = ↑u⁻¹ * ↑u * a : by rw [←h, ←mul_assoc] ... = a : by rw [u.inv_mul, one_mul] lemma inv_unique {u₁ u₂ : units α} (h : (↑u₁ : α) = ↑u₂) : (↑u₁⁻¹ : α) = ↑u₂⁻¹ := suffices ↑u₁ * (↑u₂⁻¹ : α) = 1, by exact inv_eq_of_mul_eq_one this, by rw [h, u₂.mul_inv] end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ @[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit out of `a`."] def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : units α := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid α] {a b : α} (h : a * b = 1) : (units.mk_of_mul_eq_one a b h : α) = a := rfl section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : units α) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : units α) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_inv (u : units α) : a /ₚ u⁻¹ = a * u := rfl @[simp] theorem divp_mul_cancel (a : α) (u : units α) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : units α) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_left_inj (u : units α) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_left_inj _ theorem divp_divp_eq_divp_mul (x : α) (u₁ u₂ : units α) : (x /ₚ u₁) /ₚ u₂ = x /ₚ (u₂ * u₁) := by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc] theorem divp_eq_iff_mul_eq {x : α} {u : units α} {y : α} : x /ₚ u = y ↔ y * u = x := u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩ theorem divp_eq_one_iff_eq {a : α} {u : units α} : a /ₚ u = 1 ↔ a = u := (units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : units α) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid section comm_monoid variables [comm_monoid α] theorem divp_eq_divp_iff {x y : α} {ux uy : units α} : x /ₚ ux = y /ₚ uy ↔ x * uy = y * ux := by rw [divp_eq_iff_mul_eq, mul_comm, ← divp_assoc, divp_eq_iff_mul_eq, mul_comm y ux] theorem divp_mul_divp (x y : α) (ux uy : units α) : (x /ₚ ux) * (y /ₚ uy) = (x * y) /ₚ (ux * uy) := by rw [← divp_divp_eq_divp_mul, divp_assoc, mul_comm x, divp_assoc, mul_comm] end comm_monoid /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ section is_unit variables {M : Type*} {N : Type*} /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : units M`, where `units M` is a bundled version of `is_unit`. -/ @[to_additive is_add_unit "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := ∃ u : units M, (u : M) = a @[nontriviality] lemma is_unit_of_subsingleton [monoid M] [subsingleton M] (a : M) : is_unit a := ⟨⟨a, a, subsingleton.elim _ _, subsingleton.elim _ _⟩, rfl⟩ @[simp, to_additive is_add_unit_add_unit] protected lemma units.is_unit [monoid M] (u : units M) : is_unit (u : M) := ⟨u, rfl⟩ @[simp, to_additive is_add_unit_zero] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive is_add_unit_of_add_eq_zero] theorem is_unit_of_mul_eq_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit_iff_exists_neg] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, a * b = 1 := ⟨by rintro ⟨⟨a, b, hab, _⟩, rfl⟩; exact ⟨b, hab⟩, λ ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩ @[to_additive is_add_unit_iff_exists_neg'] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] /-- Multiplication by a `u : units M` doesn't affect `is_unit`. -/ @[simp, to_additive is_add_unit_add_add_units "Addition of a `u : add_units M` doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : units M) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (assume ⟨v, hv⟩, hv ▸ ⟨v * u, (units.coe_mul v u).symm⟩) @[to_additive] lemma is_unit.mul [monoid M] {x y : M} : is_unit x → is_unit y → is_unit (x * y) := by { rintros ⟨x, rfl⟩ ⟨y, rfl⟩, exact ⟨x * y, units.coe_mul _ _⟩ } @[to_additive is_add_unit_of_add_is_add_unit_left] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm @[simp] lemma is_unit.mul_iff [comm_monoid M] {x y : M} : is_unit (x * y) ↔ is_unit x ∧ is_unit y := ⟨λ h, ⟨is_unit_of_mul_is_unit_left h, is_unit_of_mul_is_unit_right h⟩, λ h, is_unit.mul h.1 h.2⟩ @[to_additive] theorem is_unit.mul_right_inj [monoid M] {a b c : M} (ha : is_unit a) : a * b = a * c ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_right_inj] @[to_additive] theorem is_unit.mul_left_inj [monoid M] {a b c : M} (ha : is_unit a) : b * a = c * a ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_left_inj] /-- The element of the group of units, corresponding to an element of a monoid which is a unit. -/ noncomputable def is_unit.unit [monoid M] {a : M} (h : is_unit a) : units M := classical.some h lemma is_unit.unit_spec [monoid M] {a : M} (h : is_unit a) : ↑h.unit = a := classical.some_spec h end is_unit section noncomputable_defs variables {M : Type*} /-- Constructs a `group` structure on a `monoid` consisting only of units. -/ noncomputable def group_of_is_unit [hM : monoid M] (h : ∀ (a : M), is_unit a) : group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } /-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/ noncomputable def comm_group_of_is_unit [hM : comm_monoid M] (h : ∀ (a : M), is_unit a) : comm_group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } end noncomputable_defs
46ae0b9f84670635b187d2db9c246e03dc2971ac
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/logic/axioms/prop_complete.lean
2c1f4a7d1c9b89d7d9565f6e3879ce153123ef7e
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,869
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: logic.axioms.classical Author: Leonardo de Moura -/ import logic.connectives logic.quantifiers logic.cast algebra.relation import logic.axioms.em open eq.ops theorem prop_complete (a : Prop) : a = true ∨ a = false := or.elim (em a) (λ t, or.inl (propext (iff.intro (λ h, trivial) (λ h, t)))) (λ f, or.inr (propext (iff.intro (λ h, absurd h f) (λ h, false.elim h)))) definition eq_true_or_eq_false := prop_complete theorem cases_true_false (P : Prop → Prop) (H1 : P true) (H2 : P false) (a : Prop) : P a := or.elim (prop_complete a) (assume Ht : a = true, Ht⁻¹ ▸ H1) (assume Hf : a = false, Hf⁻¹ ▸ H2) theorem cases_on (a : Prop) {P : Prop → Prop} (H1 : P true) (H2 : P false) : P a := cases_true_false P H1 H2 a -- this supercedes by_cases in decidable definition by_cases {p q : Prop} (Hpq : p → q) (Hnpq : ¬p → q) : q := or.elim (em p) (assume Hp, Hpq Hp) (assume Hnp, Hnpq Hnp) -- this supercedes by_contradiction in decidable theorem by_contradiction {p : Prop} (H : ¬p → false) : p := by_cases (assume H1 : p, H1) (assume H1 : ¬p, false.rec _ (H H1)) theorem eq_false_or_eq_true (a : Prop) : a = false ∨ a = true := cases_true_false (λ x, x = false ∨ x = true) (or.inr rfl) (or.inl rfl) a theorem eq.of_iff {a b : Prop} (H : a ↔ b) : a = b := iff.elim (assume H1 H2, propext (iff.intro H1 H2)) H theorem iff_eq_eq {a b : Prop} : (a ↔ b) = (a = b) := propext (iff.intro (assume H, eq.of_iff H) (assume H, iff.of_eq H)) open relation theorem iff_congruence [instance] (P : Prop → Prop) : is_congruence iff iff P := is_congruence.mk (take (a b : Prop), assume H : a ↔ b, show P a ↔ P b, from iff.of_eq (eq.of_iff H ▸ eq.refl (P a)))
6e9b75d5564a66865a21fe4dfe39025f55fe5666
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/predicate_logic/rules_of_reasoning.lean
6a32a54526ee6b4bd3910af8c0db364df81b9597
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
13,463
lean
/- Today we will see in that proofs can be understood as formal objects in their own right. We will start to make our way through the valid rules of inference from our unit on propositional logic. We will emphasize that they are rules for combining and deriving Boolean truth values. In predicate logic, by contrast, we will reinterpret them as rules for combining and deriving *proofs*. In predicate logic, the existence of a proof is our new basis for deciding whether or not a proposition can be judged to be true. In particular, we will look at how to (1) *construct* and (2) *use* given or assumed proofs of two simple forms of propositions, namely conjunctions and disjunctions. We will see that we can view proofs as *computational* objects. In particular, we will see that we can view a proof of a conjunction, P ∧ Q, as a *pair* of proofs (a proof of P *and* a proof of Q), and thus as a value of a *product* type. We will then view a proof of a disjunction, P ∨ Q, as *either* an object constructed from a proof of P *or* an object built from a proof of Q, and thus a value of a *sum* type. Understanding proof construction and manipulation as computations involving logical types (propositions) and values (proofs) will give you the precise understanding of deductive reasoning in predicate logic that you need to handle a very wide variety of "prove it" problems in the years to come, whether or not (and more likely not) you use an automated proof assistant such as Lean or its formalized proofs. -/ /- To begin we will review our polymorphic product (pair) type. We will then see that the ∧ (and) connective in predicate logic can be understood and formalized as a completely analogous polymorphic *logical* type. It's one costructor implements the and introduction rule, and its two projection functions implement the two and elimination rules. -/ namespace hidden -- review -- prod abstract data type! -- be sure you fully understand this type definition inductive prod (α β : Type) : Type | mk (a : α) (b : β) : prod -- here's a named example of a value of this type def pair1 := prod.mk 1 1 #reduce pair1 -- by the way, we can use "example" for unnamed values example : prod nat nat := prod.mk 1 1 -- the first, or left, projection function -- implemented by pattern matching (aka elimination!) def fst {α β : Type} : prod α β → α | (prod.mk a b) := a -- the second, or right, projection function def snd {α β : Type} : prod α β → β | (prod.mk a b) := b -- and a function that from one pair derives its swap def swap {α β : Type} : prod α β → prod β α | (prod.mk a b) := prod.mk b a /- Our implementation of the and connective and its rules of inference (introduction and elimination rules) in exactly the same way, except that our and polymorphic pair type now lives in "Prop," the unverse of logical types (propositions), rather than in "Type", which as we know is the universe of computational types. As a reminder from propositional logic, here are three rules of reasoning that we showed to be semantically valid. def and_intro := P >> Q >> P ∧ Q def and_elim_left := P ∧ Q >> P def and_elim_right := P ∧ Q >> Q In propositional logic, we read these rules as involving truth values: e.g., if P "is true" and Q "is true" then "P ∧ Q" "is true". We now reconceptualize these rules to involve proofs. E.g., If we have (or assume we have) a proof, p, of P, and we have (or assume we have) a proof, q, of Q, then we can construct a proof, ⟨p, q⟩, of P ∧ Q. That's the and introduction rule. Similarly, if we have a proof (pair!), ⟨p, q⟩, then from it we can derive a proof, p, of P, and a proof, q, of Q, by nothing more complex than projection: we destructure the pair and return one of the other other of its two components. -/ structure and (P Q : Prop) : Prop := -- Prop not Type! intro :: (left : P) (right : Q) -- and.intro rule -- one poassible way to write left elimination rule def and_elim_left {P Q : Prop} : and P Q → P | (and.intro p q) := p -- here's another, with elim_left in the "and" namespace -- note that we use projection function from "structure" def and.elim_left {P Q : Prop} (pq : and P Q) : P := pq.left -- and here is the right elimination rule in two forms def and_elim_right {P Q : Prop} : and P Q → Q | (and.intro p q) := q def and.elim_right {P Q : Prop} (pq : and P Q) : Q := pq.right /- A note on notation. The Lean libraries define the and connective exactly as we've done here. In addition, the Lean library defined ∧ as an infix notation for "and". We won't define that notation here, so wherever we want to use the and connective, e.g., for P ∧ Q, we'll have to write "and P Q". Same with or. -/ -- tests def pf1 : and (1=1) (eq 0 0) := -- 1=1 and 0=0 and.intro (eq.refl 1) (eq.refl 0) -- proof of it! -- We now see that pf1 is basically a pair of proofs #reduce pf1 /- OR We also formalize the logical connective, ∨, as an inductive type with two (logical) type arguments, P and Q (two propositions). The both ∧ and ∨ take two propositions (logical types) as arguments and yield a larger proposition (logical type). We then define constructors to implement the introduction rules for the given connective. To build a proof of P ∧ Q, we need proofs of both P and of Q. To build a proof of P ∨ Q it suffices to have either a proof of P or a proof of Q. Here are the propositional logic rules we validated in the last section. def or_intro_left := P >> P ∨ Q def or_intro_right := Q >> P ∨ Q def or_elim := P ∨ Q >> (P >> R) >> (Q >> R) >> R We now reconceptualize these rules are rules about how *proofs* can be built and derived. -/ #check or inductive or (P Q : Prop) : Prop | inl {} (p : P) : or -- Q is implicit | inr {} (q : Q) : or -- P is implicit -- example, proof of 0=0 ∨ 1=0 example : or (eq 0 0) (eq 1 0) := or.inl (eq.refl 0) #check @or.elim example : or (eq 1 0) (eq 0 0) := or.inr (eq.refl 0) /- Prove that 1=1 and 2=2. Q: What's the form of this proposition? A: Conjunction. Main connective is and. Q: What rule of reasoning apply? A: The "and" introduction and elimination rules. Q: What is the form of the overall proof? A: and.intro p q, where p is a proof of P and q is a proof of Q. Q: So what remains to be done? A: It will now suffice to produce a proof of 1=1 and one of 2=2. Q: How to prove 1=1? A: By the reflexive property of equality. Q: How to prove 2 =2. A: Same way. QED! -/ -- Here it is formally example : and (1=1) (2=2) := and.intro (eq.refl 1) (eq.refl 2) /- The following versions of the introductions rules take two explicit arguments each: a *proposition* for which a proof is *not* given and a proof of the other proposition. Notice carefully the change in which type argument is implicit in each case. Sometimes Lean can't infer from, say, a proof, p, of P, what disjunction, P ∨ Q, is being proved (because it can't figure out what Q is). In such cases, you need to provide the Q type explicitly. These functions are useful in such cases. -/ def or.intro_left {P : Prop} (Q : Prop) (p : P) : or P Q := or.inl p def or.intro_right (P : Prop) {Q : Prop} (q : Q) : or P Q := or.inr q /- Prove 1=0 or 1=1. Proof: We apply the or introduction on the right rule to a proof of 1=1. Now all that remains is to to that 1=1. This is by applying the reflexive property of equality (to the value, 1). -/ -- Here is this proof formalized example : or (1=0) (1=1) := or.inr (eq.refl 1) example : or (1=0) (1=1) := or.intro_right (1=0) (eq.refl 1) def x : ℕ := 1 example : ℕ := 1 /- NEXT UP: ∀, → -/ /- ************************************************************ Universal generalizations. Propositions starting with forall. ************************************************************ -/ /- Introduction rule: To prove "∀ (p : P), Q" show that if you *assume* you're given an arbitrary but specific p, you can construct a proof of Q. This is the ∀ introduction rule of natural deduction. -/ example : ∀ (n : ℕ), or (n = 0) (n ≠ 0) := λ (n : ℕ), match n with | nat.zero := or.inl (eq.refl 0) | (nat.succ _) := _ -- Homework end /- Proof: We start by assuming that we're given an arbitrary but specific natural number, n. Now in this context, all that remains to be proved is that n = 0 or n ≠ 0. -/ /- Prove that for any propositions, P and Q, P ∧ Q → P ∨ Q -/ def aProp := ∀ (P Q : Prop), and P Q → or P Q /- We start by assuming that P and Q are arbitrary but specific propositions. In this context, what remains to be proved is the following implication: and P Q → or P Q. To prove this is to prove an implication. We do this in the same way we prove a ∀: by assuming that we're given a proof of the premise, P, and showing that, in that context, we can construct a proof of the conclusion, Q. -/ lemma and_imp_or_1 : aProp := λ (P Q : Prop), λ (pq : and P Q), or.inl (and.elim_left pq) lemma and_imp_or_2 : aProp := λ (P Q : Prop), λ (pq : and P Q), or.inr (and.elim_right pq) example : and_imp_or_1 = and_imp_or_2 := eq.refl and_imp_or_2 /- Prove that the "and" connective is commutative. -/ theorem and_commutes : ∀ {P Q : Prop}, and P Q → and Q P := λ (P Q : Prop), λ (pq : and P Q), and.intro (pq.right) (pq.left) /- Assume that P and Q are arbitary but specific propositions. We are to show that P ∧ Q → Q ∧ P. Suppose we have a proof, pq, of P ∧ Q. In this context we need to prove that we can construct a proof of Q and P. We do this by applying the and introduction rule to a proof of P and to a proof of Q. What remains to be proven is that there is a proof of P and a proof of Q. But we can get these by applying the left and right and eliminations rules to our proof, pq, of P ∧ Q. -/ /- If a proof of a ∀ or → proposition is a function in Lean, can we apply these functions to arguments to get results? The answer is yes, absolutely, and this idea is in fact the *elimination* rule for ∀ and →. If you're given a proof, pf, of either ∀ (p : P), Q, or of P → Q, which are in fact equivalent(!), then you can apply pf to a proof or value, p : P, to obtain a corresponding value/proof of Q. As an example, let's apply our proof that and is commutative -/ lemma oneeq1_and_2eq2 : and (1=1) (2=2) := and.intro (eq.refl 1) (eq.refl 2) #reduce oneeq1_and_2eq2 /- We now use the elimination rule for ∀/→ by *applying* the *general* proof of commutative of and to a *specific* proof of (and 1=1 2=2) to obtain a specific proof of (and 2=2 1=1)! -/ #reduce and_commutes oneeq1_and_2eq2 /- The *elimination* rule for ∀ all and implication is "apply!" -/ /- This principal is seen very clearly in the proof of the rule of reasoning that Aristotle called "modus ponens." It states that if, for any propositions P and Q, you know that P → Q is true and you also know that P is true then you can conclude that Q is true. If when it's raining the streets are wet (P → Q) and it's raining (P) then it must be the case that the streets are wet (Q). We now prove that this is a valid form of reasoning. -/ theorem arrow_elim : ∀ {P Q : Prop}, (P → Q) → P → Q := λ (P Q : Prop), λ (p2q : P → Q), λ (p : P), p2q p ---<<< apply proof of P→Q to proof of P! /--- TODAY ---/ /- Propositions that use ¬ -/ /- Suppose you want to prove ¬P. We have to show that there's no proof of P. Key strategy: Proof by negation. Assume that P is true, and show that this assumption leads to a contradiction. Equivalent to a proof of false. So the idea is this: assume that there is a proof of P and show that this enables you to construct a proof of false. ¬ P ==== P → false -/ example : 0 ≠ 1 := /- ¬ (0 = 1) -/ /- (0 = 1) → false -/ λ (h : 0 = 1), match h with /- NO CASES! -/ end theorem mt : ∀ {P Q}, (P → Q) → (¬Q → ¬P) := λ P Q, λ (h : P → Q), λ (nq : ¬Q), λ (p : P), nq (h p) theorem non_contradiction: ∀ (P : Prop), ¬ (P ∧ ¬ P) := λ P, -- forall introduction λ (h : P ∧ ¬P), -- proof by negation let p := (h.left) in -- and.elim_left let np := (h.right) in -- and.elim_right (np p) theorem zornz : ∀ (n : ℕ), or (n = 0) (n ≠ 0) := λ (n : ℕ), match n with | nat.zero := or.inl (eq.refl 0) | (nat.succ n') := or.inr _ -- complete this proof end /- Propositions that use ∃ -/ example : ∃ n, n = 0 := exists.intro 0 (eq.refl 0) example : ∃ n, n^2 = 25 := exists.intro 5 rfl example : ∃ x : nat, ∃ y: nat, ∃ z : ℕ, x^2 +y^2 = z^2 := exists.intro 3 (exists.intro 4 (exists.intro 5 (rfl))) /- Propositions that use both ∃ and ∀ -/ /- Still to do: def iff_intro := (P >> Q) >> (Q >> P) >> (P ↔ Q) def iff_intro' := (P >> Q) ∧ (Q >> P) >> (P ↔ Q) def iff_elim_left := (P ↔ Q) >> (P >> Q) def iff_elim_right := (P ↔ Q) >> (Q >> P) def syllogism := (P >> Q) >> (Q >> R) >> (P >> R) def modus_tollens := (P >> Q) >> (¬ Q >> ¬ P) def neg_elim := (¬ ¬ P) >> P -- not a constructive rule def excluded_middle := P ∨ (¬ P) -- not a constructive rule def neg_intro := (P >> pFalse) >> (¬ P) def true_intro : pExp := pTrue def false_elim := pFalse >> P -/ end hidden
d5f9995bf32e900d94c991261022f34282c6af5f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/pointwise_auto.lean
e99a232163ad5606195e26a1a0af15d47f99e5d1
[]
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
18,644
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.module.basic import Mathlib.data.set.finite import Mathlib.group_theory.submonoid.basic import Mathlib.PostPort universes u_1 u_2 u_3 u_4 namespace Mathlib /-! # Pointwise addition, multiplication, and scalar multiplication of sets. This file defines pointwise algebraic operations on sets. * For a type `α` with multiplication, multiplication is defined on `set α` by taking `s * t` to be the set of all `x * y` where `x ∈ s` and `y ∈ t`. Similarly for addition. * For `α` a semigroup, `set α` is a semigroup. * If `α` is a (commutative) monoid, we define an alias `set_semiring α` for `set α`, which then becomes a (commutative) semiring with union as addition and pointwise multiplication as multiplication. * For a type `β` with scalar multiplication by another type `α`, this file defines a scalar multiplication of `set β` by `set α` and a separate scalar multiplication of `set β` by `α`. * We also define pointwise multiplication on `finset`. Appropriate definitions and results are also transported to the additive theory via `to_additive`. ## Implementation notes * The following expressions are considered in simp-normal form in a group: `(λ h, h * g) ⁻¹' s`, `(λ h, g * h) ⁻¹' s`, `(λ h, h * g⁻¹) ⁻¹' s`, `(λ h, g⁻¹ * h) ⁻¹' s`, `s * t`, `s⁻¹`, `(1 : set _)` (and similarly for additive variants). Expressions equal to one of these will be simplified. ## Tags set multiplication, set addition, pointwise addition, pointwise multiplication -/ namespace set /-! ### Properties about 1 -/ protected instance has_one {α : Type u_1} [HasOne α] : HasOne (set α) := { one := singleton 1 } theorem singleton_one {α : Type u_1} [HasOne α] : singleton 1 = 1 := rfl @[simp] theorem mem_zero {α : Type u_1} {a : α} [HasZero α] : a ∈ 0 ↔ a = 0 := iff.rfl theorem one_mem_one {α : Type u_1} [HasOne α] : 1 ∈ 1 := Eq.refl 1 @[simp] theorem zero_subset {α : Type u_1} {s : set α} [HasZero α] : 0 ⊆ s ↔ 0 ∈ s := singleton_subset_iff theorem zero_nonempty {α : Type u_1} [HasZero α] : set.nonempty 0 := Exists.intro 0 rfl @[simp] theorem image_zero {α : Type u_1} {β : Type u_2} [HasZero α] {f : α → β} : f '' 0 = singleton (f 0) := image_singleton /-! ### Properties about multiplication -/ protected instance has_add {α : Type u_1} [Add α] : Add (set α) := { add := image2 Add.add } @[simp] theorem image2_mul {α : Type u_1} {s : set α} {t : set α} [Mul α] : image2 Mul.mul s t = s * t := rfl theorem mem_add {α : Type u_1} {s : set α} {t : set α} {a : α} [Add α] : a ∈ s + t ↔ ∃ (x : α), ∃ (y : α), x ∈ s ∧ y ∈ t ∧ x + y = a := iff.rfl theorem mul_mem_mul {α : Type u_1} {s : set α} {t : set α} {a : α} {b : α} [Mul α] (ha : a ∈ s) (hb : b ∈ t) : a * b ∈ s * t := mem_image2_of_mem ha hb theorem add_image_prod {α : Type u_1} {s : set α} {t : set α} [Add α] : (fun (x : α × α) => prod.fst x + prod.snd x) '' set.prod s t = s + t := image_prod Add.add @[simp] theorem image_mul_left {α : Type u_1} {t : set α} {a : α} [group α] : (fun (b : α) => a * b) '' t = (fun (b : α) => a⁻¹ * b) ⁻¹' t := sorry @[simp] theorem image_add_right {α : Type u_1} {t : set α} {b : α} [add_group α] : (fun (a : α) => a + b) '' t = (fun (a : α) => a + -b) ⁻¹' t := sorry theorem image_add_left' {α : Type u_1} {t : set α} {a : α} [add_group α] : (fun (b : α) => -a + b) '' t = (fun (b : α) => a + b) ⁻¹' t := sorry theorem image_mul_right' {α : Type u_1} {t : set α} {b : α} [group α] : (fun (a : α) => a * (b⁻¹)) '' t = (fun (a : α) => a * b) ⁻¹' t := sorry @[simp] theorem preimage_add_left_singleton {α : Type u_1} {a : α} {b : α} [add_group α] : Add.add a ⁻¹' singleton b = singleton (-a + b) := eq.mpr (id (Eq._oldrec (Eq.refl (Add.add a ⁻¹' singleton b = singleton (-a + b))) (Eq.symm image_add_left'))) (eq.mpr (id (Eq._oldrec (Eq.refl ((fun (b : α) => -a + b) '' singleton b = singleton (-a + b))) image_singleton)) (Eq.refl (singleton (-a + b)))) @[simp] theorem preimage_mul_right_singleton {α : Type u_1} {a : α} {b : α} [group α] : (fun (_x : α) => _x * a) ⁻¹' singleton b = singleton (b * (a⁻¹)) := sorry @[simp] theorem preimage_add_left_zero {α : Type u_1} {a : α} [add_group α] : (fun (b : α) => a + b) ⁻¹' 0 = singleton (-a) := sorry @[simp] theorem preimage_mul_right_one {α : Type u_1} {b : α} [group α] : (fun (a : α) => a * b) ⁻¹' 1 = singleton (b⁻¹) := sorry theorem preimage_add_left_zero' {α : Type u_1} {a : α} [add_group α] : (fun (b : α) => -a + b) ⁻¹' 0 = singleton a := sorry theorem preimage_add_right_zero' {α : Type u_1} {b : α} [add_group α] : (fun (a : α) => a + -b) ⁻¹' 0 = singleton b := sorry @[simp] theorem mul_singleton {α : Type u_1} {s : set α} {b : α} [Mul α] : s * singleton b = (fun (a : α) => a * b) '' s := image2_singleton_right @[simp] theorem singleton_add {α : Type u_1} {t : set α} {a : α} [Add α] : singleton a + t = (fun (b : α) => a + b) '' t := image2_singleton_left @[simp] theorem singleton_add_singleton {α : Type u_1} {a : α} {b : α} [Add α] : singleton a + singleton b = singleton (a + b) := image2_singleton protected instance semigroup {α : Type u_1} [semigroup α] : semigroup (set α) := semigroup.mk Mul.mul sorry protected instance monoid {α : Type u_1} [monoid α] : monoid (set α) := monoid.mk semigroup.mul sorry 1 sorry sorry protected theorem mul_comm {α : Type u_1} {s : set α} {t : set α} [comm_semigroup α] : s * t = t * s := sorry protected instance add_comm_monoid {α : Type u_1} [add_comm_monoid α] : add_comm_monoid (set α) := add_comm_monoid.mk add_monoid.add sorry add_monoid.zero sorry sorry sorry theorem singleton.is_mul_hom {α : Type u_1} [Mul α] : is_mul_hom singleton := is_mul_hom.mk fun (a b : α) => Eq.symm singleton_mul_singleton @[simp] theorem empty_add {α : Type u_1} {s : set α} [Add α] : ∅ + s = ∅ := image2_empty_left @[simp] theorem mul_empty {α : Type u_1} {s : set α} [Mul α] : s * ∅ = ∅ := image2_empty_right theorem add_subset_add {α : Type u_1} {s₁ : set α} {s₂ : set α} {t₁ : set α} {t₂ : set α} [Add α] (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ + s₂ ⊆ t₁ + t₂ := image2_subset h₁ h₂ theorem union_add {α : Type u_1} {s : set α} {t : set α} {u : set α} [Add α] : s ∪ t + u = s + u ∪ (t + u) := image2_union_left theorem mul_union {α : Type u_1} {s : set α} {t : set α} {u : set α} [Mul α] : s * (t ∪ u) = s * t ∪ s * u := image2_union_right theorem Union_mul_left_image {α : Type u_1} {s : set α} {t : set α} [Mul α] : (Union fun (a : α) => Union fun (H : a ∈ s) => (fun (x : α) => a * x) '' t) = s * t := Union_image_left fun (a x : α) => a * x theorem Union_mul_right_image {α : Type u_1} {s : set α} {t : set α} [Mul α] : (Union fun (a : α) => Union fun (H : a ∈ t) => (fun (x : α) => x * a) '' s) = s * t := Union_image_right fun (x a : α) => x * a @[simp] theorem univ_mul_univ {α : Type u_1} [monoid α] : univ * univ = univ := sorry /-- `singleton` is a monoid hom. -/ def singleton_add_hom {α : Type u_1} [add_monoid α] : α →+ set α := add_monoid_hom.mk singleton sorry sorry theorem nonempty.add {α : Type u_1} {s : set α} {t : set α} [Add α] : set.nonempty s → set.nonempty t → set.nonempty (s + t) := nonempty.image2 theorem finite.mul {α : Type u_1} {s : set α} {t : set α} [Mul α] (hs : finite s) (ht : finite t) : finite (s * t) := finite.image2 (fun (a b : α) => a * b) hs ht /-- multiplication preserves finiteness -/ def fintype_mul {α : Type u_1} [Mul α] [DecidableEq α] (s : set α) (t : set α) [hs : fintype ↥s] [ht : fintype ↥t] : fintype ↥(s * t) := set.fintype_image2 (fun (a b : α) => a * b) s t theorem bdd_above_add {α : Type u_1} [ordered_add_comm_monoid α] {A : set α} {B : set α} : bdd_above A → bdd_above B → bdd_above (A + B) := sorry /-! ### Properties about inversion -/ protected instance has_inv {α : Type u_1} [has_inv α] : has_inv (set α) := has_inv.mk (preimage has_inv.inv) @[simp] theorem mem_inv {α : Type u_1} {s : set α} {a : α} [has_inv α] : a ∈ (s⁻¹) ↔ a⁻¹ ∈ s := iff.rfl theorem inv_mem_inv {α : Type u_1} {s : set α} {a : α} [group α] : a⁻¹ ∈ (s⁻¹) ↔ a ∈ s := sorry @[simp] theorem inv_preimage {α : Type u_1} {s : set α} [has_inv α] : has_inv.inv ⁻¹' s = (s⁻¹) := rfl @[simp] theorem image_inv {α : Type u_1} {s : set α} [group α] : has_inv.inv '' s = (s⁻¹) := sorry @[simp] theorem inter_neg {α : Type u_1} {s : set α} {t : set α} [Neg α] : -(s ∩ t) = -s ∩ -t := preimage_inter @[simp] theorem union_neg {α : Type u_1} {s : set α} {t : set α} [Neg α] : -(s ∪ t) = -s ∪ -t := preimage_union @[simp] theorem compl_inv {α : Type u_1} {s : set α} [has_inv α] : sᶜ⁻¹ = (s⁻¹ᶜ) := preimage_compl @[simp] protected theorem inv_inv {α : Type u_1} {s : set α} [group α] : s⁻¹⁻¹ = s := sorry @[simp] protected theorem univ_inv {α : Type u_1} [group α] : univ⁻¹ = univ := preimage_univ @[simp] theorem neg_subset_neg {α : Type u_1} [add_group α] {s : set α} {t : set α} : -s ⊆ -t ↔ s ⊆ t := function.surjective.preimage_subset_preimage_iff (equiv.surjective (equiv.neg α)) theorem neg_subset {α : Type u_1} [add_group α] {s : set α} {t : set α} : -s ⊆ t ↔ s ⊆ -t := eq.mpr (id (Eq._oldrec (Eq.refl (-s ⊆ t ↔ s ⊆ -t)) (Eq.symm (propext neg_subset_neg)))) (eq.mpr (id (Eq._oldrec (Eq.refl ( --s ⊆ -t ↔ s ⊆ -t)) set.neg_neg)) (iff.refl (s ⊆ -t))) /-! ### Properties about scalar multiplication -/ /-- Scaling a set: multiplying every element by a scalar. -/ protected instance has_scalar_set {α : Type u_1} {β : Type u_2} [has_scalar α β] : has_scalar α (set β) := has_scalar.mk fun (a : α) => image (has_scalar.smul a) @[simp] theorem image_smul {α : Type u_1} {β : Type u_2} {a : α} [has_scalar α β] {t : set β} : (fun (x : β) => a • x) '' t = a • t := rfl theorem mem_smul_set {α : Type u_1} {β : Type u_2} {a : α} {x : β} [has_scalar α β] {t : set β} : x ∈ a • t ↔ ∃ (y : β), y ∈ t ∧ a • y = x := iff.rfl theorem smul_mem_smul_set {α : Type u_1} {β : Type u_2} {a : α} {y : β} [has_scalar α β] {t : set β} (hy : y ∈ t) : a • y ∈ a • t := Exists.intro y { left := hy, right := rfl } theorem smul_set_union {α : Type u_1} {β : Type u_2} {a : α} [has_scalar α β] {s : set β} {t : set β} : a • (s ∪ t) = a • s ∪ a • t := sorry @[simp] theorem smul_set_empty {α : Type u_1} {β : Type u_2} [has_scalar α β] (a : α) : a • ∅ = ∅ := eq.mpr (id (Eq._oldrec (Eq.refl (a • ∅ = ∅)) (Eq.symm image_smul))) (eq.mpr (id (Eq._oldrec (Eq.refl ((fun (x : β) => a • x) '' ∅ = ∅)) (image_empty fun (x : β) => a • x))) (Eq.refl ∅)) theorem smul_set_mono {α : Type u_1} {β : Type u_2} {a : α} [has_scalar α β] {s : set β} {t : set β} (h : s ⊆ t) : a • s ⊆ a • t := sorry /-- Pointwise scalar multiplication by a set of scalars. -/ protected instance has_scalar {α : Type u_1} {β : Type u_2} [has_scalar α β] : has_scalar (set α) (set β) := has_scalar.mk (image2 has_scalar.smul) @[simp] theorem image2_smul {α : Type u_1} {β : Type u_2} {s : set α} [has_scalar α β] {t : set β} : image2 has_scalar.smul s t = s • t := rfl theorem mem_smul {α : Type u_1} {β : Type u_2} {s : set α} {x : β} [has_scalar α β] {t : set β} : x ∈ s • t ↔ ∃ (a : α), ∃ (y : β), a ∈ s ∧ y ∈ t ∧ a • y = x := iff.rfl theorem image_smul_prod {α : Type u_1} {β : Type u_2} {s : set α} [has_scalar α β] {t : set β} : (fun (x : α × β) => prod.fst x • prod.snd x) '' set.prod s t = s • t := image_prod has_scalar.smul theorem range_smul_range {α : Type u_1} {β : Type u_2} [has_scalar α β] {ι : Type u_3} {κ : Type u_4} (b : ι → α) (c : κ → β) : range b • range c = range fun (p : ι × κ) => b (prod.fst p) • c (prod.snd p) := sorry theorem singleton_smul {α : Type u_1} {β : Type u_2} {a : α} [has_scalar α β] {t : set β} : singleton a • t = a • t := image2_singleton_left /-! ### `set α` as a `(∪,*)`-semiring -/ /-- An alias for `set α`, which has a semiring structure given by `∪` as "addition" and pointwise multiplication `*` as "multiplication". -/ def set_semiring (α : Type u_1) := set α /-- The identitiy function `set α → set_semiring α`. -/ /-- The identitiy function `set_semiring α → set α`. -/ protected def up {α : Type u_1} (s : set α) : set_semiring α := s protected def set_semiring.down {α : Type u_1} (s : set_semiring α) : set α := s @[simp] protected theorem down_up {α : Type u_1} {s : set α} : set_semiring.down (set.up s) = s := rfl @[simp] protected theorem up_down {α : Type u_1} {s : set_semiring α} : set.up (set_semiring.down s) = s := rfl protected instance set_semiring.semiring {α : Type u_1} [monoid α] : semiring (set_semiring α) := semiring.mk (fun (s t : set_semiring α) => s ∪ t) union_assoc ∅ empty_union union_empty union_comm monoid.mul sorry monoid.one sorry sorry sorry sorry sorry sorry protected instance set_semiring.comm_semiring {α : Type u_1} [comm_monoid α] : comm_semiring (set_semiring α) := comm_semiring.mk semiring.add sorry semiring.zero sorry sorry sorry comm_monoid.mul sorry comm_monoid.one sorry sorry sorry sorry sorry sorry sorry /-- A multiplicative action of a monoid on a type β gives also a multiplicative action on the subsets of β. -/ protected instance mul_action_set {α : Type u_1} {β : Type u_2} [monoid α] [mul_action α β] : mul_action α (set β) := mul_action.mk sorry sorry theorem image_add {α : Type u_1} {β : Type u_2} {s : set α} {t : set α} [Add α] [Add β] (m : α → β) [is_add_hom m] : m '' (s + t) = m '' s + m '' t := sorry theorem preimage_mul_preimage_subset {α : Type u_1} {β : Type u_2} [Mul α] [Mul β] (m : α → β) [is_mul_hom m] {s : set β} {t : set β} : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) := sorry /-- The image of a set under function is a ring homomorphism with respect to the pointwise operations on sets. -/ def image_hom {α : Type u_1} {β : Type u_2} [monoid α] [monoid β] (f : α →* β) : set_semiring α →+* set_semiring β := ring_hom.mk (image ⇑f) sorry sorry sorry sorry end set /-- A nonempty set in a semimodule is scaled by zero to the singleton containing 0 in the semimodule. -/ theorem zero_smul_set {α : Type u_1} {β : Type u_2} [semiring α] [add_comm_monoid β] [semimodule α β] {s : set β} (h : set.nonempty s) : 0 • s = 0 := sorry theorem mem_inv_smul_set_iff {α : Type u_1} {β : Type u_2} [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a⁻¹ • A ↔ a • x ∈ A := sorry theorem mem_smul_set_iff_inv_smul_mem {α : Type u_1} {β : Type u_2} [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a • A ↔ a⁻¹ • x ∈ A := eq.mpr (id (Eq._oldrec (Eq.refl (x ∈ a • A ↔ a⁻¹ • x ∈ A)) (Eq.symm (propext (mem_inv_smul_set_iff (inv_ne_zero ha) A x))))) (eq.mpr (id (Eq._oldrec (Eq.refl (x ∈ a • A ↔ x ∈ a⁻¹⁻¹ • A)) (inv_inv' a))) (iff.refl (x ∈ a • A))) namespace finset /-- The pointwise product of two finite sets `s` and `t`: `st = s ⬝ t = s * t = { x * y | x ∈ s, y ∈ t }`. -/ protected instance has_add {α : Type u_1} [DecidableEq α] [Add α] : Add (finset α) := { add := fun (s t : finset α) => image (fun (p : α × α) => prod.fst p + prod.snd p) (finset.product s t) } theorem mul_def {α : Type u_1} [DecidableEq α] [Mul α] {s : finset α} {t : finset α} : s * t = image (fun (p : α × α) => prod.fst p * prod.snd p) (finset.product s t) := rfl theorem mem_add {α : Type u_1} [DecidableEq α] [Add α] {s : finset α} {t : finset α} {x : α} : x ∈ s + t ↔ ∃ (y : α), ∃ (z : α), y ∈ s ∧ z ∈ t ∧ y + z = x := sorry @[simp] theorem coe_add {α : Type u_1} [DecidableEq α] [Add α] {s : finset α} {t : finset α} : ↑(s + t) = ↑s + ↑t := sorry theorem mul_mem_mul {α : Type u_1} [DecidableEq α] [Mul α] {s : finset α} {t : finset α} {x : α} {y : α} (hx : x ∈ s) (hy : y ∈ t) : x * y ∈ s * t := eq.mpr (id (propext mem_mul)) (Exists.intro x (Exists.intro y { left := hx, right := { left := hy, right := rfl } })) theorem add_card_le {α : Type u_1} [DecidableEq α] [Add α] {s : finset α} {t : finset α} : card (s + t) ≤ card s * card t := sorry theorem mul_card_le {α : Type u_1} [DecidableEq α] [Mul α] {s : finset α} {t : finset α} : card (s * t) ≤ card s * card t := sorry /-- A finite set `U` contained in the product of two sets `S * S'` is also contained in the product of two finite sets `T * T' ⊆ S * S'`. -/ theorem subset_add {M : Type u_1} [add_monoid M] {S : set M} {S' : set M} {U : finset M} (f : ↑U ⊆ S + S') : ∃ (T : finset M), ∃ (T' : finset M), ↑T ⊆ S ∧ ↑T' ⊆ S' ∧ U ⊆ T + T' := sorry end finset /-! Some lemmas about pointwise multiplication and submonoids. Ideally we put these in `group_theory.submonoid.basic`, but currently we cannot because that file is imported by this. -/ namespace submonoid theorem mul_subset {M : Type u_1} [monoid M] {s : set M} {t : set M} {S : submonoid M} (hs : s ⊆ ↑S) (ht : t ⊆ ↑S) : s * t ⊆ ↑S := sorry theorem mul_subset_closure {M : Type u_1} [monoid M] {s : set M} {t : set M} {u : set M} (hs : s ⊆ u) (ht : t ⊆ u) : s * t ⊆ ↑(closure u) := mul_subset (set.subset.trans hs subset_closure) (set.subset.trans ht subset_closure) theorem Mathlib.add_submonoid.coe_add_self_eq {M : Type u_1} [add_monoid M] (s : add_submonoid M) : ↑s + ↑s = ↑s := sorry end Mathlib
886837e371af46cce9b35b156e487dfda08ca8a9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/uniform_space/compact_separated_auto.lean
01d8be7b420d77dd69fd2e8ad64c4ec6a37e8c26
[]
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
3,731
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.uniform_space.separation import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Compact separated uniform spaces ## Main statements * `compact_space_uniformity`: On a separated compact uniform space, the topology determines the uniform structure, entourages are exactly the neighborhoods of the diagonal. * `uniform_space_of_compact_t2`: every compact T2 topological structure is induced by a uniform structure. This uniform structure is described in the previous item. * Heine-Cantor theorem: continuous functions on compact separated uniform spaces with values in uniform spaces are automatically uniformly continuous. There are several variations, the main one is `compact_space.uniform_continuous_of_continuous`. ## Implementation notes The construction `uniform_space_of_compact_t2` is not declared as an instance, as it would badly loop. ## tags uniform space, uniform continuity, compact space -/ /-! ### Uniformity on compact separated spaces -/ /-- On a separated compact uniform space, the topology determines the uniform structure, entourages are exactly the neighborhoods of the diagonal. -/ theorem compact_space_uniformity {α : Type u_1} [uniform_space α] [compact_space α] [separated_space α] : uniformity α = supr fun (x : α) => nhds (x, x) := sorry theorem unique_uniformity_of_compact_t2 {α : Type u_1} [t : topological_space α] [compact_space α] [t2_space α] {u : uniform_space α} {u' : uniform_space α} (h : uniform_space.to_topological_space = t) (h' : uniform_space.to_topological_space = t) : u = u' := sorry /-- The unique uniform structure inducing a given compact Hausdorff topological structure. -/ def uniform_space_of_compact_t2 {α : Type (max (max u_1 u_2 u_3) u_2)} [topological_space α] [compact_space α] [t2_space α] : uniform_space α := uniform_space.mk (uniform_space.core.mk (supr fun (x : α) => nhds (x, x)) sorry sorry sorry) sorry /-! ### Heine-Cantor theorem -/ /-- Heine-Cantor: a continuous function on a compact separated uniform space is uniformly continuous. -/ theorem compact_space.uniform_continuous_of_continuous {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] [compact_space α] [separated_space α] {f : α → β} (h : continuous f) : uniform_continuous f := sorry /-- Heine-Cantor: a continuous function on a compact separated set of a uniform space is uniformly continuous. -/ theorem is_compact.uniform_continuous_on_of_continuous' {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {s : set α} {f : α → β} (hs : is_compact s) (hs' : is_separated s) (hf : continuous_on f s) : uniform_continuous_on f s := eq.mpr (id (Eq._oldrec (Eq.refl (uniform_continuous_on f s)) (propext uniform_continuous_on_iff_restrict))) (compact_space.uniform_continuous_of_continuous (eq.mp (Eq._oldrec (Eq.refl (continuous_on f s)) (propext continuous_on_iff_continuous_restrict)) hf)) /-- Heine-Cantor: a continuous function on a compact set of a separated uniform space is uniformly continuous. -/ theorem is_compact.uniform_continuous_on_of_continuous {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] [separated_space α] {s : set α} {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : uniform_continuous_on f s := is_compact.uniform_continuous_on_of_continuous' hs (is_separated_of_separated_space s) hf end Mathlib
2f3e33ece45cb015353e6b90de93d53900b32a01
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/real/ennreal.lean
9dcb8635027e921368e1bbcb8a9aa7fd96a8ad83
[ "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
44,269
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Yury Kudryashov Extended non-negative reals -/ import data.real.nnreal order.bounds data.set.intervals tactic.norm_num noncomputable theory open classical set open_locale classical variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered] def ennreal := with_top nnreal localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ennreal} {r p q : nnreal} instance : inhabited ennreal := ⟨0⟩ instance : has_coe nnreal ennreal := ⟨ option.some ⟩ instance : can_lift ennreal nnreal := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ennreal) = (⊤ : ennreal) := rfl @[simp] lemma some_eq_coe (a : nnreal) : (some a : ennreal) = (↑a : ennreal) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ennreal → nnreal | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ennreal) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ennreal := coe (nnreal.of_real r) @[simp, elim_cast] lemma to_nnreal_coe : (r : ennreal).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ennreal}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ennreal} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : real} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h] lemma coe_to_nnreal_le_self : ∀{a:ennreal}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top lemma coe_nnreal_eq (r : nnreal) : (r : ennreal) = ennreal.of_real r := by { rw [ennreal.of_real, nnreal.of_real], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : real} (h : 0 ≤ x) : ennreal.of_real x = @coe nnreal ennreal _ (⟨x, h⟩ : nnreal) := by { rw [coe_nnreal_eq], refl } @[simp, elim_cast] lemma coe_zero : ↑(0 : nnreal) = (0 : ennreal) := rfl @[simp, elim_cast] lemma coe_one : ↑(1 : nnreal) = (1 : ennreal) := rfl @[simp] lemma to_real_nonneg {a : ennreal} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma coe_to_real (r : nnreal) : (r : ennreal).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ennreal).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ennreal).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ennreal) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ennreal} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ennreal → Prop} : (∀a, p a) ↔ (∀r:nnreal, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma to_nnreal_eq_zero_iff (x : ennreal) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ⊤ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:nnreal) = (0:ennreal) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ennreal) : x.to_real = 0 ↔ x = 0 ∨ x = ⊤ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ennreal) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ennreal) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, elim_cast] lemma coe_eq_coe : (↑r : ennreal) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, elim_cast] lemma coe_le_coe : (↑r : ennreal) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, elim_cast] lemma coe_lt_coe : (↑r : ennreal) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : nnreal → ennreal) := λ _ _, coe_le_coe.2 @[simp, elim_cast] lemma coe_eq_zero : (↑r : ennreal) = 0 ↔ r = 0 := coe_eq_coe @[simp, elim_cast] lemma zero_eq_coe : 0 = (↑r : ennreal) ↔ 0 = r := coe_eq_coe @[simp, elim_cast] lemma coe_eq_one : (↑r : ennreal) = 1 ↔ r = 1 := coe_eq_coe @[simp, elim_cast] lemma one_eq_coe : 1 = (↑r : ennreal) ↔ 1 = r := coe_eq_coe @[simp, elim_cast] lemma coe_nonneg : 0 ≤ (↑r : ennreal) ↔ 0 ≤ r := coe_le_coe @[simp, elim_cast] lemma coe_pos : 0 < (↑r : ennreal) ↔ 0 < r := coe_lt_coe @[simp, move_cast] lemma coe_add : ↑(r + p) = (r + p : ennreal) := with_top.coe_add @[simp, move_cast] lemma coe_mul : ↑(r * p) = (r * p : ennreal) := with_top.coe_mul @[simp, move_cast] lemma coe_bit0 : (↑(bit0 r) : ennreal) = bit0 r := coe_add @[simp, move_cast] lemma coe_bit1 : (↑(bit1 r) : ennreal) = bit1 r := by simp [bit1] lemma coe_two : ((2:nnreal) : ennreal) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ennreal) := canonically_ordered_semiring.zero_lt_one @[simp] lemma one_lt_two : (1:ennreal) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast one_lt_two @[simp] lemma two_pos : (0:ennreal) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ennreal) ≠ 0 := ne_of_gt two_pos lemma two_ne_top : (2:ennreal) ≠ ∞ := coe_two ▸ coe_ne_top @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add instance : is_semiring_hom (coe : nnreal → ennreal) := by refine_struct {..}; simp @[simp, move_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ennreal) = r^n := is_monoid_hom.map_pow coe r n lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top _ _ lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top _ _ lemma to_nnreal_add {r₁ r₂ : ennreal} (h₁ : r₁ < ⊤) (h₂ : r₂ < ⊤) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ennreal _ _ ⊤, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top {a b : ennreal} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_ne_top {a b : ennreal} : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simp [(≠), mul_eq_top] {contextual := tt} lemma mul_lt_top {a b : ennreal} : a < ⊤ → b < ⊤ → a * b < ⊤ := by simpa only [ennreal.lt_top_iff_ne_top] using mul_ne_top lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞ | 0 := by simp | (n+1) := λ o, (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, move_cast] lemma coe_finset_sum {s : finset α} {f : α → nnreal} : ↑(s.sum f) = (s.sum (λa, f a) : ennreal) := (s.sum_hom coe).symm @[simp, move_cast] lemma coe_finset_prod {s : finset α} {f : α → nnreal} : ↑(s.prod f) = (s.prod (λa, f a) : ennreal) := (s.prod_hom coe).symm section order @[simp] lemma bot_eq_zero : (⊥ : ennreal) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ (⊤:ennreal) ≤ ↑r := with_top.not_top_le_coe r lemma zero_lt_coe_iff : 0 < (↑p : ennreal) ↔ 0 < p := coe_lt_coe @[simp, elim_cast] lemma one_le_coe_iff : (1:ennreal) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, elim_cast] lemma coe_le_one_iff : ↑r ≤ (1:ennreal) ↔ r ≤ 1 := coe_le_coe @[simp, elim_cast] lemma coe_lt_one_iff : (↑p : ennreal) < 1 ↔ p < 1 := coe_lt_coe @[simp, elim_cast] lemma one_lt_coe_iff : 1 < (↑p : ennreal) ↔ 1 < p := coe_lt_coe @[simp, squash_cast] lemma coe_nat (n : nat) : ((n : nnreal) : ennreal) = n := with_top.coe_nat n @[simp] lemma nat_ne_top (n : nat) : (n : ennreal) ≠ ⊤ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : nat) : (⊤ : ennreal) ≠ n := with_top.top_ne_nat n lemma le_coe_iff : a ≤ ↑r ↔ (∃p:nnreal, a = p ∧ p ≤ r) := with_top.le_coe_iff r a lemma coe_le_iff : ↑r ≤ a ↔ (∀p:nnreal, a = p → r ≤ p) := with_top.coe_le_iff r a lemma lt_iff_exists_coe : a < b ↔ (∃p:nnreal, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe a b @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [le_zero_iff_eq.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) -- TODO: why this is not a `rfl`? There is some hidden diamond here. @[simp] lemma sup_eq_max : a ⊔ b = max a b := eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [zero_lt_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ⊤ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ⊤ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ⊤) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_epsilon_le : ∀{a b : ennreal}, (∀ε:nnreal, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have (⊤:ennreal) ≤ ↑a + ↑(1:nnreal), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_epsilon_le h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ennreal) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases dense h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ennreal) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:nnreal, a < r ∧ (r : ennreal) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : nnreal, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_add_right (le_refl _)) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : nnreal := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : nnreal.of_real c = d, by { rw [← nnreal.coe_eq, nnreal.coe_of_real _ c_nonneg], refl }, rw [add_comm, this], exact nnreal.sub_add_cancel_of_le (le_of_lt ad) end lemma coe_nat_lt_coe {n : ℕ} : (n : ennreal) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ennreal) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[elim_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ennreal) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ennreal) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ennreal) := λ _ _, coe_nat_lt_coe_nat.2 @[elim_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ennreal) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ennreal := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ennreal} (h : r ≠ ⊤) : ∃n:ℕ, r < n := begin rcases lt_iff_exists_coe.1 (lt_top_iff_ne_top.2 h) with ⟨r, rfl, hb⟩, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin rcases dense ac with ⟨a', aa', a'c⟩, rcases lt_iff_exists_coe.1 aa' with ⟨aR, rfl, _⟩, rcases lt_iff_exists_coe.1 a'c with ⟨a'R, rfl, _⟩, rcases dense bd with ⟨b', bb', b'd⟩, rcases lt_iff_exists_coe.1 bb' with ⟨bR, rfl, _⟩, rcases lt_iff_exists_coe.1 b'd with ⟨b'R, rfl, _⟩, have I : ↑aR + ↑bR < ↑a'R + ↑b'R := begin rw [← coe_add, ← coe_add, coe_lt_coe], apply add_lt_add (coe_lt_coe.1 aa') (coe_lt_coe.1 bb') end, have J : ↑a'R + ↑b'R ≤ c + d := add_le_add' (le_of_lt a'c) (le_of_lt b'd), apply lt_of_lt_of_le I J end @[move_cast] lemma coe_min : ((min r p:nnreal):ennreal) = min r p := coe_mono.map_min @[move_cast] lemma coe_max : ((max r p:nnreal):ennreal) = max r p := coe_mono.map_max end order section complete_lattice lemma coe_Sup {s : set nnreal} : bdd_above s → (↑(Sup s) : ennreal) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set nnreal} : s.nonempty → (↑(Inf s) : ennreal) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ennreal} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set nnreal} : ↑r ∈ upper_bounds ((coe : nnreal → ennreal) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨅n, f n) = (⨅n:nnreal, f n) ⊓ f ⊤ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩) end complete_lattice section mul lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := canonically_ordered_semiring.mul_le_mul lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a) lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a) lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (zero_lt_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left lemma mul_eq_zero {a b : ennreal} : a * b = 0 ↔ a = 0 ∨ b = 0 := canonically_ordered_comm_semiring.mul_eq_zero_iff _ _ end mul section sub instance : has_sub ennreal := ⟨λa b, Inf {d | a ≤ d + b}⟩ @[move_cast] lemma coe_sub : ↑(p - r) = (↑p:ennreal) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ennreal) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _ @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le _) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add' (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ennreal}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_left_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_right_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_left_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ennreal}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right' h) (assume h : a ≤ c + b, calc a - b ≤ (c + b) - b : sub_le_sub h (le_refl _) ... ≤ c : Inf_le (le_refl (c + b))) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_sub_self : a ≠ ⊤ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, zero_lt_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact zero_lt_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ennreal) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_of_nonneg_right' $ zero_le _ @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left' le_sub_add_self ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_right_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_left_inj {a b c : ennreal} (ha : a < ⊤) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- sum of finte numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ennreal} : (∀a∈s, f a < ⊤) → s.sum f < ⊤ := with_top.sum_lt_top /-- sum of finte numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ennreal} : s.sum f < ⊤ ↔ (∀a∈s, f a < ⊤) := with_top.sum_lt_top_iff /-- seeing `ennreal` as `nnreal` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ⊤) : ennreal.to_nnreal (s.sum f) = s.sum (λa, ennreal.to_nnreal (f a)) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, rw coe_to_nnreal, rw ← ennreal.lt_top_iff_ne_top, exact hf x hx }, { rw ← ennreal.lt_top_iff_ne_top, exact sum_lt_top hf } end /-- seeing `ennreal` as `real` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ⊤) : ennreal.to_real (s.sum f) = s.sum (λa, ennreal.to_real (f a)) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } end sum section interval variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ⊤ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ⊤ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_sub_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_right_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ennreal := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : has_div ennreal := ⟨λa b, a * b⁻¹⟩ lemma div_def : a / b = a * b⁻¹ := rfl lemma mul_div_assoc : (a * b) / c = a * (b / c) := mul_assoc _ _ _ @[simp] lemma inv_zero : (0 : ennreal)⁻¹ = ∞ := show Inf {b : ennreal | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : (∞ : ennreal)⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ennreal) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, nnreal.mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ennreal) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, nnreal.inv_zero, inv_zero, coe_zero, zero_le] else by simp only [coe_inv hr, le_refl] @[elim_cast] lemma coe_inv_two : ((2⁻¹:nnreal):ennreal) = 2⁻¹ := by rw [coe_inv (ne_of_gt zero_lt_two), coe_two] @[simp, elim_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ennreal) = p / r := show ↑(p * r⁻¹) = ↑p * (↑r)⁻¹, by rw [coe_mul, coe_inv hr] @[simp] lemma inv_one : (1:ennreal)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 nnreal.inv_one @[simp] lemma div_one {a : ennreal} : a / 1 = a := by simp [ennreal.div_def] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv, nnreal.inv_pow, coe_pow], rw [← ne.def] at h, rw [← zero_lt_iff_ne_zero] at *, apply pow_pos h end @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_involutive : function.involutive (λ a:ennreal, a⁻¹) := λ a, ennreal.inv_inv lemma inv_bijective : function.bijective (λ a:ennreal, a⁻¹) := ennreal.inv_involutive.bijective @[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_eq_inv lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_eq_inv lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := zero_lt_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha; cases eq_or_lt_of_le (zero_le b) with hb hb, { subst a, subst b, simp }, { subst a, simp }, { subst b, simp [zero_lt_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [div_def, top_mul, *] @[simp] lemma div_top : a / ∞ = 0 := by simp only [div_def, inv_top, mul_zero] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ⊤ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ⊤ ∧ b ≠ ⊤) := by simp [ennreal.div_def, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ⊤ ∨ c ≠ ⊤) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ⊤ = ⊤, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ennreal) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_def, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, nnreal.mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ⊤, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ⊤) (hbt : b ≠ ⊤ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_def], apply (le_div_iff_mul_le _ _).symm, simpa [inv_ne_zero] using hbt, simpa [inv_ne_zero] using hb0 end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ⊤, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ⊤ → a ≠ 0) → (a = ⊤ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_def, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ⊤) : a * a⁻¹ = 1 := begin lift a to nnreal using ht, norm_cast at h0, rw [← coe_inv h0], norm_cast, exact nnreal.mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma mul_le_iff_le_inv {a b r : ennreal} (hr₀ : r ≠ 0) (hr₁ : r ≠ ⊤) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_lt_one_mul_lt : ∀{x y : ennreal}, (∀a<1, a * x ≤ y) → x ≤ y := forall_ennreal.2 $ and.intro (assume r, forall_ennreal.2 $ and.intro (assume q h, coe_le_coe.2 $ nnreal.le_of_forall_lt_one_mul_lt $ assume a ha, begin rw [← coe_le_coe, coe_mul], exact h _ (coe_lt_coe.2 ha) end) (assume h, le_top)) (assume r hr, have ((1 / 2 : nnreal) : ennreal) * ⊤ ≤ r := hr _ (coe_lt_coe.2 ((@nnreal.coe_lt_coe (1/2) 1).1 one_half_lt_one)), have ne : ((1 / 2 : nnreal) : ennreal) ≠ 0, begin rw [(≠), coe_eq_zero], refine zero_lt_iff_ne_zero.1 _, show 0 < (1 / 2 : ℝ), exact div_pos zero_lt_one _root_.two_pos end, by rwa [mul_top, if_neg ne] at this) lemma div_add_div_same {a b c : ennreal} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_def, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma inv_two_add_inv_two : (2:ennreal)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_def, div_self two_ne_zero two_ne_top] lemma add_halves (a : ennreal) : a / 2 + a / 2 = a := by rw [div_def, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma div_zero_iff {a b : ennreal} : a / b = 0 ↔ a = 0 ∨ b = ⊤ := by simp [div_def, mul_eq_zero] @[simp] lemma div_pos_iff {a b : ennreal} : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ⊤ := by simp [zero_lt_iff_ne_zero, not_or_distrib] lemma half_pos {a : ennreal} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma one_half_lt_one : (2⁻¹:ennreal) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ennreal} (hz : a ≠ 0) (ht : a ≠ ⊤) : a / 2 < a := begin lift a to nnreal using ht, norm_cast at *, rw [← coe_div _root_.two_ne_zero'], -- `norm_cast` fails to apply `coe_div` norm_cast, exact nnreal.half_lt_self hz end lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to nnreal using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end lemma one_sub_inv_two : (1:ennreal) - 2⁻¹ = 2⁻¹ := by simpa only [div_def, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ennreal} (h : a ≠ 0) : ∃n:ℕ, (n:ennreal)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] end inv section real lemma to_real_add (ha : a ≠ ⊤) (hb : b ≠ ⊤) : (a+b).to_real = a.to_real + b.to_real := begin lift a to nnreal using ha, lift b to nnreal using hb, refl end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ⊤ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ⊤ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, nnreal.of_real_add hp hq] @[simp] lemma to_real_le_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to nnreal using ha, lift b to nnreal using hb, norm_cast end @[simp] lemma to_real_lt_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real < b.to_real ↔ a < b := begin lift a to nnreal using ha, lift b to nnreal using hb, norm_cast end lemma to_real_max (hr : a ≠ ⊤) (hp : b ≠ ⊤) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, nnreal.of_real_le_of_real h] @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] lemma of_real_le_iff_le_to_real {a : ℝ} {b : ennreal} (hb : b ≠ ⊤) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to nnreal using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ennreal} (ha : 0 ≤ a) (hb : b ≠ ⊤) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to nnreal using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ennreal} {b : ℝ} (ha : a ≠ ⊤) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to nnreal using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.le_of_real_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ennreal} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ⊤, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ennreal} {b : ℝ} (ha : a ≠ ⊤) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to nnreal using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.lt_of_real_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact nnreal.of_real_mul hp } lemma to_real_of_real_mul (c : ℝ) (a : ennreal) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply nnreal.coe_of_real, exact h } end @[simp] lemma to_real_mul_top (a : ennreal) : ennreal.to_real (a * ⊤) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_real] }, { rw [mul_top, if_neg h, top_to_real] } end @[simp] lemma to_real_top_mul (a : ennreal) : ennreal.to_real (⊤ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real {a b : ennreal} (ha : a < ⊤) (hb : b < ⊤) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin rw ennreal.lt_top_iff_ne_top at *, split, { assume h, apply le_antisymm, rw ← to_real_le_to_real ha hb, exact le_of_eq h, rw ← to_real_le_to_real hb ha, exact le_of_eq h.symm }, { assume h, rw h } end lemma to_real_mul_to_real {a b : ennreal} : (ennreal.to_real a) * (ennreal.to_real b) = ennreal.to_real (a * b) := begin by_cases ha : a = ⊤, { rw ha, simp }, by_cases hb : b = ⊤, { rw hb, simp }, have ha : ennreal.of_real (ennreal.to_real a) = a := of_real_to_real ha, have hb : ennreal.of_real (ennreal.to_real b) = b := of_real_to_real hb, conv_rhs { rw [← ha, ← hb, ← of_real_mul to_real_nonneg] }, rw [to_real_of_real (mul_nonneg to_real_nonneg to_real_nonneg)] end end real section infi variables {ι : Sort*} {f g : ι → ennreal} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add' (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ennreal} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ennreal} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add' (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ennreal} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, s.sum (f i)) = s.sum (λa, ⨅i, f i a) := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + s.sum (f k) ≤ f i a + s.sum (f j), from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add' (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] end infi section supr lemma supr_coe_nat : (⨆n:ℕ, (n : ennreal)) = ⊤ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr end ennreal
871f29470eaf2bdaa4a7c53db6443722a2ccaa0b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/test/simps.lean
74a558af4b53f3afd8a949e6e51b38a3da2018a5
[ "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
36,111
lean
import algebra.hom.group import data.sum.basic import tactic.simps universes v u w -- set_option trace.simps.verbose true -- set_option trace.simps.debug true -- set_option trace.app_builder true open function tactic expr structure equiv' (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) local infix (name := equiv') ` ≃ `:25 := equiv' /- Since `prod` and `pprod` are a special case for `@[simps]`, we define a new structure to test the basic functionality.-/ structure my_prod (α β : Type*) := (fst : α) (snd : β) def myprod.map {α α' β β'} (f : α → α') (g : β → β') (x : my_prod α β) : my_prod α' β' := ⟨f x.1, g x.2⟩ namespace foo @[simps] protected def rfl {α} : α ≃ α := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ /- simps adds declarations -/ run_cmd do e ← get_env, e.get `foo.rfl_to_fun, e.get `foo.rfl_inv_fun, success_if_fail (e.get `foo.rfl_left_inv), success_if_fail (e.get `foo.rfl_right_inv) example (n : ℕ) : foo.rfl.to_fun n = n := by rw [foo.rfl_to_fun, id] example (n : ℕ) : foo.rfl.inv_fun n = n := by rw [foo.rfl_inv_fun] /- the declarations are `simp` lemmas -/ @[simps] def foo : ℕ × ℤ := (1, 2) example : foo.1 = 1 := by simp example : foo.2 = 2 := by simp example : foo.1 = 1 := by { dsimp, refl } -- check that dsimp also unfolds example : foo.2 = 2 := by { dsimp, refl } example {α} (x : α) : foo.rfl.to_fun x = x := by simp example {α} (x : α) : foo.rfl.inv_fun x = x := by simp example {α} (x : α) : foo.rfl.to_fun = @id α := by { success_if_fail {simp}, refl } /- check some failures -/ def bar1 : ℕ := 1 -- type is not a structure noncomputable def bar2 {α} : α ≃ α := classical.choice ⟨foo.rfl⟩ run_cmd do success_if_fail_with_msg (simps_tac `foo.bar1) "Invalid `simps` attribute. Target nat is not a structure", success_if_fail_with_msg (simps_tac `foo.bar2) "Invalid `simps` attribute. The body is not a constructor application: classical.choice bar2._proof_1", e ← get_env, let nm := `foo.bar1, d ← e.get nm, let lhs : expr := const d.to_name (d.univ_params.map level.param), simps_add_projections e nm d.type lhs d.value [] d.univ_params ff {} [] [] /- test that if a non-constructor is given as definition, then `{rhs_md := semireducible, simp_rhs := tt}` is applied automatically. -/ @[simps] def rfl2 {α} : α ≃ α := foo.rfl example {α} (x : α) : rfl2.to_fun x = x ∧ rfl2.inv_fun x = x := begin dsimp only [rfl2_to_fun, rfl2_inv_fun], guard_target (x = x ∧ x = x), exact ⟨rfl, rfl⟩ end /- test `fully_applied` option -/ @[simps {fully_applied := ff}] def rfl3 {α} : α ≃ α := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ end foo /- we reduce the type when applying [simps] -/ def my_equiv := equiv' @[simps] def baz : my_equiv ℕ ℕ := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ /- test name clashes -/ def name_clash_fst := 1 def name_clash_snd := 1 def name_clash_snd_2 := 1 @[simps] def name_clash := (2, 3) run_cmd do e ← get_env, e.get `name_clash_fst_2, e.get `name_clash_snd_3 /- check projections for nested structures -/ namespace count_nested @[simps {attrs := [`simp, `norm]}] def nested1 : my_prod ℕ $ my_prod ℤ ℕ := ⟨2, -1, 1⟩ @[simps {attrs := []}] def nested2 : ℕ × my_prod ℕ ℕ := ⟨2, myprod.map nat.succ nat.pred ⟨1, 2⟩⟩ end count_nested run_cmd do e ← get_env, e.get `count_nested.nested1_fst, e.get `count_nested.nested1_snd_fst, e.get `count_nested.nested1_snd_snd, e.get `count_nested.nested2_fst, e.get `count_nested.nested2_snd, is_simp_lemma `count_nested.nested1_fst >>= λ b, guard b, -- simp attribute is global is_simp_lemma `count_nested.nested2_fst >>= λ b, guard $ ¬b, --lemmas_only doesn't add simp lemma guard $ 7 = e.fold 0 -- there are no other lemmas generated (λ d n, n + if d.to_name.components.init.ilast = `count_nested then 1 else 0) -- testing with arguments @[simps] def bar {α : Type*} (n m : ℕ) : ℕ × ℤ := ⟨n - m, n + m⟩ structure equiv_plus_data (α β) extends α ≃ β := (P : (α → β) → Prop) (data : P to_fun) structure automorphism_plus_data α extends α ⊕ α ≃ α ⊕ α := (P : (α ⊕ α → α ⊕ α) → Prop) (data : P to_fun) (extra : bool → my_prod ℕ ℕ) @[simps] def refl_with_data {α} : equiv_plus_data α α := { P := λ f, f = id, data := rfl, ..foo.rfl } @[simps] def refl_with_data' {α} : equiv_plus_data α α := { P := λ f, f = id, data := rfl, to_equiv' := foo.rfl } /- test whether eta expansions are reduced correctly -/ @[simps] def test {α} : automorphism_plus_data α := { P := λ f, f = id, data := rfl, extra := λ b, ⟨(⟨3, 5⟩ : my_prod _ _).1, (⟨3, 5⟩ : my_prod _ _).2⟩, ..foo.rfl } /- test whether this is indeed rejected as a valid eta expansion -/ @[simps] def test_sneaky {α} : automorphism_plus_data α := { P := λ f, f = id, data := rfl, extra := λ b, ⟨(3,5).1,(3,5).2⟩, ..foo.rfl } run_cmd do e ← get_env, e.get `refl_with_data_to_equiv', e.get `refl_with_data'_to_equiv', e.get `test_extra, e.get `test_sneaky_extra_fst, success_if_fail (e.get `refl_with_data_to_equiv_to_fun), success_if_fail (e.get `refl_with_data'_to_equiv_to_fun), success_if_fail (e.get `test_extra_fst), success_if_fail (e.get `test_sneaky_extra) structure partially_applied_str := (data : ℕ → my_prod ℕ ℕ) /- if we have a partially applied constructor, we treat it as if it were eta-expanded -/ @[simps] def partially_applied_term : partially_applied_str := ⟨my_prod.mk 3⟩ @[simps] def another_term : partially_applied_str := ⟨λ n, ⟨n + 1, n + 2⟩⟩ run_cmd do e ← get_env, e.get `partially_applied_term_data_fst, e.get `partially_applied_term_data_snd structure very_partially_applied_str := (data : ∀β, ℕ → β → my_prod ℕ β) /- if we have a partially applied constructor, we treat it as if it were eta-expanded. (this is not very useful, and we could remove this behavior if convenient) -/ @[simps] def very_partially_applied_term : very_partially_applied_str := ⟨@my_prod.mk ℕ⟩ run_cmd do e ← get_env, e.get `very_partially_applied_term_data_fst, e.get `very_partially_applied_term_data_snd @[simps] def let1 : ℕ × ℤ := let n := 3 in ⟨n + 4, 5⟩ @[simps] def let2 : ℕ × ℤ := let n := 3, m := 4 in let k := 5 in ⟨n + m, k⟩ @[simps] def let3 : ℕ → ℕ × ℤ := λ n, let m := 4, k := 5 in ⟨n + m, k⟩ @[simps] def let4 : ℕ → ℕ × ℤ := let m := 4, k := 5 in λ n, ⟨n + m, k⟩ run_cmd do e ← get_env, e.get `let1_fst, e.get `let2_fst, e.get `let3_fst, e.get `let4_fst, e.get `let1_snd, e.get `let2_snd, e.get `let3_snd, e.get `let4_snd namespace specify @[simps fst] def specify1 : ℕ × ℕ × ℕ := (1, 2, 3) @[simps snd] def specify2 : ℕ × ℕ × ℕ := (1, 2, 3) @[simps snd_fst] def specify3 : ℕ × ℕ × ℕ := (1, 2, 3) @[simps snd snd_snd snd_snd] def specify4 : ℕ × ℕ × ℕ := (1, 2, 3) -- last argument is ignored @[simps] noncomputable def specify5 : ℕ × ℕ × ℕ := (1, classical.choice ⟨(2, 3)⟩) end specify run_cmd do e ← get_env, e.get `specify.specify1_fst, e.get `specify.specify2_snd, e.get `specify.specify3_snd_fst, e.get `specify.specify4_snd_snd, e.get `specify.specify4_snd, e.get `specify.specify5_fst, e.get `specify.specify5_snd, guard $ 12 = e.fold 0 -- there are no other lemmas generated (λ d n, n + if d.to_name.components.init.ilast = `specify then 1 else 0), success_if_fail_with_msg (simps_tac `specify.specify1 {} ["fst_fst"]) "Invalid simp lemma specify.specify1_fst_fst. Projection fst doesn't exist, because target is not a structure.", success_if_fail_with_msg (simps_tac `specify.specify1 {} ["foo_fst"]) "Invalid simp lemma specify.specify1_foo_fst. Structure prod does not have projection foo. The known projections are: [fst, snd] You can also see this information by running `initialize_simps_projections? prod`. Note: these projection names might not correspond to the projection names of the structure.", success_if_fail_with_msg (simps_tac `specify.specify1 {} ["snd_bar"]) "Invalid simp lemma specify.specify1_snd_bar. Structure prod does not have projection bar. The known projections are: [fst, snd] You can also see this information by running `initialize_simps_projections? prod`. Note: these projection names might not correspond to the projection names of the structure.", success_if_fail_with_msg (simps_tac `specify.specify5 {} ["snd_snd"]) "Invalid simp lemma specify.specify5_snd_snd. The given definition is not a constructor application: classical.choice specify.specify5._proof_1" /- We also eta-reduce if we explicitly specify the projection. -/ attribute [simps extra] test run_cmd do e ← get_env, d1 ← e.get `test_extra, d2 ← e.get `test_extra_2, guard $ d1.type =ₐ d2.type, skip /- check simp_rhs option -/ @[simps {simp_rhs := tt}] def equiv'.trans {α β γ} (f : α ≃ β) (g : β ≃ γ) : α ≃ γ := ⟨g.to_fun ∘ f.to_fun, f.inv_fun ∘ g.inv_fun, by { intro x, simp [equiv'.left_inv _ _] }, by { intro x, simp [equiv'.right_inv _ _] }⟩ example {α β γ : Type} (f : α ≃ β) (g : β ≃ γ) (x : α) : (f.trans g).to_fun x = (f.trans g).to_fun x := begin dsimp only [equiv'.trans_to_fun], guard_target g.to_fun (f.to_fun x) = g.to_fun (f.to_fun x), refl, end local attribute [simp] nat.zero_add nat.one_mul nat.mul_one @[simps {simp_rhs := tt}] def my_nat_equiv : ℕ ≃ ℕ := ⟨λ n, 0 + n, λ n, 1 * n * 1, by { intro n, simp }, by { intro n, simp }⟩ run_cmd success_if_fail (has_attribute `_refl_lemma `my_nat_equiv'_to_fun) >> has_attribute `_refl_lemma `equiv'.trans_to_fun example (n : ℕ) : my_nat_equiv.to_fun (my_nat_equiv.to_fun $ my_nat_equiv.inv_fun n) = n := by { success_if_fail { refl }, simp only [my_nat_equiv_to_fun, my_nat_equiv_inv_fun] } @[simps {simp_rhs := tt}] def succeed_without_simplification_possible : ℕ ≃ ℕ := ⟨λ n, n, λ n, n, by { intro n, refl }, by { intro n, refl }⟩ /- test that we don't recursively take projections of `prod` and `pprod` -/ @[simps] def pprod_equiv_prod : pprod ℕ ℕ ≃ ℕ × ℕ := { to_fun := λ x, ⟨x.1, x.2⟩, inv_fun := λ x, ⟨x.1, x.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } run_cmd do e ← get_env, e.get `pprod_equiv_prod_to_fun, e.get `pprod_equiv_prod_inv_fun attribute [simps to_fun_fst inv_fun_snd] pprod_equiv_prod run_cmd do e ← get_env, e.get `pprod_equiv_prod_to_fun_fst, e.get `pprod_equiv_prod_inv_fun_snd -- we can disable this behavior with the option `not_recursive`. @[simps {not_recursive := []}] def pprod_equiv_prod2 : pprod ℕ ℕ ≃ ℕ × ℕ := pprod_equiv_prod run_cmd do e ← get_env, e.get `pprod_equiv_prod2_to_fun_fst, e.get `pprod_equiv_prod2_to_fun_snd, e.get `pprod_equiv_prod2_inv_fun_fst, e.get `pprod_equiv_prod2_inv_fun_snd /- Tests with universe levels -/ class has_hom (obj : Type u) : Type (max u (v+1)) := (hom : obj → obj → Type v) infixr ` ⟶ `:10 := has_hom.hom -- type as \h class category_struct (obj : Type u) extends has_hom.{v} obj : Type (max u (v+1)) := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg @[simps] instance types : category_struct (Type u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } example (X : Type u) : (X ⟶ X) = (X → X) := by simp example (X : Type u) : 𝟙 X = (λ x, x) := by { funext, simp } example (X Y Z : Type u) (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := by { funext, simp } namespace coercing structure foo_str := (c : Type) (x : c) instance : has_coe_to_sort foo_str Type := ⟨foo_str.c⟩ @[simps] def foo : foo_str := ⟨ℕ, 3⟩ @[simps] def foo2 : foo_str := ⟨ℕ, 34⟩ example : ↥foo = ℕ := by simp only [foo_c] example : foo.x = (3 : ℕ) := by simp only [foo_x] structure voo_str (n : ℕ) := (c : Type) (x : c) instance has_coe_voo_str (n : ℕ) : has_coe_to_sort (voo_str n) Type := ⟨voo_str.c⟩ @[simps] def voo : voo_str 7 := ⟨ℕ, 3⟩ @[simps] def voo2 : voo_str 4 := ⟨ℕ, 34⟩ example : ↥voo = ℕ := by simp only [voo_c] example : voo.x = (3 : ℕ) := by simp only [voo_x] structure equiv2 (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) instance {α β} : has_coe_to_fun (equiv2 α β) (λ _, α → β) := ⟨equiv2.to_fun⟩ @[simps] protected def rfl2 {α} : equiv2 α α := ⟨λ x, x, λ x, x, λ x, rfl, λ x, rfl⟩ example {α} (x : α) : coercing.rfl2 x = x := by rw [coercing.rfl2_to_fun] example {α} (x : α) : coercing.rfl2 x = x := by simp example {α} (x : α) : coercing.rfl2.inv_fun x = x := by simp @[simps] protected def equiv2.symm {α β} (f : equiv2 α β) : equiv2 β α := ⟨f.inv_fun, f, f.right_inv, f.left_inv⟩ @[simps] protected def equiv2.symm2 {α β} (f : equiv2 α β) : equiv2 β α := ⟨f.inv_fun, f.to_fun, f.right_inv, f.left_inv⟩ @[simps {fully_applied := ff}] protected def equiv2.symm3 {α β} (f : equiv2 α β) : equiv2 β α := ⟨f.inv_fun, f, f.right_inv, f.left_inv⟩ example {α β} (f : equiv2 α β) (y : β) : f.symm y = f.inv_fun y := by simp example {α β} (f : equiv2 α β) (x : α) : f.symm.inv_fun x = f x := by simp example {α β} (f : equiv2 α β) : f.symm.inv_fun = f := by { success_if_fail {simp}, refl } example {α β} (f : equiv2 α β) : f.symm3.inv_fun = f := by simp section set_option old_structure_cmd true class semigroup (G : Type u) extends has_mul G := (mul_assoc : ∀ a b c : G, a * b * c = a * (b * c)) end @[simps] instance {α β} [semigroup α] [semigroup β] : semigroup (α × β) := { mul := λ x y, (x.1 * y.1, x.2 * y.2), mul_assoc := by { intros, simp only [semigroup.mul_assoc], refl } } example {α β} [semigroup α] [semigroup β] (x y : α × β) : x * y = (x.1 * y.1, x.2 * y.2) := by simp example {α β} [semigroup α] [semigroup β] (x y : α × β) : (x * y).1 = x.1 * y.1 := by simp structure Semigroup := (G : Type*) (op : G → G → G) (infix (name := op) ` * ` := op) (op_assoc : ∀ (x y z : G), (x * y) * z = x * (y * z)) namespace Group instance : has_coe_to_sort Semigroup Type* := ⟨Semigroup.G⟩ -- We could try to generate lemmas with this `has_mul` instance, but it is unused in mathlib. -- Therefore, this is ignored. instance (G : Semigroup) : has_mul G := ⟨G.op⟩ @[simps] def prod_Semigroup (G H : Semigroup) : Semigroup := { G := G × H, op := λ x y, (x.1 * y.1, x.2 * y.2), op_assoc := by { intros, dsimp [Group.has_mul], simp [Semigroup.op_assoc] }} end Group section set_option old_structure_cmd true class extending_stuff (G : Type u) extends has_mul G, has_zero G, has_neg G, has_subset G := (new_axiom : ∀ x : G, x * - 0 ⊆ - x) end @[simps] def bar : extending_stuff ℕ := { mul := (*), zero := 0, neg := nat.succ, subset := λ x y, true, new_axiom := λ x, trivial } section local attribute [instance] bar example (x : ℕ) : x * - 0 ⊆ - x := by simp end class new_extending_stuff (G : Type u) extends has_mul G, has_zero G, has_neg G, has_subset G := (new_axiom : ∀ x : G, x * - 0 ⊆ - x) @[simps] def new_bar : new_extending_stuff ℕ := { mul := (*), zero := 0, neg := nat.succ, subset := λ x y, true, new_axiom := λ x, trivial } section local attribute [instance] new_bar example (x : ℕ) : x * - 0 ⊆ - x := by simp end end coercing namespace manual_coercion structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := manual_coercion.equiv variables {α β γ : Sort*} instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ def equiv.simps.inv_fun (e : α ≃ β) : β → α := e.symm /-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/ @[simps {simp_rhs := tt}] protected def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ example (e₁ : α ≃ β) (e₂ : β ≃ γ) (x : γ) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := by simp only [equiv.trans_inv_fun] end manual_coercion namespace faulty_manual_coercion structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := faulty_manual_coercion.equiv variables {α β γ : Sort*} /-- See Note [custom simps projection] -/ noncomputable def equiv.simps.inv_fun (e : α ≃ β) : β → α := classical.choice ⟨e.inv_fun⟩ run_cmd do e ← get_env, success_if_fail_with_msg (simps_get_raw_projections e `faulty_manual_coercion.equiv) "Invalid custom projection: λ {α : Sort u_1} {β : Sort u_2} (e : α ≃ β), classical.choice _ Expression is not definitionally equal to λ (α : Sort u_1) (β : Sort u_2) (x : α ≃ β), x.inv_fun" end faulty_manual_coercion namespace manual_initialize /- defining a manual coercion. -/ variables {α β γ : Sort*} structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := manual_initialize.equiv instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ -- test: intentionally using different unvierse levels for equiv.symm than for equiv def equiv.simps.inv_fun (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv run_cmd has_attribute `_simps_str `manual_initialize.equiv /-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/ @[simps {simp_rhs := tt}] protected def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ end manual_initialize namespace faulty_universes variables {α β γ : Sort*} structure equiv (α : Sort u) (β : Sort v) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := faulty_universes.equiv instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ -- test: intentionally using different names for the universe variables for equiv.symm than for -- equiv def equiv.simps.inv_fun {α : Type u} {β : Type v} (e : α ≃ β) : β → α := e.symm run_cmd do e ← get_env, success_if_fail_with_msg (simps_get_raw_projections e `faulty_universes.equiv) "Invalid custom projection: λ {α : Type u} {β : Type v} (e : α ≃ β), ⇑(e.symm) Expression has different type than faulty_universes.equiv.inv_fun. Given type: Π {α : Type u} {β : Type v} (e : α ≃ β), (λ (_x : β ≃ α), β → α) e.symm Expected type: Π (α : Sort u) (β : Sort v), α ≃ β → β → α" end faulty_universes namespace manual_universes variables {α β γ : Sort*} structure equiv (α : Sort u) (β : Sort v) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := manual_universes.equiv instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ -- test: intentionally using different unvierse levels for equiv.symm than for equiv def equiv.simps.inv_fun {α : Sort w} {β : Sort u} (e : α ≃ β) : β → α := e.symm -- check whether we can generate custom projections even if the universe names don't match initialize_simps_projections equiv end manual_universes namespace manual_projection_names structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := manual_projection_names.equiv variables {α β γ : Sort*} instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ def equiv.simps.symm_apply (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply) run_cmd do e ← get_env, data ← simps_get_raw_projections e `manual_projection_names.equiv, guard $ data.2.map projection_data.name = [`apply, `symm_apply] @[simps {simp_rhs := tt}] protected def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ example (e₁ : α ≃ β) (e₂ : β ≃ γ) (x : α) : (e₁.trans e₂) x = e₂ (e₁ x) := by simp only [equiv.trans_apply] example (e₁ : α ≃ β) (e₂ : β ≃ γ) (x : γ) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := by simp only [equiv.trans_symm_apply] -- the new projection names are parsed correctly (the old projection names won't work anymore) @[simps apply symm_apply] protected def equiv.trans2 (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ end manual_projection_names namespace prefix_projection_names structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := prefix_projection_names.equiv variables {α β γ : Sort*} instance : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ def equiv.simps.symm_apply (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv (to_fun → coe as_prefix, inv_fun → symm_apply) run_cmd do e ← get_env, data ← simps_get_raw_projections e `prefix_projection_names.equiv, guard $ data.2.map projection_data.name = [`coe, `symm_apply], guard $ data.2.map projection_data.is_prefix = [tt, ff] @[simps {simp_rhs := tt}] protected def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ example (e₁ : α ≃ β) (e₂ : β ≃ γ) (x : α) : (e₁.trans e₂) x = e₂ (e₁ x) := by simp only [equiv.coe_trans] -- the new projection names are parsed correctly @[simps coe symm_apply] protected def equiv.trans2 (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ -- it interacts somewhat well with multiple projections (though the generated name is not great) @[simps snd_coe_fst] def foo {α β γ δ : Type*} (x : α) (e₁ : α ≃ β) (e₂ : γ ≃ δ) : α × (α × γ ≃ β × δ) := ⟨x, prod.map e₁ e₂, prod.map e₁.symm e₂.symm⟩ example {α β γ δ : Type*} (x : α) (e₁ : α ≃ β) (e₂ : γ ≃ δ) (z : α × γ) : ((foo x e₁ e₂).2 z).1 = e₁ z.1 := by simp only [coe_foo_snd_fst] end prefix_projection_names -- test transparency setting structure set_plus (α : Type) := (s : set α) (x : α) (h : x ∈ s) @[simps] def nat_set_plus : set_plus ℕ := ⟨set.univ, 1, trivial⟩ example : nat_set_plus.s = set.univ := begin dsimp only [nat_set_plus_s], guard_target @set.univ ℕ = set.univ, refl end @[simps {type_md := semireducible}] def nat_set_plus2 : set_plus ℕ := ⟨set.univ, 1, trivial⟩ example : nat_set_plus2.s = set.univ := begin success_if_fail { dsimp only [nat_set_plus2_s] }, refl end @[simps {rhs_md := semireducible}] def nat_set_plus3 : set_plus ℕ := nat_set_plus example : nat_set_plus3.s = set.univ := begin dsimp only [nat_set_plus3_s], guard_target @set.univ ℕ = set.univ, refl end namespace nested_non_fully_applied structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix (name := equiv) ` ≃ `:25 := nested_non_fully_applied.equiv variables {α β γ : Sort*} @[simps] def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ @[simps {rhs_md := semireducible, fully_applied := ff}] def equiv.symm2 : (α ≃ β) ≃ (β ≃ α) := ⟨equiv.symm, equiv.symm⟩ example (e : α ≃ β) : (equiv.symm2.inv_fun e).to_fun = e.inv_fun := begin dsimp only [equiv.symm2_inv_fun_to_fun], guard_target e.inv_fun = e.inv_fun, refl end /- do not prematurely unfold `equiv.symm`, unless necessary -/ @[simps to_fun to_fun_to_fun {rhs_md := semireducible}] def equiv.symm3 : (α ≃ β) ≃ (β ≃ α) := equiv.symm2 example (e : α ≃ β) (y : β) : (equiv.symm3.to_fun e).to_fun y = e.inv_fun y ∧ (equiv.symm3.to_fun e).to_fun y = e.inv_fun y := begin split, { dsimp only [equiv.symm3_to_fun], guard_target e.symm.to_fun y = e.inv_fun y, refl }, { dsimp only [equiv.symm3_to_fun_to_fun], guard_target e.inv_fun y = e.inv_fun y, refl } end end nested_non_fully_applied -- test that type classes which are props work class prop_class (n : ℕ) : Prop := (has_true : true) instance has_prop_class (n : ℕ) : prop_class n := ⟨trivial⟩ structure needs_prop_class (n : ℕ) [prop_class n] := (t : true) @[simps] def test_prop_class : needs_prop_class 1 := { t := trivial } /- check that when the coercion is given in eta-expanded form, we can also find the coercion. -/ structure alg_hom (R A B : Type*) := (to_fun : A → B) instance (R A B : Type*) : has_coe_to_fun (alg_hom R A B) (λ _, A → B) := ⟨λ f, f.to_fun⟩ @[simps] def my_alg_hom : alg_hom unit bool bool := { to_fun := id } example (x : bool) : my_alg_hom x = id x := by simp only [my_alg_hom_to_fun] structure ring_hom (A B : Type*) := (to_fun : A → B) instance (A B : Type*) : has_coe_to_fun (ring_hom A B) (λ _, A → B) := ⟨λ f, f.to_fun⟩ @[simps] def my_ring_hom : ring_hom bool bool := { to_fun := id } example (x : bool) : my_ring_hom x = id x := by simp only [my_ring_hom_to_fun] /- check interaction with the `@[to_additive]` attribute -/ @[to_additive, simps] instance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ run_cmd do get_decl `prod.has_mul_mul, get_decl `prod.has_add_add, has_attribute `to_additive `prod.has_mul, has_attribute `to_additive `prod.has_mul_mul, has_attribute `simp `prod.has_mul_mul, has_attribute `simp `prod.has_add_add example {M N} [has_mul M] [has_mul N] (p q : M × N) : p * q = ⟨p.1 * q.1, p.2 * q.2⟩ := by simp example {M N} [has_add M] [has_add N] (p q : M × N) : p + q = ⟨p.1 + q.1, p.2 + q.2⟩ := by simp /- The names of the generated simp lemmas for the additive version are not great if the definition had a custom additive name -/ @[to_additive my_add_instance, simps] instance my_instance {M N} [has_one M] [has_one N] : has_one (M × N) := ⟨(1, 1)⟩ run_cmd do get_decl `my_instance_one, get_decl `my_add_instance_zero, has_attribute `to_additive `my_instance, has_attribute `to_additive `my_instance_one, has_attribute `simp `my_instance_one, has_attribute `simp `my_add_instance_zero example {M N} [has_one M] [has_one N] : (1 : M × N) = ⟨1, 1⟩ := by simp example {M N} [has_zero M] [has_zero N] : (0 : M × N) = ⟨0, 0⟩ := by simp section /-! Test `dsimp, simp` with the option `simp_rhs` -/ local attribute [simp] nat.add structure my_type := (A : Type) @[simps {simp_rhs := tt}] def my_type_def : my_type := ⟨{ x : fin (nat.add 3 0) // 1 + 1 = 2 }⟩ example (h : false) (x y : { x : fin (nat.add 3 0) // 1 + 1 = 2 }) : my_type_def.A = unit := begin simp only [my_type_def_A], guard_target ({ x : fin 3 // true } = unit), /- note: calling only one of `simp` or `dsimp` does not produce the current target, as the following tests show. -/ success_if_fail { guard_hyp x : { x : fin 3 // true } }, dsimp at x, success_if_fail { guard_hyp x : { x : fin 3 // true } }, simp at y, success_if_fail { guard_hyp y : { x : fin 3 // true } }, simp at x, dsimp at y, guard_hyp x : { x : fin 3 // true }, guard_hyp y : { x : fin 3 // true }, contradiction end /- Test that `to_additive` copies the `@[_refl_lemma]` attribute correctly -/ @[to_additive, simps] def monoid_hom.my_comp {M N P : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] (hnp : N →* P) (hmn : M →* N) : M →* P := { to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp, } -- `simps` adds the `_refl_lemma` attribute to `monoid_hom.my_comp_apply` example {M N P : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] (hnp : N →* P) (hmn : M →* N) (m : M) : hnp.my_comp hmn m = hnp (hmn m) := by { dsimp, guard_target (hnp (hmn m) = hnp (hmn m)), refl } -- `to_additive` adds the `_refl_lemma` attribute to `add_monoid_hom.my_comp_apply` example {M N P : Type*} [add_zero_class M] [add_zero_class N] [add_zero_class P] (hnp : N →+ P) (hmn : M →+ N) (m : M) : hnp.my_comp hmn m = hnp (hmn m) := by { dsimp, guard_target (hnp (hmn m) = hnp (hmn m)), refl } -- test that `to_additive` works with a custom name @[to_additive some_test2, simps] def some_test1 (M : Type*) [comm_monoid M] : subtype (λ f : M, true) := ⟨1, trivial⟩ run_cmd get_decl `some_test2_coe end /- Test custom compositions of projections. -/ section comp_projs instance {α β} : has_coe_to_fun (α ≃ β) (λ _, α → β) := ⟨equiv'.to_fun⟩ @[simps] protected def equiv'.symm {α β} (f : α ≃ β) : β ≃ α := ⟨f.inv_fun, f, f.right_inv, f.left_inv⟩ structure decorated_equiv (α : Sort*) (β : Sort*) extends equiv' α β := (P_to_fun : function.injective to_fun ) (P_inv_fun : function.injective inv_fun) instance {α β} : has_coe_to_fun (decorated_equiv α β) (λ _, α → β) := ⟨λ f, f.to_equiv'⟩ def decorated_equiv.symm {α β : Sort*} (e : decorated_equiv α β) : decorated_equiv β α := { to_equiv' := e.to_equiv'.symm, P_to_fun := e.P_inv_fun, P_inv_fun := e.P_to_fun } def decorated_equiv.simps.apply {α β : Sort*} (e : decorated_equiv α β) : α → β := e def decorated_equiv.simps.symm_apply {α β : Sort*} (e : decorated_equiv α β) : β → α := e.symm initialize_simps_projections decorated_equiv (to_equiv'_to_fun → apply, to_equiv'_inv_fun → symm_apply, -to_equiv') @[simps] def foo (α : Type) : decorated_equiv α α := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h } example {α : Type} (x : α) : (foo α).symm x = x := by { dsimp, guard_target (x = x), refl } @[simps to_equiv' apply symm_apply] def foo2 (α : Type) : decorated_equiv α α := { P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h, ..foo.rfl } example {α : Type} (x : α) : (foo2 α).to_equiv' x = x := by { dsimp, guard_target (foo.rfl x = x), refl } example {α : Type} (x : α) : foo2 α x = x := by { dsimp, guard_target (x = x), refl } structure further_decorated_equiv (α : Sort*) (β : Sort*) extends decorated_equiv α β := (Q_to_fun : function.surjective to_fun ) (Q_inv_fun : function.surjective inv_fun ) instance {α β} : has_coe_to_fun (further_decorated_equiv α β) (λ _, α → β) := ⟨λ f, f.to_decorated_equiv⟩ def further_decorated_equiv.symm {α β : Sort*} (e : further_decorated_equiv α β) : further_decorated_equiv β α := { to_decorated_equiv := e.to_decorated_equiv.symm, Q_to_fun := e.Q_inv_fun, Q_inv_fun := e.Q_to_fun } def further_decorated_equiv.simps.apply {α β : Sort*} (e : further_decorated_equiv α β) : α → β := e def further_decorated_equiv.simps.symm_apply {α β : Sort*} (e : further_decorated_equiv α β) : β → α := e.symm initialize_simps_projections further_decorated_equiv (to_decorated_equiv_to_equiv'_to_fun → apply, to_decorated_equiv_to_equiv'_inv_fun → symm_apply, -to_decorated_equiv, to_decorated_equiv_to_equiv' → to_equiv', -to_equiv') @[simps] def ffoo (α : Type) : further_decorated_equiv α α := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h, Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩ } example {α : Type} (x : α) : (ffoo α).symm x = x := by { dsimp, guard_target (x = x), refl } @[simps] def ffoo3 (α : Type) : further_decorated_equiv α α := { Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩, .. foo α } @[simps apply to_equiv'_to_fun to_decorated_equiv_apply] def ffoo4 (α : Type) : further_decorated_equiv α α := { Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩, to_decorated_equiv := foo α } structure one_more (α : Sort*) (β : Sort*) extends further_decorated_equiv α β instance {α β} : has_coe_to_fun (one_more α β) (λ _, α → β) := ⟨λ f, f.to_further_decorated_equiv⟩ def one_more.symm {α β : Sort*} (e : one_more α β) : one_more β α := { to_further_decorated_equiv := e.to_further_decorated_equiv.symm } def one_more.simps.apply {α β : Sort*} (e : one_more α β) : α → β := e def one_more.simps.symm_apply {α β : Sort*} (e : one_more α β) : β → α := e.symm initialize_simps_projections one_more (to_further_decorated_equiv_to_decorated_equiv_to_equiv'_to_fun → apply, to_further_decorated_equiv_to_decorated_equiv_to_equiv'_inv_fun → symm_apply, -to_further_decorated_equiv, to_further_decorated_equiv_to_decorated_equiv → to_dequiv, -to_dequiv) @[simps] def fffoo (α : Type) : one_more α α := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h, Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩ } example {α : Type} (x : α) : (fffoo α).symm x = x := by { dsimp, guard_target (x = x), refl } @[simps apply to_dequiv_apply to_further_decorated_equiv_apply to_dequiv] def fffoo2 (α : Type) : one_more α α := fffoo α /- test the case where a projection takes additional arguments. -/ variables {ι : Type*} [decidable_eq ι] (A : ι → Type*) class something [has_add ι] [Π i, add_comm_monoid (A i)] := (mul {i} : A i →+ A i) def something.simps.apply [has_add ι] [Π i, add_comm_monoid (A i)] [something A] {i : ι} (x : A i) : A i := something.mul ι x initialize_simps_projections something (mul_to_fun → apply, -mul) class something2 [has_add ι] := (mul {i j} : A i ≃ (A j ≃ A (i + j))) def something2.simps.mul [has_add ι] [something2 A] {i j : ι} (x : A i) (y : A j) : A (i + j) := something2.mul x y initialize_simps_projections something2 (mul → mul', mul_to_fun_to_fun → mul, -mul') attribute [ext] equiv' @[simps] def thing (h : bool ≃ (bool ≃ bool)) : something2 (λ x : ℕ, bool) := { mul := λ i j, { to_fun := λ b, { to_fun := h b, inv_fun := (h b).symm, left_inv := (h b).left_inv, right_inv := (h b).right_inv }, inv_fun := h.symm, left_inv := by { convert h.left_inv, ext x; refl }, right_inv := by { convert h.right_inv, ext x; refl } } } example (h : bool ≃ (bool ≃ bool)) (i j : ℕ) (b1 b2 : bool) : @something2.mul _ _ _ _ (thing h) i j b1 b2 = h b1 b2 := by simp only [thing_mul] end comp_projs section /-! Check that the tactic also works if the elaborated type of `type` reduces to `Sort*`, but is not `Sort*` itself. -/ structure my_functor (C D : Type*) := (obj [] : C → D) local infixr ` ⥤ `:26 := my_functor @[simps] def foo_sum {I J : Type*} (C : I → Type*) {D : J → Type*} : (Π i, C i) ⥤ (Π j, D j) ⥤ (Π s : I ⊕ J, sum.elim C D s) := { obj := λ f, { obj := λ g s, sum.rec f g s }} end
644c20fcdd429b089fcf8f80340cb8624c459d0a
649957717d58c43b5d8d200da34bf374293fe739
/src/analysis/calculus/deriv.lean
2c404b69b7a5f63bf2d88c38c8daaec31dbd232c
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
45,558
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel The Fréchet derivative. Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[k] F` a continuous k-linear map, where `k` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at k f s x` (where `k` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at k f x`, `differentiable_on k f s` and `differentiable k f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within k f s x` and `fderiv k f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * bounded bilinear maps * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) -/ -- import topology.sequences topology.opens import analysis.asymptotics import analysis.calculus.tangent_cone open filter asymptotics continuous_linear_map set noncomputable theory local attribute [instance, priority 0] classical.decidable_inhabited classical.prop_decidable set_option class.instance_max_depth 100 section variables {k : Type*} [nondiscrete_normed_field k] variables {E : Type*} [normed_group E] [normed_space k E] variables {F : Type*} [normed_group F] [normed_space k F] variables {G : Type*} [normed_group G] [normed_space k G] def has_fderiv_at_filter (f : E → F) (f' : E →L[k] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L def has_fderiv_within_at (f : E → F) (f' : E →L[k] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (nhds_within x s) def has_fderiv_at (f : E → F) (f' : E →L[k] F) (x : E) := has_fderiv_at_filter f f' x (nhds x) variables (k) def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[k] F, has_fderiv_within_at f f' s x def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[k] F, has_fderiv_at f f' x def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[k] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 def fderiv (f : E → F) (x : E) : E →L[k] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at k f s x def differentiable (f : E → F) := ∀x, differentiable_at k f x variables {k} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[k] F} variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at k s x) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := begin have A : ∀y ∈ tangent_cone_at k s x, f' y = f₁' y, { assume y hy, rcases hy with ⟨c, d, hd, hc, ylim⟩, have at_top_is_finer : at_top ≤ comap (λ (n : ℕ), x + d n) (nhds_within (x + 0) s), { rw [←tendsto_iff_comap, nhds_within, tendsto_inf], split, { apply tendsto_add tendsto_const_nhds (tangent_cone_at.lim_zero hc ylim) }, { rwa tendsto_principal } }, rw add_zero at at_top_is_finer, have : is_o (λ y, f₁' (y - x) - f' (y - x)) (λ y, y - x) (nhds_within x s), by simpa using h.sub h₁, have : is_o (λ n:ℕ, f₁' ((x + d n) - x) - f' ((x + d n) - x)) (λ n, (x + d n) - x) ((nhds_within x s).comap (λn, x+ d n)) := is_o.comp this _, have L1 : is_o (λ n:ℕ, f₁' (d n) - f' (d n)) d ((nhds_within x s).comap (λn, x + d n)) := by simpa using this, have L2 : is_o (λn:ℕ, f₁' (d n) - f' (d n)) d at_top := is_o.mono at_top_is_finer L1, have L3 : is_o (λn:ℕ, c n • (f₁' (d n) - f' (d n))) (λn, c n • d n) at_top := is_o_smul L2, have L4 : is_o (λn:ℕ, c n • (f₁' (d n) - f' (d n))) (λn, (1:ℝ)) at_top := L3.trans_is_O (is_O_one_of_tendsto ylim), have L : tendsto (λn:ℕ, c n • (f₁' (d n) - f' (d n))) at_top (nhds 0) := is_o_one_iff.1 L4, have L' : tendsto (λ (n : ℕ), c n • (f₁' (d n) - f' (d n))) at_top (nhds (f₁' y - f' y)), { simp only [smul_sub, (continuous_linear_map.map_smul _ _ _).symm], apply tendsto_sub ((f₁'.continuous.tendsto _).comp ylim) ((f'.continuous.tendsto _).comp ylim) }, have : f₁' y - f' y = 0 := tendsto_nhds_unique (by simp) L' L, exact (sub_eq_zero_iff_eq.1 this).symm }, have B : ∀y ∈ submodule.span k (tangent_cone_at k s x), f' y = f₁' y, { assume y hy, apply submodule.span_induction hy, { exact λy hy, A y hy }, { simp only [continuous_linear_map.map_zero] }, { simp {contextual := tt} }, { simp {contextual := tt} } }, have C : ∀y ∈ closure ((submodule.span k (tangent_cone_at k s x)) : set E), f' y = f₁' y, { assume y hy, let K := {y | f' y = f₁' y}, have : (submodule.span k (tangent_cone_at k s x) : set E) ⊆ K := B, have : closure (submodule.span k (tangent_cone_at k s x) : set E) ⊆ closure K := closure_mono this, have : y ∈ closure K := this hy, rwa closure_eq_of_is_closed (is_closed_eq f'.continuous f₁'.continuous) at this }, unfold unique_diff_within_at at H, rw H.1 at C, ext y, exact C y (mem_univ _) end theorem unique_diff_on.eq (H : unique_diff_on k s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := unique_diff_within_at.eq (H x hx) h h₁ end derivative_uniqueness /- Basic properties of the derivative -/ section fderiv_properties theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (nhds 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 ((norm_eq_zero (x' - x)).1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto.congr'r (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds_within x s) (nhds 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds x) (nhds 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := is_o.mono hst h theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ nhds x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter lattice.inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at k f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at k f x := ⟨f', h⟩ lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at k f s x) : has_fderiv_within_at f (fderiv_within k f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at k f x) : has_fderiv_at f (fderiv k f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_within_at.mono {t : set E} (h : s ⊆ t) (h : differentiable_within_at k f t x) : differentiable_within_at k f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono h⟩ end lemma differentiable_within_univ_at : differentiable_within_at k f univ x ↔ differentiable_at k f x := begin unfold differentiable_within_at has_fderiv_within_at, rw nhds_within_univ, refl end @[simp] lemma has_fderiv_within_univ_at : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } theorem has_fderiv_at_unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_univ_at at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma differentiable_at.differentiable_within_at (h : differentiable_at k f x) : differentiable_within_at k f s x := differentiable_within_at.mono (subset_univ _) (differentiable_within_univ_at.2 h) lemma differentiable_within_at.differentiable_at' (h : differentiable_within_at k f s x) (hs : s ∈ nhds x) : differentiable_at k f x := begin unfold differentiable_within_at has_fderiv_within_at at h, have : nhds_within x s = nhds x := lattice.inf_of_le_left (le_principal_iff.2 hs), rwa this at h, end lemma differentiable_within_at.differentiable_at (h : differentiable_within_at k f s x) (hx : x ∈ s) (hs : is_open s) : differentiable_at k f x := h.differentiable_at' (mem_nhds_sets hs hx) lemma has_fderiv_within_at.fderiv_within {f' : E →L[k] F} (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at k s x) : fderiv_within k f s x = f' := by { ext, rw hxs.eq h h.differentiable_within_at.has_fderiv_within_at } lemma has_fderiv_at.fderiv {f' : E →L[k] F} (h : has_fderiv_at f f' x) : fderiv k f x = f' := by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at } lemma differentiable.fderiv_within (h : differentiable_at k f x) (hxs : unique_diff_within_at k s x) : fderiv_within k f s x = fderiv k f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono {f : E → F} {s t : set E} (h : differentiable_on k f t) (st : s ⊆ t) : differentiable_on k f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on k f univ ↔ differentiable k f := by { simp [differentiable_on, differentiable_within_univ_at], refl } lemma differentiable.differentiable_on (h : differentiable k f) : differentiable_on k f s := (differentiable_on_univ.2 h).mono (subset_univ _) @[simp] lemma fderiv_within_univ : fderiv_within k f univ = fderiv k f := begin ext x : 1, by_cases h : differentiable_at k f x, { apply has_fderiv_within_at.fderiv_within _ (is_open_univ.unique_diff_within_at (mem_univ _)), rw has_fderiv_within_univ_at, apply h.has_fderiv_at }, { have : fderiv k f x = 0, by { unfold differentiable_at at h, simp [fderiv, h] }, rw this, have : ¬(differentiable_within_at k f univ x), by rwa differentiable_within_univ_at, unfold differentiable_within_at at this, simp [fderiv_within, this, -has_fderiv_within_univ_at] } end lemma differentiable_within_at_inter (xs : x ∈ s) (xt : x ∈ t) (ht : is_open t) : differentiable_within_at k f (s ∩ t) x ↔ differentiable_within_at k f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict s xt ht] lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on k f (s ∩ u)) : differentiable_on k f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter xs xt t_open).1 (ht x ⟨xs, xt⟩) end end fderiv_properties /- Congr -/ section congr theorem has_fderiv_at_filter_congr' (hx : f₀ x = f₁ x) (h₀ : {x | f₀ x = f₁ x} ∈ L) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := by { rw (ext h₁), exact is_o_congr (by filter_upwards [h₀] λ x (h : _ = _), by simp [h, hx]) (univ_mem_sets' $ λ _, rfl) } theorem has_fderiv_at_filter_congr (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := has_fderiv_at_filter_congr' (h₀ _) (univ_mem_sets' h₀) h₁ theorem has_fderiv_at_filter.congr (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L → has_fderiv_at_filter f₁ f₁' x L := (has_fderiv_at_filter_congr h₀ h₁).1 theorem has_fderiv_within_at_congr (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_within_at f₀ f₀' s x ↔ has_fderiv_within_at f₁ f₁' s x := has_fderiv_at_filter_congr h₀ h₁ theorem has_fderiv_within_at.congr (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_within_at f₀ f₀' s x → has_fderiv_within_at f₁ f₁' s x := (has_fderiv_within_at_congr h₀ h₁).1 theorem has_fderiv_at_congr (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at f₀ f₀' x ↔ has_fderiv_at f₁ f₁' x := has_fderiv_at_filter_congr h₀ h₁ theorem has_fderiv_at.congr (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at f₀ f₀' x → has_fderiv_at f₁ f₁' x := (has_fderiv_at_congr h₀ h₁).1 lemma has_fderiv_at_filter.congr' (h : has_fderiv_at_filter f f' x L) (hL : {x | f₁ x = f x} ∈ L) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := begin refine (asymptotics.is_o_congr_left _).1 h, convert hL, ext, finish [hx], end lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr' (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma differentiable_within_at.congr_mono (h : differentiable_within_at k f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at k f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_at.congr (h : differentiable_at k f x) (h' : ∀x, f₁ x = f x) : differentiable_at k f₁ x := by { have : f₁ = f, by { ext y, exact h' y }, rwa this } lemma differentiable_on.congr_mono (h : differentiable_on k f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on k f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable.congr (h : differentiable k f) (h' : ∀x, f₁ x = f x) : differentiable k f₁ := by { have : f₁ = f, by { ext y, exact h' y }, rwa this } lemma differentiable.congr' (h : differentiable_at k f x) (hL : {y | f₁ y = f y} ∈ nhds x) (hx : f₁ x = f x) : differentiable_at k f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr' h.has_fderiv_at hL hx) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at k f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at k t x) (h₁ : t ⊆ s) : fderiv_within k f₁ t x = fderiv_within k f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma differentiable_at.fderiv_congr (h : differentiable_at k f x) (h' : ∀x, f₁ x = f x) : fderiv k f₁ x = fderiv k f x := by { have : f₁ = f, by { ext y, exact h' y }, rwa this } lemma differentiable_at.fderiv_congr' (h : differentiable_at k f x) (hL : {y | f₁ y = f y} ∈ nhds x) (hx : f₁ x = f x) : fderiv k f₁ x = fderiv k f x := has_fderiv_at.fderiv (has_fderiv_at_filter.congr' h.has_fderiv_at hL hx) end congr /- id -/ section id theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id : E →L[k] E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id : E →L[k] E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id : E →L[k] E) x := has_fderiv_at_filter_id _ _ lemma differentiable_at_id : differentiable_at k id x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at k id s x := differentiable_at_id.differentiable_within_at lemma differentiable_id : differentiable k (id : E → E) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on k id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv k id x = id := has_fderiv_at.fderiv (has_fderiv_at_id x) lemma fderiv_within_id (hxs : unique_diff_within_at k s x) : fderiv_within k id s x = id := begin rw differentiable.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end end id /- constants -/ section const theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[k] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[k] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[k] F) x := has_fderiv_at_filter_const _ _ _ lemma differentiable_at_const (c : F) : differentiable_at k (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at k (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const (c : F) : fderiv k (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) lemma fderiv_within_const (c : F) (hxs : unique_diff_within_at k s x) : fderiv_within k (λy, c) s x = 0 := begin rw differentiable.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const _ end lemma differentiable_const (c : F) : differentiable k (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on k (λx, c) s := (differentiable_const _).differentiable_on end const /- Bounded linear maps -/ section is_bounded_linear_map lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map k f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := begin have : (λ (x' : E), f x' - f x - h.to_continuous_linear_map (x' - x)) = λx', 0, { ext, have : ∀a, h.to_continuous_linear_map a = f a := λa, rfl, simp, simp [this] }, rw [has_fderiv_at_filter, this], exact asymptotics.is_o_zero _ _ end lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map k f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map k f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map k f) : differentiable_at k f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map k f) : differentiable_within_at k f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map k f) : fderiv k f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map k f) (hxs : unique_diff_within_at k s x) : fderiv_within k f s x = h.to_continuous_linear_map := begin rw differentiable.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map k f) : differentiable k f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map k f) : differentiable_on k f s := h.differentiable.differentiable_on end is_bounded_linear_map /- multiplication by a constant -/ section smul_const theorem has_fderiv_at_filter.smul (h : has_fderiv_at_filter f f' x L) (c : k) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (is_o_const_smul_left h c).congr_left $ λ x, by simp [smul_neg, smul_add] theorem has_fderiv_within_at.smul (h : has_fderiv_within_at f f' s x) (c : k) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.smul c theorem has_fderiv_at.smul (h : has_fderiv_at f f' x) (c : k) : has_fderiv_at (λ x, c • f x) (c • f') x := h.smul c lemma differentiable_within_at.smul (h : differentiable_within_at k f s x) (c : k) : differentiable_within_at k (λy, c • f y) s x := (h.has_fderiv_within_at.smul c).differentiable_within_at lemma differentiable_at.smul (h : differentiable_at k f x) (c : k) : differentiable_at k (λy, c • f y) x := (h.has_fderiv_at.smul c).differentiable_at lemma differentiable_on.smul (h : differentiable_on k f s) (c : k) : differentiable_on k (λy, c • f y) s := λx hx, (h x hx).smul c lemma differentiable.smul (h : differentiable k f) (c : k) : differentiable k (λy, c • f y) := λx, (h x).smul c lemma fderiv_within_smul (hxs : unique_diff_within_at k s x) (h : differentiable_within_at k f s x) (c : k) : fderiv_within k (λy, c • f y) s x = c • fderiv_within k f s x := (h.has_fderiv_within_at.smul c).fderiv_within hxs lemma fderiv_smul (h : differentiable_at k f x) (c : k) : fderiv k (λy, c • f y) x = c • fderiv k f x := (h.has_fderiv_at.smul c).fderiv end smul_const /- add -/ section add theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at k f s x) (hg : differentiable_within_at k g s x) : differentiable_within_at k (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.add (hf : differentiable_at k f x) (hg : differentiable_at k g x) : differentiable_at k (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on k f s) (hg : differentiable_on k g s) : differentiable_on k (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) lemma differentiable.add (hf : differentiable k f) (hg : differentiable k g) : differentiable k (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at k s x) (hf : differentiable_within_at k f s x) (hg : differentiable_within_at k g s x) : fderiv_within k (λy, f y + g y) s x = fderiv_within k f s x + fderiv_within k g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at k f x) (hg : differentiable_at k g x) : fderiv k (λy, f y + g y) x = fderiv k f x + fderiv k g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv end add /- neg -/ section neg theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (h.smul (-1:k)).congr (by simp) (by simp) theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at k f s x) : differentiable_within_at k (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at lemma differentiable_at.neg (h : differentiable_at k f x) : differentiable_at k (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at lemma differentiable_on.neg (h : differentiable_on k f s) : differentiable_on k (λy, -f y) s := λx hx, (h x hx).neg lemma differentiable.neg (h : differentiable k f) : differentiable k (λy, -f y) := λx, (h x).neg lemma fderiv_within_neg (hxs : unique_diff_within_at k s x) (h : differentiable_within_at k f s x) : fderiv_within k (λy, -f y) s x = - fderiv_within k f s x := h.has_fderiv_within_at.neg.fderiv_within hxs lemma fderiv_neg (h : differentiable_at k f x) : fderiv k (λy, -f y) x = - fderiv k f x := h.has_fderiv_at.neg.fderiv end neg /- sub -/ section sub theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at k f s x) (hg : differentiable_within_at k g s x) : differentiable_within_at k (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.sub (hf : differentiable_at k f x) (hg : differentiable_at k g x) : differentiable_at k (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on k f s) (hg : differentiable_on k g s) : differentiable_on k (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) lemma differentiable.sub (hf : differentiable k f) (hg : differentiable k g) : differentiable k (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at k s x) (hf : differentiable_within_at k f s x) (hg : differentiable_within_at k g s x) : fderiv_within k (λy, f y - g y) s x = fderiv_within k f s x - fderiv_within k g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at k f x) (hg : differentiable_at k g x) : fderiv k (λy, f y - g y) x = fderiv k f x - fderiv k g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.to_is_O.congr_of_sub.2 (f'.is_O_sub _ _) end sub /- Continuity -/ section continuous theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ nhds x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (nhds (f x)) := begin have : tendsto (λ x', f x' - f x) L (nhds 0), { refine h.is_O_sub.trans_tendsto (tendsto_le_left hL _), rw ← sub_self x, exact tendsto_sub tendsto_id tendsto_const_nhds }, have := tendsto_add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds lattice.inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at k f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at k f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on k f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable k f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at end continuous /- Bounded bilinear maps -/ section bilinear_map variables {b : E × F → G} {u : set (E × F) } lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map k b) (p : E × F) : has_fderiv_at b (h.deriv p) p := begin have : (λ (x : E × F), b x - b p - (h.deriv p) (x - p)) = (λx, b (x.1 - p.1, x.2 - p.2)), { ext x, delta is_bounded_bilinear_map.deriv, change b x - b p - (b (p.1, x.2-p.2) + b (x.1-p.1, p.2)) = b (x.1 - p.1, x.2 - p.2), have : b x = b (x.1, x.2), by { cases x, refl }, rw this, have : b p = b (p.1, p.2), by { cases p, refl }, rw this, simp only [h.map_sub_left, h.map_sub_right], abel }, rw [has_fderiv_at, has_fderiv_at_filter, this], rcases h.bound with ⟨C, Cpos, hC⟩, have A : asymptotics.is_O (λx : E × F, b (x.1 - p.1, x.2 - p.2)) (λx, ∥x - p∥ * ∥x - p∥) (nhds p) := ⟨C, Cpos, filter.univ_mem_sets' (λx, begin simp only [mem_set_of_eq, norm_mul, norm_norm], calc ∥b (x.1 - p.1, x.2 - p.2)∥ ≤ C * ∥x.1 - p.1∥ * ∥x.2 - p.2∥ : hC _ _ ... ≤ C * ∥x-p∥ * ∥x-p∥ : by apply_rules [mul_le_mul, le_max_left, le_max_right, norm_nonneg, le_of_lt Cpos, le_refl, mul_nonneg, norm_nonneg, norm_nonneg] ... = C * (∥x-p∥ * ∥x-p∥) : mul_assoc _ _ _ end)⟩, have B : asymptotics.is_o (λ (x : E × F), ∥x - p∥ * ∥x - p∥) (λx, 1 * ∥x - p∥) (nhds p), { apply asymptotics.is_o_mul_right _ (asymptotics.is_O_refl _ _), rw [asymptotics.is_o_iff_tendsto], { simp only [div_one], have : 0 = ∥p - p∥, by simp, rw this, have : continuous (λx, ∥x-p∥) := continuous_norm.comp (continuous_sub continuous_id continuous_const), exact this.tendsto p }, simp only [forall_prop_of_false, not_false_iff, one_ne_zero, forall_true_iff] }, simp only [one_mul, asymptotics.is_o_norm_right] at B, exact A.trans_is_o B end lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map k b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map k b) (p : E × F) : differentiable_at k b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map k b) (p : E × F) : differentiable_within_at k b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map k b) (p : E × F) : fderiv k b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map k b) (p : E × F) (hxs : unique_diff_within_at k u p) : fderiv_within k b u p = h.deriv p := begin rw differentiable.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map k b) : differentiable k b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map k b) : differentiable_on k b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map k b) : continuous b := h.differentiable.continuous end bilinear_map /- Cartesian products -/ section cartesian_product variables {f₂ : E → G} {f₂' : E →L[k] G} lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x L := begin have : (λ (x' : E), (f₁ x', f₂ x') - (f₁ x, f₂ x) - (continuous_linear_map.prod f₁' f₂') (x' -x)) = (λ (x' : E), (f₁ x' - f₁ x - f₁' (x' - x), f₂ x' - f₂ x - f₂' (x' - x))) := rfl, rw [has_fderiv_at_filter, this], rw [asymptotics.is_o_prod_left], exact ⟨hf₁, hf₂⟩ end lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at k f₁ s x) (hf₂ : differentiable_within_at k f₂ s x) : differentiable_within_at k (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.prod (hf₁ : differentiable_at k f₁ x) (hf₂ : differentiable_at k f₂ x) : differentiable_at k (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on k f₁ s) (hf₂ : differentiable_on k f₂ s) : differentiable_on k (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) lemma differentiable.prod (hf₁ : differentiable k f₁) (hf₂ : differentiable k f₂) : differentiable k (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at k f₁ x) (hf₂ : differentiable_at k f₂ x) : fderiv k (λx:E, (f₁ x, f₂ x)) x = continuous_linear_map.prod (fderiv k f₁ x) (fderiv k f₂ x) := has_fderiv_at.fderiv (has_fderiv_at.prod hf₁.has_fderiv_at hf₂.has_fderiv_at) lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at k f₁ s x) (hf₂ : differentiable_within_at k f₂ s x) (hxs : unique_diff_within_at k s x) : fderiv_within k (λx:E, (f₁ x, f₂ x)) s x = continuous_linear_map.prod (fderiv_within k f₁ s x) (fderiv_within k f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end cartesian_product /- Composition -/ section composition /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[k] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := ((hg.comp f).mono le_comap_map).trans_is_O hf.is_O_sub in by { refine eq₂.tri (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[k] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from (hg.comp f).mono le_comap_map, have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.tri eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[k] G} (hg : has_fderiv_within_at g g' (f '' s) (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := (has_fderiv_at_filter.mono hg hf.continuous_within_at.tendsto_nhds_within_image).comp x hf /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[k] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[k] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_univ_at at hg, exact has_fderiv_within_at.comp x (hg.mono (subset_univ _)) hf end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at k g t (f x)) (hf : differentiable_within_at k f s x) (h : f '' s ⊆ t) : differentiable_within_at k (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', (hg'.mono h).comp x hf'⟩ end lemma differentiable_at.comp {g : F → G} (hg : differentiable_at k g (f x)) (hf : differentiable_at k f x) : differentiable_at k (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at k g t (f x)) (hf : differentiable_within_at k f s x) (h : f '' s ⊆ t) (hxs : unique_diff_within_at k s x) : fderiv_within k (g ∘ f) s x = continuous_linear_map.comp (fderiv_within k g t (f x)) (fderiv_within k f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, apply has_fderiv_within_at.comp x _ (hf.has_fderiv_within_at), apply hg.has_fderiv_within_at.mono h end lemma fderiv.comp {g : F → G} (hg : differentiable_at k g (f x)) (hf : differentiable_at k f x) : fderiv k (g ∘ f) x = continuous_linear_map.comp (fderiv k g (f x)) (fderiv k f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on k g t) (hf : differentiable_on k f s) (st : f '' s ⊆ t) : differentiable_on k (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st (mem_image_of_mem _ hx))) (hf x hx) st end composition /- Multiplication by a scalar function -/ section smul variables {c : E → k} {c' : E →L[k] k} theorem has_fderiv_within_at.smul' (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.scalar_prod_space_iso (f x)) s x := begin have : is_bounded_bilinear_map k (λ (p : k × F), p.1 • p.2) := is_bounded_bilinear_map_smul, exact has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, f x)) (hc.prod hf) end theorem has_fderiv_at.smul' (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.scalar_prod_space_iso (f x)) x := begin have : is_bounded_bilinear_map k (λ (p : k × F), p.1 • p.2) := is_bounded_bilinear_map_smul, exact has_fderiv_at.comp x (this.has_fderiv_at (c x, f x)) (hc.prod hf) end lemma differentiable_within_at.smul' (hc : differentiable_within_at k c s x) (hf : differentiable_within_at k f s x) : differentiable_within_at k (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul' hf.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.smul' (hc : differentiable_at k c x) (hf : differentiable_at k f x) : differentiable_at k (λ y, c y • f y) x := (hc.has_fderiv_at.smul' hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul' (hc : differentiable_on k c s) (hf : differentiable_on k f s) : differentiable_on k (λ y, c y • f y) s := λx hx, (hc x hx).smul' (hf x hx) lemma differentiable.smul' (hc : differentiable k c) (hf : differentiable k f) : differentiable k (λ y, c y • f y) := λx, (hc x).smul' (hf x) lemma fderiv_within_smul' (hxs : unique_diff_within_at k s x) (hc : differentiable_within_at k c s x) (hf : differentiable_within_at k f s x) : fderiv_within k (λ y, c y • f y) s x = c x • fderiv_within k f s x + (fderiv_within k c s x).scalar_prod_space_iso (f x) := (hc.has_fderiv_within_at.smul' hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul' (hc : differentiable_at k c x) (hf : differentiable_at k f x) : fderiv k (λ y, c y • f y) x = c x • fderiv k f x + (fderiv k c x).scalar_prod_space_iso (f x) := (hc.has_fderiv_at.smul' hf.has_fderiv_at).fderiv end smul /- Multiplication of scalar functions -/ section mul set_option class.instance_max_depth 120 variables {c d : E → k} {c' d' : E →L[k] k} theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := begin have : is_bounded_bilinear_map k (λ (p : k × k), p.1 * p.2) := is_bounded_bilinear_map_mul, convert has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, d x)) (hc.prod hd), ext z, change c x * d' z + d x * c' z = c x * d' z + c' z * d x, ring end theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := begin have : is_bounded_bilinear_map k (λ (p : k × k), p.1 * p.2) := is_bounded_bilinear_map_mul, convert has_fderiv_at.comp x (this.has_fderiv_at (c x, d x)) (hc.prod hd), ext z, change c x * d' z + d x * c' z = c x * d' z + c' z * d x, ring end lemma differentiable_within_at.mul (hc : differentiable_within_at k c s x) (hd : differentiable_within_at k d s x) : differentiable_within_at k (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.mul (hc : differentiable_at k c x) (hd : differentiable_at k d x) : differentiable_at k (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on k c s) (hd : differentiable_on k d s) : differentiable_on k (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) lemma differentiable.mul (hc : differentiable k c) (hd : differentiable k d) : differentiable k (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at k s x) (hc : differentiable_within_at k c s x) (hd : differentiable_within_at k d s x) : fderiv_within k (λ y, c y * d y) s x = c x • fderiv_within k d s x + d x • fderiv_within k c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at k c x) (hd : differentiable_at k d x) : fderiv k (λ y, c y * d y) x = c x • fderiv k d x + d x • fderiv k c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv end mul end /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ section variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {G : Type*} [normed_group G] [normed_space ℝ G] theorem has_fderiv_at_filter_real_equiv {f : E → F} {f' : E →L[ℝ] F} {x : E} {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (nhds 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (nhds 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto.congr'r (λ x', _), have : ∥x' + -x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end end
1d14855fd50ef295394b824e59230bed9b224857
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/625.lean
82546e0d5e3dffee5f1a0c993c7163e37b75f345
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
648
lean
import Lean open Lean Lean.PrettyPrinter def pfoo : PUnit → PUnit := id def px : PUnit := () @[appUnexpander foo] def unexpandFoo : Unexpander := fun _ => `(sorry) #eval show MetaM Format from do let e : Expr := mkApp (mkMData {} $ mkConst `foo [levelOne]) (mkConst `x) formatTerm (← delab Name.anonymous [] e) #eval show MetaM Format from do let opts := ({}: Options).setBool `pp.universes true -- the MData annotation should make it not a regular application, -- so the unexpander should not be called. let e : Expr := mkApp (mkMData opts $ mkConst `foo [levelOne]) (mkConst `x) formatTerm (← delab Name.anonymous [] e)
757789ed842e4de1a95eb81071880bc7fbb00256
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/constructions/over/connected.lean
b6f3351bf48368f1368a3f188c54cd2af8dfd36a
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
2,907
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import category_theory.over import category_theory.limits.connected import category_theory.limits.creates /-! # Connected limits in the over category Shows that the forgetful functor `over B ⥤ C` creates connected limits, in particular `over B` has any connected limit which `C` has. -/ universes v u -- morphism levels before object levels. See note [category_theory universes]. noncomputable theory open category_theory category_theory.limits variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] variable {X : C} namespace category_theory.over namespace creates_connected /-- (Impl) Given a diagram in the over category, produce a natural transformation from the diagram legs to the specific object. -/ def nat_trans_in_over {B : C} (F : J ⥤ over B) : F ⋙ forget B ⟶ (category_theory.functor.const J).obj B := { app := λ j, (F.obj j).hom } local attribute [tidy] tactic.case_bash /-- (Impl) Given a cone in the base category, raise it to a cone in the over category. Note this is where the connected assumption is used. -/ @[simps] def raise_cone [is_connected J] {B : C} {F : J ⥤ over B} (c : cone (F ⋙ forget B)) : cone F := { X := over.mk (c.π.app (classical.arbitrary J) ≫ (F.obj (classical.arbitrary J)).hom), π := { app := λ j, over.hom_mk (c.π.app j) (nat_trans_from_is_connected (c.π ≫ nat_trans_in_over F) j _) } } lemma raised_cone_lowers_to_original [is_connected J] {B : C} {F : J ⥤ over B} (c : cone (F ⋙ forget B)) (t : is_limit c) : (forget B).map_cone (raise_cone c) = c := by tidy /-- (Impl) Show that the raised cone is a limit. -/ def raised_cone_is_limit [is_connected J] {B : C} {F : J ⥤ over B} {c : cone (F ⋙ forget B)} (t : is_limit c) : is_limit (raise_cone c) := { lift := λ s, over.hom_mk (t.lift ((forget B).map_cone s)) (by { dsimp, simp }), uniq' := λ s m K, by { ext1, apply t.hom_ext, intro j, simp [← K j] } } end creates_connected /-- The forgetful functor from the over category creates any connected limit. -/ instance forget_creates_connected_limits [is_connected J] {B : C} : creates_limits_of_shape J (forget B) := { creates_limit := λ K, creates_limit_of_reflects_iso (λ c t, { lifted_cone := creates_connected.raise_cone c, valid_lift := eq_to_iso (creates_connected.raised_cone_lowers_to_original c t), makes_limit := creates_connected.raised_cone_is_limit t } ) } /-- The over category has any connected limit which the original category has. -/ instance has_connected_limits {B : C} [is_connected J] [has_limits_of_shape J C] : has_limits_of_shape J (over B) := { has_limit := λ F, has_limit_of_created F (forget B) } end category_theory.over
ad1c39a5e1ad6fa8bbe3e1bbce5d1853471c2229
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/vec_inv3.lean
7fa820c1dcf9aedb1039a7832b3498bcb5d80289
[ "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
715
lean
import data.nat.basic data.empty data.prod open nat eq.ops prod inductive vector (T : Type) : ℕ → Type := | nil {} : vector T 0 | cons : T → ∀{n}, vector T n → vector T (succ n) set_option pp.metavar_args true set_option pp.implicit true set_option pp.notation false namespace vector variables {A B C : Type} variables {n m : nat} theorem z_cases_on {C : vector A 0 → Type} (v : vector A 0) (Hnil : C nil) : C v := by cases v; apply Hnil protected definition destruct (v : vector A (succ n)) {P : Π {n : nat}, vector A (succ n) → Type} (H : Π {n : nat} (h : A) (t : vector A n), P (cons h t)) : P v := by cases v with [h', n', t']; apply (H h' t') end vector
3869dcde66d2eb2b8c3fd791957206a84f1f4fc4
f00cc9c04d77f9621aa57d1406d35c522c3ff82c
/library/init/data/list/instances.lean
981dd507bf8dc0c9d28c6aff203a3311a1a9f745
[ "Apache-2.0" ]
permissive
shonfeder/lean
444c66a74676d74fb3ef682d88cd0f5c1bf928a5
24d5a1592d80cefe86552d96410c51bb07e6d411
refs/heads/master
1,619,338,440,905
1,512,842,340,000
1,512,842,340,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,418
lean
/- Copyright (c) 2016 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.list.lemmas import init.meta.mk_dec_eq_instance open list universes u v local attribute [simp] join ret instance : monad list := {pure := @list.ret, bind := @list.bind, id_map := begin intros _ xs, induction xs with x xs ih, { refl }, { dsimp [function.comp] at ih, dsimp [function.comp], simp [*] } end, pure_bind := by simp_intros, bind_assoc := begin intros _ _ _ xs _ _, induction xs, { refl }, { simp [*] } end} instance : alternative list := { failure := @list.nil, orelse := @list.append, ..list.monad } instance {α : Type u} [decidable_eq α] : decidable_eq (list α) := by tactic.mk_dec_eq_instance namespace list variables {α β : Type u} (p : α → Prop) [decidable_pred p] instance bin_tree_to_list : has_coe (bin_tree α) (list α) := ⟨bin_tree.to_list⟩ instance decidable_bex : ∀ (l : list α), decidable (∃ x ∈ l, p x) | [] := is_false (by simp) | (x::xs) := by simp; have := decidable_bex xs; apply_instance instance decidable_ball (l : list α) : decidable (∀ x ∈ l, p x) := if h : ∃ x ∈ l, ¬ p x then is_false $ let ⟨x, h, np⟩ := h in λ al, np (al x h) else is_true $ λ x hx, if h' : p x then h' else false.elim $ h ⟨x, hx, h'⟩ end list
c9f3be3cd73ef492f6df800328c9d641c1191ab1
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/nat/parity.lean
3dd6e757b90c957bb44f1e277470232d3ee23f39
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,977
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Benjamin Davidson -/ import data.nat.modeq /-! # Parity of natural numbers This file contains theorems about the `even` and `odd` predicates on the natural numbers. ## Tags even, odd -/ namespace nat variables {m n : ℕ} @[simp] theorem mod_two_ne_one : ¬ n % 2 = 1 ↔ n % 2 = 0 := by cases mod_two_eq_zero_or_one n with h h; simp [h] @[simp] theorem mod_two_ne_zero : ¬ n % 2 = 0 ↔ n % 2 = 1 := by cases mod_two_eq_zero_or_one n with h h; simp [h] theorem even_iff : even n ↔ n % 2 = 0 := ⟨λ ⟨m, hm⟩, by simp [hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [h])⟩⟩ theorem odd_iff : odd n ↔ n % 2 = 1 := ⟨λ ⟨m, hm⟩, by norm_num [hm, add_mod], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by rw [h, add_comm])⟩⟩ lemma not_even_iff : ¬ even n ↔ n % 2 = 1 := by rw [even_iff, mod_two_ne_zero] lemma not_odd_iff : ¬ odd n ↔ n % 2 = 0 := by rw [odd_iff, mod_two_ne_one] lemma even_iff_not_odd : even n ↔ ¬ odd n := by rw [not_odd_iff, even_iff] @[simp] lemma odd_iff_not_even : odd n ↔ ¬ even n := by rw [not_even_iff, odd_iff] lemma is_compl_even_odd : is_compl {n : ℕ | even n} {n | odd n} := by simp [← set.compl_set_of, is_compl_compl] lemma even_or_odd (n : ℕ) : even n ∨ odd n := or.imp_right odd_iff_not_even.2 $ em $ even n lemma even_or_odd' (n : ℕ) : ∃ k, n = 2 * k ∨ n = 2 * k + 1 := by simpa only [exists_or_distrib, ← odd, ← even] using even_or_odd n lemma even_xor_odd (n : ℕ) : xor (even n) (odd n) := begin cases even_or_odd n with h, { exact or.inl ⟨h, even_iff_not_odd.mp h⟩ }, { exact or.inr ⟨h, odd_iff_not_even.mp h⟩ }, end lemma even_xor_odd' (n : ℕ) : ∃ k, xor (n = 2 * k) (n = 2 * k + 1) := begin rcases even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; use k, { simpa only [xor, true_and, eq_self_iff_true, not_true, or_false, and_false] using (succ_ne_self (2*k)).symm }, { simp only [xor, add_right_eq_self, false_or, eq_self_iff_true, not_true, not_false_iff, one_ne_zero, and_self] }, end lemma odd_gt_zero (h : odd n) : 0 < n := by { obtain ⟨k, rfl⟩ := h, exact succ_pos' } @[simp] theorem two_dvd_ne_zero : ¬ 2 ∣ n ↔ n % 2 = 1 := not_even_iff instance : decidable_pred (even : ℕ → Prop) := λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm instance decidable_pred_odd : decidable_pred (odd : ℕ → Prop) := λ n, decidable_of_decidable_of_iff (by apply_instance) odd_iff_not_even.symm mk_simp_attribute parity_simps "Simp attribute for lemmas about `even`" @[simp] theorem even_zero : even 0 := ⟨0, dec_trivial⟩ @[simp] theorem not_even_one : ¬ even 1 := by rw even_iff; norm_num @[simp] theorem even_bit0 (n : ℕ) : even (bit0 n) := ⟨n, by rw [bit0, two_mul]⟩ @[parity_simps] theorem even_add : even (m + n) ↔ (even m ↔ even n) := by cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, nat.add_mod]; norm_num theorem even.add_even (hm : even m) (hn : even n) : even (m + n) := even_add.2 $ iff_of_true hm hn theorem even_add' : even (m + n) ↔ (odd m ↔ odd n) := by rw [even_add, even_iff_not_odd, even_iff_not_odd, not_iff_not] theorem odd.add_odd (hm : odd m) (hn : odd n) : even (m + n) := even_add'.2 $ iff_of_true hm hn @[simp] theorem not_even_bit1 (n : ℕ) : ¬ even (bit1 n) := by simp [bit1] with parity_simps lemma two_not_dvd_two_mul_add_one (n : ℕ) : ¬(2 ∣ 2 * n + 1) := by convert not_even_bit1 n; exact two_mul n lemma two_not_dvd_two_mul_sub_one : Π {n} (w : 0 < n), ¬(2 ∣ 2 * n - 1) | (n + 1) _ := two_not_dvd_two_mul_add_one n @[parity_simps] theorem even_sub (h : n ≤ m) : even (m - n) ↔ (even m ↔ even n) := begin conv { to_rhs, rw [←nat.sub_add_cancel h, even_add] }, by_cases h : even n; simp [h] end theorem even.sub_even (hm : even m) (hn : even n) : even (m - n) := (le_total n m).elim (λ h, by simp only [even_sub h, *]) (λ h, by simp only [nat.sub_eq_zero_of_le h, even_zero]) theorem even_sub' (h : n ≤ m) : even (m - n) ↔ (odd m ↔ odd n) := by rw [even_sub h, even_iff_not_odd, even_iff_not_odd, not_iff_not] theorem odd.sub_odd (hm : odd m) (hn : odd n) : even (m - n) := (le_total n m).elim (λ h, by simp only [even_sub' h, *]) (λ h, by simp only [nat.sub_eq_zero_of_le h, even_zero]) @[parity_simps] theorem even_succ : even (succ n) ↔ ¬ even n := by rw [succ_eq_add_one, even_add]; simp [not_even_one] @[parity_simps] theorem even_mul : even (m * n) ↔ even m ∨ even n := by cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, nat.mul_mod]; norm_num theorem odd_mul : odd (m * n) ↔ odd m ∧ odd n := by simp [not_or_distrib] with parity_simps theorem even.mul_left (hm : even m) (n) : even (m * n) := even_mul.mpr $ or.inl hm theorem even.mul_right (m) (hn : even n) : even (m * n) := even_mul.mpr $ or.inr hn theorem odd.mul (hm : odd m) (hn : odd n) : odd (m * n) := odd_mul.mpr ⟨hm, hn⟩ theorem odd.of_mul_left (h : odd (m * n)) : odd m := (odd_mul.mp h).1 theorem odd.of_mul_right (h : odd (m * n)) : odd n := (odd_mul.mp h).2 /-- If `m` and `n` are natural numbers, then the natural number `m^n` is even if and only if `m` is even and `n` is positive. -/ @[parity_simps] theorem even_pow : even (m ^ n) ↔ even m ∧ n ≠ 0 := by { induction n with n ih; simp [*, pow_succ', even_mul], tauto } theorem even_pow' (h : n ≠ 0) : even (m ^ n) ↔ even m := even_pow.trans $ and_iff_left h theorem even_div : even (m / n) ↔ m % (2 * n) / n = 0 := by rw [even_iff_two_dvd, dvd_iff_mod_eq_zero, nat.div_mod_eq_mod_mul_div, mul_comm] @[parity_simps] theorem odd_add : odd (m + n) ↔ (odd m ↔ even n) := by rw [odd_iff_not_even, even_add, not_iff, odd_iff_not_even] theorem odd.add_even (hm : odd m) (hn : even n) : odd (m + n) := odd_add.2 $ iff_of_true hm hn theorem odd_add' : odd (m + n) ↔ (odd n ↔ even m) := by rw [add_comm, odd_add] theorem even.add_odd (hm : even m) (hn : odd n) : odd (m + n) := odd_add'.2 $ iff_of_true hn hm lemma ne_of_odd_add (h : odd (m + n)) : m ≠ n := λ hnot, by simpa [hnot] with parity_simps using h @[parity_simps] theorem odd_sub (h : n ≤ m) : odd (m - n) ↔ (odd m ↔ even n) := by rw [odd_iff_not_even, even_sub h, not_iff, odd_iff_not_even] theorem odd.sub_even (h : n ≤ m) (hm : odd m) (hn : even n) : odd (m - n) := (odd_sub h).mpr $ iff_of_true hm hn theorem odd_sub' (h : n ≤ m) : odd (m - n) ↔ (odd n ↔ even m) := by rw [odd_iff_not_even, even_sub h, not_iff, not_iff_comm, odd_iff_not_even] theorem even.sub_odd (h : n ≤ m) (hm : even m) (hn : odd n) : odd (m - n) := (odd_sub' h).mpr $ iff_of_true hn hm lemma even_mul_succ_self (n : ℕ) : even (n * (n + 1)) := begin rw even_mul, convert n.even_or_odd, simp with parity_simps end variables {R : Type*} [ring R] theorem neg_one_pow_eq_one_iff_even (h1 : (-1 : R) ≠ 1) : (-1 : R) ^ n = 1 ↔ even n := ⟨λ h, n.mod_two_eq_zero_or_one.elim (dvd_iff_mod_eq_zero _ _).2 (λ hn, by rw [neg_one_pow_eq_pow_mod_two, hn, pow_one] at h; exact (h1 h).elim), λ ⟨m, hm⟩, by rw [neg_one_pow_eq_pow_mod_two, hm]; simp⟩ @[simp] theorem neg_one_sq : (-1 : R) ^ 2 = 1 := by simp alias nat.neg_one_sq ← nat.neg_one_pow_two theorem neg_one_pow_of_even : even n → (-1 : R) ^ n = 1 := by { rintro ⟨c, rfl⟩, simp [pow_mul] } theorem neg_one_pow_of_odd : odd n → (-1 : R) ^ n = -1 := by { rintro ⟨c, rfl⟩, simp [pow_add, pow_mul] } -- Here are examples of how `parity_simps` can be used with `nat`. example (m n : ℕ) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) := by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps example : ¬ even 25394535 := by simp end nat
e1af6e7fbf2139af69d0593c00fe620ae319aebd
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/simp_result.lean
9831c840d56513d5bb05a15b41a74eb7a58d857c
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,914
lean
import tactic.simp_result import data.equiv.basic open tactic -- Check that we can walk. example : true := by { simp_result { trivial } } -- Comparison without `dsimp_result`: example : true := begin exact (id trivial), (do `(id trivial) ← result, skip), success_if_fail { (do `(trivial) ← result, skip) }, end -- Check that `dsimp_result` removes unnecessary `id`s. example : true := begin dsimp_result { exact (id trivial) }, success_if_fail { (do `(id trivial) ← result, skip) }, (do `(trivial) ← result, skip), end -- Comparison without `dsimp_result`: example (a : ℕ) (b : list ℕ) (h : b.length < a) : ℕ := begin revert a, intros a h, exact 0, (do `((λ (h : list.length _ < _), 0) _) ← result, skip), success_if_fail { (do `(0) ← result, skip) }, end -- Check that `dsimp_result` does beta-reductions after `revert`. example (a : ℕ) (b : list ℕ) (h : b.length < a) : ℕ := begin dsimp_result { revert a, intros a h, exact 0, }, success_if_fail { (do `((λ (h : list.length _ < _), 0) _) ← result, skip), }, (do `(0) ← result, skip), end -- This test tactic internally sets `pp.all ff`, and `pp.proofs tt`. -- This isn't very robust, as the user setting any other `pp` options -- will cause tests to break, but I don't think it needs to be. meta def guard_result_pp (s : string) : tactic unit := do o ← get_options, set_options ((o.set_bool `pp.all ff).set_bool `pp.proofs tt), r ← (to_string <$> (result >>= pp)), guard (r = s) <|> fail format!"result was {r} but expected {s}" -- Comparison without `simp_result`: example {α β : Type} (e : α ≃ β) (a : α) : β := begin exact e (e.symm (e a)), guard_result_pp "⇑e (⇑(equiv.symm e) (⇑e a))", end -- Check that `simp_result` applies non-definitional simplifications to the result. example {α β : Type} (e : α ≃ β) (a : α) : β := begin simp_result { exact e (e.symm (e a)) }, guard_result_pp "⇑e a", end -- Check that `simp_result only [...]` behaves as expected. example {α β : Type} (e : α ≃ β) (a : α) : β := begin simp_result only [equiv.apply_symm_apply] { exact e (e.symm (e a)) }, guard_result_pp "⇑e a", end -- Check that `simp_result only []` does not simplify. -- (Note the `simp_result` succeeds even if no simplification occurs.) example {α β : Type} (e : α ≃ β) (a : α) : β := begin simp_result only [] { exact e (e.symm (e a)) }, guard_result_pp "⇑e (⇑(equiv.symm e) (⇑e a))", end -- Comparison without `simp_result` example {α : Type} (a b : α) (h : a = b) : ℕ := begin subst h, exact 0, guard_result_pp "eq.rec 0 h", end -- Check that we can remove `eq.rec` transports through constant families -- introduced by irrelevant use of `subst`. example {α : Type} (a b : α) (h : a = b) : ℕ := begin simp_result only [eq_rec_constant] { subst h, exact 0, }, guard_result_pp "0", end -- Check that `simp_result` performs simplifications on all results. example : ℕ × ℕ := begin split, simp_result { exact id 0, exact id 1, }, guard_result_pp "(0, 1)", end -- Check that `simp_result` can cope with incomplete goals. example {α β : Type} (e : α ≃ β) (a : α) : β := begin simp_result { apply e.to_fun, apply e.inv_fun, apply e.to_fun, }, guard_result_pp "⇑e ?m_1", exact a, end -- Check that we can: -- * cope with metavariables in the result -- * perform beta redex after `revert` -- * simplify `eq.rec` after `subst` example {α β : Type} (e : α ≃ β) (S : has_mul α) : has_mul β := begin fconstructor, simp_result { have mul := S.mul, have e' := equiv.arrow_congr e (equiv.arrow_congr e e), have h : mul = e'.symm (e' mul) := by simp, revert h, generalize : e' mul = mul', intro h, subst h, }, exact mul', guard_result_pp "{mul := ⇑(equiv.arrow_congr e (equiv.arrow_congr e e)) has_mul.mul}", end
a834e9867ba1c93c3ee022ab7224de254822b517
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/nat/psub.lean
d675962351cf3e7b574fba2765687bba9f5ed6bc
[ "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,505
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.nat.basic /-! # Partial predecessor and partial subtraction on the natural numbers The usual definition of natural number subtraction (`nat.sub`) returns 0 as a "garbage value" for `a - b` when `a < b`. Similarly, `nat.pred 0` is defined to be `0`. The functions in this file wrap the result in an `option` type instead: ## Main definitions - `nat.ppred`: a partial predecessor operation - `nat.psub`: a partial subtraction operation -/ namespace nat /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ @[simp] def ppred : ℕ → option ℕ | 0 := none | (n+1) := some n /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ @[simp] def psub (m : ℕ) : ℕ → option ℕ | 0 := some m | (n+1) := psub n >>= ppred theorem pred_eq_ppred (n : ℕ) : pred n = (ppred n).get_or_else 0 := by cases n; refl theorem sub_eq_psub (m : ℕ) : ∀ n, m - n = (psub m n).get_or_else 0 | 0 := rfl | (n+1) := (pred_eq_ppred (m-n)).trans $ by rw [sub_eq_psub, psub]; cases psub m n; refl @[simp] theorem ppred_eq_some {m : ℕ} : ∀ {n}, ppred n = some m ↔ succ m = n | 0 := by split; intro h; contradiction | (n+1) := by dsimp; split; intro h; injection h; subst n @[simp] theorem ppred_eq_none : ∀ {n : ℕ}, ppred n = none ↔ n = 0 | 0 := by simp | (n+1) := by dsimp; split; contradiction theorem psub_eq_some {m : ℕ} : ∀ {n k}, psub m n = some k ↔ k + n = m | 0 k := by simp [eq_comm] | (n+1) k := begin dsimp, apply option.bind_eq_some.trans, simp [psub_eq_some, add_comm, add_left_comm, nat.succ_eq_add_one] end theorem psub_eq_none (m n : ℕ) : psub m n = none ↔ m < n := begin cases s : psub m n; simp [eq_comm], { show m < n, refine lt_of_not_ge (λ h, _), cases le.dest h with k e, injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) }, { show n ≤ m, rw ← psub_eq_some.1 s, apply le_add_left } end theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 $ succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≤ m) : psub m n = some (m - n) := psub_eq_some.2 $ nat.sub_add_cancel h theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k := by induction k; simp [*, add_succ, bind_assoc] end nat
46aaf52d82cb204dd612cde2d78c89a8eb0db34b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/ImplementedByAttr.lean
f9179ee525ec3b2cc057617df6512de2e41aa586
[ "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
2,062
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Attributes import Lean.Declaration import Lean.MonadEnv import Lean.Elab.InfoTree namespace Lean.Compiler builtin_initialize implementedByAttr : ParametricAttribute Name ← registerParametricAttribute { name := `implemented_by descr := "name of the Lean (probably unsafe) function that implements opaque constant" getParam := fun declName stx => do let decl ← getConstInfo declName let fnNameStx ← Attribute.Builtin.getIdent stx let fnName ← Elab.resolveGlobalConstNoOverloadWithInfo fnNameStx let fnDecl ← getConstInfo fnName unless decl.levelParams.length == fnDecl.levelParams.length do throwError "invalid 'implemented_by' argument '{fnName}', '{fnName}' has {fnDecl.levelParams.length} universe level parameter(s), but '{declName}' has {decl.levelParams.length}" let declType := decl.type let fnType ← Core.instantiateTypeLevelParams fnDecl (decl.levelParams.map mkLevelParam) unless declType == fnType do throwError "invalid 'implemented_by' argument '{fnName}', '{fnName}' has type{indentExpr fnType}\nbut '{declName}' has type{indentExpr declType}" if decl.name == fnDecl.name then throwError "invalid 'implemented_by' argument '{fnName}', function cannot be implemented by itself" return fnName } @[export lean_get_implemented_by] def getImplementedBy? (env : Environment) (declName : Name) : Option Name := implementedByAttr.getParam? env declName def setImplementedBy (env : Environment) (declName : Name) (impName : Name) : Except String Environment := implementedByAttr.setParam env declName impName end Compiler def setImplementedBy {m} [Monad m] [MonadEnv m] [MonadError m] (declName : Name) (impName : Name) : m Unit := do let env ← getEnv match Compiler.setImplementedBy env declName impName with | Except.ok env => setEnv env | Except.error ex => throwError ex end Lean
0316488e8d87fc64f4cac677411201d80b68c4c0
3705439886316285035ef1fd985632bc87eb06e7
/native/LeanProtoNativeHelpers.lean
22be3142a3c6001fcb1207a6c924abb9d784069c
[ "MIT" ]
permissive
zygi/lean-proto
ce74f29d33f12f240878f0f8cbe4960c41b70fcb
4d64844d8978c68c8038886013d33048c23a7674
refs/heads/master
1,680,996,798,349
1,618,444,323,000
1,618,444,323,000
342,923,095
0
0
null
null
null
null
UTF-8
Lean
false
false
1,673
lean
namespace Float @[extern c inline "*(double*)(&#1)"] constant ofUInt64Transmute (i: UInt64) : Float @[extern c inline "(double)(*(float*)(&#1))"] constant ofUInt32Transmute (i: UInt32) : Float -- Too many casts to put inline @[extern "proto_lean_transmute_double_to_uint32"] constant toUInt32Transmute (i: Float) : UInt32 @[extern c inline "*(uint64_t*)(&#1)"] constant toUInt64Transmute (i: Float) : UInt64 end Float namespace UInt64 @[extern c inline "((uint64_t)#1)"] def ofUInt8 (a : UInt8) : UInt64 := a.toNat.toUInt64 @[extern c inline "((uint64_t)#1)"] def ofUInt16 (a : UInt16) : UInt64 := a.toNat.toUInt64 @[extern c inline "((uint64_t)#1)"] def ofUInt32 (a : UInt32) : UInt64 := a.toNat.toUInt64 -- TODO: overflows are UB. Fix. @[extern c inline "(int32_t)(*(int64_t*)(&#1))"] constant toInt32Transmute (a: UInt64) : UInt32 -- Pretending `a` holds an Int64, do an arithmetic right shift @[extern "arith_right_shift_64"] constant arithShiftRight (a: UInt64) (b: UInt64) : UInt64 end UInt64 namespace UInt32 @[extern c inline "((uint32_t)#1)"] def ofUInt8 (a : UInt8) : UInt32 := a.toNat.toUInt32 @[extern c inline "((uint32_t)#1)"] def ofUInt16 (a : UInt16) : UInt32 := a.toNat.toUInt32 @[extern c inline "((uint32_t)#1)"] def ofUInt64Lossy (a : UInt64) : UInt32 := a.toNat.toUInt32 -- Pretending `a` holds an Int32, do an arithmetic right shift @[extern "arith_right_shift_32"] constant arithShiftRight (a: UInt32) (b: UInt32) : UInt32 -- Casts Int32 to Int64 -- This is getting awkward enough that I should probably just wrap Ints @[extern c inline "(int64_t)(*(int32_t*)(&#1))"] constant sextPretendingThisIsInt32 (a: UInt32) : UInt64 end UInt32
23b296ef8f3495a5dd85e45a2b52dc478b714807
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/algebra/algebra.lean
a339814d4114472ecda30d99bbcf50bdcf0aef19
[ "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
5,979
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.algebra.subalgebra.basic import topology.algebra.module.basic import topology.algebra.field /-! # Topological (sub)algebras A topological algebra over a topological semiring `R` is a topological semiring with a compatible continuous scalar multiplication by elements of `R`. We reuse typeclass `has_continuous_smul` for topological algebras. ## Results This is just a minimal stub for now! The topological closure of a subalgebra is still a subalgebra, which as an algebra is a topological algebra. -/ open classical set topological_space algebra open_locale classical universes u v w section topological_algebra variables (R : Type*) [topological_space R] [comm_semiring R] variables (A : Type u) [topological_space A] variables [semiring A] lemma continuous_algebra_map_iff_smul [algebra R A] [topological_semiring A] : continuous (algebra_map R A) ↔ continuous (λ p : R × A, p.1 • p.2) := begin refine ⟨λ h, _, λ h, _⟩, { simp only [algebra.smul_def], exact (h.comp continuous_fst).mul continuous_snd }, { rw algebra_map_eq_smul_one', exact h.comp (continuous_id.prod_mk continuous_const) } end @[continuity] lemma continuous_algebra_map [algebra R A] [topological_semiring A] [has_continuous_smul R A] : continuous (algebra_map R A) := (continuous_algebra_map_iff_smul R A).2 continuous_smul lemma has_continuous_smul_of_algebra_map [algebra R A] [topological_semiring A] (h : continuous (algebra_map R A)) : has_continuous_smul R A := ⟨(continuous_algebra_map_iff_smul R A).1 h⟩ end topological_algebra section topological_algebra variables {R : Type*} [comm_semiring R] variables {A : Type u} [topological_space A] variables [semiring A] [algebra R A] instance subalgebra.has_continuous_smul [topological_space R] [has_continuous_smul R A] (s : subalgebra R A) : has_continuous_smul R s := s.to_submodule.has_continuous_smul variables [topological_semiring A] /-- The closure of a subalgebra in a topological algebra as a subalgebra. -/ def subalgebra.topological_closure (s : subalgebra R A) : subalgebra R A := { carrier := closure (s : set A), algebra_map_mem' := λ r, s.to_subsemiring.subring_topological_closure (s.algebra_map_mem r), .. s.to_subsemiring.topological_closure } @[simp] lemma subalgebra.topological_closure_coe (s : subalgebra R A) : (s.topological_closure : set A) = closure (s : set A) := rfl instance subalgebra.topological_semiring (s : subalgebra R A) : topological_semiring s := s.to_subsemiring.topological_semiring lemma subalgebra.subalgebra_topological_closure (s : subalgebra R A) : s ≤ s.topological_closure := subset_closure lemma subalgebra.is_closed_topological_closure (s : subalgebra R A) : is_closed (s.topological_closure : set A) := by convert is_closed_closure lemma subalgebra.topological_closure_minimal (s : subalgebra R A) {t : subalgebra R A} (h : s ≤ t) (ht : is_closed (t : set A)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a subalgebra of a topological algebra is commutative, then so is its topological closure. -/ def subalgebra.comm_semiring_topological_closure [t2_space A] (s : subalgebra R A) (hs : ∀ (x y : s), x * y = y * x) : comm_semiring s.topological_closure := { ..s.topological_closure.to_semiring, ..s.to_submonoid.comm_monoid_topological_closure hs } /-- This is really a statement about topological algebra isomorphisms, but we don't have those, so we use the clunky approach of talking about an algebra homomorphism, and a separate homeomorphism, along with a witness that as functions they are the same. -/ lemma subalgebra.topological_closure_comap_homeomorph (s : subalgebra R A) {B : Type*} [topological_space B] [ring B] [topological_ring B] [algebra R B] (f : B →ₐ[R] A) (f' : B ≃ₜ A) (w : (f : B → A) = f') : s.topological_closure.comap f = (s.comap f).topological_closure := begin apply set_like.ext', simp only [subalgebra.topological_closure_coe], simp only [subalgebra.coe_comap, subsemiring.coe_comap, alg_hom.coe_to_ring_hom], rw [w], exact f'.preimage_closure _, end end topological_algebra section ring variables {R : Type*} [comm_ring R] variables {A : Type u} [topological_space A] variables [ring A] variables [algebra R A] [topological_ring A] /-- If a subalgebra of a topological algebra is commutative, then so is its topological closure. See note [reducible non-instances]. -/ @[reducible] def subalgebra.comm_ring_topological_closure [t2_space A] (s : subalgebra R A) (hs : ∀ (x y : s), x * y = y * x) : comm_ring s.topological_closure := { ..s.topological_closure.to_ring, ..s.to_submonoid.comm_monoid_topological_closure hs } variables (R) /-- The topological closure of the subalgebra generated by a single element. -/ def algebra.elemental_algebra (x : A) : subalgebra R A := (algebra.adjoin R ({x} : set A)).topological_closure lemma algebra.self_mem_elemental_algebra (x : A) : x ∈ algebra.elemental_algebra R x := set_like.le_def.mp (subalgebra.subalgebra_topological_closure (algebra.adjoin R ({x} : set A))) $ algebra.self_mem_adjoin_singleton R x variables {R} instance [t2_space A] {x : A} : comm_ring (algebra.elemental_algebra R x) := subalgebra.comm_ring_topological_closure _ begin letI : comm_ring (algebra.adjoin R ({x} : set A)) := algebra.adjoin_comm_ring_of_comm R (λ y hy z hz, by {rw [mem_singleton_iff] at hy hz, rw [hy, hz]}), exact λ _ _, mul_comm _ _, end end ring section division_ring /-- The action induced by `algebra_rat` is continuous. -/ instance division_ring.has_continuous_const_smul_rat {A} [division_ring A] [topological_space A] [has_continuous_mul A] [char_zero A] : has_continuous_const_smul ℚ A := ⟨λ r, by { simpa only [algebra.smul_def] using continuous_const.mul continuous_id }⟩ end division_ring
f8d245cf29aecf7d196c5bd694510725f2b335a6
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Server/FileWorker/WidgetRequests.lean
2c7fa57884695dd13c32a5370358a1215f2b9977
[ "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
5,248
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Widget.Basic import Lean.Widget.InteractiveCode import Lean.Widget.InteractiveGoal import Lean.Widget.InteractiveDiagnostic import Lean.Server.Rpc.RequestHandling import Lean.Server.FileWorker.RequestHandling /-! Registers all widget-related RPC procedures. -/ namespace Lean.Widget open Server Lean.Elab structure MsgToInteractive where msg : WithRpcRef MessageData indent : Nat deriving Inhabited, RpcEncodable builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.InteractiveDiagnostics.msgToInteractive MsgToInteractive (TaggedText MsgEmbed) fun ⟨⟨m⟩, i⟩ => RequestM.asTask do msgToInteractive m i (hasWidgets := true) /-- The information that the infoview uses to render a popup for when the user hovers over an expression. -/ structure InfoPopup where type : Option CodeWithInfos /-- Show the term with the implicit arguments. -/ exprExplicit : Option CodeWithInfos /-- Docstring. In markdown. -/ doc : Option String deriving Inhabited, RpcEncodable /-- Given elaborator info for a particular subexpression. Produce the `InfoPopup`. The intended usage of this is for the infoview to pass the `InfoWithCtx` which was stored for a particular `SubexprInfo` tag in a `TaggedText` generated with `ppExprTagged`. -/ def makePopup : WithRpcRef InfoWithCtx → RequestM (RequestTask InfoPopup) | ⟨i⟩ => RequestM.asTask do i.ctx.runMetaM i.info.lctx do let type? ← match (← i.info.type?) with | some type => some <$> (ppExprTagged =<< instantiateMVars type) | none => pure none let exprExplicit? ← match i.info with | Elab.Info.ofTermInfo ti => let ti ← ppExprTagged ti.expr (explicit := true) -- remove top-level expression highlight pure <| some <| match ti with | .tag _ tt => tt | tt => tt | Elab.Info.ofFieldInfo fi => pure <| some <| TaggedText.text fi.fieldName.toString | _ => pure none return { type := type? exprExplicit := exprExplicit? doc := ← i.info.docString? : InfoPopup } builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.InteractiveDiagnostics.infoToInteractive (WithRpcRef InfoWithCtx) InfoPopup makePopup builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.getInteractiveGoals Lsp.PlainGoalParams (Option InteractiveGoals) FileWorker.getInteractiveGoals builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.getInteractiveTermGoal Lsp.PlainTermGoalParams (Option InteractiveTermGoal) FileWorker.getInteractiveTermGoal structure GetInteractiveDiagnosticsParams where /-- Return diagnostics for these lines only if present, otherwise return all diagnostics. -/ lineRange? : Option Lsp.LineRange deriving Inhabited, FromJson, ToJson open RequestM in def getInteractiveDiagnostics (params : GetInteractiveDiagnosticsParams) : RequestM (RequestTask (Array InteractiveDiagnostic)) := do let doc ← readDoc let rangeEnd := params.lineRange?.map fun range => doc.meta.text.lspPosToUtf8Pos ⟨range.«end», 0⟩ let t := doc.cmdSnaps.waitUntil fun snap => rangeEnd.any (snap.endPos >= ·) pure <| t.map fun (snaps, _) => let diags? := snaps.getLast?.map fun snap => snap.interactiveDiags.toArray.filter fun diag => params.lineRange?.all fun ⟨s, e⟩ => -- does [s,e) intersect [diag.fullRange.start.line,diag.fullRange.end.line)? s ≤ diag.fullRange.start.line ∧ diag.fullRange.start.line < e ∨ diag.fullRange.start.line ≤ s ∧ s < diag.fullRange.end.line pure <| diags?.getD #[] builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.getInteractiveDiagnostics GetInteractiveDiagnosticsParams (Array InteractiveDiagnostic) getInteractiveDiagnostics structure GetGoToLocationParams where kind : GoToKind info : WithRpcRef InfoWithCtx deriving RpcEncodable builtin_initialize registerBuiltinRpcProcedure `Lean.Widget.getGoToLocation GetGoToLocationParams (Array Lsp.LocationLink) fun ⟨kind, ⟨i⟩⟩ => RequestM.asTask do let rc ← read let ls ← FileWorker.locationLinksOfInfo kind i if !ls.isEmpty then return ls -- TODO(WN): unify handling of delab'd (infoview) and elab'd (editor) applications let .ofTermInfo ti := i.info | return #[] let .app _ _ := ti.expr | return #[] let some nm := ti.expr.getAppFn.constName? | return #[] i.ctx.runMetaM ti.lctx <| locationLinksFromDecl rc.srcSearchPath rc.doc.meta.uri nm none def lazyTraceChildrenToInteractive (children : WithRpcRef LazyTraceChildren) : RequestM (RequestTask (Array (TaggedText MsgEmbed))) := RequestM.asTask do let ⟨indent, children⟩ := children children.mapM fun ⟨child⟩ => msgToInteractive child (hasWidgets := true) (indent := indent) builtin_initialize registerBuiltinRpcProcedure ``lazyTraceChildrenToInteractive _ _ lazyTraceChildrenToInteractive end Lean.Widget
acd3e95a91fd22cb13718fc39d130669d32b5cc4
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/group_power/basic.lean
25f2d4387ea00c772427f94af702471ef83b09fe
[ "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
27,731
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.ordered_ring import tactic.monotonicity.basic import deprecated.group /-! # Power operations on monoids and groups The power operation on monoids and groups. We separate this from group, because it depends on `ℕ`, which in turn depends on other parts of algebra. This module contains the definitions of `monoid.pow` and `group.pow` and their additive counterparts `nsmul` and `gsmul`, along with a few lemmas. Further lemmas can be found in `algebra.group_power.lemmas`. ## Notation The class `has_pow α β` provides the notation `a^b` for powers. We define instances of `has_pow M ℕ`, for monoids `M`, and `has_pow G ℤ` for groups `G`. We also define infix operators `•ℕ` and `•ℤ` for scalar multiplication by a natural and an integer numbers, respectively. ## Implementation details We adopt the convention that `0^0 = 1`. This module provides the instance `has_pow ℕ ℕ` (via `monoid.has_pow`) and is imported by `data.nat.basic`, so it has to live low in the import hierarchy. Not all of its imports are needed yet; the intent is to move more lemmas here from `.lemmas` so that they are available in `data.nat.basic`, and the imports will be required then. -/ 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₂} /-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/ def monoid.pow [has_mul M] [has_one M] (a : M) : ℕ → M | 0 := 1 | (n+1) := a * monoid.pow n /-- The scalar multiplication in an additive monoid. `n •ℕ a = a+a+...+a` n times. -/ def nsmul [has_add A] [has_zero A] (n : ℕ) (a : A) : A := @monoid.pow (multiplicative A) _ _ a n infix ` •ℕ `:70 := nsmul instance monoid.has_pow [monoid M] : has_pow M ℕ := ⟨monoid.pow⟩ @[simp] lemma monoid.pow_eq_has_pow [monoid M] (a : M) (n : ℕ) : monoid.pow a n = a^n := rfl /-! ### Commutativity First we prove some facts about `semiconj_by` and `commute`. They do not require any theory about `pow` and/or `nsmul` and will be useful later in this file. -/ namespace semiconj_by variables [monoid M] @[simp] lemma pow_right {a x y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x^n) (y^n) := nat.rec_on n (one_right a) $ λ n ihn, h.mul_right ihn end semiconj_by namespace commute variables [monoid M] {a b : M} @[simp] theorem pow_right (h : commute a b) (n : ℕ) : commute a (b ^ n) := h.pow_right n @[simp] theorem pow_left (h : commute a b) (n : ℕ) : commute (a ^ n) b := (h.symm.pow_right n).symm @[simp] theorem pow_pow (h : commute a b) (m n : ℕ) : commute (a ^ m) (b ^ n) := (h.pow_left m).pow_right n @[simp] theorem self_pow (a : M) (n : ℕ) : commute a (a ^ n) := (commute.refl a).pow_right n @[simp] theorem pow_self (a : M) (n : ℕ) : commute (a ^ n) a := (commute.refl a).pow_left n @[simp] theorem pow_pow_self (a : M) (m n : ℕ) : commute (a ^ m) (a ^ n) := (commute.refl a).pow_pow m n end commute section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem pow_zero (a : M) : a^0 = 1 := rfl @[simp] theorem zero_nsmul (a : A) : 0 •ℕ a = 0 := rfl theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := rfl theorem succ_nsmul (a : A) (n : ℕ) : (n+1) •ℕ a = a + n •ℕ a := rfl theorem pow_two (a : M) : a^2 = a * a := show a*(a*1)=a*a, by rw mul_one theorem two_nsmul (a : A) : 2 •ℕ a = a + a := @pow_two (multiplicative A) _ a theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := commute.pow_self a n theorem nsmul_add_comm' : ∀ (a : A) (n : ℕ), n •ℕ a + a = a + n •ℕ a := @pow_mul_comm' (multiplicative A) _ theorem pow_succ' (a : M) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] theorem succ_nsmul' (a : A) (n : ℕ) : (n+1) •ℕ a = n •ℕ a + a := @pow_succ' (multiplicative A) _ _ _ theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [nat.add_zero, pow_zero, mul_one], rw [pow_succ', ← mul_assoc, ← ih, ← pow_succ', nat.add_assoc]] theorem add_nsmul : ∀ (a : A) (m n : ℕ), (m + n) •ℕ a = m •ℕ a + n •ℕ a := @pow_add (multiplicative A) _ @[simp] theorem pow_one (a : M) : a^1 = a := mul_one _ @[simp] theorem one_nsmul (a : A) : 1 •ℕ a = a := add_zero _ @[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) : a ^ (if P then b else c) = if P then a ^ b else a ^ c := by split_ifs; refl @[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) : (if P then a else b) ^ c = if P then a ^ c else b ^ c := by split_ifs; refl @[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) : a ^ (if P then 1 else 0) = if P then a else 1 := by simp @[simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 := by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]] @[simp] theorem nsmul_zero (n : ℕ) : n •ℕ (0 : A) = 0 := by induction n with n ih; [refl, rw [succ_nsmul, ih, zero_add]] theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with n ih; [rw nat.mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl theorem mul_nsmul' : ∀ (a : A) (m n : ℕ), m * n •ℕ a = n •ℕ (m •ℕ a) := @pow_mul (multiplicative A) _ theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [nat.mul_comm, pow_mul] theorem mul_nsmul (a : A) (m n : ℕ) : m * n •ℕ a = m •ℕ (n •ℕ a) := @pow_mul' (multiplicative A) _ a m n theorem pow_mul_pow_sub (a : M) {m n : ℕ} (h : m ≤ n) : a ^ m * a ^ (n - m) = a ^ n := by rw [←pow_add, nat.add_comm, nat.sub_add_cancel h] theorem nsmul_add_sub_nsmul (a : A) {m n : ℕ} (h : m ≤ n) : (m •ℕ a) + ((n - m) •ℕ a) = n •ℕ a := @pow_mul_pow_sub (multiplicative A) _ _ _ _ h theorem pow_sub_mul_pow (a : M) {m n : ℕ} (h : m ≤ n) : a ^ (n - m) * a ^ m = a ^ n := by rw [←pow_add, nat.sub_add_cancel h] theorem sub_nsmul_nsmul_add (a : A) {m n : ℕ} (h : m ≤ n) : ((n - m) •ℕ a) + (m •ℕ a) = n •ℕ a := @pow_sub_mul_pow (multiplicative A) _ _ _ _ h theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ theorem bit0_nsmul (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ a + n •ℕ a := add_nsmul _ _ _ theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] theorem bit1_nsmul : ∀ (a : A) (n : ℕ), bit1 n •ℕ a = n •ℕ a + n •ℕ a + a := @pow_bit1 (multiplicative A) _ theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m := commute.pow_pow_self a m n theorem nsmul_add_comm : ∀ (a : A) (m n : ℕ), m •ℕ a + n •ℕ a = n •ℕ a + m •ℕ a := @pow_mul_comm (multiplicative A) _ @[simp] theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := f.map_one | (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow] @[simp] theorem add_monoid_hom.map_nsmul (f : A →+ B) (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a := f.to_multiplicative.map_pow a n theorem is_monoid_hom.map_pow (f : M → N) [is_monoid_hom f] (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n := (monoid_hom.of f).map_pow a theorem is_add_monoid_hom.map_nsmul (f : A → B) [is_add_monoid_hom f] (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a := (add_monoid_hom.of f).map_nsmul a n lemma commute.mul_pow {a b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := nat.rec_on n (by simp) $ λ n ihn, by simp only [pow_succ, ihn, ← mul_assoc, (h.pow_left n).right_comm] theorem neg_pow [ring R] (a : R) (n : ℕ) : (- a) ^ n = (-1) ^ n * a ^ n := (neg_one_mul a) ▸ (commute.neg_one_left a).mul_pow n theorem pow_bit0' (a : M) (n : ℕ) : a ^ bit0 n = (a * a) ^ n := by rw [pow_bit0, (commute.refl a).mul_pow] theorem bit0_nsmul' (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ (a + a) := @pow_bit0' (multiplicative A) _ _ _ theorem pow_bit1' (a : M) (n : ℕ) : a ^ bit1 n = (a * a) ^ n * a := by rw [bit1, pow_succ', pow_bit0'] theorem bit1_nsmul' : ∀ (a : A) (n : ℕ), bit1 n •ℕ a = n •ℕ (a + a) + a := @pow_bit1' (multiplicative A) _ @[simp] theorem neg_pow_bit0 [ring R] (a : R) (n : ℕ) : (- a) ^ (bit0 n) = a ^ (bit0 n) := by rw [pow_bit0', neg_mul_neg, pow_bit0'] @[simp] theorem neg_pow_bit1 [ring R] (a : R) (n : ℕ) : (- a) ^ (bit1 n) = - a ^ (bit1 n) := by simp only [bit1, pow_succ, neg_pow_bit0, neg_mul_eq_neg_mul] end monoid /-! ### Commutative (additive) monoid -/ section comm_monoid variables [comm_monoid M] [add_comm_monoid A] theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_pow n theorem nsmul_add : ∀ (a b : A) (n : ℕ), n •ℕ (a + b) = n •ℕ a + n •ℕ b := @mul_pow (multiplicative A) _ instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : M → M) := { map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ } instance nsmul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (nsmul n : A → A) := { map_add := λ _ _, nsmul_add _ _ _, map_zero := nsmul_zero _ } lemma dvd_pow {x y : M} : ∀ {n : ℕ} (hxy : x ∣ y) (hn : n ≠ 0), x ∣ y^n | 0 hxy hn := (hn rfl).elim | (n+1) hxy hn := by { rw [pow_succ], exact dvd_mul_of_dvd_left hxy _ } end comm_monoid section group variables [group G] [group H] [add_group A] [add_group B] open int /-- The power operation in a group. This extends `monoid.pow` to negative integers with the definition `a^(-n) = (a^n)⁻¹`. -/ def gpow (a : G) : ℤ → G | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ /-- The scalar multiplication by integers on an additive group. This extends `nsmul` to negative integers with the definition `(-n) •ℤ a = -(n •ℕ a)`. -/ def gsmul (n : ℤ) (a : A) : A := @gpow (multiplicative A) _ a n instance group.has_pow : has_pow G ℤ := ⟨gpow⟩ infix ` •ℤ `:70 := gsmul @[simp] lemma group.gpow_eq_has_pow (a : G) (n : ℤ) : gpow a n = a ^ n := rfl section nat @[simp] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := by induction n with n ih; [exact one_inv.symm, rw [pow_succ', pow_succ, ih, mul_inv_rev]] @[simp] theorem neg_nsmul : ∀ (a : A) (n : ℕ), n •ℕ (-a) = -(n •ℕ a) := @inv_pow (multiplicative A) _ theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem nsmul_sub : ∀ (a : A) {m n : ℕ}, n ≤ m → (m - n) •ℕ a = m •ℕ a - n •ℕ a := by simpa only [sub_eq_add_neg] using @pow_sub (multiplicative A) _ theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := (commute.refl a).inv_left.pow_pow m n theorem nsmul_neg_comm : ∀ (a : A) (m n : ℕ), m •ℕ (-a) + n •ℕ a = n •ℕ a + m •ℕ (-a) := @pow_inv_comm (multiplicative A) _ end nat @[simp] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl @[simp] theorem gsmul_coe_nat (a : A) (n : ℕ) : n •ℤ a = n •ℕ a := rfl theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := rfl theorem gsmul_of_nat (a : A) (n : ℕ) : of_nat n •ℤ a = n •ℕ a := rfl @[simp] theorem gpow_neg_succ_of_nat (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl @[simp] theorem gsmul_neg_succ_of_nat (a : A) (n : ℕ) : -[1+n] •ℤ a = - (n.succ •ℕ a) := rfl @[simp] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := rfl @[simp] theorem zero_gsmul (a : A) : (0:ℤ) •ℤ a = 0 := rfl @[simp] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := pow_one a @[simp] theorem one_gsmul (a : A) : (1:ℤ) •ℤ a = a := add_zero _ @[simp] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1 | (n : ℕ) := one_pow _ | -[1+ n] := show _⁻¹=(1:G), by rw [one_pow, one_inv] @[simp] theorem gsmul_zero : ∀ (n : ℤ), n •ℤ (0 : A) = 0 := @one_gpow (multiplicative A) _ @[simp] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := rfl | 0 := one_inv.symm | -[1+ n] := (inv_inv _).symm lemma mul_gpow_neg_one (a b : G) : (a*b)^(-(1:ℤ)) = b^(-(1:ℤ))*a^(-(1:ℤ)) := by simp only [mul_inv_rev, gpow_one, gpow_neg] @[simp] theorem neg_gsmul : ∀ (a : A) (n : ℤ), -n •ℤ a = -(n •ℤ a) := @gpow_neg (multiplicative A) _ theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x theorem neg_one_gsmul (x : A) : (-1:ℤ) •ℤ x = -x := congr_arg has_neg.neg $ one_nsmul x theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := inv_pow a n | -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1) theorem gsmul_neg (a : A) (n : ℤ) : gsmul n (- a) = - gsmul n a := @inv_gpow (multiplicative A) _ a n theorem commute.mul_gpow {a b : G} (h : commute a b) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n | (n : ℕ) := h.mul_pow n | -[1+n] := by simp [h.mul_pow, (h.pow_pow n.succ n.succ).inv_inv.symm.eq] end group section comm_group variables [comm_group G] [add_comm_group A] theorem mul_gpow (a b : G) (n : ℤ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_gpow n theorem gsmul_add : ∀ (a b : A) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b := @mul_gpow (multiplicative A) _ theorem gsmul_sub (a b : A) (n : ℤ) : gsmul n (a - b) = gsmul n a - gsmul n b := by simp only [gsmul_add, gsmul_neg, sub_eq_add_neg] instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : G → G) := { map_mul := λ _ _, mul_gpow _ _ n } instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : A → A) := { map_add := λ _ _, gsmul_add _ _ n } end comm_group lemma zero_pow [monoid_with_zero R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0 | (n+1) _ := zero_mul _ lemma zero_pow_eq [monoid_with_zero R] (n : ℕ) : (0 : R)^n = if n = 0 then 1 else 0 := begin split_ifs with h, { rw [h, pow_zero], }, { rw [zero_pow (nat.pos_of_ne_zero h)] }, end namespace ring_hom variables [semiring R] [semiring S] @[simp] lemma map_pow (f : R →+* S) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := f.to_monoid_hom.map_pow a end ring_hom section variables (R) theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl rfl | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) end @[simp] lemma neg_one_pow_mul_eq_zero_iff [ring R] {n : ℕ} {r : R} : (-1)^n * r = 0 ↔ r = 0 := by rcases neg_one_pow_eq_or R n; simp [h] @[simp] lemma mul_neg_one_pow_eq_zero_iff [ring R] {n : ℕ} {r : R} : r * (-1)^n = 0 ↔ r = 0 := by rcases neg_one_pow_eq_or R n; simp [h] lemma pow_dvd_pow [monoid R] (a : R) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_comm, nat.sub_add_cancel h]⟩ theorem pow_dvd_pow_of_dvd [comm_monoid R] {a b : R} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul h (pow_dvd_pow_of_dvd n) lemma pow_two_sub_pow_two {R : Type*} [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by simp only [pow_two, mul_sub, add_mul, sub_sub, add_sub, mul_comm, sub_add_cancel] lemma eq_or_eq_neg_of_pow_two_eq_pow_two [integral_domain R] (a b : R) (h : a ^ 2 = b ^ 2) : a = b ∨ a = -b := by rwa [← add_eq_zero_iff_eq_neg, ← sub_eq_zero, or_comm, ← mul_eq_zero, ← pow_two_sub_pow_two a b, sub_eq_zero] theorem sq_sub_sq [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by rw [pow_two, pow_two, mul_self_sub_mul_self] theorem pow_eq_zero [monoid_with_zero R] [no_zero_divisors R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, exact or.cases_on (mul_eq_zero.1 H) id ih end @[simp] lemma pow_eq_zero_iff [monoid_with_zero R] [no_zero_divisors R] {a : R} {n : ℕ} (hn : 0 < n) : a ^ n = 0 ↔ a = 0 := begin refine ⟨pow_eq_zero, _⟩, rintros rfl, exact zero_pow hn, end @[field_simps] theorem pow_ne_zero [monoid_with_zero R] [no_zero_divisors R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h lemma pow_abs [linear_ordered_comm_ring R] (a : R) (n : ℕ) : (abs a)^n = abs (a^n) := (abs_hom.to_monoid_hom.map_pow a n).symm lemma abs_neg_one_pow [linear_ordered_comm_ring R] (n : ℕ) : abs ((-1 : R)^n) = 1 := by rw [←pow_abs, abs_neg, abs_one, one_pow] section add_monoid variable [ordered_add_comm_monoid A] theorem nsmul_nonneg {a : A} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n •ℕ a | 0 := le_refl _ | (n+1) := add_nonneg H (nsmul_nonneg n) lemma nsmul_pos {a : A} (ha : 0 < a) {k : ℕ} (hk : 0 < k) : 0 < k •ℕ a := begin rcases nat.exists_eq_succ_of_ne_zero (ne_of_gt hk) with ⟨l, rfl⟩, clear hk, induction l with l IH, { simpa using ha }, { exact add_pos ha IH } end theorem nsmul_le_nsmul {a : A} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℕ a ≤ m •ℕ a := let ⟨k, hk⟩ := nat.le.dest h in calc n •ℕ a = n •ℕ a + 0 : (add_zero _).symm ... ≤ n •ℕ a + k •ℕ a : add_le_add_left (nsmul_nonneg ha _) _ ... = m •ℕ a : by rw [← hk, add_nsmul] lemma nsmul_le_nsmul_of_le_right {a b : A} (hab : a ≤ b) : ∀ i : ℕ, i •ℕ a ≤ i •ℕ b | 0 := by simp | (k+1) := add_le_add hab (nsmul_le_nsmul_of_le_right _) end add_monoid section add_group variable [ordered_add_comm_group A] theorem gsmul_nonneg {a : A} (H : 0 ≤ a) {n : ℤ} (hn : 0 ≤ n) : 0 ≤ n •ℤ a := begin lift n to ℕ using hn, apply nsmul_nonneg H end end add_group section cancel_add_monoid variable [ordered_cancel_add_comm_monoid A] theorem nsmul_lt_nsmul {a : A} {n m : ℕ} (ha : 0 < a) (h : n < m) : n •ℕ a < m •ℕ a := let ⟨k, hk⟩ := nat.le.dest h in begin have succ_swap : n.succ + k = n + k.succ := nat.succ_add n k, calc n •ℕ a = (n •ℕ a : A) + (0 : A) : (add_zero _).symm ... < n •ℕ a + (k.succ •ℕ a : A) : add_lt_add_left (nsmul_pos ha (nat.succ_pos k)) _ ... = m •ℕ a : by rw [← hk, succ_swap, add_nsmul] end end cancel_add_monoid section semiring variables [semiring R] lemma min_pow_dvd_add {n m : ℕ} {a b c : R} (ha : c ^ n ∣ a) (hb : c ^ m ∣ b) : c ^ (min n m) ∣ a + b := begin replace ha := dvd.trans (pow_dvd_pow c (min_le_left n m)) ha, replace hb := dvd.trans (pow_dvd_pow c (min_le_right n m)) hb, exact dvd_add ha hb end end semiring section comm_semiring variables [comm_semiring R] lemma add_pow_two (a b : R) : (a + b) ^ 2 = a ^ 2 + 2 * a * b + b ^ 2 := by simp only [pow_two, add_mul_self_eq] end comm_semiring namespace canonically_ordered_semiring variable [canonically_ordered_comm_semiring R] theorem pow_pos {a : R} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n | 0 := by { nontriviality, exact canonically_ordered_semiring.zero_lt_one } | (n+1) := canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩ @[mono] lemma pow_le_pow_of_le_left {a b : R} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k) theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := by simpa only [one_pow] using pow_le_pow_of_le_left H n theorem pow_le_one {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:= by simpa only [one_pow] using pow_le_pow_of_le_left H n end canonically_ordered_semiring section ordered_semiring variable [ordered_semiring R] @[simp] theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := by { nontriviality, exact zero_lt_one } | (n+1) := mul_pos H (pow_pos _) @[simp] theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := zero_le_one | (n+1) := mul_nonneg H (pow_nonneg _) theorem pow_add_pow_le {x y : R} {n : ℕ} (hx : 0 ≤ x) (hy : 0 ≤ y) (hn : n ≠ 0) : x ^ n + y ^ n ≤ (x + y) ^ n := begin rcases nat.exists_eq_succ_of_ne_zero hn with ⟨k, rfl⟩, induction k with k ih, { simp only [pow_one] }, let n := k.succ, have h1 := add_nonneg (mul_nonneg hx (pow_nonneg hy n)) (mul_nonneg hy (pow_nonneg hx n)), have h2 := add_nonneg hx hy, calc x^n.succ + y^n.succ ≤ x*x^n + y*y^n + (x*y^n + y*x^n) : le_add_of_nonneg_right h1 ... = (x+y) * (x^n + y^n) : by rw [add_mul, mul_add, mul_add, add_comm (y*x^n), ← add_assoc, ← add_assoc, add_assoc (x*x^n) (x*y^n), add_comm (x*y^n) (y*y^n), ← add_assoc] ... ≤ (x+y)^n.succ : mul_le_mul_of_nonneg_left (ih (nat.succ_ne_zero k)) h2, end theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ←nat.sub_add_cancel Hnpos, induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end theorem strict_mono_incr_on_pow {n : ℕ} (hn : 0 < n) : strict_mono_incr_on (λ x : R, x ^ n) (set.Ici 0) := λ x hx y hy h, pow_lt_pow_of_lt_left h hx hn theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := le_refl _ | (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) lemma pow_mono {a : R} (h : 1 ≤ a) : monotone (λ n : ℕ, a ^ n) := monotone_of_monotone_nat $ λ n, le_mul_of_one_le_left (pow_nonneg (zero_le_one.trans h) _) h theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := pow_mono ha h lemma strict_mono_pow {a : R} (h : 1 < a) : strict_mono (λ n : ℕ, a ^ n) := have 0 < a := zero_le_one.trans_lt h, strict_mono.nat $ λ n, by simpa only [one_mul, pow_succ] using mul_lt_mul h (le_refl (a ^ n)) (pow_pos this _) this.le lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := strict_mono_pow h h2 lemma pow_lt_pow_iff {a : R} {n m : ℕ} (h : 1 < a) : a ^ n < a ^ m ↔ n < m := (strict_mono_pow h).lt_iff_lt @[mono] lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) end ordered_semiring section linear_ordered_semiring variable [linear_ordered_semiring R] theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) (Hxyn : x ^ n = y ^ n) : x = y := (@strict_mono_incr_on_pow R _ _ Hnpos).inj_on Hxpos Hypos Hxyn lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h lemma le_of_pow_le_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (hn : 0 < n) (h : a ^ n ≤ b ^ n) : a ≤ b := le_of_not_lt $ λ h1, not_le_of_lt (pow_lt_pow_of_lt_left h1 hb hn) h end linear_ordered_semiring section linear_ordered_ring variable [linear_ordered_ring R] theorem pow_bit0_nonneg (a : R) (n : ℕ) : 0 ≤ a ^ bit0 n := by { rw pow_bit0, exact mul_self_nonneg _ } theorem pow_two_nonneg (a : R) : 0 ≤ a ^ 2 := pow_bit0_nonneg a 1 theorem pow_bit0_pos {a : R} (h : a ≠ 0) (n : ℕ) : 0 < a ^ bit0 n := (pow_bit0_nonneg a n).lt_of_ne (pow_ne_zero _ h).symm theorem pow_two_pos_of_ne_zero (a : R) (h : a ≠ 0) : 0 < a ^ 2 := pow_bit0_pos h 1 variables {x y : R} theorem sqr_abs (x : R) : abs x ^ 2 = x ^ 2 := by simpa only [pow_two] using abs_mul_abs_self x theorem abs_sqr (x : R) : abs (x ^ 2) = x ^ 2 := by simpa only [pow_two] using abs_mul_self x theorem sqr_lt_sqr (h : abs x < y) : x ^ 2 < y ^ 2 := by simpa only [sqr_abs] using pow_lt_pow_of_lt_left h (abs_nonneg x) (1:ℕ).succ_pos theorem sqr_lt_sqr' (h1 : -y < x) (h2 : x < y) : x ^ 2 < y ^ 2 := sqr_lt_sqr (abs_lt.mpr ⟨h1, h2⟩) theorem sqr_le_sqr (h : abs x ≤ y) : x ^ 2 ≤ y ^ 2 := by simpa only [sqr_abs] using pow_le_pow_of_le_left (abs_nonneg x) h 2 theorem sqr_le_sqr' (h1 : -y ≤ x) (h2 : x ≤ y) : x ^ 2 ≤ y ^ 2 := sqr_le_sqr (abs_le.mpr ⟨h1, h2⟩) theorem abs_lt_abs_of_sqr_lt_sqr (h : x^2 < y^2) : abs x < abs y := lt_of_pow_lt_pow 2 (abs_nonneg y) $ by rwa [← sqr_abs x, ← sqr_abs y] at h theorem abs_lt_of_sqr_lt_sqr (h : x^2 < y^2) (hy : 0 ≤ y) : abs x < y := begin rw [← abs_of_nonneg hy], exact abs_lt_abs_of_sqr_lt_sqr h, end theorem abs_lt_of_sqr_lt_sqr' (h : x^2 < y^2) (hy : 0 ≤ y) : -y < x ∧ x < y := abs_lt.mp $ abs_lt_of_sqr_lt_sqr h hy theorem abs_le_abs_of_sqr_le_sqr (h : x^2 ≤ y^2) : abs x ≤ abs y := le_of_pow_le_pow 2 (abs_nonneg y) (1:ℕ).succ_pos $ by rwa [← sqr_abs x, ← sqr_abs y] at h theorem abs_le_of_sqr_le_sqr (h : x^2 ≤ y^2) (hy : 0 ≤ y) : abs x ≤ y := begin rw [← abs_of_nonneg hy], exact abs_le_abs_of_sqr_le_sqr h, end theorem abs_le_of_sqr_le_sqr' (h : x^2 ≤ y^2) (hy : 0 ≤ y) : -y ≤ x ∧ x ≤ y := abs_le.mp $ abs_le_of_sqr_le_sqr h hy end linear_ordered_ring @[simp] lemma eq_of_pow_two_eq_pow_two [linear_ordered_comm_ring R] {a b : R} (ha : 0 ≤ a) (hb : 0 ≤ b) : a ^ 2 = b ^ 2 ↔ a = b := begin refine ⟨_, congr_arg _⟩, intros h, refine (eq_or_eq_neg_of_pow_two_eq_pow_two _ _ h).elim id _, rintros rfl, rw le_antisymm (neg_nonneg.mp ha) hb, exact neg_zero end @[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [pow, monoid.pow] lemma sub_pow_two {R} [comm_ring R] (a b : R) : (a - b) ^ 2 = a ^ 2 - 2 * a * b + b ^ 2 := by rw [sub_eq_add_neg, add_pow_two, neg_square, mul_neg_eq_neg_mul_symm, ← sub_eq_add_neg] /-- Arithmetic mean-geometric mean (AM-GM) inequality for linearly ordered commutative rings. -/ lemma two_mul_le_add_pow_two {R} [linear_ordered_comm_ring R] (a b : R) : 2 * a * b ≤ a ^ 2 + b ^ 2 := sub_nonneg.mp ((sub_add_eq_add_sub _ _ _).subst ((sub_pow_two a b).subst (pow_two_nonneg _))) lemma of_add_nsmul [add_monoid A] (x : A) (n : ℕ) : multiplicative.of_add (n •ℕ x) = (multiplicative.of_add x)^n := rfl lemma of_add_gsmul [add_group A] (x : A) (n : ℤ) : multiplicative.of_add (n •ℤ x) = (multiplicative.of_add x)^n := rfl lemma of_mul_pow {A : Type*} [monoid A] (x : A) (n : ℕ) : additive.of_mul (x ^ n) = n •ℕ (additive.of_mul x) := (congr_arg additive.of_mul (of_add_nsmul (additive.of_mul x) n)).symm lemma of_mul_gpow [group G] (x : G) (n : ℤ) : additive.of_mul (x ^ n) = n •ℤ additive.of_mul x := by { cases n; simp [gsmul_of_nat, gpow_of_nat, of_mul_pow] } @[simp] lemma semiconj_by.gpow_right [group G] {a x y : G} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (x^m) (y^m) | (n : ℕ) := h.pow_right n | -[1+n] := (h.pow_right n.succ).inv_right namespace commute variables [group G] {a b : G} @[simp] lemma gpow_right (h : commute a b) (m : ℤ) : commute a (b^m) := h.gpow_right m @[simp] lemma gpow_left (h : commute a b) (m : ℤ) : commute (a^m) b := (h.symm.gpow_right m).symm lemma gpow_gpow (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.gpow_left m).gpow_right n variables (a) (m n : ℕ) @[simp] theorem self_gpow : commute a (a ^ n) := (commute.refl a).gpow_right n @[simp] theorem gpow_self : commute (a ^ n) a := (commute.refl a).gpow_left n @[simp] theorem gpow_gpow_self : commute (a ^ m) (a ^ n) := (commute.refl a).gpow_gpow m n end commute
b7f9a5eaaeea4504ebfbc3923ebf1d3c691998ee
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/number_theory/pythagorean_triples.lean
e6c22d425db2acd58a8046789d395d673e1feb5a
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
26,068
lean
/- Copyright (c) 2020 Paul van Wamelen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Paul van Wamelen. -/ import algebra.field import ring_theory.int.basic import algebra.group_with_zero.power import tactic.ring import tactic.ring_exp import tactic.field_simp /-! # Pythagorean Triples The main result is the classification of pythagorean triples. The final result is for general pythagorean triples. It follows from the more interesting relatively prime case. We use the "rational parametrization of the circle" method for the proof. The parametrization maps the point `(x / z, y / z)` to the slope of the line through `(-1 , 0)` and `(x / z, y / z)`. This quickly shows that `(x / z, y / z) = (2 * m * n / (m ^ 2 + n ^ 2), (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))` where `m / n` is the slope. In order to identify numerators and denominators we now need results showing that these are coprime. This is easy except for the prime 2. In order to deal with that we have to analyze the parity of `x`, `y`, `m` and `n` and eliminate all the impossible cases. This takes up the bulk of the proof below. -/ noncomputable theory open_locale classical /-- Three integers `x`, `y`, and `z` form a Pythagorean triple if `x * x + y * y = z * z`. -/ def pythagorean_triple (x y z : ℤ) : Prop := x * x + y * y = z * z /-- Pythagorean triples are interchangable, i.e `x * x + y * y = y * y + x * x = z * z`. This comes from additive commutativity. -/ lemma pythagorean_triple_comm {x y z : ℤ} : (pythagorean_triple x y z) ↔ (pythagorean_triple y x z) := by { delta pythagorean_triple, rw add_comm } /-- The zeroth Pythagorean triple is all zeros. -/ lemma pythagorean_triple.zero : pythagorean_triple 0 0 0 := by simp only [pythagorean_triple, zero_mul, zero_add] namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma eq : x * x + y * y = z * z := h @[symm] lemma symm : pythagorean_triple y x z := by rwa [pythagorean_triple_comm] /-- A triple is still a triple if you multiply `x`, `y` and `z` by a constant `k`. -/ lemma mul (k : ℤ) : pythagorean_triple (k * x) (k * y) (k * z) := begin by_cases hk : k = 0, { simp only [pythagorean_triple, hk, zero_mul, zero_add], }, { calc (k * x) * (k * x) + (k * y) * (k * y) = k ^ 2 * (x * x + y * y) : by ring ... = k ^ 2 * (z * z) : by rw h.eq ... = (k * z) * (k * z) : by ring } end omit h /-- `(k*x, k*y, k*z)` is a Pythagorean triple if and only if `(x, y, z)` is also a triple. -/ lemma mul_iff (k : ℤ) (hk : k ≠ 0) : pythagorean_triple (k * x) (k * y) (k * z) ↔ pythagorean_triple x y z := begin refine ⟨_, λ h, h.mul k⟩, simp only [pythagorean_triple], intro h, rw ← mul_left_inj' (mul_ne_zero hk hk), convert h using 1; ring, end include h /-- A pythogorean triple `x, y, z` is “classified” if there exist integers `k, m, n` such that either * `x = k * (m ^ 2 - n ^ 2)` and `y = k * (2 * m * n)`, or * `x = k * (2 * m * n)` and `y = k * (m ^ 2 - n ^ 2)`. -/ @[nolint unused_arguments] def is_classified := ∃ (k m n : ℤ), ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ int.gcd m n = 1 /-- A primitive pythogorean triple `x, y, z` is a pythagorean triple with `x` and `y` coprime. Such a triple is “primitively classified” if there exist coprime integers `m, n` such that either * `x = m ^ 2 - n ^ 2` and `y = 2 * m * n`, or * `x = 2 * m * n` and `y = m ^ 2 - n ^ 2`. -/ @[nolint unused_arguments] def is_primitive_classified := ∃ (m n : ℤ), ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) lemma mul_is_classified (k : ℤ) (hc : h.is_classified) : (h.mul k).is_classified := begin obtain ⟨l, m, n, ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co⟩⟩ := hc, { use [k * l, m, n], apply and.intro _ co, left, split; ring }, { use [k * l, m, n], apply and.intro _ co, right, split; ring }, end lemma even_odd_of_coprime (hc : int.gcd x y = 1) : (x % 2 = 0 ∧ y % 2 = 1) ∨ (x % 2 = 1 ∧ y % 2 = 0) := begin cases int.mod_two_eq_zero_or_one x with hx hx; cases int.mod_two_eq_zero_or_one y with hy hy, { -- x even, y even exfalso, apply nat.not_coprime_of_dvd_of_dvd (dec_trivial : 1 < 2) _ _ hc, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hx }, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hy } }, { left, exact ⟨hx, hy⟩ }, -- x even, y odd { right, exact ⟨hx, hy⟩ }, -- x odd, y even { -- x odd, y odd exfalso, obtain ⟨x0, y0, rfl, rfl⟩ : ∃ x0 y0, x = x0* 2 + 1 ∧ y = y0 * 2 + 1, { cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hx) with x0 hx2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hy) with y0 hy2, rw sub_eq_iff_eq_add at hx2 hy2, exact ⟨x0, y0, hx2, hy2⟩ }, have hz : (z * z) % 4 = 2, { rw show z * z = 4 * (x0 * x0 + x0 + y0 * y0 + y0) + 2, by { rw ← h.eq, ring }, simp only [int.add_mod, int.mul_mod_right, int.mod_mod, zero_add], refl }, have : ∀ (k : ℤ), 0 ≤ k → k < 4 → k * k % 4 ≠ 2 := dec_trivial, have h4 : (4 : ℤ) ≠ 0 := dec_trivial, apply this (z % 4) (int.mod_nonneg z h4) (int.mod_lt z h4), rwa [← int.mul_mod] }, end lemma gcd_dvd : (int.gcd x y : ℤ) ∣ z := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hz, dvd_zero], }, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul], rw [← int.pow_dvd_pow_iff (dec_trivial : 0 < 2), pow_two z, ← h.eq], rw (by ring : x0 * k * (x0 * k) + y0 * k * (y0 * k) = k ^ 2 * (x0 * x0 + y0 * y0)), exact dvd_mul_right _ _ end lemma normalize : pythagorean_triple (x / int.gcd x y) (y / int.gcd x y) (z / int.gcd x y) := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hx, hy, hz, int.zero_div], exact zero }, rcases h.gcd_dvd with ⟨z0, rfl⟩, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), have hk : (k : ℤ) ≠ 0, { norm_cast, rwa pos_iff_ne_zero at k0 }, rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul] at h ⊢, rw [mul_comm x0, mul_comm y0, mul_iff k hk] at h, rwa [int.mul_div_cancel _ hk, int.mul_div_cancel _ hk, int.mul_div_cancel_left _ hk], end lemma is_classified_of_is_primitive_classified (hp : h.is_primitive_classified) : h.is_classified := begin obtain ⟨m, n, H⟩ := hp, use [1, m, n], rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩; { apply and.intro _ co, rw one_mul, rw one_mul, tauto } end lemma is_classified_of_normalize_is_primitive_classified (hc : h.normalize.is_primitive_classified) : h.is_classified := begin convert h.normalize.mul_is_classified (int.gcd x y) (is_classified_of_is_primitive_classified h.normalize hc); rw int.mul_div_cancel', { exact int.gcd_dvd_left x y }, { exact int.gcd_dvd_right x y }, { exact h.gcd_dvd } end lemma ne_zero_of_coprime (hc : int.gcd x y = 1) : z ≠ 0 := begin suffices : 0 < z * z, { rintro rfl, norm_num at this }, rw [← h.eq, ← pow_two, ← pow_two], have hc' : int.gcd x y ≠ 0, { rw hc, exact one_ne_zero }, cases int.ne_zero_of_gcd hc' with hxz hyz, { apply lt_add_of_pos_of_le (pow_two_pos_of_ne_zero x hxz) (pow_two_nonneg y) }, { apply lt_add_of_le_of_pos (pow_two_nonneg x) (pow_two_pos_of_ne_zero y hyz) } end lemma is_primitive_classified_of_coprime_of_zero_left (hc : int.gcd x y = 1) (hx : x = 0) : h.is_primitive_classified := begin subst x, change nat.gcd 0 (int.nat_abs y) = 1 at hc, rw [nat.gcd_zero_left (int.nat_abs y)] at hc, cases int.nat_abs_eq y with hy hy, { use [1, 0], rw [hy, hc, int.gcd_zero_right], norm_num }, { use [0, 1], rw [hy, hc, int.gcd_zero_left], norm_num } end lemma coprime_of_coprime (hc : int.gcd x y = 1) : int.gcd y z = 1 := begin by_contradiction H, obtain ⟨p, hp, hpy, hpz⟩ := nat.prime.not_coprime_iff_dvd.mp H, apply hp.not_dvd_one, rw [← hc], apply nat.dvd_gcd (int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp _ _) hpy, rw [pow_two, eq_sub_of_add_eq h], rw [← int.coe_nat_dvd_left] at hpy hpz, exact dvd_sub (dvd_mul_of_dvd_left (hpz) _) (dvd_mul_of_dvd_left (hpy) _), end end pythagorean_triple section circle_equiv_gen /-! ### A parametrization of the unit circle For the classification of pythogorean triples, we will use a parametrization of the unit circle. -/ variables {K : Type*} [field K] /-- A parameterization of the unit circle that is useful for classifying Pythagorean triples. (To be applied in the case where `K = ℚ`.) -/ def circle_equiv_gen (hk : ∀ x : K, 1 + x^2 ≠ 0) : K ≃ {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := { to_fun := λ x, ⟨⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩, by { field_simp [hk x, div_pow], ring }, begin simp only [ne.def, div_eq_iff (hk x), ←neg_mul_eq_neg_mul, one_mul, neg_add, sub_eq_add_neg, add_left_inj], simpa only [eq_neg_iff_add_eq_zero, one_pow] using hk 1, end⟩, inv_fun := λ p, (p : K × K).1 / ((p : K × K).2 + 1), left_inv := λ x, begin have h2 : (1 + 1 : K) = 2 := rfl, have h3 : (2 : K) ≠ 0, { convert hk 1, rw [one_pow 2, h2] }, field_simp [hk x, h2, add_assoc, add_comm, add_sub_cancel'_right, mul_comm], end, right_inv := λ ⟨⟨x, y⟩, hxy, hy⟩, begin change x ^ 2 + y ^ 2 = 1 at hxy, have h2 : y + 1 ≠ 0, { apply mt eq_neg_of_add_eq_zero, exact hy }, have h3 : (y + 1) ^ 2 + x ^ 2 = 2 * (y + 1), { rw [(add_neg_eq_iff_eq_add.mpr hxy.symm).symm], ring }, have h4 : (2 : K) ≠ 0, { convert hk 1, rw one_pow 2, refl }, simp only [prod.mk.inj_iff, subtype.mk_eq_mk], split, { field_simp [h3], ring }, { field_simp [h3], rw [← add_neg_eq_iff_eq_add.mpr hxy.symm], ring } end } @[simp] lemma circle_equiv_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (x : K) : (circle_equiv_gen hk x : K × K) = ⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩ := rfl @[simp] lemma circle_equiv_symm_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (v : {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1}) : (circle_equiv_gen hk).symm v = (v : K × K).1 / ((v : K × K).2 + 1) := rfl end circle_equiv_gen private lemma coprime_pow_two_sub_pow_two_add_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have h2m : (p : ℤ) ∣ 2 * m ^ 2, { convert dvd_add hp2 hp1, ring }, have h2n : (p : ℤ) ∣ 2 * n ^ 2, { convert dvd_sub hp2 hp1, ring }, have hmc : p = 2 ∨ p ∣ int.nat_abs m, { exact prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2m }, have hnc : p = 2 ∨ p ∣ int.nat_abs n, { exact prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2n }, by_cases h2 : p = 2, { have h3 : (m ^ 2 + n ^ 2) % 2 = 1, { norm_num [pow_two, int.add_mod, int.mul_mod, hm, hn] }, have h4 : (m ^ 2 + n ^ 2) % 2 = 0, { apply int.mod_eq_zero_of_dvd, rwa h2 at hp2 }, rw h4 at h3, exact zero_ne_one h3 }, { apply hp.not_dvd_one, rw ← h, exact nat.dvd_gcd (or.resolve_left hmc h2) (or.resolve_left hnc h2), } end private lemma coprime_pow_two_sub_pow_two_add_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0): int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2), add_comm], apply coprime_pow_two_sub_pow_two_add_of_even_odd _ hn hm, rwa [int.gcd_comm], end private lemma coprime_pow_two_sub_mul_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have hnp : ¬ (p : ℤ) ∣ int.gcd m n, { rw h, norm_cast, exact mt nat.dvd_one.mp (nat.prime.ne_one hp) }, cases int.prime.dvd_mul hp hp2 with hp2m hpn, { rw int.nat_abs_mul at hp2m, cases (nat.prime.dvd_mul hp).mp hp2m with hp2 hpm, { have hp2' : p = 2, { exact le_antisymm (nat.le_of_dvd zero_lt_two hp2) (nat.prime.two_le hp) }, revert hp1, rw hp2', apply mt int.mod_eq_zero_of_dvd, norm_num [pow_two, int.sub_mod, int.mul_mod, hm, hn], }, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpm)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : n * n = - (m ^ 2 - n ^ 2) + m * m), apply dvd_add (dvd_neg_of_dvd hp1), exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpm) m }, rw int.gcd_comm at hnp, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpn)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : m * m = (m ^ 2 - n ^ 2) + n * n), apply dvd_add hp1, exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpn) n end private lemma coprime_pow_two_sub_mul_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : 2 * m * n = 2 * n * m), (by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2)], apply coprime_pow_two_sub_mul_of_even_odd _ hn hm, rwa [int.gcd_comm] end private lemma coprime_pow_two_sub_mul {m n : ℤ} (h : int.gcd m n = 1) (hmn : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin cases hmn with h1 h2, { exact coprime_pow_two_sub_mul_of_even_odd h h1.left h1.right }, { exact coprime_pow_two_sub_mul_of_odd_even h h2.left h2.right } end private lemma coprime_pow_two_sub_pow_two_sum_of_odd_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 1) : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 := begin cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hm) with m0 hm2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hn) with n0 hn2, rw sub_eq_iff_eq_add at hm2 hn2, subst m, subst n, have h1 : (m0 * 2 + 1) ^ 2 + (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 + n0 ^ 2 + m0 + n0) + 1), by ring_exp, have h2 : (m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 - n0 ^ 2 + m0 - n0)), by ring_exp, have h3 : ((m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2) / 2 % 2 = 0, { rw [h2, int.mul_div_cancel_left, int.mul_mod_right], exact dec_trivial }, refine ⟨⟨_, h1⟩, ⟨_, h2⟩, h3, _⟩, have h20 : (2:ℤ) ≠ 0 := dec_trivial, rw [h1, h2, int.mul_div_cancel_left _ h20, int.mul_div_cancel_left _ h20], by_contra h4, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp h4, apply hp.not_dvd_one, rw ← h, rw ← int.coe_nat_dvd_left at hp1 hp2, apply nat.dvd_gcd, { apply int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp, convert dvd_add hp1 hp2, ring_exp }, { apply int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp, convert dvd_sub hp2 hp1, ring_exp }, end namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma is_primitive_classified_aux (hc : x.gcd y = 1) (hzpos : 0 < z) {m n : ℤ} (hm2n2 : 0 < m ^ 2 + n ^ 2) (hv2 : (x : ℚ) / z = 2 * m * n / (m ^ 2 + n ^ 2)) (hw2 : (y : ℚ) / z = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2)) (H : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1) (co : int.gcd m n = 1) (pp : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)): h.is_primitive_classified := begin have hz : z ≠ 0, apply ne_of_gt hzpos, have h2 : y = m ^ 2 - n ^ 2 ∧ z = m ^ 2 + n ^ 2, { apply rat.div_int_inj hzpos hm2n2 (h.coprime_of_coprime hc) H, rw [hw2], norm_cast }, use [m, n], apply and.intro _ (and.intro co pp), right, refine ⟨_, h2.left⟩, rw [← rat.coe_int_inj _ _, ← div_left_inj' ((mt (rat.coe_int_inj z 0).mp) hz), hv2, h2.right], norm_cast end theorem is_primitive_classified_of_coprime_of_odd_of_pos (hc : int.gcd x y = 1) (hyo : y % 2 = 1) (hzpos : 0 < z) : h.is_primitive_classified := begin by_cases h0 : x = 0, { exact h.is_primitive_classified_of_coprime_of_zero_left hc h0 }, let v := (x : ℚ) / z, let w := (y : ℚ) / z, have hz : z ≠ 0, apply ne_of_gt hzpos, have hq : v ^ 2 + w ^ 2 = 1, { field_simp [hz, pow_two], norm_cast, exact h }, have hvz : v ≠ 0, { field_simp [hz], exact h0 }, have hw1 : w ≠ -1, { contrapose! hvz with hw1, rw [hw1, neg_square, one_pow, add_left_eq_self] at hq, exact pow_eq_zero hq, }, have hQ : ∀ x : ℚ, 1 + x^2 ≠ 0, { intro q, apply ne_of_gt, exact lt_add_of_pos_of_le zero_lt_one (pow_two_nonneg q) }, have hp : (⟨v, w⟩ : ℚ × ℚ) ∈ {p : ℚ × ℚ | p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := ⟨hq, hw1⟩, let q := (circle_equiv_gen hQ).symm ⟨⟨v, w⟩, hp⟩, have ht4 : v = 2 * q / (1 + q ^ 2) ∧ w = (1 - q ^ 2) / (1 + q ^ 2), { apply prod.mk.inj, have := ((circle_equiv_gen hQ).apply_symm_apply ⟨⟨v, w⟩, hp⟩).symm, exact congr_arg subtype.val this, }, let m := (q.denom : ℤ), let n := q.num, have hm0 : m ≠ 0, { norm_cast, apply rat.denom_ne_zero q }, have hq2 : q = n / m, { rw [int.cast_coe_nat], exact (rat.cast_id q).symm }, have hm2n2 : 0 < m ^ 2 + n ^ 2, { apply lt_add_of_pos_of_le _ (pow_two_nonneg n), exact lt_of_le_of_ne (pow_two_nonneg m) (ne.symm (pow_ne_zero 2 hm0)) }, have hw2 : w = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2), { rw [ht4.2, hq2], field_simp [hm2n2, (rat.denom_ne_zero q)] }, have hm2n20 : (m : ℚ) ^ 2 + (n : ℚ) ^ 2 ≠ 0, { norm_cast, simpa only [int.coe_nat_pow] using ne_of_gt hm2n2 }, have hv2 : v = 2 * m * n / (m ^ 2 + n ^ 2), { apply eq.symm, apply (div_eq_iff hm2n20).mpr, rw [ht4.1], field_simp [hQ q], rw [hq2] {occs := occurrences.pos [2, 3]}, field_simp [rat.denom_ne_zero q], ring }, have hnmcp : int.gcd n m = 1 := q.cop, have hmncp : int.gcd m n = 1, { rw int.gcd_comm, exact hnmcp }, cases int.mod_two_eq_zero_or_one m with hm2 hm2; cases int.mod_two_eq_zero_or_one n with hn2 hn2, { -- m even, n even exfalso, have h1 : 2 ∣ (int.gcd n m : ℤ), { exact int.dvd_gcd (int.dvd_of_mod_eq_zero hn2) (int.dvd_of_mod_eq_zero hm2) }, rw hnmcp at h1, revert h1, norm_num }, { -- m even, n odd apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_left, exact and.intro hm2 hn2 }, { apply coprime_pow_two_sub_pow_two_add_of_even_odd hmncp hm2 hn2 } }, { -- m odd, n even apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_right, exact and.intro hm2 hn2 }, apply coprime_pow_two_sub_pow_two_add_of_odd_even hmncp hm2 hn2 }, { -- m odd, n odd exfalso, have h1 : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1, { exact coprime_pow_two_sub_pow_two_sum_of_odd_odd hmncp hm2 hn2 }, have h2 : y = (m ^ 2 - n ^ 2) / 2 ∧ z = (m ^ 2 + n ^ 2) / 2, { apply rat.div_int_inj hzpos _ (h.coprime_of_coprime hc) h1.2.2.2, { show w = _, rw [←rat.mk_eq_div, ←(rat.div_mk_div_cancel_left (by norm_num : (2 : ℤ) ≠ 0))], rw [int.div_mul_cancel h1.1, int.div_mul_cancel h1.2.1, hw2], norm_cast }, { apply (mul_lt_mul_right (by norm_num : 0 < (2 : ℤ))).mp, rw [int.div_mul_cancel h1.1, zero_mul], exact hm2n2 } }, rw [h2.1, h1.2.2.1] at hyo, revert hyo, norm_num } end theorem is_primitive_classified_of_coprime_of_pos (hc : int.gcd x y = 1) (hzpos : 0 < z): h.is_primitive_classified := begin cases h.even_odd_of_coprime hc with h1 h2, { exact (h.is_primitive_classified_of_coprime_of_odd_of_pos hc h1.right hzpos) }, rw int.gcd_comm at hc, obtain ⟨m, n, H⟩ := (h.symm.is_primitive_classified_of_coprime_of_odd_of_pos hc h2.left hzpos), use [m, n], tauto end theorem is_primitive_classified_of_coprime (hc : int.gcd x y = 1) : h.is_primitive_classified := begin by_cases hz : 0 < z, { exact h.is_primitive_classified_of_coprime_of_pos hc hz }, have h' : pythagorean_triple x y (-z), { simpa [pythagorean_triple, neg_mul_neg] using h.eq, }, apply h'.is_primitive_classified_of_coprime_of_pos hc, apply lt_of_le_of_ne _ (h'.ne_zero_of_coprime hc).symm, exact le_neg.mp (not_lt.mp hz) end theorem classified : h.is_classified := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, use [0, 1, 0], norm_num [hx, hy], }, apply h.is_classified_of_normalize_is_primitive_classified, apply h.normalize.is_primitive_classified_of_coprime, apply int.gcd_div_gcd_div_gcd (nat.pos_of_ne_zero h0), end omit h theorem coprime_classification : pythagorean_triple x y z ∧ int.gcd x y = 1 ↔ ∃ m n, ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ (z = m ^ 2 + n ^ 2 ∨ z = - (m ^ 2 + n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) := begin split, { intro h, obtain ⟨m, n, H⟩ := h.left.is_primitive_classified_of_coprime h.right, use [m, n], rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [pow_two, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [pow_two, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this } }, { delta pythagorean_triple, rintro ⟨m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl, co, pp⟩; { split, { ring }, exact coprime_pow_two_sub_mul co pp } <|> { split, { ring }, rw int.gcd_comm, exact coprime_pow_two_sub_mul co pp } } end /-- by assuming `x` is odd and `z` is positive we get a slightly more precise classification of the pythagorean triple `x ^ 2 + y ^ 2 = z ^ 2`-/ theorem coprime_classification' {x y z : ℤ} (h : pythagorean_triple x y z) (h_coprime : int.gcd x y = 1) (h_parity : x % 2 = 1) (h_pos : 0 < z) : ∃ m n, x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n ∧ z = m ^ 2 + n ^ 2 ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) ∧ 0 ≤ m := begin obtain ⟨m, n, ht1, ht2, ht3, ht4⟩ := pythagorean_triple.coprime_classification.mp (and.intro h h_coprime), cases le_or_lt 0 m with hm hm, { use [m, n], cases ht1 with h_odd h_even, { apply and.intro h_odd.1, apply and.intro h_odd.2, cases ht2 with h_pos h_neg, { apply and.intro h_pos (and.intro ht3 (and.intro ht4 hm)) }, { exfalso, revert h_pos, rw h_neg, exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (pow_two_nonneg m) (pow_two_nonneg n)))) } }, exfalso, rcases h_even with ⟨rfl, -⟩, rw [mul_assoc, int.mul_mod_right] at h_parity, exact zero_ne_one h_parity }, { use [-m, -n], cases ht1 with h_odd h_even, { rw [neg_square m], rw [neg_square n], apply and.intro h_odd.1, split, { rw h_odd.2, ring }, cases ht2 with h_pos h_neg, { apply and.intro h_pos, split, { delta int.gcd, rw [int.nat_abs_neg, int.nat_abs_neg], exact ht3 }, { rw [int.neg_mod_two, int.neg_mod_two], apply and.intro ht4, linarith } }, { exfalso, revert h_pos, rw h_neg, exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (pow_two_nonneg m) (pow_two_nonneg n)))) } }, exfalso, rcases h_even with ⟨rfl, -⟩, rw [mul_assoc, int.mul_mod_right] at h_parity, exact zero_ne_one h_parity } end theorem classification : pythagorean_triple x y z ↔ ∃ k m n, ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ (z = k * (m ^ 2 + n ^ 2) ∨ z = - k * (m ^ 2 + n ^ 2)) := begin split, { intro h, obtain ⟨k, m, n, H⟩ := h.classified, use [k, m, n], rcases H with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [pow_two, ← h.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [pow_two, ← h.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this } }, { rintro ⟨k, m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl⟩; delta pythagorean_triple; ring } end end pythagorean_triple
9c697e91eb9c5656a2d45e202b1c2a6bcc9efade
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/class_number/admissible_card_pow_degree.lean
dfb55c2f566e643ee6749e4c280e09b2f5d4294e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
13,942
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import number_theory.class_number.admissible_absolute_value import analysis.special_functions.pow.real import ring_theory.ideal.local_ring import data.polynomial.degree.card_pow_degree /-! # Admissible absolute values on polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines an admissible absolute value `polynomial.card_pow_degree_is_admissible` which we use to show the class number of the ring of integers of a function field is finite. ## Main results * `polynomial.card_pow_degree_is_admissible` shows `card_pow_degree`, mapping `p : polynomial 𝔽_q` to `q ^ degree p`, is admissible -/ namespace polynomial open_locale polynomial open absolute_value real variables {Fq : Type*} [fintype Fq] /-- If `A` is a family of enough low-degree polynomials over a finite semiring, there is a pair of equal elements in `A`. -/ lemma exists_eq_polynomial [semiring Fq] {d : ℕ} {m : ℕ} (hm : fintype.card Fq ^ d ≤ m) (b : Fq[X]) (hb : nat_degree b ≤ d) (A : fin m.succ → Fq[X]) (hA : ∀ i, degree (A i) < degree b) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ A i₁ = A i₀ := begin -- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients, -- there must be two elements of A with the same coefficients at -- `0`, ... `degree b - 1` ≤ `d - 1`. -- In other words, the following map is not injective: set f : fin m.succ → (fin d → Fq) := λ i j, (A i).coeff j, have : fintype.card (fin d → Fq) < fintype.card (fin m.succ), { simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) }, -- Therefore, the differences have all coefficients higher than `deg b - d` equal. obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this, use [i₀, i₁, i_ne], ext j, -- The coefficients higher than `deg b` are the same because they are equal to 0. by_cases hbj : degree b ≤ j, { rw [coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj), coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj)] }, -- So we only need to look for the coefficients between `0` and `deg b`. rw not_le at hbj, apply congr_fun i_eq.symm ⟨j, _⟩, exact lt_of_lt_of_le (coe_lt_degree.mp hbj) hb end /-- If `A` is a family of enough low-degree polynomials over a finite ring, there is a pair of elements in `A` (with different indices but not necessarily distinct), such that their difference has small degree. -/ lemma exists_approx_polynomial_aux [ring Fq] {d : ℕ} {m : ℕ} (hm : fintype.card Fq ^ d ≤ m) (b : Fq[X]) (A : fin m.succ → Fq[X]) (hA : ∀ i, degree (A i) < degree b) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ degree (A i₁ - A i₀) < ↑(nat_degree b - d) := begin have hb : b ≠ 0, { rintro rfl, specialize hA 0, rw degree_zero at hA, exact not_lt_of_le bot_le hA }, -- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients, -- there must be two elements of A with the same coefficients at -- `degree b - 1`, ... `degree b - d`. -- In other words, the following map is not injective: set f : fin m.succ → (fin d → Fq) := λ i j, (A i).coeff (nat_degree b - j.succ), have : fintype.card (fin d → Fq) < fintype.card (fin m.succ), { simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) }, -- Therefore, the differences have all coefficients higher than `deg b - d` equal. obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this, use [i₀, i₁, i_ne], refine (degree_lt_iff_coeff_zero _ _).mpr (λ j hj, _), -- The coefficients higher than `deg b` are the same because they are equal to 0. by_cases hbj : degree b ≤ j, { refine coeff_eq_zero_of_degree_lt (lt_of_lt_of_le _ hbj), exact lt_of_le_of_lt (degree_sub_le _ _) (max_lt (hA _) (hA _)) }, -- So we only need to look for the coefficients between `deg b - d` and `deg b`. rw [coeff_sub, sub_eq_zero], rw [not_le, degree_eq_nat_degree hb, with_bot.coe_lt_coe] at hbj, have hj : nat_degree b - j.succ < d, { by_cases hd : nat_degree b < d, { exact lt_of_le_of_lt tsub_le_self hd }, { rw not_lt at hd, have := lt_of_le_of_lt hj (nat.lt_succ_self j), rwa [tsub_lt_iff_tsub_lt hd hbj] at this } }, have : j = b.nat_degree - (nat_degree b - j.succ).succ, { rw [← nat.succ_sub hbj, nat.succ_sub_succ, tsub_tsub_cancel_of_le hbj.le] }, convert congr_fun i_eq.symm ⟨nat_degree b - j.succ, hj⟩ end variables [field Fq] /-- If `A` is a family of enough low-degree polynomials over a finite field, there is a pair of elements in `A` (with different indices but not necessarily distinct), such that the difference of their remainders is close together. -/ lemma exists_approx_polynomial {b : Fq[X]} (hb : b ≠ 0) {ε : ℝ} (hε : 0 < ε) (A : fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊).succ → Fq[X]) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin have hbε : 0 < card_pow_degree b • ε, { rw [algebra.smul_def, eq_int_cast], exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε }, have one_lt_q : 1 < fintype.card Fq := fintype.one_lt_card, have one_lt_q' : (1 : ℝ) < fintype.card Fq, { assumption_mod_cast }, have q_pos : 0 < fintype.card Fq, { linarith }, have q_pos' : (0 : ℝ) < fintype.card Fq, { assumption_mod_cast }, -- If `b` is already small enough, then the remainders are equal and we are done. by_cases le_b : b.nat_degree ≤ ⌈- log ε / log (fintype.card Fq)⌉₊, { obtain ⟨i₀, i₁, i_ne, mod_eq⟩ := exists_eq_polynomial le_rfl b le_b (λ i, A i % b) (λ i, euclidean_domain.mod_lt (A i) hb), refine ⟨i₀, i₁, i_ne, _⟩, simp only at mod_eq, rwa [mod_eq, sub_self, absolute_value.map_zero, int.cast_zero] }, -- Otherwise, it suffices to choose two elements whose difference is of small enough degree. rw not_le at le_b, obtain ⟨i₀, i₁, i_ne, deg_lt⟩ := exists_approx_polynomial_aux le_rfl b (λ i, A i % b) (λ i, euclidean_domain.mod_lt (A i) hb), simp only at deg_lt, use [i₀, i₁, i_ne], -- Again, if the remainders are equal we are done. by_cases h : A i₁ % b = A i₀ % b, { rwa [h, sub_self, absolute_value.map_zero, int.cast_zero] }, have h' : A i₁ % b - A i₀ % b ≠ 0 := mt sub_eq_zero.mp h, -- If the remainders are not equal, we'll show their difference is of small degree. -- In particular, we'll show the degree is less than the following: suffices : (nat_degree (A i₁ % b - A i₀ % b) : ℝ) < b.nat_degree + log ε / log (fintype.card Fq), { rwa [← real.log_lt_log_iff (int.cast_pos.mpr (card_pow_degree.pos h')) hbε, card_pow_degree_nonzero _ h', card_pow_degree_nonzero _ hb, algebra.smul_def, eq_int_cast, int.cast_pow, int.cast_coe_nat, int.cast_pow, int.cast_coe_nat, log_mul (pow_ne_zero _ q_pos'.ne') hε.ne', ← rpow_nat_cast, ← rpow_nat_cast, log_rpow q_pos', log_rpow q_pos', ← lt_div_iff (log_pos one_lt_q'), add_div, mul_div_cancel _ (log_pos one_lt_q').ne'] }, -- And that result follows from manipulating the result from `exists_approx_polynomial_aux` -- to turn the `-⌈-stuff⌉₊` into `+ stuff`. refine lt_of_lt_of_le (nat.cast_lt.mpr (with_bot.coe_lt_coe.mp _)) _, swap, { convert deg_lt, rw degree_eq_nat_degree h' }, rw [← sub_neg_eq_add, neg_div], refine le_trans _ (sub_le_sub_left (nat.le_ceil _) (b.nat_degree : ℝ)), rw ← neg_div, exact le_of_eq (nat.cast_sub le_b.le) end /-- If `x` is close to `y` and `y` is close to `z`, then `x` and `z` are at least as close. -/ lemma card_pow_degree_anti_archimedean {x y z : Fq[X]} {a : ℤ} (hxy : card_pow_degree (x - y) < a) (hyz : card_pow_degree (y - z) < a) : card_pow_degree (x - z) < a := begin have ha : 0 < a := lt_of_le_of_lt (absolute_value.nonneg _ _) hxy, by_cases hxy' : x = y, { rwa hxy' }, by_cases hyz' : y = z, { rwa ← hyz' }, by_cases hxz' : x = z, { rwa [hxz', sub_self, absolute_value.map_zero] }, rw [← ne.def, ← sub_ne_zero] at hxy' hyz' hxz', refine lt_of_le_of_lt _ (max_lt hxy hyz), rw [card_pow_degree_nonzero _ hxz', card_pow_degree_nonzero _ hxy', card_pow_degree_nonzero _ hyz'], have : (1 : ℤ) ≤ fintype.card Fq, { exact_mod_cast (@fintype.one_lt_card Fq _ _).le }, simp only [int.cast_pow, int.cast_coe_nat, le_max_iff], refine or.imp (pow_le_pow this) (pow_le_pow this) _, rw [nat_degree_le_iff_degree_le, nat_degree_le_iff_degree_le, ← le_max_iff, ← degree_eq_nat_degree hxy', ← degree_eq_nat_degree hyz'], convert degree_add_le (x - y) (y - z) using 2, exact (sub_add_sub_cancel _ _ _).symm end /-- A slightly stronger version of `exists_partition` on which we perform induction on `n`: for all `ε > 0`, we can partition the remainders of any family of polynomials `A` into equivalence classes, where the equivalence(!) relation is "closer than `ε`". -/ lemma exists_partition_polynomial_aux (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : Fq[X]} (hb : b ≠ 0) (A : fin n → Fq[X]) : ∃ (t : fin n → fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊)), ∀ (i₀ i₁ : fin n), t i₀ = t i₁ ↔ (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin have hbε : 0 < card_pow_degree b • ε, { rw [algebra.smul_def, eq_int_cast], exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε }, -- We go by induction on the size `A`. induction n with n ih, { refine ⟨fin_zero_elim, fin_zero_elim⟩ }, -- Show `anti_archimedean` also holds for real distances. have anti_archim' : ∀ {i j k} {ε : ℝ}, (card_pow_degree (A i % b - A j % b) : ℝ) < ε → (card_pow_degree (A j % b - A k % b) : ℝ) < ε → (card_pow_degree (A i % b - A k % b) : ℝ) < ε, { intros i j k ε, simp_rw [← int.lt_ceil], exact card_pow_degree_anti_archimedean }, obtain ⟨t', ht'⟩ := ih (fin.tail A), -- We got rid of `A 0`, so determine the index `j` of the partition we'll re-add it to. rsuffices ⟨j, hj⟩ : ∃ j, ∀ i, t' i = j ↔ (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { refine ⟨fin.cons j t', λ i₀ i₁, _⟩, refine fin.cases _ (λ i₀, _) i₀; refine fin.cases _ (λ i₁, _) i₁, { simpa using hbε }, { rw [fin.cons_succ, fin.cons_zero, eq_comm, absolute_value.map_sub], exact hj i₁ }, { rw [fin.cons_succ, fin.cons_zero], exact hj i₀ }, { rw [fin.cons_succ, fin.cons_succ], exact ht' i₀ i₁ } }, -- `exists_approx_polynomial` guarantees that we can insert `A 0` into some partition `j`, -- but not that `j` is uniquely defined (which is needed to keep the induction going). obtain ⟨j, hj⟩ : ∃ j, ∀ (i : fin n), t' i = j → (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { by_contra this, push_neg at this, obtain ⟨j₀, j₁, j_ne, approx⟩ := exists_approx_polynomial hb hε (fin.cons (A 0) (λ j, A (fin.succ (classical.some (this j))))), revert j_ne approx, refine fin.cases _ (λ j₀, _) j₀; refine fin.cases (λ j_ne approx, _) (λ j₁ j_ne approx, _) j₁, { exact absurd rfl j_ne }, { rw [fin.cons_succ, fin.cons_zero, ← not_le, absolute_value.map_sub] at approx, have := (classical.some_spec (this j₁)).2, contradiction }, { rw [fin.cons_succ, fin.cons_zero, ← not_le] at approx, have := (classical.some_spec (this j₀)).2, contradiction }, { rw [fin.cons_succ, fin.cons_succ] at approx, rw [ne.def, fin.succ_inj] at j_ne, have : j₀ = j₁ := (classical.some_spec (this j₀)).1.symm.trans (((ht' (classical.some (this j₀)) (classical.some (this j₁))).mpr approx).trans (classical.some_spec (this j₁)).1), contradiction } }, -- However, if one of those partitions `j` is inhabited by some `i`, then this `j` works. by_cases exists_nonempty_j : ∃ j, (∃ i, t' i = j) ∧ ∀ i, t' i = j → (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { obtain ⟨j, ⟨i, hi⟩, hj⟩ := exists_nonempty_j, refine ⟨j, λ i', ⟨hj i', λ hi', trans ((ht' _ _).mpr _) hi⟩⟩, apply anti_archim' _ hi', rw absolute_value.map_sub, exact hj _ hi }, -- And otherwise, we can just take any `j`, since those are empty. refine ⟨j, λ i, ⟨hj i, λ hi, _⟩⟩, have := exists_nonempty_j ⟨t' i, ⟨i, rfl⟩, λ i' hi', anti_archim' hi ((ht' _ _).mp hi')⟩, contradiction end /-- For all `ε > 0`, we can partition the remainders of any family of polynomials `A` into classes, where all remainders in a class are close together. -/ lemma exists_partition_polynomial (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : Fq[X]} (hb : b ≠ 0) (A : fin n → Fq[X]) : ∃ (t : fin n → fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊)), ∀ (i₀ i₁ : fin n), t i₀ = t i₁ → (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin obtain ⟨t, ht⟩ := exists_partition_polynomial_aux n hε hb A, exact ⟨t, λ i₀ i₁ hi, (ht i₀ i₁).mp hi⟩ end /-- `λ p, fintype.card Fq ^ degree p` is an admissible absolute value. We set `q ^ degree 0 = 0`. -/ noncomputable def card_pow_degree_is_admissible : is_admissible (card_pow_degree : absolute_value Fq[X] ℤ) := { card := λ ε, fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊, exists_partition' := λ n ε hε b hb, exists_partition_polynomial n hε hb, .. @card_pow_degree_is_euclidean Fq _ _ } end polynomial
60b4c327a6cce957d5a9f6bd4489a3a9ae217df3
618003631150032a5676f229d13a079ac875ff77
/src/algebra/group/units_hom.lean
50e48dbeddade8064a07d32310c1876269538330
[ "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,977
lean
/- Copyright (c) 2018 Johan Commelin All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes, Kevin Buzzard -/ import algebra.group.units import algebra.group.hom /-! # Lift monoid homomorphisms to group homomorphisms of their units subgroups. -/ universes u v w namespace units variables {M : Type u} {N : Type v} {P : Type w} [monoid M] [monoid N] [monoid P] /-- The group homomorphism on units induced by a `monoid_hom`. -/ @[to_additive "The `add_group` homomorphism on `add_unit`s induced by an `add_monoid_hom`."] def map (f : M →* N) : units M →* units N := monoid_hom.mk' (λ u, ⟨f u.val, f u.inv, by rw [← f.map_mul, u.val_inv, f.map_one], by rw [← f.map_mul, u.inv_val, f.map_one]⟩) (λ x y, ext (f.map_mul x y)) @[simp, to_additive] lemma coe_map (f : M →* N) (x : units M) : ↑(map f x) = f x := rfl @[simp, to_additive] lemma map_comp (f : M →* N) (g : N →* P) : map (g.comp f) = (map g).comp (map f) := rfl variables (M) @[simp, to_additive] lemma map_id : map (monoid_hom.id M) = monoid_hom.id (units M) := by ext; refl /-- Coercion `units M → M` as a monoid homomorphism. -/ @[to_additive "Coercion `add_units M → M` as an add_monoid homomorphism."] def coe_hom : units M →* M := ⟨coe, coe_one, coe_mul⟩ variable {M} @[simp, to_additive] lemma coe_hom_apply (x : units M) : coe_hom M x = ↑x := rfl /-- If a map `g : M → units N` agrees with a homomorphism `f : M →* N`, then this map is a monoid homomorphism too. -/ @[to_additive "If a map `g : M → add_units N` agrees with a homomorphism `f : M →+ N`, then this map is an add_monoid homomorphism too."] def lift_right (f : M →* N) (g : M → units N) (h : ∀ x, ↑(g x) = f x) : M →* units N := { to_fun := g, map_one' := units.ext $ (h 1).symm ▸ f.map_one, map_mul' := λ x y, units.ext $ by simp only [h, coe_mul, f.map_mul] } @[simp, to_additive] lemma coe_lift_right {f : M →* N} {g : M → units N} (h : ∀ x, ↑(g x) = f x) (x) : (lift_right f g h x : N) = f x := h x @[simp, to_additive] lemma mul_lift_right_inv {f : M →* N} {g : M → units N} (h : ∀ x, ↑(g x) = f x) (x) : f x * ↑(lift_right f g h x)⁻¹ = 1 := by rw [units.mul_inv_eq_iff_eq_mul, one_mul, coe_lift_right] @[simp, to_additive] lemma lift_right_inv_mul {f : M →* N} {g : M → units N} (h : ∀ x, ↑(g x) = f x) (x) : ↑(lift_right f g h x)⁻¹ * f x = 1 := by rw [units.inv_mul_eq_iff_eq_mul, mul_one, coe_lift_right] end units namespace monoid_hom /-- If `f` is a homomorphism from a group `G` to a monoid `M`, then its image lies in the units of `M`, and `f.to_hom_units` is the corresponding monoid homomorphism from `G` to `units M`. -/ @[to_additive "If `f` is a homomorphism from an additive group `G` to an additive monoid `M`, then its image lies in the `add_units` of `M`, and `f.to_hom_units` is the corresponding homomorphism from `G` to `add_units M`."] def to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) : G →* units M := { to_fun := λ g, ⟨f g, f (g⁻¹), by rw [← f.map_mul, mul_inv_self, f.map_one], by rw [← f.map_mul, inv_mul_self, f.map_one]⟩, map_one' := units.ext (f.map_one), map_mul' := λ _ _, units.ext (f.map_mul _ _) } @[simp] lemma coe_to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) (g : G): (f.to_hom_units g : M) = f g := rfl end monoid_hom section is_unit variables {M : Type*} {N : Type*} @[to_additive] lemma is_unit.map [monoid M] [monoid N] (f : M →* N) {x : M} (h : is_unit x) : is_unit (f x) := by rcases h with ⟨y, rfl⟩; exact is_unit_unit (units.map f y) /-- If a homomorphism `f : M →* N` sends each element to an `is_unit`, then it can be lifted to `f : M →* units N`. See also `units.lift_right` for a computable version. -/ @[to_additive "If a homomorphism `f : M →+ N` sends each element to an `is_add_unit`, then it can be lifted to `f : M →+ add_units N`. See also `add_units.lift_right` for a computable version."] noncomputable def is_unit.lift_right [monoid M] [monoid N] (f : M →* N) (hf : ∀ x, is_unit (f x)) : M →* units N := units.lift_right f (λ x, classical.some (hf x)) $ λ x, classical.some_spec (hf x) @[to_additive] lemma is_unit.coe_lift_right [monoid M] [monoid N] (f : M →* N) (hf : ∀ x, is_unit (f x)) (x) : (is_unit.lift_right f hf x : N) = f x := units.coe_lift_right _ x @[simp, to_additive] lemma is_unit.mul_lift_right_inv [monoid M] [monoid N] (f : M →* N) (h : ∀ x, is_unit (f x)) (x) : f x * ↑(is_unit.lift_right f h x)⁻¹ = 1 := units.mul_lift_right_inv (λ y, classical.some_spec $ h y) x @[simp, to_additive] lemma is_unit.lift_right_inv_mul [monoid M] [monoid N] (f : M →* N) (h : ∀ x, is_unit (f x)) (x) : ↑(is_unit.lift_right f h x)⁻¹ * f x = 1 := units.lift_right_inv_mul (λ y, classical.some_spec $ h y) x end is_unit
4293154d380f173fd988ae03ebdac99b3bac3413
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/homotopy/sphere.hlean
9f44cf7b32d7ccbb70e435710114c9ebd3a48140
[ "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
10,246
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of the n-spheres -/ import .susp types.trunc open eq nat susp bool is_trunc unit pointed algebra /- We can define spheres with the following possible indices: - trunc_index (defining S^-2 = S^-1 = empty) - nat (forgetting that S^-1 = empty) - nat, but counting wrong (S^0 = empty, S^1 = bool, ...) - some new type "integers >= -1" We choose the last option here. -/ /- Sphere levels -/ inductive sphere_index : Type₀ := | minus_one : sphere_index | succ : sphere_index → sphere_index notation `ℕ₋₁` := sphere_index namespace trunc_index definition sub_one [reducible] (n : ℕ₋₁) : ℕ₋₂ := sphere_index.rec_on n -2 (λ n k, k.+1) postfix `..-1`:(max+1) := sub_one definition of_sphere_index [reducible] (n : ℕ₋₁) : ℕ₋₂ := n..-1.+1 -- we use a double dot to distinguish with the notation .-1 in trunc_index (of type ℕ → ℕ₋₂) end trunc_index namespace sphere_index /- notation for sphere_index is -1, 0, 1, ... from 0 and up this comes from a coercion from num to sphere_index (via nat) -/ postfix `.+1`:(max+1) := sphere_index.succ postfix `.+2`:(max+1) := λ(n : sphere_index), (n .+1 .+1) notation `-1` := minus_one definition has_zero_sphere_index [instance] : has_zero ℕ₋₁ := has_zero.mk (succ minus_one) definition has_one_sphere_index [instance] : has_one ℕ₋₁ := has_one.mk (succ (succ minus_one)) definition add_plus_one (n m : ℕ₋₁) : ℕ₋₁ := sphere_index.rec_on m n (λ k l, l .+1) -- addition of sphere_indices, where (-1 + -1) is defined to be -1. protected definition add (n m : ℕ₋₁) : ℕ₋₁ := sphere_index.cases_on m (sphere_index.cases_on n -1 id) (sphere_index.rec n (λn' r, succ r)) inductive le (a : ℕ₋₁) : ℕ₋₁ → Type := | sp_refl : le a a | step : Π {b}, le a b → le a (b.+1) infix `+1+`:65 := sphere_index.add_plus_one definition has_add_sphere_index [instance] [priority 2000] [reducible] : has_add ℕ₋₁ := has_add.mk sphere_index.add definition has_le_sphere_index [instance] : has_le ℕ₋₁ := has_le.mk sphere_index.le definition of_nat [coercion] [reducible] (n : nat) : ℕ₋₁ := (nat.rec_on n -1 (λ n k, k.+1)).+1 definition sub_one [reducible] (n : ℕ) : ℕ₋₁ := nat.rec_on n -1 (λ n k, k.+1) postfix `..-1`:(max+1) := sub_one -- we use a double dot to distinguish with the notation .-1 in trunc_index (of type ℕ → ℕ₋₂) definition succ_sub_one (n : ℕ) : (nat.succ n)..-1 = n :> ℕ₋₁ := idp definition succ_le_succ {n m : ℕ₋₁} (H : n ≤ m) : n.+1 ≤[ℕ₋₁] m.+1 := by induction H with m H IH; apply le.sp_refl; exact le.step IH definition minus_one_le (n : ℕ₋₁) : -1 ≤[ℕ₋₁] n := by induction n with n IH; apply le.sp_refl; exact le.step IH open decidable protected definition has_decidable_eq [instance] : Π(n m : ℕ₋₁), decidable (n = m) | has_decidable_eq -1 -1 := inl rfl | has_decidable_eq (n.+1) -1 := inr (by contradiction) | has_decidable_eq -1 (m.+1) := inr (by contradiction) | has_decidable_eq (n.+1) (m.+1) := match has_decidable_eq n m with | inl xeqy := inl (by rewrite xeqy) | inr xney := inr (λ h : succ n = succ m, by injection h with xeqy; exact absurd xeqy xney) end definition not_succ_le_minus_two {n : sphere_index} (H : n .+1 ≤[ℕ₋₁] -1) : empty := by cases H protected definition le_trans {n m k : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m) (H2 : m ≤[ℕ₋₁] k) : n ≤[ℕ₋₁] k := begin induction H2 with k H2 IH, { exact H1}, { exact le.step IH} end definition le_of_succ_le_succ {n m : ℕ₋₁} (H : n.+1 ≤[ℕ₋₁] m.+1) : n ≤[ℕ₋₁] m := begin cases H with m H', { apply le.sp_refl}, { exact sphere_index.le_trans (le.step !le.sp_refl) H'} end theorem not_succ_le_self {n : ℕ₋₁} : ¬n.+1 ≤[ℕ₋₁] n := begin induction n with n IH: intro H, { exact not_succ_le_minus_two H}, { exact IH (le_of_succ_le_succ H)} end protected definition le_antisymm {n m : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m) (H2 : m ≤[ℕ₋₁] n) : n = m := begin induction H2 with n H2 IH, { reflexivity}, { exfalso, apply @not_succ_le_self n, exact sphere_index.le_trans H1 H2} end protected definition le_succ {n m : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m): n ≤[ℕ₋₁] m.+1 := le.step H1 /- warning: if this coercion is available, the coercion ℕ → ℕ₋₂ is the composition of the coercions ℕ → ℕ₋₁ → ℕ₋₂. We don't want this composition as coercion, because it has worse computational properties. You can rewrite it with trans_to_of_sphere_index_eq defined below. -/ attribute trunc_index.of_sphere_index [coercion] end sphere_index open sphere_index definition weak_order_sphere_index [trans_instance] [reducible] : weak_order sphere_index := weak_order.mk le sphere_index.le.sp_refl @sphere_index.le_trans @sphere_index.le_antisymm namespace trunc_index definition sub_two_eq_sub_one_sub_one (n : ℕ) : n.-2 = n..-1..-1 := nat.rec_on n idp (λn p, ap trunc_index.succ p) definition succ_sub_one (n : ℕ₋₁) : n.+1..-1 = n :> ℕ₋₂ := idp definition of_sphere_index_of_nat (n : ℕ) : of_sphere_index (sphere_index.of_nat n) = of_nat n :> ℕ₋₂ := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition trans_to_of_sphere_index_eq (n : ℕ) : trunc_index._trans_to_of_sphere_index n = of_nat n :> ℕ₋₂ := of_sphere_index_of_nat n end trunc_index open sphere_index equiv definition sphere : ℕ₋₁ → Type₀ | -1 := empty | n.+1 := susp (sphere n) namespace sphere export [notation] [coercion] sphere_index definition base {n : ℕ} : sphere n := north definition pointed_sphere [instance] [constructor] (n : ℕ) : pointed (sphere n) := pointed.mk base definition psphere [constructor] (n : ℕ) : Type* := pointed.mk' (sphere n) namespace ops abbreviation S := sphere notation `S.` := psphere end ops open sphere.ops definition sphere_minus_one : S -1 = empty := idp definition sphere_succ (n : ℕ₋₁) : S n.+1 = susp (S n) := idp definition equator (n : ℕ) : map₊ (S. n) (Ω (S. (succ n))) := pmap.mk (λa, merid a ⬝ (merid base)⁻¹) !con.right_inv definition surf {n : ℕ} : Ω[n] S. n := nat.rec_on n (proof base qed) (begin intro m s, refine cast _ (apn m (equator m) s), exact ap carrier !loop_space_succ_eq_in⁻¹ end) definition bool_of_sphere : S 0 → bool := proof susp.rec ff tt (λx, empty.elim x) qed definition sphere_of_bool : bool → S 0 | ff := proof north qed | tt := proof south qed definition sphere_equiv_bool : S 0 ≃ bool := equiv.MK bool_of_sphere sphere_of_bool (λb, match b with | tt := idp | ff := idp end) (λx, proof susp.rec_on x idp idp (empty.rec _) qed) definition sphere_eq_bool : S 0 = bool := ua sphere_equiv_bool definition sphere_eq_pbool : S. 0 = pbool := pType_eq sphere_equiv_bool idp -- TODO1: the commented-out part makes the forward function below "apn _ surf" -- TODO2: we could make this a pointed equivalence definition pmap_sphere (A : Type*) (n : ℕ) : map₊ (S. n) A ≃ Ω[n] A := begin -- fapply equiv_change_fun, -- { revert A, induction n with n IH: intro A, { apply tr_rev (λx, x →* _ ≃ _) sphere_eq_pbool, apply pmap_bool_equiv}, { refine susp_adjoint_loop (S. n) A ⬝e !IH ⬝e _, rewrite [loop_space_succ_eq_in]} -- }, -- { intro f, exact apn n f surf}, -- { revert A, induction n with n IH: intro A f, -- { exact sorry}, -- { exact sorry}} end protected definition elim {n : ℕ} {P : Type*} (p : Ω[n] P) : map₊ (S. n) P := to_inv !pmap_sphere p -- definition elim_surf {n : ℕ} {P : Type*} (p : Ω[n] P) : apn n (sphere.elim p) surf = p := -- begin -- induction n with n IH, -- { esimp [apn,surf,sphere.elim,pmap_sphere], apply sorry}, -- { apply sorry} -- end end sphere open sphere sphere.ops namespace is_trunc open trunc_index variables {n : ℕ} {A : Type} definition is_trunc_of_pmap_sphere_constant (H : Π(a : A) (f : map₊ (S. n) (pointed.Mk a)) (x : S n), f x = f base) : is_trunc (n.-2.+1) A := begin apply iff.elim_right !is_trunc_iff_is_contr_loop, intro a, apply is_trunc_equiv_closed, apply pmap_sphere, fapply is_contr.mk, { exact pmap.mk (λx, a) idp}, { intro f, fapply pmap_eq, { intro x, esimp, refine !respect_pt⁻¹ ⬝ (!H ⬝ !H⁻¹)}, { rewrite [▸*,con.right_inv,▸*,con.left_inv]}} end definition is_trunc_iff_map_sphere_constant (H : Π(f : S n → A) (x : S n), f x = f base) : is_trunc (n.-2.+1) A := begin apply is_trunc_of_pmap_sphere_constant, intros, cases f with f p, esimp at *, apply H end definition pmap_sphere_constant_of_is_trunc' [H : is_trunc (n.-2.+1) A] (a : A) (f : map₊ (S. n) (pointed.Mk a)) (x : S n) : f x = f base := begin let H' := iff.elim_left (is_trunc_iff_is_contr_loop n A) H a, note H'' := @is_trunc_equiv_closed_rev _ _ _ !pmap_sphere H', have p : (f = pmap.mk (λx, f base) (respect_pt f)), by apply is_prop.elim, exact ap10 (ap pmap.to_fun p) x end definition pmap_sphere_constant_of_is_trunc [H : is_trunc (n.-2.+1) A] (a : A) (f : map₊ (S. n) (pointed.Mk a)) (x y : S n) : f x = f y := let H := pmap_sphere_constant_of_is_trunc' a f in !H ⬝ !H⁻¹ definition map_sphere_constant_of_is_trunc [H : is_trunc (n.-2.+1) A] (f : S n → A) (x y : S n) : f x = f y := pmap_sphere_constant_of_is_trunc (f base) (pmap.mk f idp) x y definition map_sphere_constant_of_is_trunc_self [H : is_trunc (n.-2.+1) A] (f : S n → A) (x : S n) : map_sphere_constant_of_is_trunc f x x = idp := !con.right_inv end is_trunc
0e744aed17e8a16c147ae80cb2c141f905447ed9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/connected.lean
14e3ea02576ae2c74be27301e239663b19586e10
[ "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
46,071
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, Yury Kudryashov -/ import topology.subset_properties /-! # Connected subsets of topological spaces In this file we define connected subsets of a topological spaces and various other properties and classes related to connectivity. ## Main definitions We define the following properties for sets in a topological space: * `is_connected`: a nonempty set that has no non-trivial open partition. See also the section below in the module doc. * `connected_component` is the connected component of an element in the space. * `is_totally_disconnected`: all of its connected components are singletons. * `is_totally_separated`: any two points can be separated by two disjoint opens that cover the set. For each of these definitions, we also have a class stating that the whole space satisfies that property: `connected_space`, `totally_disconnected_space`, `totally_separated_space`. ## On the definition of connected sets/spaces In informal mathematics, connected spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preconnected`. In other words, the only difference is whether the empty space counts as connected. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set function topological_space open_locale classical topological_space universes u v variables {α : Type u} {β : Type v} [topological_space α] {s t : set α} section preconnected /-- A preconnected set is one where there is no non-trivial open partition. -/ def is_preconnected (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/ def is_connected (s : set α) : Prop := s.nonempty ∧ is_preconnected s lemma is_connected.nonempty {s : set α} (h : is_connected s) : s.nonempty := h.1 lemma is_connected.is_preconnected {s : set α} (h : is_connected s) : is_preconnected s := h.2 theorem is_preirreducible.is_preconnected {s : set α} (H : is_preirreducible s) : is_preconnected s := λ _ _ hu hv _, H _ _ hu hv theorem is_irreducible.is_connected {s : set α} (H : is_irreducible s) : is_connected s := ⟨H.nonempty, H.is_preirreducible.is_preconnected⟩ theorem is_preconnected_empty : is_preconnected (∅ : set α) := is_preirreducible_empty.is_preconnected theorem is_connected_singleton {x} : is_connected ({x} : set α) := is_irreducible_singleton.is_connected theorem is_preconnected_singleton {x} : is_preconnected ({x} : set α) := is_connected_singleton.is_preconnected theorem set.subsingleton.is_preconnected {s : set α} (hs : s.subsingleton) : is_preconnected s := hs.induction_on is_preconnected_empty (λ x, is_preconnected_singleton) /-- If any point of a set is joined to a fixed point by a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall {s : set α} (x : α) (H : ∀ y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩, have xs : x ∈ s, by { rcases H y ys with ⟨t, ts, xt, yt, ht⟩, exact ts xt }, wlog xu : x ∈ u := hs xs using [u v y z, v u z y], rcases H y ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- If any two points of a set are contained in a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall_pair {s : set α} (H : ∀ x y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rcases eq_empty_or_nonempty s with (rfl|⟨x, hx⟩), exacts [is_preconnected_empty, is_preconnected_of_forall x (λ y, H x y hx)], end /-- A union of a family of preconnected sets with a common point is preconnected as well. -/ theorem is_preconnected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s) (H2 : ∀ s ∈ c, is_preconnected s) : is_preconnected (⋃₀ c) := begin apply is_preconnected_of_forall x, rintros y ⟨s, sc, ys⟩, exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩ end theorem is_preconnected_Union {ι : Sort*} {s : ι → set α} (h₁ : (⋂ i, s i).nonempty) (h₂ : ∀ i, is_preconnected (s i)) : is_preconnected (⋃ i, s i) := exists.elim h₁ $ λ f hf, is_preconnected_sUnion f _ hf (forall_range_iff.2 h₂) theorem is_preconnected.union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t) (H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) := sUnion_pair s t ▸ is_preconnected_sUnion x {s, t} (by rintro r (rfl | rfl | h); assumption) (by rintro r (rfl | rfl | h); assumption) theorem is_connected.union {s t : set α} (H : (s ∩ t).nonempty) (Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) := begin rcases H with ⟨x, hx⟩, refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, _⟩, exact is_preconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx) Hs.is_preconnected Ht.is_preconnected end /-- Theorem of bark and tree : if a set is within a (pre)connected set and its closure, then it is (pre)connected as well. -/ theorem is_preconnected.subset_closure {s : set α} {t : set α} (H : is_preconnected s) (Kst : s ⊆ t) (Ktcs : t ⊆ closure s) : is_preconnected t := λ u v hu hv htuv ⟨y, hyt, hyu⟩ ⟨z, hzt, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 (Ktcs hyt) u hu hyu, ⟨q, hqv, hqs⟩ := mem_closure_iff.1 (Ktcs hzt) v hv hzv, ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans Kst htuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, Kst hrs, hruv⟩ theorem is_connected.subset_closure {s : set α} {t : set α} (H : is_connected s) (Kst : s ⊆ t) (Ktcs : t ⊆ closure s): is_connected t := let hsne := H.left, ht := Kst, htne := nonempty.mono ht hsne in ⟨nonempty.mono Kst H.left, is_preconnected.subset_closure H.right Kst Ktcs ⟩ /-- The closure of a (pre)connected set is (pre)connected as well. -/ theorem is_preconnected.closure {s : set α} (H : is_preconnected s) : is_preconnected (closure s) := is_preconnected.subset_closure H subset_closure $ subset.refl $ closure s theorem is_connected.closure {s : set α} (H : is_connected s) : is_connected (closure s) := is_connected.subset_closure H subset_closure $ subset.refl $ closure s /-- The image of a (pre)connected set is (pre)connected as well. -/ theorem is_preconnected.image [topological_space β] {s : set α} (H : is_preconnected s) (f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) := begin -- Unfold/destruct definitions in hypotheses rintros u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, -- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'` replace huv : s ⊆ u' ∪ v', { rw [image_subset_iff, preimage_union] at huv, replace huv := subset_inter huv (subset.refl _), rw [inter_distrib_right, u'_eq, v'_eq, ← inter_distrib_right] at huv, exact (subset_inter_iff.1 huv).1 }, -- Now `s ⊆ u' ∪ v'`, so we can apply `‹is_preconnected s›` obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).nonempty, { refine H u' v' hu' hv' huv ⟨x, _⟩ ⟨y, _⟩; rw inter_comm, exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] }, rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc, inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz, exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩ end theorem is_connected.image [topological_space β] {s : set α} (H : is_connected s) (f : α → β) (hf : continuous_on f s) : is_connected (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preconnected.image f hf⟩ theorem is_preconnected_closed_iff {s : set α} : is_preconnected s ↔ ∀ t t', is_closed t → is_closed t' → s ⊆ t ∪ t' → (s ∩ t).nonempty → (s ∩ t').nonempty → (s ∩ (t ∩ t')).nonempty := ⟨begin rintros h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xt' : x ∉ t', from (h' xs).elim (absurd xt) id, have yt : y ∉ t, from (h' ys).elim id (absurd yt'), have := ne_empty_iff_nonempty.2 (h tᶜ t'ᶜ (is_open_compl_iff.2 ht) (is_open_compl_iff.2 ht') h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end, begin rintros h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xv : x ∉ v, from (h' xs).elim (absurd xu) id, have yu : y ∉ u, from (h' ys).elim id (absurd yv), have := ne_empty_iff_nonempty.2 (h uᶜ vᶜ (is_closed_compl_iff.2 hu) (is_closed_compl_iff.2 hv) h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end⟩ theorem is_preconnected.prod [topological_space β] {s : set α} {t : set β} (hs : is_preconnected s) (ht : is_preconnected t) : is_preconnected (s.prod t) := begin apply is_preconnected_of_forall_pair, rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ⟨ha₁, hb₁⟩ ⟨ha₂, hb₂⟩, refine ⟨prod.mk a₁ '' t ∪ flip prod.mk b₂ '' s, _, or.inl ⟨b₁, hb₁, rfl⟩, or.inr ⟨a₂, ha₂, rfl⟩, _⟩, { rintro _ (⟨y, hy, rfl⟩|⟨x, hx, rfl⟩), exacts [⟨ha₁, hy⟩, ⟨hx, hb₂⟩] }, { exact (ht.image _ (continuous.prod.mk _).continuous_on).union (a₁, b₂) ⟨b₂, hb₂, rfl⟩ ⟨a₁, ha₁, rfl⟩ (hs.image _ (continuous_id.prod_mk continuous_const).continuous_on) } end theorem is_connected.prod [topological_space β] {s : set α} {t : set β} (hs : is_connected s) (ht : is_connected t) : is_connected (s.prod t) := ⟨hs.1.prod ht.1, hs.2.prod ht.2⟩ theorem is_preconnected_univ_pi {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] {s : Π i, set (π i)} (hs : ∀ i, is_preconnected (s i)) : is_preconnected (pi univ s) := begin rintros u v uo vo hsuv ⟨f, hfs, hfu⟩ ⟨g, hgs, hgv⟩, rcases exists_finset_piecewise_mem_of_mem_nhds (uo.mem_nhds hfu) g with ⟨I, hI⟩, induction I using finset.induction_on with i I hi ihI, { refine ⟨g, hgs, ⟨_, hgv⟩⟩, simpa using hI }, { rw [finset.piecewise_insert] at hI, have := I.piecewise_mem_set_pi hfs hgs, refine (hsuv this).elim ihI (λ h, _), set S := update (I.piecewise f g) i '' (s i), have hsub : S ⊆ pi univ s, { refine image_subset_iff.2 (λ z hz, _), rwa update_preimage_univ_pi, exact λ j hj, this j trivial }, have hconn : is_preconnected S, from (hs i).image _ (continuous_const.update i continuous_id).continuous_on, have hSu : (S ∩ u).nonempty, from ⟨_, mem_image_of_mem _ (hfs _ trivial), hI⟩, have hSv : (S ∩ v).nonempty, from ⟨_, ⟨_, this _ trivial, update_eq_self _ _⟩, h⟩, refine (hconn u v uo vo (hsub.trans hsuv) hSu hSv).mono _, exact inter_subset_inter_left _ hsub } end @[simp] theorem is_connected_univ_pi {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] {s : Π i, set (π i)} : is_connected (pi univ s) ↔ ∀ i, is_connected (s i) := begin simp only [is_connected, ← univ_pi_nonempty_iff, forall_and_distrib, and.congr_right_iff], refine λ hne, ⟨λ hc i, _, is_preconnected_univ_pi⟩, rw [← eval_image_univ_pi hne], exact hc.image _ (continuous_apply _).continuous_on end /-- The connected component of a point is the maximal connected set that contains this point. -/ def connected_component (x : α) : set α := ⋃₀ { s : set α | is_preconnected s ∧ x ∈ s } /-- The connected component of a point inside a set. -/ def connected_component_in (F : set α) (x : F) : set α := coe '' (connected_component x) theorem mem_connected_component {x : α} : x ∈ connected_component x := mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton.is_preconnected, mem_singleton x⟩ theorem is_preconnected_connected_component {x : α} : is_preconnected (connected_component x) := is_preconnected_sUnion x _ (λ _, and.right) (λ _, and.left) theorem is_connected_connected_component {x : α} : is_connected (connected_component x) := ⟨⟨x, mem_connected_component⟩, is_preconnected_connected_component⟩ theorem is_preconnected.subset_connected_component {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) : s ⊆ connected_component x := λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩ theorem is_connected.subset_connected_component {x : α} {s : set α} (H1 : is_connected s) (H2 : x ∈ s) : s ⊆ connected_component x := H1.2.subset_connected_component H2 theorem connected_component_eq {x y : α} (h : y ∈ connected_component x) : connected_component x = connected_component y := eq_of_subset_of_subset (is_connected_connected_component.subset_connected_component h) (is_connected_connected_component.subset_connected_component (set.mem_of_mem_of_subset mem_connected_component (is_connected_connected_component.subset_connected_component h))) lemma connected_component_disjoint {x y : α} (h : connected_component x ≠ connected_component y) : disjoint (connected_component x) (connected_component y) := set.disjoint_left.2 (λ a h1 h2, h ((connected_component_eq h1).trans (connected_component_eq h2).symm)) theorem is_closed_connected_component {x : α} : is_closed (connected_component x) := closure_eq_iff_is_closed.1 $ subset.antisymm (is_connected_connected_component.closure.subset_connected_component (subset_closure mem_connected_component)) subset_closure lemma continuous.image_connected_component_subset {β : Type*} [topological_space β] {f : α → β} (h : continuous f) (a : α) : f '' connected_component a ⊆ connected_component (f a) := (is_connected_connected_component.image f h.continuous_on).subset_connected_component ((mem_image f (connected_component a) (f a)).2 ⟨a, mem_connected_component, rfl⟩) theorem irreducible_component_subset_connected_component {x : α} : irreducible_component x ⊆ connected_component x := is_irreducible_irreducible_component.is_connected.subset_connected_component mem_irreducible_component /-- A preconnected space is one where there is no non-trivial open partition. -/ class preconnected_space (α : Type u) [topological_space α] : Prop := (is_preconnected_univ : is_preconnected (univ : set α)) export preconnected_space (is_preconnected_univ) /-- A connected space is a nonempty one where there is no non-trivial open partition. -/ class connected_space (α : Type u) [topological_space α] extends preconnected_space α : Prop := (to_nonempty : nonempty α) attribute [instance, priority 50] connected_space.to_nonempty -- see Note [lower instance priority] lemma is_preconnected_range [topological_space β] [preconnected_space α] {f : α → β} (h : continuous f) : is_preconnected (range f) := @image_univ _ _ f ▸ is_preconnected_univ.image _ h.continuous_on lemma is_connected_range [topological_space β] [connected_space α] {f : α → β} (h : continuous f) : is_connected (range f) := ⟨range_nonempty f, is_preconnected_range h⟩ lemma dense_range.preconnected_space [topological_space β] [preconnected_space α] {f : α → β} (hf : dense_range f) (hc : continuous f) : preconnected_space β := ⟨hf.closure_eq ▸ (is_preconnected_range hc).closure⟩ lemma connected_space_iff_connected_component : connected_space α ↔ ∃ x : α, connected_component x = univ := begin split, { rintros ⟨h, ⟨x⟩⟩, exactI ⟨x, eq_univ_of_univ_subset $ is_preconnected_univ.subset_connected_component (mem_univ x)⟩ }, { rintros ⟨x, h⟩, haveI : preconnected_space α := ⟨by { rw ← h, exact is_preconnected_connected_component }⟩, exact ⟨⟨x⟩⟩ } end instance [topological_space β] [preconnected_space α] [preconnected_space β] : preconnected_space (α × β) := ⟨by { rw ← univ_prod_univ, exact is_preconnected_univ.prod is_preconnected_univ }⟩ instance [topological_space β] [connected_space α] [connected_space β] : connected_space (α × β) := ⟨prod.nonempty⟩ instance {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)] [∀ i, preconnected_space (π i)] : preconnected_space (Π i, π i) := ⟨by { rw ← pi_univ univ, exact is_preconnected_univ_pi (λ i, is_preconnected_univ) }⟩ instance {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)] [∀ i, connected_space (π i)] : connected_space (Π i, π i) := ⟨classical.nonempty_pi.2 $ λ i, by apply_instance⟩ @[priority 100] -- see Note [lower instance priority] instance preirreducible_space.preconnected_space (α : Type u) [topological_space α] [preirreducible_space α] : preconnected_space α := ⟨(preirreducible_space.is_preirreducible_univ α).is_preconnected⟩ @[priority 100] -- see Note [lower instance priority] instance irreducible_space.connected_space (α : Type u) [topological_space α] [irreducible_space α] : connected_space α := { to_nonempty := irreducible_space.to_nonempty α } theorem nonempty_inter [preconnected_space α] {s t : set α} : is_open s → is_open t → s ∪ t = univ → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preconnected_space.is_preconnected_univ α _ _ s t theorem is_clopen_iff [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ := ⟨λ hs, classical.by_contradiction $ λ h, have h1 : s ≠ ∅ ∧ sᶜ ≠ ∅, from ⟨mt or.inl h, mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩, let ⟨_, h2, h3⟩ := nonempty_inter hs.1 hs.2.is_open_compl (union_compl_self s) (ne_empty_iff_nonempty.1 h1.1) (ne_empty_iff_nonempty.1 h1.2) in h3 h2, by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩ lemma eq_univ_of_nonempty_clopen [preconnected_space α] {s : set α} (h : s.nonempty) (h' : is_clopen s) : s = univ := by { rw is_clopen_iff at h', finish [h.ne_empty] } lemma subtype.preconnected_space {s : set α} (h : is_preconnected s) : preconnected_space s := { is_preconnected_univ := begin intros u v hu hv hs hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv _ ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩, intros z hz, rcases hs (mem_univ ⟨z, hz⟩) with hzu|hzv, { left, assumption }, { right, assumption } end } lemma subtype.connected_space {s : set α} (h : is_connected s) : connected_space s := { is_preconnected_univ := (subtype.preconnected_space h.is_preconnected).is_preconnected_univ, to_nonempty := h.nonempty.to_subtype } lemma is_preconnected_iff_preconnected_space {s : set α} : is_preconnected s ↔ preconnected_space s := ⟨subtype.preconnected_space, begin introI, simpa using is_preconnected_univ.image (coe : s → α) continuous_subtype_coe.continuous_on end⟩ lemma is_connected_iff_connected_space {s : set α} : is_connected s ↔ connected_space s := ⟨subtype.connected_space, λ h, ⟨nonempty_subtype.mp h.2, is_preconnected_iff_preconnected_space.mpr h.1⟩⟩ /-- A set `s` is preconnected if and only if for every cover by two open sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ lemma is_preconnected_iff_subset_of_disjoint {s : set α} : is_preconnected s ↔ ∀ (u v : set α) (hu : is_open u) (hv : is_open v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅), s ⊆ u ∨ s ⊆ v := begin split; intro h, { intros u v hu hv hs huv, specialize h u v hu hv hs, contrapose! huv, rw ne_empty_iff_nonempty, simp [not_subset] at huv, rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩, have hxv : x ∈ v := or_iff_not_imp_left.mp (hs hxs) hxu, have hyu : y ∈ u := or_iff_not_imp_right.mp (hs hys) hyv, exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ }, { intros u v hu hv hs hsu hsv, rw ← ne_empty_iff_nonempty, intro H, specialize h u v hu hv hs H, contrapose H, apply ne_empty_iff_nonempty.mpr, cases h, { rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ }, { rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } } end /-- A set `s` is connected if and only if for every cover by a finite collection of open sets that are pairwise disjoint on `s`, it is contained in one of the members of the collection. -/ lemma is_connected_iff_sUnion_disjoint_open {s : set α} : is_connected s ↔ ∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → (s ∩ (u ∩ v)).nonempty → u = v) (hU : ∀ u ∈ U, is_open u) (hs : s ⊆ ⋃₀ ↑U), ∃ u ∈ U, s ⊆ u := begin rw [is_connected, is_preconnected_iff_subset_of_disjoint], split; intro h, { intro U, apply finset.induction_on U, { rcases h.left, suffices : s ⊆ ∅ → false, { simpa }, intro, solve_by_elim }, { intros u U hu IH hs hU H, rw [finset.coe_insert, sUnion_insert] at H, cases h.2 u (⋃₀ ↑U) _ _ H _ with hsu hsU, { exact ⟨u, finset.mem_insert_self _ _, hsu⟩ }, { rcases IH _ _ hsU with ⟨v, hvU, hsv⟩, { exact ⟨v, finset.mem_insert_of_mem hvU, hsv⟩ }, { intros, apply hs; solve_by_elim [finset.mem_insert_of_mem] }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sUnion, intros, solve_by_elim [finset.mem_insert_of_mem] }, { apply eq_empty_of_subset_empty, rintro x ⟨hxs, hxu, hxU⟩, rw mem_sUnion at hxU, rcases hxU with ⟨v, hvU, hxv⟩, rcases hs u v (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hvU) _ with rfl, { contradiction }, { exact ⟨x, hxs, hxu, hxv⟩ } } } }, { split, { rw ← ne_empty_iff_nonempty, by_contradiction hs, subst hs, simpa using h ∅ _ _ _; simp }, intros u v hu hv hs hsuv, rcases h {u, v} _ _ _ with ⟨t, ht, ht'⟩, { rw [finset.mem_insert, finset.mem_singleton] at ht, rcases ht with rfl|rfl; tauto }, { intros t₁ t₂ ht₁ ht₂ hst, rw ← ne_empty_iff_nonempty at hst, rw [finset.mem_insert, finset.mem_singleton] at ht₁ ht₂, rcases ht₁ with rfl|rfl; rcases ht₂ with rfl|rfl, all_goals { refl <|> contradiction <|> skip }, rw inter_comm t₁ at hst, contradiction }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using hs } } end /-- Preconnected sets are either contained in or disjoint to any given clopen set. -/ theorem subset_or_disjoint_of_clopen {α : Type*} [topological_space α] {s t : set α} (h : is_preconnected t) (h1 : is_clopen s) : s ∩ t = ∅ ∨ t ⊆ s := begin by_contradiction h2, have h3 : (s ∩ t).nonempty := ne_empty_iff_nonempty.mp (mt or.inl h2), have h4 : (t ∩ sᶜ).nonempty, { apply inter_compl_nonempty_iff.2, push_neg at h2, exact h2.2 }, rw [inter_comm] at h3, apply ne_empty_iff_nonempty.2 (h s sᶜ h1.1 (is_open_compl_iff.2 h1.2) _ h3 h4), { rw [inter_compl_self, inter_empty] }, { rw [union_compl_self], exact subset_univ t }, end /-- A set `s` is preconnected if and only if for every cover by two closed sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ theorem is_preconnected_iff_subset_of_disjoint_closed {α : Type*} {s : set α} [topological_space α] : is_preconnected s ↔ ∀ (u v : set α) (hu : is_closed u) (hv : is_closed v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅), s ⊆ u ∨ s ⊆ v := begin split; intro h, { intros u v hu hv hs huv, rw is_preconnected_closed_iff at h, specialize h u v hu hv hs, contrapose! huv, rw ne_empty_iff_nonempty, simp [not_subset] at huv, rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩, have hxv : x ∈ v := or_iff_not_imp_left.mp (hs hxs) hxu, have hyu : y ∈ u := or_iff_not_imp_right.mp (hs hys) hyv, exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ }, { rw is_preconnected_closed_iff, intros u v hu hv hs hsu hsv, rw ← ne_empty_iff_nonempty, intro H, specialize h u v hu hv hs H, contrapose H, apply ne_empty_iff_nonempty.mpr, cases h, { rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ }, { rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } } end /-- A closed set `s` is preconnected if and only if for every cover by two closed sets that are disjoint, it is contained in one of the two covering sets. -/ theorem is_preconnected_iff_subset_of_fully_disjoint_closed {s : set α} (hs : is_closed s) : is_preconnected s ↔ ∀ (u v : set α) (hu : is_closed u) (hv : is_closed v) (hss : s ⊆ u ∪ v) (huv : u ∩ v = ∅), s ⊆ u ∨ s ⊆ v := begin split, { intros h u v hu hv hss huv, apply is_preconnected_iff_subset_of_disjoint_closed.1 h u v hu hv hss, rw huv, exact inter_empty s }, intro H, rw is_preconnected_iff_subset_of_disjoint_closed, intros u v hu hv hss huv, have H1 := H (u ∩ s) (v ∩ s), rw [subset_inter_iff, subset_inter_iff] at H1, simp only [subset.refl, and_true] at H1, apply H1 (is_closed.inter hu hs) (is_closed.inter hv hs), { rw ←inter_distrib_right, apply subset_inter_iff.2, exact ⟨hss, subset.refl s⟩ }, { rw [inter_comm v s, inter_assoc, ←inter_assoc s, inter_self s, inter_comm, inter_assoc, inter_comm v u, huv] } end /-- The connected component of a point is always a subset of the intersection of all its clopen neighbourhoods. -/ lemma connected_component_subset_Inter_clopen {x : α} : connected_component x ⊆ ⋂ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z := begin apply subset_Inter (λ Z, _), cases (subset_or_disjoint_of_clopen (@is_connected_connected_component _ _ x).2 Z.2.1), { exfalso, apply nonempty.ne_empty (nonempty_of_mem (mem_inter (@mem_connected_component _ _ x) Z.2.2)), rw inter_comm, exact h }, exact h, end /-- A clopen set is the union of its connected components. -/ lemma is_clopen.eq_union_connected_components {Z : set α} (h : is_clopen Z) : Z = (⋃ (x : α) (H : x ∈ Z), connected_component x) := eq_of_subset_of_subset (λ x xZ, mem_Union.2 ⟨x, mem_Union.2 ⟨xZ, mem_connected_component⟩⟩) (Union_subset $ λ x, Union_subset $ λ xZ, (by { apply subset.trans connected_component_subset_Inter_clopen (Inter_subset _ ⟨Z, ⟨h, xZ⟩⟩) })) /-- The preimage of a connected component is preconnected if the function has connected fibers and a subset is closed iff the preimage is. -/ lemma preimage_connected_component_connected {β : Type*} [topological_space β] {f : α → β} (connected_fibers : ∀ t : β, is_connected (f ⁻¹' {t})) (hcl : ∀ (T : set β), is_closed T ↔ is_closed (f ⁻¹' T)) (t : β) : is_connected (f ⁻¹' connected_component t) := begin -- The following proof is essentially https://stacks.math.columbia.edu/tag/0377 -- although the statement is slightly different have hf : surjective f := surjective.of_comp (λ t : β, (connected_fibers t).1), split, { cases hf t with s hs, use s, rw [mem_preimage, hs], exact mem_connected_component }, have hT : is_closed (f ⁻¹' connected_component t) := (hcl (connected_component t)).1 is_closed_connected_component, -- To show it's preconnected we decompose (f ⁻¹' connected_component t) as a subset of two -- closed disjoint sets in α. We want to show that it's a subset of either. rw is_preconnected_iff_subset_of_fully_disjoint_closed hT, intros u v hu hv huv uv_disj, -- To do this we decompose connected_component t into T₁ and T₂ -- we will show that connected_component t is a subset of either and hence -- (f ⁻¹' connected_component t) is a subset of u or v let T₁ := {t' ∈ connected_component t | f ⁻¹' {t'} ⊆ u}, let T₂ := {t' ∈ connected_component t | f ⁻¹' {t'} ⊆ v}, have fiber_decomp : ∀ t' ∈ connected_component t, f ⁻¹' {t'} ⊆ u ∨ f ⁻¹' {t'} ⊆ v, { intros t' ht', apply is_preconnected_iff_subset_of_disjoint_closed.1 (connected_fibers t').2 u v hu hv, { exact subset.trans (hf.preimage_subset_preimage_iff.2 (singleton_subset_iff.2 ht')) huv }, rw uv_disj, exact inter_empty _ }, have T₁_u : f ⁻¹' T₁ = (f ⁻¹' connected_component t) ∩ u, { apply eq_of_subset_of_subset, { rw ←bUnion_preimage_singleton, refine bUnion_subset (λ t' ht', subset_inter _ ht'.2), rw [hf.preimage_subset_preimage_iff, singleton_subset_iff], exact ht'.1 }, rintros a ⟨hat, hau⟩, constructor, { exact mem_preimage.1 hat }, dsimp only, cases fiber_decomp (f a) (mem_preimage.1 hat), { exact h }, { exfalso, rw ←not_nonempty_iff_eq_empty at uv_disj, exact uv_disj (nonempty_of_mem (mem_inter hau (h rfl))) } }, -- This proof is exactly the same as the above (modulo some symmetry) have T₂_v : f ⁻¹' T₂ = (f ⁻¹' connected_component t) ∩ v, { apply eq_of_subset_of_subset, { rw ←bUnion_preimage_singleton, refine bUnion_subset (λ t' ht', subset_inter _ ht'.2), rw [hf.preimage_subset_preimage_iff, singleton_subset_iff], exact ht'.1 }, rintros a ⟨hat, hav⟩, constructor, { exact mem_preimage.1 hat }, dsimp only, cases fiber_decomp (f a) (mem_preimage.1 hat), { exfalso, rw ←not_nonempty_iff_eq_empty at uv_disj, exact uv_disj (nonempty_of_mem (mem_inter (h rfl) hav)) }, { exact h } }, -- Now we show T₁, T₂ are closed, cover connected_component t and are disjoint. have hT₁ : is_closed T₁ := ((hcl T₁).2 (T₁_u.symm ▸ (is_closed.inter hT hu))), have hT₂ : is_closed T₂ := ((hcl T₂).2 (T₂_v.symm ▸ (is_closed.inter hT hv))), have T_decomp : connected_component t ⊆ T₁ ∪ T₂, { intros t' ht', rw mem_union t' T₁ T₂, cases fiber_decomp t' ht' with htu htv, { left, exact ⟨ht', htu⟩ }, right, exact ⟨ht', htv⟩ }, have T_disjoint : T₁ ∩ T₂ = ∅, { rw ←image_preimage_eq (T₁ ∩ T₂) hf, suffices : f ⁻¹' (T₁ ∩ T₂) = ∅, { rw this, exact image_empty _ }, rw [preimage_inter, T₁_u, T₂_v], rw inter_comm at uv_disj, conv { congr, rw [inter_assoc], congr, skip, rw [←inter_assoc, inter_comm, ←inter_assoc, uv_disj, empty_inter], }, exact inter_empty _ }, -- Now we do cases on whether (connected_component t) is a subset of T₁ or T₂ to show -- that the preimage is a subset of u or v. cases (is_preconnected_iff_subset_of_fully_disjoint_closed is_closed_connected_component).1 is_preconnected_connected_component T₁ T₂ hT₁ hT₂ T_decomp T_disjoint, { left, rw subset.antisymm_iff at T₁_u, suffices : f ⁻¹' connected_component t ⊆ f ⁻¹' T₁, { exact subset.trans (subset.trans this T₁_u.1) (inter_subset_right _ _) }, exact preimage_mono h }, right, rw subset.antisymm_iff at T₂_v, suffices : f ⁻¹' connected_component t ⊆ f ⁻¹' T₂, { exact subset.trans (subset.trans this T₂_v.1) (inter_subset_right _ _) }, exact preimage_mono h, end end preconnected section totally_disconnected /-- A set `s` is called totally disconnected if every subset `t ⊆ s` which is preconnected is a subsingleton, ie either empty or a singleton.-/ def is_totally_disconnected (s : set α) : Prop := ∀ t, t ⊆ s → is_preconnected t → t.subsingleton theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) := λ _ ht _ _ x_in _ _, (ht x_in).elim theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) := λ _ ht _, subsingleton.mono subsingleton_singleton ht /-- A space is totally disconnected if all of its connected components are singletons. -/ class totally_disconnected_space (α : Type u) [topological_space α] : Prop := (is_totally_disconnected_univ : is_totally_disconnected (univ : set α)) lemma is_preconnected.subsingleton [totally_disconnected_space α] {s : set α} (h : is_preconnected s) : s.subsingleton := totally_disconnected_space.is_totally_disconnected_univ s (subset_univ s) h instance pi.totally_disconnected_space {α : Type*} {β : α → Type*} [t₂ : Πa, topological_space (β a)] [∀a, totally_disconnected_space (β a)] : totally_disconnected_space (Π (a : α), β a) := ⟨λ t h1 h2, have this : ∀ a, is_preconnected ((λ x : Π a, β a, x a) '' t), from λ a, h2.image (λ x, x a) (continuous_apply a).continuous_on, λ x x_in y y_in, funext $ λ a, (this a).subsingleton ⟨x, x_in, rfl⟩ ⟨y, y_in, rfl⟩⟩ instance prod.totally_disconnected_space [topological_space β] [totally_disconnected_space α] [totally_disconnected_space β] : totally_disconnected_space (α × β) := ⟨λ t h1 h2, have H1 : is_preconnected (prod.fst '' t), from h2.image prod.fst continuous_fst.continuous_on, have H2 : is_preconnected (prod.snd '' t), from h2.image prod.snd continuous_snd.continuous_on, λ x hx y hy, prod.ext (H1.subsingleton ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩) (H2.subsingleton ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩)⟩ /-- A space is totally disconnected iff its connected components are subsingletons. -/ lemma totally_disconnected_space_iff_connected_component_subsingleton : totally_disconnected_space α ↔ ∀ x : α, (connected_component x).subsingleton := begin split, { intros h x, apply h.1, { exact subset_univ _ }, exact is_preconnected_connected_component }, intro h, constructor, intros s s_sub hs, rcases eq_empty_or_nonempty s with rfl | ⟨x, x_in⟩, { exact subsingleton_empty }, { exact (h x).mono (hs.subset_connected_component x_in) } end /-- A space is totally disconnected iff its connected components are singletons. -/ lemma totally_disconnected_space_iff_connected_component_singleton : totally_disconnected_space α ↔ ∀ x : α, connected_component x = {x} := begin rw totally_disconnected_space_iff_connected_component_subsingleton, apply forall_congr (λ x, _), rw set.subsingleton_iff_singleton, exact mem_connected_component end /-- The image of a connected component in a totally disconnected space is a singleton. -/ @[simp] lemma continuous.image_connected_component_eq_singleton {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) (a : α) : f '' connected_component a = {f a} := (set.subsingleton_iff_singleton $ mem_image_of_mem f mem_connected_component).mp (is_preconnected_connected_component.image f h.continuous_on).subsingleton lemma is_totally_disconnected_of_totally_disconnected_space [totally_disconnected_space α] (s : set α) : is_totally_disconnected s := λ t hts ht, totally_disconnected_space.is_totally_disconnected_univ _ t.subset_univ ht lemma is_totally_disconnected_of_image [topological_space β] {f : α → β} (hf : continuous_on f s) (hf' : injective f) (h : is_totally_disconnected (f '' s)) : is_totally_disconnected s := λ t hts ht x x_in y y_in, hf' $ h _ (image_subset f hts) (ht.image f $ hf.mono hts) (mem_image_of_mem f x_in) (mem_image_of_mem f y_in) lemma embedding.is_totally_disconnected [topological_space β] {f : α → β} (hf : embedding f) {s : set α} (h : is_totally_disconnected (f '' s)) : is_totally_disconnected s := is_totally_disconnected_of_image hf.continuous.continuous_on hf.inj h instance subtype.totally_disconnected_space {α : Type*} {p : α → Prop} [topological_space α] [totally_disconnected_space α] : totally_disconnected_space (subtype p) := ⟨embedding_subtype_coe.is_totally_disconnected (is_totally_disconnected_of_totally_disconnected_space _)⟩ end totally_disconnected section totally_separated /-- A set `s` is called totally separated if any two points of this set can be separated by two disjoint open sets covering `s`. -/ def is_totally_separated (s : set α) : Prop := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅ theorem is_totally_separated_empty : is_totally_separated (∅ : set α) := λ x, false.elim theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) := λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim theorem is_totally_disconnected_of_is_totally_separated {s : set α} (H : is_totally_separated s) : is_totally_disconnected s := begin intros t hts ht x x_in y y_in, by_contra h, obtain ⟨u : set α, v : set α, hu : is_open u, hv : is_open v, hxu : x ∈ u, hyv : y ∈ v, hs : s ⊆ u ∪ v, huv : u ∩ v = ∅⟩ := H x (hts x_in) y (hts y_in) h, have : (t ∩ u).nonempty → (t ∩ v).nonempty → (t ∩ (u ∩ v)).nonempty := ht _ _ hu hv (subset.trans hts hs), obtain ⟨z, hz : z ∈ t ∩ (u ∩ v)⟩ := this ⟨x, x_in, hxu⟩ ⟨y, y_in, hyv⟩, simpa [huv] using hz end alias is_totally_disconnected_of_is_totally_separated ← is_totally_separated.is_totally_disconnected /-- A space is totally separated if any two points can be separated by two disjoint open sets covering the whole space. -/ class totally_separated_space (α : Type u) [topological_space α] : Prop := (is_totally_separated_univ [] : is_totally_separated (univ : set α)) @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α] [totally_separated_space α] : totally_disconnected_space α := ⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩ @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.of_discrete (α : Type*) [topological_space α] [discrete_topology α] : totally_separated_space α := ⟨λ a _ b _ h, ⟨{b}ᶜ, {b}, is_open_discrete _, is_open_discrete _, by simpa⟩⟩ lemma exists_clopen_of_totally_separated {α : Type*} [topological_space α] [totally_separated_space α] {x y : α} (hxy : x ≠ y) : ∃ (U : set α) (hU : is_clopen U), x ∈ U ∧ y ∈ Uᶜ := begin obtain ⟨U, V, hU, hV, Ux, Vy, f, disj⟩ := totally_separated_space.is_totally_separated_univ α x (set.mem_univ x) y (set.mem_univ y) hxy, have clopen_U := is_clopen_inter_of_disjoint_cover_clopen (is_clopen_univ) f hU hV disj, rw set.univ_inter _ at clopen_U, rw [←set.subset_compl_iff_disjoint, set.subset_compl_comm] at disj, exact ⟨U, clopen_U, Ux, disj Vy⟩, end end totally_separated section connected_component_setoid /-- The setoid of connected components of a topological space -/ def connected_component_setoid (α : Type*) [topological_space α] : setoid α := ⟨λ x y, connected_component x = connected_component y, ⟨λ x, by trivial, λ x y h1, h1.symm, λ x y z h1 h2, h1.trans h2⟩⟩ -- see Note [lower instance priority] local attribute [instance, priority 100] connected_component_setoid lemma connected_component_rel_iff {x y : α} : ⟦x⟧ = ⟦y⟧ ↔ connected_component x = connected_component y := ⟨λ h, quotient.exact h, λ h, quotient.sound h⟩ lemma connected_component_nrel_iff {x y : α} : ⟦x⟧ ≠ ⟦y⟧ ↔ connected_component x ≠ connected_component y := by { rw not_iff_not, exact connected_component_rel_iff } /-- The quotient of a space by its connected components -/ def connected_components (α : Type u) [topological_space α] := quotient (connected_component_setoid α) instance [inhabited α] : inhabited (connected_components α) := ⟨quotient.mk (default _)⟩ instance connected_components.topological_space : topological_space (connected_components α) := quotient.topological_space lemma continuous.image_eq_of_equiv {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) (a b : α) (hab : a ≈ b) : f a = f b := singleton_eq_singleton_iff.1 $ h.image_connected_component_eq_singleton a ▸ h.image_connected_component_eq_singleton b ▸ hab ▸ rfl /-- The lift to `connected_components α` of a continuous map from `α` to a totally disconnected space -/ def continuous.connected_components_lift {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) : connected_components α → β := quotient.lift f h.image_eq_of_equiv @[continuity] lemma continuous.connected_components_lift_continuous {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) : continuous h.connected_components_lift := continuous_quotient_lift h.image_eq_of_equiv h @[simp] lemma continuous.connected_components_lift_factors {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) : h.connected_components_lift ∘ quotient.mk = f := rfl lemma continuous.connected_components_lift_unique {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) (g : connected_components α → β) (hg : g ∘ quotient.mk = f) : g = h.connected_components_lift := by { subst hg, ext1 x, exact quotient.induction_on x (λ a, refl _) } lemma connected_components_lift_unique' {β : Type*} (g₁ : connected_components α → β) (g₂ : connected_components α → β) (hg : g₁ ∘ quotient.mk = g₂ ∘ quotient.mk ) : g₁ = g₂ := begin ext1 x, refine quotient.induction_on x (λ a, _), change (g₁ ∘ quotient.mk) a = (g₂ ∘ quotient.mk) a, rw hg, end /-- The preimage of a singleton in `connected_components` is the connected component of an element in the equivalence class. -/ lemma connected_components_preimage_singleton {t : α} : connected_component t = quotient.mk ⁻¹' {⟦t⟧} := begin apply set.eq_of_subset_of_subset; intros a ha, { have H : ⟦a⟧ = ⟦t⟧ := quotient.sound (connected_component_eq ha).symm, rw [mem_preimage, H], exact mem_singleton ⟦t⟧ }, rw [mem_preimage, mem_singleton_iff] at ha, have ha' : connected_component a = connected_component t := quotient.exact ha, rw ←ha', exact mem_connected_component, end /-- The preimage of the image of a set under the quotient map to `connected_components α` is the union of the connected components of the elements in it. -/ lemma connected_components_preimage_image (U : set α) : quotient.mk ⁻¹' (quotient.mk '' U) = ⋃ (x : α) (h : x ∈ U), connected_component x := begin apply set.eq_of_subset_of_subset, { rintros a ⟨b, hb, hab⟩, refine mem_Union.2 ⟨b, mem_Union.2 ⟨hb, _⟩⟩, rw connected_component_rel_iff.1 hab, exact mem_connected_component }, refine Union_subset (λ a, Union_subset (λ ha, _)), rw [connected_components_preimage_singleton, (surjective_quotient_mk _).preimage_subset_preimage_iff, singleton_subset_iff], exact ⟨a, ha, refl _⟩, end instance connected_components.totally_disconnected_space : totally_disconnected_space (connected_components α) := begin rw totally_disconnected_space_iff_connected_component_singleton, refine λ x, quotient.induction_on x (λ a, _), apply eq_of_subset_of_subset _ (singleton_subset_iff.2 mem_connected_component), rw subset_singleton_iff, refine λ x, quotient.induction_on x (λ b hb, _), rw [connected_component_rel_iff, connected_component_eq], suffices : is_preconnected (quotient.mk ⁻¹' connected_component ⟦a⟧), { apply mem_of_subset_of_mem (this.subset_connected_component hb), exact mem_preimage.2 mem_connected_component }, apply (@preimage_connected_component_connected _ _ _ _ _ _ _ _).2, { refine λ t, quotient.induction_on t (λ s, _), rw ←connected_components_preimage_singleton, exact is_connected_connected_component }, refine λ T, ⟨λ hT, hT.preimage continuous_quotient_mk, λ hT, _⟩, rwa [← is_open_compl_iff, ← preimage_compl, quotient_map_quotient_mk.is_open_preimage, is_open_compl_iff] at hT, end /-- Functoriality of `connected_components` -/ def continuous.connected_components_map {β : Type*} [topological_space β] {f : α → β} (h : continuous f) : connected_components α → connected_components β := continuous.connected_components_lift (continuous_quotient_mk.comp h) lemma continuous.connected_components_map_continuous {β : Type*} [topological_space β] {f : α → β} (h : continuous f) : continuous h.connected_components_map := continuous.connected_components_lift_continuous (continuous_quotient_mk.comp h) end connected_component_setoid
3c2328b00777fcb9c6631736a622ddaddc7a102d
cb3da1b91380e7462b579b426a278072c688954a
/src/xu.lean
ab8b495ce2f5e4547f3d4f6cd277d85f7f378920
[]
no_license
hcheval/tikhonov-mann
35c93e46a8287f6479a848a9d4f02013e0bc2035
6ab7fcefe9e1156c20bd5d1998a7deabd1eeb018
refs/heads/master
1,689,232,126,344
1,630,182,255,000
1,630,182,255,000
399,859,996
0
0
null
null
null
null
UTF-8
Lean
false
false
1,349
lean
import rates import leu_pin open_locale big_operators open finset (range) def xu_rate (χ γ δ₀ : ℕ → ℕ) (L : ℕ) (k : ℕ) : ℕ := max (γ (3 * L * (k + 1) * (δ₀ k) - 1)) (χ (3 * k + 2) + 1) + 1 open leu_pin (δ) lemma xu_quantitative (a c s : ℕ → ℝ) (L : ℕ) (χ : ℕ → ℕ) (γ : ℕ → ℕ) (δ₀ : ℕ → ℕ) (a0 : ∀ n : ℕ, 0 ≤ a n) (a1 : ∀ n : ℕ, a n < 1) (c0 : ∀ n : ℕ, 0 ≤ c n) (s0 : ∀ n : ℕ, 0 ≤ s n) (L_pos : 0 < L) (h : ∀ n : ℕ, s (n + 1) ≤ (1 - a n) * (s n) + c n) (L_bound_s : ∀ n : ℕ, s n ≤ L) (χ_cauchy_mod : is_cauchy_modulus χ (λ n, ∑ i in range (n + 1), c i)) (γ_conv_rate : is_rate_of_convergence_towards γ (λ n, ∏ i in range (n + 1), (1 - a i)) 0) (hδ₀ : ∀ k : ℕ, 1 / (δ₀ k : ℝ) ≤ (∏ i in range ((χ $ 3 * k + 2) + 1), (1 - a i))) : is_rate_of_convergence_towards (xu_rate χ γ δ₀ L) s 0 := begin have δ_of_zero : ∀ k, δ (λ _, 0) χ k = (χ $ 3 * k + 2) + 1 := by simp only [forall_const, max_eq_right_iff, zero_le'], have := leu_pin.leu_pin_3_5 a (λ _, 0) c s L (λ _, 0) χ γ δ₀ a0 a1 c0 s0 (by simpa) L_pos (λ _ _ _, by { simp only [one_div, inv_nonneg], exact nat.cast_nonneg _ }) χ_cauchy_mod γ_conv_rate hδ₀, all_goals {simp_rw [δ_of_zero] at *,}, exact this, end #check nat.cast_nonneg
9fd867fe2fcb03ce5b757083da7c721228736c4e
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Elab/Deriving.lean
6f380820c16b163504450e60d40aa9a5c3ffa3f1
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
426
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util import Lean.Elab.Deriving.Inhabited import Lean.Elab.Deriving.BEq import Lean.Elab.Deriving.DecEq import Lean.Elab.Deriving.Repr import Lean.Elab.Deriving.FromToJson import Lean.Elab.Deriving.SizeOf
89a4f3d339cbea248a298e3dd771afe2f3521d54
bb31430994044506fa42fd667e2d556327e18dfe
/src/number_theory/bertrand.lean
a3cc2fd71c6d64de7011ade49eed9ae098679e35
[ "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
11,297
lean
/- Copyright (c) 2020 Patrick Stevens. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Stevens, Bolton Bailey -/ import data.nat.choose.factorization import data.nat.prime_norm_num import number_theory.primorial import analysis.convex.specific_functions /-! # Bertrand's Postulate This file contains a proof of Bertrand's postulate: That between any positive number and its double there is a prime. The proof follows the outline of the Erdős proof presented in "Proofs from THE BOOK": One considers the prime factorization of `(2 * n).choose n`, and splits the constituent primes up into various groups, then upper bounds the contribution of each group. This upper bounds the central binomial coefficient, and if the postulate does not hold, this upper bound conflicts with a simple lower bound for large enough `n`. This proves the result holds for large enough `n`, and for smaller `n` an explicit list of primes is provided which covers the remaining cases. As in the [Metamath implementation](carneiro2015arithmetic), we rely on some optimizations from [Shigenori Tochiori](tochiori_bertrand). In particular we use the cleaner bound on the central binomial coefficient given in `nat.four_pow_lt_mul_central_binom`. ## References * [M. Aigner and G. M. Ziegler _Proofs from THE BOOK_][aigner1999proofs] * [S. Tochiori, _Considering the Proof of “There is a Prime between n and 2n”_][tochiori_bertrand] * [M. Carneiro, _Arithmetic in Metamath, Case Study: Bertrand's Postulate_][carneiro2015arithmetic] ## Tags Bertrand, prime, binomial coefficients -/ open_locale big_operators section real open real namespace bertrand /-- A reified version of the `bertrand.main_inequality` below. This is not best possible: it actually holds for 464 ≤ x. -/ lemma real_main_inequality {x : ℝ} (n_large : (512 : ℝ) ≤ x) : x * (2 * x) ^ (sqrt (2 * x)) * 4 ^ (2 * x / 3) ≤ 4 ^ x := begin let f : ℝ → ℝ := λ x, log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x, have hf' : ∀ x, 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3) := λ x h, div_pos (mul_pos h (rpow_pos_of_pos (mul_pos two_pos h) _)) (rpow_pos_of_pos four_pos _), have hf : ∀ x, 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)), { intros x h5, have h6 := mul_pos (zero_lt_two' ℝ) h5, have h7 := rpow_pos_of_pos h6 (sqrt (2 * x)), rw [log_div (mul_pos h5 h7).ne' (rpow_pos_of_pos four_pos _).ne', log_mul h5.ne' h7.ne', log_rpow h6, log_rpow zero_lt_four, ← mul_div_right_comm, ← mul_div, mul_comm x] }, have h5 : 0 < x := lt_of_lt_of_le (by norm_num1) n_large, rw [← div_le_one (rpow_pos_of_pos four_pos x), ← div_div_eq_mul_div, ← rpow_sub four_pos, ← mul_div 2 x, mul_div_left_comm, ← mul_one_sub, (by norm_num1 : (1 : ℝ) - 2 / 3 = 1 / 3), mul_one_div, ← log_nonpos_iff (hf' x h5), ← hf x h5], have h : concave_on ℝ (set.Ioi 0.5) f, { refine ((strict_concave_on_log_Ioi.concave_on.subset (set.Ioi_subset_Ioi _) (convex_Ioi 0.5)).add ((strict_concave_on_sqrt_mul_log_Ioi.concave_on.comp_linear_map ((2 : ℝ) • linear_map.id)).subset (λ a ha, lt_of_eq_of_lt _ ((mul_lt_mul_left two_pos).mpr ha)) (convex_Ioi 0.5))).sub ((convex_on_id (convex_Ioi (0.5 : ℝ))).smul (div_nonneg (log_nonneg _) _)); norm_num1 }, suffices : ∃ x1 x2, 0.5 < x1 ∧ x1 < x2 ∧ x2 ≤ x ∧ 0 ≤ f x1 ∧ f x2 ≤ 0, { obtain ⟨x1, x2, h1, h2, h0, h3, h4⟩ := this, exact (h.right_le_of_le_left'' h1 ((h1.trans h2).trans_le h0) h2 h0 (h4.trans h3)).trans h4 }, refine ⟨18, 512, by norm_num1, by norm_num1, le_trans (by norm_num1) n_large, _, _⟩, { have : sqrt (2 * 18) = 6 := (sqrt_eq_iff_mul_self_eq_of_pos (by norm_num1)).mpr (by norm_num1), rw [hf, log_nonneg_iff (hf' 18 _), this]; norm_num1 }, { have : sqrt (2 * 512) = 32, { exact (sqrt_eq_iff_mul_self_eq_of_pos (by norm_num1)).mpr (by norm_num1) }, rw [hf, log_nonpos_iff (hf' _ _), this, div_le_one (rpow_pos_of_pos four_pos _), ← rpow_le_rpow_iff _ (rpow_pos_of_pos four_pos _).le three_pos, ← rpow_mul]; norm_num1 }, end end bertrand end real section nat open nat /-- The inequality which contradicts Bertrand's postulate, for large enough `n`. -/ lemma bertrand_main_inequality {n : ℕ} (n_large : 512 ≤ n) : n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n := begin rw ← @cast_le ℝ, simp only [cast_bit0, cast_add, cast_one, cast_mul, cast_pow, ← real.rpow_nat_cast], have n_pos : 0 < n := (dec_trivial : 0 < 512).trans_le n_large, have n2_pos : 1 ≤ 2 * n := mul_pos dec_trivial n_pos, refine trans (mul_le_mul _ _ _ _) (bertrand.real_main_inequality (by exact_mod_cast n_large)), { refine mul_le_mul_of_nonneg_left _ (nat.cast_nonneg _), refine real.rpow_le_rpow_of_exponent_le (by exact_mod_cast n2_pos) _, exact_mod_cast real.nat_sqrt_le_real_sqrt }, { exact real.rpow_le_rpow_of_exponent_le (by norm_num1) (cast_div_le.trans (by norm_cast)) }, { exact real.rpow_nonneg_of_nonneg (by norm_num1) _ }, { refine mul_nonneg (nat.cast_nonneg _) _, exact real.rpow_nonneg_of_nonneg (mul_nonneg zero_le_two (nat.cast_nonneg _)) _, }, end /-- A lemma that tells us that, in the case where Bertrand's postulate does not hold, the prime factorization of the central binomial coefficent only has factors at most `2 * n / 3 + 1`. -/ lemma central_binom_factorization_small (n : ℕ) (n_large : 2 < n) (no_prime: ¬∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n) : central_binom n = ∏ p in finset.range (2 * n / 3 + 1), p ^ ((central_binom n).factorization p) := begin refine (eq.trans _ n.prod_pow_factorization_central_binom).symm, apply finset.prod_subset, { exact finset.range_subset.2 (add_le_add_right (nat.div_le_self _ _) _) }, intros x hx h2x, rw [finset.mem_range, lt_succ_iff] at hx h2x, rw [not_le, div_lt_iff_lt_mul' three_pos, mul_comm x] at h2x, replace no_prime := not_exists.mp no_prime x, rw [←and_assoc, not_and', not_and_distrib, not_lt] at no_prime, cases no_prime hx with h h, { rw [factorization_eq_zero_of_non_prime n.central_binom h, pow_zero] }, { rw [factorization_central_binom_of_two_mul_self_lt_three_mul n_large h h2x, pow_zero] }, end /-- An upper bound on the central binomial coefficient used in the proof of Bertrand's postulate. The bound splits the prime factors of `central_binom n` into those 1. At most `sqrt (2 * n)`, which contribute at most `2 * n` for each such prime. 2. Between `sqrt (2 * n)` and `2 * n / 3`, which contribute at most `4^(2 * n / 3)` in total. 3. Between `2 * n / 3` and `n`, which do not exist. 4. Between `n` and `2 * n`, which would not exist in the case where Bertrand's postulate is false. 5. Above `2 * n`, which do not exist. -/ lemma central_binom_le_of_no_bertrand_prime (n : ℕ) (n_big : 2 < n) (no_prime : ¬∃ (p : ℕ), nat.prime p ∧ n < p ∧ p ≤ 2 * n) : central_binom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) := begin have n_pos : 0 < n := (nat.zero_le _).trans_lt n_big, have n2_pos : 1 ≤ 2 * n := mul_pos (zero_lt_two' ℕ) n_pos, let S := (finset.range (2 * n / 3 + 1)).filter nat.prime, let f := λ x, x ^ n.central_binom.factorization x, have : ∏ (x : ℕ) in S, f x = ∏ (x : ℕ) in finset.range (2 * n / 3 + 1), f x, { refine finset.prod_filter_of_ne (λ p hp h, _), contrapose! h, dsimp only [f], rw [factorization_eq_zero_of_non_prime n.central_binom h, pow_zero] }, rw [central_binom_factorization_small n n_big no_prime, ← this, ← finset.prod_filter_mul_prod_filter_not S (≤ sqrt (2 * n))], apply mul_le_mul', { refine (finset.prod_le_prod'' (λ p hp, (_ : f p ≤ 2 * n))).trans _, { exact pow_factorization_choose_le (mul_pos two_pos n_pos) }, have : (finset.Icc 1 (sqrt (2 * n))).card = sqrt (2 * n), { rw [card_Icc, nat.add_sub_cancel] }, rw finset.prod_const, refine pow_le_pow n2_pos ((finset.card_le_of_subset (λ x hx, _)).trans this.le), obtain ⟨h1, h2⟩ := finset.mem_filter.1 hx, exact finset.mem_Icc.mpr ⟨(finset.mem_filter.1 h1).2.one_lt.le, h2⟩ }, { refine le_trans _ (primorial_le_4_pow (2 * n / 3)), refine (finset.prod_le_prod' (λ p hp, (_ : f p ≤ p))).trans _, { obtain ⟨h1, h2⟩ := finset.mem_filter.1 hp, refine (pow_le_pow (finset.mem_filter.1 h1).2.one_lt.le _).trans (pow_one p).le, exact nat.factorization_choose_le_one (sqrt_lt'.mp $ not_le.1 h2) }, refine finset.prod_le_prod_of_subset_of_one_le' (finset.filter_subset _ _) _, exact λ p hp _, (finset.mem_filter.1 hp).2.one_lt.le } end namespace nat /-- Proves that Bertrand's postulate holds for all sufficiently large `n`. -/ lemma exists_prime_lt_and_le_two_mul_eventually (n : ℕ) (n_big : 512 ≤ n) : ∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n := begin -- Assume there is no prime in the range. by_contradiction no_prime, -- Then we have the above sub-exponential bound on the size of this central binomial coefficient. -- We now couple this bound with an exponential lower bound on the central binomial coefficient, -- yielding an inequality which we have seen is false for large enough n. have H1 : n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n := bertrand_main_inequality n_big, have H2 : 4 ^ n < n * n.central_binom := nat.four_pow_lt_mul_central_binom n (le_trans (by norm_num1) n_big), have H3 : n.central_binom ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) := central_binom_le_of_no_bertrand_prime n (lt_of_lt_of_le (by norm_num1) n_big) no_prime, rw mul_assoc at H1, exact not_le.2 H2 ((mul_le_mul_left' H3 n).trans H1), end /-- Proves that Bertrand's postulate holds over all positive naturals less than n by identifying a descending list of primes, each no more than twice the next, such that the list contains a witness for each number ≤ n. -/ lemma exists_prime_lt_and_le_two_mul_succ {n} (q) {p : ℕ} (prime_p : nat.prime p) (covering : p ≤ 2 * q) (H : n < q → ∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n) (hn : n < p) : ∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n := begin by_cases p ≤ 2 * n, { exact ⟨p, prime_p, hn, h⟩ }, exact H (lt_of_mul_lt_mul_left' (lt_of_lt_of_le (not_le.1 h) covering)) end /-- **Bertrand's Postulate**: For any positive natural number, there is a prime which is greater than it, but no more than twice as large. -/ theorem exists_prime_lt_and_le_two_mul (n : ℕ) (hn0 : n ≠ 0) : ∃ p, nat.prime p ∧ n < p ∧ p ≤ 2 * n := begin -- Split into cases whether `n` is large or small cases lt_or_le 511 n, -- If `n` is large, apply the lemma derived from the inequalities on the central binomial -- coefficient. { exact exists_prime_lt_and_le_two_mul_eventually n h, }, replace h : n < 521 := h.trans_lt (by norm_num1), revert h, -- For small `n`, supply a list of primes to cover the initial cases. ([317, 163, 83, 43, 23, 13, 7, 5, 3, 2].mmap' $ λ n, `[refine exists_prime_lt_and_le_two_mul_succ %%(reflect n) (by norm_num1) (by norm_num1) _]), exact λ h2, ⟨2, prime_two, h2, nat.mul_le_mul_left 2 (nat.pos_of_ne_zero hn0)⟩, end alias nat.exists_prime_lt_and_le_two_mul ← bertrand end nat end nat
01ddc373f2673eb6a402d9119e694fa9df8e31cb
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/mean_inequalities_pow.lean
af0dfc85fa8155d86536127efb770004a6f475e9
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,913
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Sébastien Gouëzel, Rémy Degenne -/ import analysis.convex.specific_functions /-! # Mean value inequalities In this file we prove several mean inequalities for finite sums. Versions for integrals of some of these inequalities are available in `measure_theory.mean_inequalities`. ## Main theorems: generalized mean inequality The inequality says that for two non-negative vectors $w$ and $z$ with $\sum_{i\in s} w_i=1$ and $p ≤ q$ we have $$ \sqrt[p]{\sum_{i\in s} w_i z_i^p} ≤ \sqrt[q]{\sum_{i\in s} w_i z_i^q}. $$ Currently we only prove this inequality for $p=1$. As in the rest of `mathlib`, we provide different theorems for natural exponents (`pow_arith_mean_le_arith_mean_pow`), integer exponents (`zpow_arith_mean_le_arith_mean_zpow`), and real exponents (`rpow_arith_mean_le_arith_mean_rpow` and `arith_mean_le_rpow_mean`). In the first two cases we prove $$ \left(\sum_{i\in s} w_i z_i\right)^n ≤ \sum_{i\in s} w_i z_i^n $$ in order to avoid using real exponents. For real exponents we prove both this and standard versions. ## TODO - each inequality `A ≤ B` should come with a theorem `A = B ↔ _`; one of the ways to prove them is to define `strict_convex_on` functions. - generalized mean inequality with any `p ≤ q`, including negative numbers; - prove that the power mean tends to the geometric mean as the exponent tends to zero. -/ universes u v open finset open_locale classical big_operators nnreal ennreal noncomputable theory variables {ι : Type u} (s : finset ι) namespace real theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) (n : ℕ) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := (convex_on_pow n).map_sum_le hw hw' hz theorem pow_arith_mean_le_arith_mean_pow_of_even (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) {n : ℕ} (hn : even n) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := hn.convex_on_pow.map_sum_le hw hw' (λ _ _, trivial) theorem zpow_arith_mean_le_arith_mean_zpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 < z i) (m : ℤ) : (∑ i in s, w i * z i) ^ m ≤ ∑ i in s, (w i * z i ^ m) := (convex_on_zpow m).map_sum_le hw hw' hz theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := (convex_on_rpow hp).map_sum_le hw hw' hz theorem arith_mean_le_rpow_mean (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : ∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) := begin have : 0 < p := lt_of_lt_of_le zero_lt_one hp, rw [← rpow_le_rpow_iff _ _ this, ← rpow_mul, one_div_mul_cancel (ne_of_gt this), rpow_one], exact rpow_arith_mean_le_arith_mean_rpow s w z hw hw' hz hp, all_goals { apply_rules [sum_nonneg, rpow_nonneg_of_nonneg], intros i hi, apply_rules [mul_nonneg, rpow_nonneg_of_nonneg, hw i hi, hz i hi] }, end end real namespace nnreal /-- Weighted generalized mean inequality, version sums over finite sets, with `ℝ≥0`-valued functions and natural exponent. -/ theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) (n : ℕ) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := by exact_mod_cast real.pow_arith_mean_le_arith_mean_pow s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) n /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := by exact_mod_cast real.rpow_arith_mean_le_arith_mean_rpow s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp /-- Weighted generalized mean inequality, version for two elements of `ℝ≥0` and real exponents. -/ theorem rpow_arith_mean_le_arith_mean2_rpow (w₁ w₂ z₁ z₂ : ℝ≥0) (hw' : w₁ + w₂ = 1) {p : ℝ} (hp : 1 ≤ p) : (w₁ * z₁ + w₂ * z₂) ^ p ≤ w₁ * z₁ ^ p + w₂ * z₂ ^ p := begin have h := rpow_arith_mean_le_arith_mean_rpow univ ![w₁, w₂] ![z₁, z₂] _ hp, { simpa [fin.sum_univ_succ] using h, }, { simp [hw', fin.sum_univ_succ], }, end /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem arith_mean_le_rpow_mean (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : ∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) := by exact_mod_cast real.arith_mean_le_rpow_mean s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp end nnreal namespace nnreal private lemma add_rpow_le_one_of_add_le_one {p : ℝ} (a b : ℝ≥0) (hab : a + b ≤ 1) (hp1 : 1 ≤ p) : a ^ p + b ^ p ≤ 1 := begin have h_le_one : ∀ x : ℝ≥0, x ≤ 1 → x ^ p ≤ x, from λ x hx, rpow_le_self_of_le_one hx hp1, have ha : a ≤ 1, from (self_le_add_right a b).trans hab, have hb : b ≤ 1, from (self_le_add_left b a).trans hab, exact (add_le_add (h_le_one a ha) (h_le_one b hb)).trans hab, end lemma add_rpow_le_rpow_add {p : ℝ} (a b : ℝ≥0) (hp1 : 1 ≤ p) : a ^ p + b ^ p ≤ (a + b) ^ p := begin have hp_pos : 0 < p := lt_of_lt_of_le zero_lt_one hp1, by_cases h_zero : a + b = 0, { simp [add_eq_zero_iff.mp h_zero, hp_pos.ne'] }, have h_nonzero : ¬(a = 0 ∧ b = 0), by rwa add_eq_zero_iff at h_zero, have h_add : a/(a+b) + b/(a+b) = 1, by rw [div_add_div_same, div_self h_zero], have h := add_rpow_le_one_of_add_le_one (a/(a+b)) (b/(a+b)) h_add.le hp1, rw [div_rpow a (a+b), div_rpow b (a+b)] at h, have hab_0 : (a + b)^p ≠ 0, by simp [hp_pos, h_nonzero], have hab_0' : 0 < (a + b) ^ p := zero_lt_iff.mpr hab_0, have h_mul : (a + b)^p * (a ^ p / (a + b) ^ p + b ^ p / (a + b) ^ p) ≤ (a + b)^p, { nth_rewrite 3 ←mul_one ((a + b)^p), exact (mul_le_mul_left hab_0').mpr h, }, rwa [div_eq_mul_inv, div_eq_mul_inv, mul_add, mul_comm (a^p), mul_comm (b^p), ←mul_assoc, ←mul_assoc, mul_inv_cancel hab_0, one_mul, one_mul] at h_mul, end lemma rpow_add_rpow_le_add {p : ℝ} (a b : ℝ≥0) (hp1 : 1 ≤ p) : (a ^ p + b ^ p) ^ (1/p) ≤ a + b := begin rw ←@nnreal.le_rpow_one_div_iff _ _ (1/p) (by simp [lt_of_lt_of_le zero_lt_one hp1]), rw one_div_one_div, exact add_rpow_le_rpow_add _ _ hp1, end theorem rpow_add_rpow_le {p q : ℝ} (a b : ℝ≥0) (hp_pos : 0 < p) (hpq : p ≤ q) : (a ^ q + b ^ q) ^ (1/q) ≤ (a ^ p + b ^ p) ^ (1/p) := begin have h_rpow : ∀ a : ℝ≥0, a^q = (a^p)^(q/p), from λ a, by rw [←nnreal.rpow_mul, div_eq_inv_mul, ←mul_assoc, _root_.mul_inv_cancel hp_pos.ne.symm, one_mul], have h_rpow_add_rpow_le_add : ((a^p)^(q/p) + (b^p)^(q/p)) ^ (1/(q/p)) ≤ a^p + b^p, { refine rpow_add_rpow_le_add (a^p) (b^p) _, rwa one_le_div hp_pos, }, rw [h_rpow a, h_rpow b, nnreal.le_rpow_one_div_iff hp_pos, ←nnreal.rpow_mul, mul_comm, mul_one_div], rwa one_div_div at h_rpow_add_rpow_le_add, end lemma rpow_add_le_add_rpow {p : ℝ} (a b : ℝ≥0) (hp_pos : 0 < p) (hp1 : p ≤ 1) : (a + b) ^ p ≤ a ^ p + b ^ p := begin have h := rpow_add_rpow_le a b hp_pos hp1, rw one_div_one at h, repeat { rw nnreal.rpow_one at h }, exact (nnreal.le_rpow_one_div_iff hp_pos).mp h end end nnreal namespace ennreal /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0∞`-valued functions and real exponents. -/ theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ≥0∞) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := begin have hp_pos : 0 < p, from lt_of_lt_of_le zero_lt_one hp, have hp_nonneg : 0 ≤ p, from le_of_lt hp_pos, have hp_not_nonpos : ¬ p ≤ 0, by simp [hp_pos], have hp_not_neg : ¬ p < 0, by simp [hp_nonneg], have h_top_iff_rpow_top : ∀ (i : ι) (hi : i ∈ s), w i * z i = ⊤ ↔ w i * (z i) ^ p = ⊤, by simp [hp_pos, hp_nonneg, hp_not_nonpos, hp_not_neg], refine le_of_top_imp_top_of_to_nnreal_le _ _, { -- first, prove `(∑ i in s, w i * z i) ^ p = ⊤ → ∑ i in s, (w i * z i ^ p) = ⊤` rw [rpow_eq_top_iff, sum_eq_top_iff, sum_eq_top_iff], intro h, simp only [and_false, hp_not_neg, false_or] at h, rcases h.left with ⟨a, H, ha⟩, use [a, H], rwa ←h_top_iff_rpow_top a H, }, { -- second, suppose both `(∑ i in s, w i * z i) ^ p ≠ ⊤` and `∑ i in s, (w i * z i ^ p) ≠ ⊤`, -- and prove `((∑ i in s, w i * z i) ^ p).to_nnreal ≤ (∑ i in s, (w i * z i ^ p)).to_nnreal`, -- by using `nnreal.rpow_arith_mean_le_arith_mean_rpow`. intros h_top_rpow_sum _, -- show hypotheses needed to put the `.to_nnreal` inside the sums. have h_top : ∀ (a : ι), a ∈ s → w a * z a ≠ ⊤, { have h_top_sum : ∑ (i : ι) in s, w i * z i ≠ ⊤, { intro h, rw [h, top_rpow_of_pos hp_pos] at h_top_rpow_sum, exact h_top_rpow_sum rfl, }, exact λ a ha, (lt_top_of_sum_ne_top h_top_sum ha).ne }, have h_top_rpow : ∀ (a : ι), a ∈ s → w a * z a ^ p ≠ ⊤, { intros i hi, specialize h_top i hi, rwa [ne.def, ←h_top_iff_rpow_top i hi], }, -- put the `.to_nnreal` inside the sums. simp_rw [to_nnreal_sum h_top_rpow, ←to_nnreal_rpow, to_nnreal_sum h_top, to_nnreal_mul, ←to_nnreal_rpow], -- use corresponding nnreal result refine nnreal.rpow_arith_mean_le_arith_mean_rpow s (λ i, (w i).to_nnreal) (λ i, (z i).to_nnreal) _ hp, -- verify the hypothesis `∑ i in s, (w i).to_nnreal = 1`, using `∑ i in s, w i = 1` . have h_sum_nnreal : (∑ i in s, w i) = ↑(∑ i in s, (w i).to_nnreal), { rw coe_finset_sum, refine sum_congr rfl (λ i hi, (coe_to_nnreal _).symm), refine (lt_top_of_sum_ne_top _ hi).ne, exact hw'.symm ▸ ennreal.one_ne_top }, rwa [←coe_eq_coe, ←h_sum_nnreal], }, end /-- Weighted generalized mean inequality, version for two elements of `ℝ≥0∞` and real exponents. -/ theorem rpow_arith_mean_le_arith_mean2_rpow (w₁ w₂ z₁ z₂ : ℝ≥0∞) (hw' : w₁ + w₂ = 1) {p : ℝ} (hp : 1 ≤ p) : (w₁ * z₁ + w₂ * z₂) ^ p ≤ w₁ * z₁ ^ p + w₂ * z₂ ^ p := begin have h := rpow_arith_mean_le_arith_mean_rpow univ ![w₁, w₂] ![z₁, z₂] _ hp, { simpa [fin.sum_univ_succ] using h, }, { simp [hw', fin.sum_univ_succ], }, end end ennreal namespace ennreal lemma add_rpow_le_rpow_add {p : ℝ} (a b : ℝ≥0∞) (hp1 : 1 ≤ p) : a ^ p + b ^ p ≤ (a + b) ^ p := begin have hp_pos : 0 < p := lt_of_lt_of_le zero_lt_one hp1, by_cases h_top : a + b = ⊤, { rw ←@ennreal.rpow_eq_top_iff_of_pos (a + b) p hp_pos at h_top, rw h_top, exact le_top, }, obtain ⟨ha_top, hb_top⟩ := add_ne_top.mp h_top, lift a to ℝ≥0 using ha_top, lift b to ℝ≥0 using hb_top, simpa [← ennreal.coe_rpow_of_nonneg _ hp_pos.le] using ennreal.coe_le_coe.2 (nnreal.add_rpow_le_rpow_add a b hp1), end lemma rpow_add_rpow_le_add {p : ℝ} (a b : ℝ≥0∞) (hp1 : 1 ≤ p) : (a ^ p + b ^ p) ^ (1/p) ≤ a + b := begin rw ←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [lt_of_lt_of_le zero_lt_one hp1]), rw one_div_one_div, exact add_rpow_le_rpow_add _ _ hp1, end theorem rpow_add_rpow_le {p q : ℝ} (a b : ℝ≥0∞) (hp_pos : 0 < p) (hpq : p ≤ q) : (a ^ q + b ^ q) ^ (1/q) ≤ (a ^ p + b ^ p) ^ (1/p) := begin have h_rpow : ∀ a : ℝ≥0∞, a^q = (a^p)^(q/p), from λ a, by rw [←ennreal.rpow_mul, div_eq_inv_mul, ←mul_assoc, _root_.mul_inv_cancel hp_pos.ne.symm, one_mul], have h_rpow_add_rpow_le_add : ((a^p)^(q/p) + (b^p)^(q/p)) ^ (1/(q/p)) ≤ a^p + b^p, { refine rpow_add_rpow_le_add (a^p) (b^p) _, rwa one_le_div hp_pos, }, rw [h_rpow a, h_rpow b, ennreal.le_rpow_one_div_iff hp_pos, ←ennreal.rpow_mul, mul_comm, mul_one_div], rwa one_div_div at h_rpow_add_rpow_le_add, end lemma rpow_add_le_add_rpow {p : ℝ} (a b : ℝ≥0∞) (hp_pos : 0 < p) (hp1 : p ≤ 1) : (a + b) ^ p ≤ a ^ p + b ^ p := begin have h := rpow_add_rpow_le a b hp_pos hp1, rw one_div_one at h, repeat { rw ennreal.rpow_one at h }, exact (ennreal.le_rpow_one_div_iff hp_pos).mp h, end end ennreal
28e6aa047e554b3fa545110a0edcf49ae2e754d4
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/linear_algebra/affine_space/affine_map.lean
e8c156cf20950b2d4ee38bc6a60fcbb25957a2b2
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,821
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.affine_space.basic import linear_algebra.tensor_product import linear_algebra.prod import linear_algebra.pi import data.set.intervals.unordered_interval import tactic.abel /-! # Affine maps This file defines affine maps. ## Main definitions * `affine_map` is the type of affine maps between two affine spaces with the same ring `k`. Various basic examples of affine maps are defined, including `const`, `id`, `line_map` and `homothety`. ## Notations * `P1 →ᵃ[k] P2` is a notation for `affine_map k P1 P2`; * `affine_space V P`: a localized notation for `add_torsor V P` defined in `linear_algebra.affine_space.basic`. ## Implementation notes `out_param` is used in the definition of `[add_torsor V P]` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ open_locale affine /-- An `affine_map k P1 P2` (notation: `P1 →ᵃ[k] P2`) is a map from `P1` to `P2` that induces a corresponding linear map from `V1` to `V2`. -/ structure affine_map (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] := (to_fun : P1 → P2) (linear : V1 →ₗ[k] V2) (map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear v +ᵥ to_fun p) notation P1 ` →ᵃ[`:25 k:25 `] `:0 P2:0 := affine_map k P1 P2 instance (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2]: has_coe_to_fun (P1 →ᵃ[k] P2) (λ _, P1 → P2) := ⟨affine_map.to_fun⟩ namespace linear_map variables {k : Type*} {V₁ : Type*} {V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_comm_group V₂] [module k V₂] (f : V₁ →ₗ[k] V₂) /-- Reinterpret a linear map as an affine map. -/ def to_affine_map : V₁ →ᵃ[k] V₂ := { to_fun := f, linear := f, map_vadd' := λ p v, f.map_add v p } @[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl @[simp] lemma to_affine_map_linear : f.to_affine_map.linear = f := rfl end linear_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*} {V3 : Type*} {P3 : Type*} {V4 : Type*} {P4 : Type*} [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] [add_comm_group V3] [module k V3] [affine_space V3 P3] [add_comm_group V4] [module k V4] [affine_space V4 P4] include V1 V2 /-- Constructing an affine map and coercing back to a function produces the same map. -/ @[simp] lemma coe_mk (f : P1 → P2) (linear add) : ((mk f linear add : P1 →ᵃ[k] P2) : P1 → P2) = f := rfl /-- `to_fun` is the same as the result of coercing to a function. -/ @[simp] lemma to_fun_eq_coe (f : P1 →ᵃ[k] P2) : f.to_fun = ⇑f := rfl /-- An affine map on the result of adding a vector to a point produces the same result as the linear map applied to that vector, added to the affine map applied to that point. -/ @[simp] lemma map_vadd (f : P1 →ᵃ[k] P2) (p : P1) (v : V1) : f (v +ᵥ p) = f.linear v +ᵥ f p := f.map_vadd' p v /-- The linear map on the result of subtracting two points is the result of subtracting the result of the affine map on those two points. -/ @[simp] lemma linear_map_vsub (f : P1 →ᵃ[k] P2) (p1 p2 : P1) : f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 := by conv_rhs { rw [←vsub_vadd p1 p2, map_vadd, vadd_vsub] } /-- Two affine maps are equal if they coerce to the same function. -/ @[ext] lemma ext {f g : P1 →ᵃ[k] P2} (h : ∀ p, f p = g p) : f = g := begin rcases f with ⟨f, f_linear, f_add⟩, rcases g with ⟨g, g_linear, g_add⟩, have : f = g := funext h, subst g, congr' with v, cases (add_torsor.nonempty : nonempty P1) with p, apply vadd_right_cancel (f p), erw [← f_add, ← g_add] end lemma ext_iff {f g : P1 →ᵃ[k] P2} : f = g ↔ ∀ p, f p = g p := ⟨λ h p, h ▸ rfl, ext⟩ lemma coe_fn_injective : @function.injective (P1 →ᵃ[k] P2) (P1 → P2) coe_fn := λ f g H, ext $ congr_fun H protected lemma congr_arg (f : P1 →ᵃ[k] P2) {x y : P1} (h : x = y) : f x = f y := congr_arg _ h protected lemma congr_fun {f g : P1 →ᵃ[k] P2} (h : f = g) (x : P1) : f x = g x := h ▸ rfl variables (k P1) /-- Constant function as an `affine_map`. -/ def const (p : P2) : P1 →ᵃ[k] P2 := { to_fun := function.const P1 p, linear := 0, map_vadd' := λ p v, by simp } @[simp] lemma coe_const (p : P2) : ⇑(const k P1 p) = function.const P1 p := rfl @[simp] lemma const_linear (p : P2) : (const k P1 p).linear = 0 := rfl variables {k P1} instance nonempty : nonempty (P1 →ᵃ[k] P2) := (add_torsor.nonempty : nonempty P2).elim $ λ p, ⟨const k P1 p⟩ /-- Construct an affine map by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/ def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) : P1 →ᵃ[k] P2 := { to_fun := f, linear := f', map_vadd' := λ p' v, by rw [h, h p', vadd_vsub_assoc, f'.map_add, vadd_vadd] } @[simp] lemma coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f := rfl @[simp] lemma mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' := rfl /-- The set of affine maps to a vector space is an additive commutative group. -/ instance : add_comm_group (P1 →ᵃ[k] V2) := { zero := ⟨0, 0, λ p v, (zero_vadd _ _).symm⟩, add := λ f g, ⟨f + g, f.linear + g.linear, λ p v, by simp [add_add_add_comm]⟩, neg := λ f, ⟨-f, -f.linear, λ p v, by simp [add_comm]⟩, add_assoc := λ f₁ f₂ f₃, ext $ λ p, add_assoc _ _ _, zero_add := λ f, ext $ λ p, zero_add (f p), add_zero := λ f, ext $ λ p, add_zero (f p), add_comm := λ f g, ext $ λ p, add_comm (f p) (g p), add_left_neg := λ f, ext $ λ p, add_left_neg (f p) } @[simp, norm_cast] lemma coe_zero : ⇑(0 : P1 →ᵃ[k] V2) = 0 := rfl @[simp] lemma zero_linear : (0 : P1 →ᵃ[k] V2).linear = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : P1 →ᵃ[k] V2) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : P1 →ᵃ[k] V2) : ⇑(-f) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : P1 →ᵃ[k] V2) : ⇑(f - g) = f - g := by simp [sub_eq_add_neg] @[simp] lemma add_linear (f g : P1 →ᵃ[k] V2) : (f + g).linear = f.linear + g.linear := rfl /-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine maps from `P1` to the vector space `V2` corresponding to `P2`. -/ instance : affine_space (P1 →ᵃ[k] V2) (P1 →ᵃ[k] P2) := { vadd := λ f g, ⟨λ p, f p +ᵥ g p, f.linear + g.linear, λ p v, by simp [vadd_vadd, add_right_comm]⟩, zero_vadd := λ f, ext $ λ p, zero_vadd _ (f p), add_vadd := λ f₁ f₂ f₃, ext $ λ p, add_vadd (f₁ p) (f₂ p) (f₃ p), vsub := λ f g, ⟨λ p, f p -ᵥ g p, f.linear - g.linear, λ p v, by simp [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, sub_add_eq_add_sub]⟩, vsub_vadd' := λ f g, ext $ λ p, vsub_vadd (f p) (g p), vadd_vsub' := λ f g, ext $ λ p, vadd_vsub (f p) (g p) } @[simp] lemma vadd_apply (f : P1 →ᵃ[k] V2) (g : P1 →ᵃ[k] P2) (p : P1) : (f +ᵥ g) p = f p +ᵥ g p := rfl @[simp] lemma vsub_apply (f g : P1 →ᵃ[k] P2) (p : P1) : (f -ᵥ g : P1 →ᵃ[k] V2) p = f p -ᵥ g p := rfl /-- `prod.fst` as an `affine_map`. -/ def fst : (P1 × P2) →ᵃ[k] P1 := { to_fun := prod.fst, linear := linear_map.fst k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_fst : ⇑(fst : (P1 × P2) →ᵃ[k] P1) = prod.fst := rfl @[simp] lemma fst_linear : (fst : (P1 × P2) →ᵃ[k] P1).linear = linear_map.fst k V1 V2 := rfl /-- `prod.snd` as an `affine_map`. -/ def snd : (P1 × P2) →ᵃ[k] P2 := { to_fun := prod.snd, linear := linear_map.snd k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_snd : ⇑(snd : (P1 × P2) →ᵃ[k] P2) = prod.snd := rfl @[simp] lemma snd_linear : (snd : (P1 × P2) →ᵃ[k] P2).linear = linear_map.snd k V1 V2 := rfl variables (k P1) omit V2 /-- Identity map as an affine map. -/ def id : P1 →ᵃ[k] P1 := { to_fun := id, linear := linear_map.id, map_vadd' := λ p v, rfl } /-- The identity affine map acts as the identity. -/ @[simp] lemma coe_id : ⇑(id k P1) = _root_.id := rfl @[simp] lemma id_linear : (id k P1).linear = linear_map.id := rfl variable {P1} /-- The identity affine map acts as the identity. -/ lemma id_apply (p : P1) : id k P1 p = p := rfl variables {k P1} instance : inhabited (P1 →ᵃ[k] P1) := ⟨id k P1⟩ include V2 V3 /-- Composition of affine maps. -/ def comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : P1 →ᵃ[k] P3 := { to_fun := f ∘ g, linear := f.linear.comp g.linear, map_vadd' := begin intros p v, rw [function.comp_app, g.map_vadd, f.map_vadd], refl end } /-- Composition of affine maps acts as applying the two functions. -/ @[simp] lemma coe_comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : ⇑(f.comp g) = f ∘ g := rfl /-- Composition of affine maps acts as applying the two functions. -/ lemma comp_apply (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) (p : P1) : f.comp g p = f (g p) := rfl omit V3 @[simp] lemma comp_id (f : P1 →ᵃ[k] P2) : f.comp (id k P1) = f := ext $ λ p, rfl @[simp] lemma id_comp (f : P1 →ᵃ[k] P2) : (id k P2).comp f = f := ext $ λ p, rfl include V3 V4 lemma comp_assoc (f₃₄ : P3 →ᵃ[k] P4) (f₂₃ : P2 →ᵃ[k] P3) (f₁₂ : P1 →ᵃ[k] P2) : (f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) := rfl omit V2 V3 V4 instance : monoid (P1 →ᵃ[k] P1) := { one := id k P1, mul := comp, one_mul := id_comp, mul_one := comp_id, mul_assoc := comp_assoc } @[simp] lemma coe_mul (f g : P1 →ᵃ[k] P1) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : P1 →ᵃ[k] P1) = _root_.id := rfl include V2 @[simp] lemma injective_iff_linear_injective (f : P1 →ᵃ[k] P2) : function.injective f.linear ↔ function.injective f := begin obtain ⟨p⟩ := (infer_instance : nonempty P1), have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p), { ext v, simp [f.map_vadd, vadd_vsub_assoc], }, rw [h, equiv.comp_injective, equiv.injective_comp], end @[simp] lemma surjective_iff_linear_surjective (f : P1 →ᵃ[k] P2) : function.surjective f.linear ↔ function.surjective f := begin obtain ⟨p⟩ := (infer_instance : nonempty P1), have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p), { ext v, simp [f.map_vadd, vadd_vsub_assoc], }, rw [h, equiv.comp_surjective, equiv.surjective_comp], end lemma image_vsub_image {s t : set P1} (f : P1 →ᵃ[k] P2) : (f '' s) -ᵥ (f '' t) = f.linear '' (s -ᵥ t) := begin ext v, simp only [set.mem_vsub, set.mem_image, exists_exists_and_eq_and, exists_and_distrib_left, ← f.linear_map_vsub], split, { rintros ⟨x, hx, y, hy, hv⟩, exact ⟨x -ᵥ y, ⟨x, hx, y, hy, rfl⟩, hv⟩, }, { rintros ⟨-, ⟨x, hx, y, hy, rfl⟩, rfl⟩, exact ⟨x, hx, y, hy, rfl⟩, }, end omit V2 /-! ### Definition of `affine_map.line_map` and lemmas about it -/ /-- The affine map from `k` to `P1` sending `0` to `p₀` and `1` to `p₁`. -/ def line_map (p₀ p₁ : P1) : k →ᵃ[k] P1 := ((linear_map.id : k →ₗ[k] k).smul_right (p₁ -ᵥ p₀)).to_affine_map +ᵥ const k k p₀ lemma coe_line_map (p₀ p₁ : P1) : (line_map p₀ p₁ : k → P1) = λ c, c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c = c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply_module' (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = c • (p₁ - p₀) + p₀ := rfl lemma line_map_apply_module (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = (1 - c) • p₀ + c • p₁ := by simp [line_map_apply_module', smul_sub, sub_smul]; abel omit V1 lemma line_map_apply_ring' (a b c : k) : line_map a b c = c * (b - a) + a := rfl lemma line_map_apply_ring (a b c : k) : line_map a b c = (1 - c) * a + c * b := line_map_apply_module a b c include V1 lemma line_map_vadd_apply (p : P1) (v : V1) (c : k) : line_map p (v +ᵥ p) c = c • v +ᵥ p := by rw [line_map_apply, vadd_vsub] @[simp] lemma line_map_linear (p₀ p₁ : P1) : (line_map p₀ p₁ : k →ᵃ[k] P1).linear = linear_map.id.smul_right (p₁ -ᵥ p₀) := add_zero _ lemma line_map_same_apply (p : P1) (c : k) : line_map p p c = p := by simp [line_map_apply] @[simp] lemma line_map_same (p : P1) : line_map p p = const k k p := ext $ line_map_same_apply p @[simp] lemma line_map_apply_zero (p₀ p₁ : P1) : line_map p₀ p₁ (0:k) = p₀ := by simp [line_map_apply] @[simp] lemma line_map_apply_one (p₀ p₁ : P1) : line_map p₀ p₁ (1:k) = p₁ := by simp [line_map_apply] include V2 @[simp] lemma apply_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) (c : k) : f (line_map p₀ p₁ c) = line_map (f p₀) (f p₁) c := by simp [line_map_apply] @[simp] lemma comp_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) : f.comp (line_map p₀ p₁) = line_map (f p₀) (f p₁) := ext $ f.apply_line_map p₀ p₁ @[simp] lemma fst_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).1 = line_map p₀.1 p₁.1 c := fst.apply_line_map p₀ p₁ c @[simp] lemma snd_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).2 = line_map p₀.2 p₁.2 c := snd.apply_line_map p₀ p₁ c omit V2 lemma line_map_symm (p₀ p₁ : P1) : line_map p₀ p₁ = (line_map p₁ p₀).comp (line_map (1:k) (0:k)) := by { rw [comp_line_map], simp } lemma line_map_apply_one_sub (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ (1 - c) = line_map p₁ p₀ c := by { rw [line_map_symm p₀, comp_apply], congr, simp [line_map_apply] } @[simp] lemma line_map_vsub_left (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₀ = c • (p₁ -ᵥ p₀) := vadd_vsub _ _ @[simp] lemma left_vsub_line_map (p₀ p₁ : P1) (c : k) : p₀ -ᵥ line_map p₀ p₁ c = c • (p₀ -ᵥ p₁) := by rw [← neg_vsub_eq_vsub_rev, line_map_vsub_left, ← smul_neg, neg_vsub_eq_vsub_rev] @[simp] lemma line_map_vsub_right (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₁ = (1 - c) • (p₀ -ᵥ p₁) := by rw [← line_map_apply_one_sub, line_map_vsub_left] @[simp] lemma right_vsub_line_map (p₀ p₁ : P1) (c : k) : p₁ -ᵥ line_map p₀ p₁ c = (1 - c) • (p₁ -ᵥ p₀) := by rw [← line_map_apply_one_sub, left_vsub_line_map] lemma line_map_vadd_line_map (v₁ v₂ : V1) (p₁ p₂ : P1) (c : k) : line_map v₁ v₂ c +ᵥ line_map p₁ p₂ c = line_map (v₁ +ᵥ p₁) (v₂ +ᵥ p₂) c := ((fst : V1 × P1 →ᵃ[k] V1) +ᵥ snd).apply_line_map (v₁, p₁) (v₂, p₂) c lemma line_map_vsub_line_map (p₁ p₂ p₃ p₄ : P1) (c : k) : line_map p₁ p₂ c -ᵥ line_map p₃ p₄ c = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₄) c := -- Why Lean fails to find this instance without a hint? by letI : affine_space (V1 × V1) (P1 × P1) := prod.add_torsor; exact ((fst : P1 × P1 →ᵃ[k] P1) -ᵥ (snd : P1 × P1 →ᵃ[k] P1)).apply_line_map (_, _) (_, _) c /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp (f : V1 →ᵃ[k] V2) : (f : V1 → V2) = f.linear + (λ z, f 0) := begin ext x, calc f x = f.linear x +ᵥ f 0 : by simp [← f.map_vadd] ... = (f.linear.to_fun + λ (z : V1), f 0) x : by simp end /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp' (f : V1 →ᵃ[k] V2) : (f.linear : V1 → V2) = f - (λ z, f 0) := by rw decomp ; simp only [linear_map.map_zero, pi.add_apply, add_sub_cancel, zero_add] omit V1 lemma image_interval {k : Type*} [linear_ordered_field k] (f : k →ᵃ[k] k) (a b : k) : f '' set.interval a b = set.interval (f a) (f b) := begin have : ⇑f = (λ x, x + f 0) ∘ λ x, x * (f 1 - f 0), { ext x, change f x = x • (f 1 -ᵥ f 0) +ᵥ f 0, rw [← f.linear_map_vsub, ← f.linear.map_smul, ← f.map_vadd], simp only [vsub_eq_sub, add_zero, mul_one, vadd_eq_add, sub_zero, smul_eq_mul] }, rw [this, set.image_comp], simp only [set.image_add_const_interval, set.image_mul_const_interval] end section variables {ι : Type*} {V : Π i : ι, Type*} {P : Π i : ι, Type*} [Π i, add_comm_group (V i)] [Π i, module k (V i)] [Π i, add_torsor (V i) (P i)] include V /-- Evaluation at a point as an affine map. -/ def proj (i : ι) : (Π i : ι, P i) →ᵃ[k] P i := { to_fun := λ f, f i, linear := @linear_map.proj k ι _ V _ _ i, map_vadd' := λ p v, rfl } @[simp] lemma proj_apply (i : ι) (f : Π i, P i) : @proj k _ ι V P _ _ _ i f = f i := rfl @[simp] lemma proj_linear (i : ι) : (@proj k _ ι V P _ _ _ i).linear = @linear_map.proj k ι _ V _ _ i := rfl lemma pi_line_map_apply (f g : Π i, P i) (c : k) (i : ι) : line_map f g c i = line_map (f i) (g i) c := (proj i : (Π i, P i) →ᵃ[k] P i).apply_line_map f g c end end affine_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} [comm_ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] include V1 /-- If `k` is a commutative ring, then the set of affine maps with codomain in a `k`-module is a `k`-module. -/ instance : module k (P1 →ᵃ[k] V2) := { smul := λ c f, ⟨c • f, c • f.linear, λ p v, by simp [smul_add]⟩, one_smul := λ f, ext $ λ p, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ p, mul_smul _ _ _, smul_add := λ c f g, ext $ λ p, smul_add _ _ _, smul_zero := λ c, ext $ λ p, smul_zero _, add_smul := λ c₁ c₂ f, ext $ λ p, add_smul _ _ _, zero_smul := λ f, ext $ λ p, zero_smul _ _ } @[simp] lemma coe_smul (c : k) (f : P1 →ᵃ[k] V2) : ⇑(c • f) = c • f := rfl /-- `homothety c r` is the homothety (also known as dilation) about `c` with scale factor `r`. -/ def homothety (c : P1) (r : k) : P1 →ᵃ[k] P1 := r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c lemma homothety_def (c : P1) (r : k) : homothety c r = r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c := rfl lemma homothety_apply (c : P1) (r : k) (p : P1) : homothety c r p = r • (p -ᵥ c : V1) +ᵥ c := rfl lemma homothety_eq_line_map (c : P1) (r : k) (p : P1) : homothety c r p = line_map c p r := rfl @[simp] lemma homothety_one (c : P1) : homothety c (1:k) = id k P1 := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_apply_same (c : P1) (r : k) : homothety c r c = c := line_map_same_apply c r lemma homothety_mul (c : P1) (r₁ r₂ : k) : homothety c (r₁ * r₂) = (homothety c r₁).comp (homothety c r₂) := by { ext p, simp [homothety_apply, mul_smul] } @[simp] lemma homothety_zero (c : P1) : homothety c (0:k) = const k P1 c := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_add (c : P1) (r₁ r₂ : k) : homothety c (r₁ + r₂) = r₁ • (id k P1 -ᵥ const k P1 c) +ᵥ homothety c r₂ := by simp only [homothety_def, add_smul, vadd_vadd] /-- `homothety` as a multiplicative monoid homomorphism. -/ def homothety_hom (c : P1) : k →* P1 →ᵃ[k] P1 := ⟨homothety c, homothety_one c, homothety_mul c⟩ @[simp] lemma coe_homothety_hom (c : P1) : ⇑(homothety_hom c : k →* _) = homothety c := rfl /-- `homothety` as an affine map. -/ def homothety_affine (c : P1) : k →ᵃ[k] (P1 →ᵃ[k] P1) := ⟨homothety c, (linear_map.lsmul k _).flip (id k P1 -ᵥ const k P1 c), function.swap (homothety_add c)⟩ @[simp] lemma coe_homothety_affine (c : P1) : ⇑(homothety_affine c : k →ᵃ[k] _) = homothety c := rfl end affine_map
5891a494917ae6841d68742b05ee94524905f8f7
82e44445c70db0f03e30d7be725775f122d72f3e
/src/category_theory/opposites.lean
69d308c5b79840935dc9645f31f742994e7bd670
[ "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
15,116
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison -/ import category_theory.types import category_theory.equivalence universes v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes]. open opposite variables {C : Type u₁} section quiver variables [quiver.{v₁} C] lemma quiver.hom.op_inj {X Y : C} : function.injective (quiver.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) := λ _ _ H, congr_arg quiver.hom.unop H lemma quiver.hom.unop_inj {X Y : Cᵒᵖ} : function.injective (quiver.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) := λ _ _ H, congr_arg quiver.hom.op H @[simp] lemma quiver.hom.unop_op {X Y : C} (f : X ⟶ Y) : f.op.unop = f := rfl @[simp] lemma quiver.hom.op_unop {X Y : Cᵒᵖ} (f : X ⟶ Y) : f.unop.op = f := rfl end quiver namespace category_theory variables [category.{v₁} C] /-- The opposite category. See https://stacks.math.columbia.edu/tag/001M. -/ instance category.opposite : category.{v₁} Cᵒᵖ := { comp := λ _ _ _ f g, (g.unop ≫ f.unop).op, id := λ X, (𝟙 (unop X)).op } @[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).op = g.op ≫ f.op := rfl @[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl @[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).unop = g.unop ≫ f.unop := rfl @[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl @[simp] lemma unop_id_op {X : C} : (𝟙 (op X)).unop = 𝟙 X := rfl @[simp] lemma op_id_unop {X : Cᵒᵖ} : (𝟙 (unop X)).op = 𝟙 X := rfl section variables (C) /-- The functor from the double-opposite of a category to the underlying category. -/ @[simps] def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C := { obj := λ X, unop (unop X), map := λ X Y f, f.unop.unop } /-- The functor from a category to its double-opposite. -/ @[simps] def unop_unop : C ⥤ Cᵒᵖᵒᵖ := { obj := λ X, op (op X), map := λ X Y f, f.op.op } /-- The double opposite category is equivalent to the original. -/ @[simps] def op_op_equivalence : Cᵒᵖᵒᵖ ≌ C := { functor := op_op C, inverse := unop_unop C, unit_iso := iso.refl (𝟭 Cᵒᵖᵒᵖ), counit_iso := iso.refl (unop_unop C ⋙ op_op C) } end /-- If `f.op` is an isomorphism `f` must be too. (This cannot be an instance as it would immediately loop!) -/ lemma is_iso_of_op {X Y : C} (f : X ⟶ Y) [is_iso f.op] : is_iso f := ⟨⟨(inv (f.op)).unop, ⟨quiver.hom.op_inj (by simp), quiver.hom.op_inj (by simp)⟩⟩⟩ namespace functor section variables {D : Type u₂} [category.{v₂} D] variables {C D} /-- The opposite of a functor, i.e. considering a functor `F : C ⥤ D` as a functor `Cᵒᵖ ⥤ Dᵒᵖ`. In informal mathematics no distinction is made between these. -/ @[simps] protected def op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (unop X)), map := λ X Y f, (F.map f.unop).op } /-- Given a functor `F : Cᵒᵖ ⥤ Dᵒᵖ` we can take the "unopposite" functor `F : C ⥤ D`. In informal mathematics no distinction is made between these. -/ @[simps] protected def unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D := { obj := λ X, unop (F.obj (op X)), map := λ X Y f, (F.map f.op).unop } /-- The isomorphism between `F.op.unop` and `F`. -/ @[simps] def op_unop_iso (F : C ⥤ D) : F.op.unop ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) /-- The isomorphism between `F.unop.op` and `F`. -/ @[simps] def unop_op_iso (F : Cᵒᵖ ⥤ Dᵒᵖ) : F.unop.op ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) variables (C D) /-- Taking the opposite of a functor is functorial. -/ @[simps] def op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) := { obj := λ F, (unop F).op, map := λ F G α, { app := λ X, (α.unop.app (unop X)).op, naturality' := λ X Y f, quiver.hom.unop_inj (α.unop.naturality f.unop).symm } } /-- Take the "unopposite" of a functor is functorial. -/ @[simps] def op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ := { obj := λ F, op F.unop, map := λ F G α, quiver.hom.op { app := λ X, (α.app (op X)).unop, naturality' := λ X Y f, quiver.hom.op_inj $ (α.naturality f.op).symm } } variables {C D} /-- Another variant of the opposite of functor, turning a functor `C ⥤ Dᵒᵖ` into a functor `Cᵒᵖ ⥤ D`. In informal mathematics no distinction is made. -/ @[simps] protected def left_op (F : C ⥤ Dᵒᵖ) : Cᵒᵖ ⥤ D := { obj := λ X, unop (F.obj (unop X)), map := λ X Y f, (F.map f.unop).unop } /-- Another variant of the opposite of functor, turning a functor `Cᵒᵖ ⥤ D` into a functor `C ⥤ Dᵒᵖ`. In informal mathematics no distinction is made. -/ @[simps] protected def right_op (F : Cᵒᵖ ⥤ D) : C ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (op X)), map := λ X Y f, (F.map f.op).op } instance {F : C ⥤ D} [full F] : full F.op := { preimage := λ X Y f, (F.preimage f.unop).op } instance {F : C ⥤ D} [faithful F] : faithful F.op := { map_injective' := λ X Y f g h, quiver.hom.unop_inj $ by simpa using map_injective F (quiver.hom.op_inj h) } /-- If F is faithful then the right_op of F is also faithful. -/ instance right_op_faithful {F : Cᵒᵖ ⥤ D} [faithful F] : faithful F.right_op := { map_injective' := λ X Y f g h, quiver.hom.op_inj (map_injective F (quiver.hom.op_inj h)) } /-- If F is faithful then the left_op of F is also faithful. -/ instance left_op_faithful {F : C ⥤ Dᵒᵖ} [faithful F] : faithful F.left_op := { map_injective' := λ X Y f g h, quiver.hom.unop_inj (map_injective F (quiver.hom.unop_inj h)) } /-- The isomorphism between `F.left_op.right_op` and `F`. -/ @[simps] def left_op_right_op_iso (F : C ⥤ Dᵒᵖ) : F.left_op.right_op ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) /-- The isomorphism between `F.right_op.left_op` and `F`. -/ @[simps] def right_op_left_op_iso (F : Cᵒᵖ ⥤ D) : F.right_op.left_op ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) end end functor namespace nat_trans variables {D : Type u₂} [category.{v₂} D] section variables {F G : C ⥤ D} /-- The opposite of a natural transformation. -/ @[simps] protected def op (α : F ⟶ G) : G.op ⟶ F.op := { app := λ X, (α.app (unop X)).op, naturality' := begin tidy, simp_rw [← op_comp, α.naturality] end } @[simp] lemma op_id (F : C ⥤ D) : nat_trans.op (𝟙 F) = 𝟙 (F.op) := rfl /-- The "unopposite" of a natural transformation. -/ @[simps] protected def unop {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ⟶ G) : G.unop ⟶ F.unop := { app := λ X, (α.app (op X)).unop, naturality' := begin tidy, simp_rw [← unop_comp, α.naturality] end } @[simp] lemma unop_id (F : Cᵒᵖ ⥤ Dᵒᵖ) : nat_trans.unop (𝟙 F) = 𝟙 (F.unop) := rfl /-- Given a natural transformation `α : F.op ⟶ G.op`, we can take the "unopposite" of each component obtaining a natural transformation `G ⟶ F`. -/ @[simps] protected def remove_op (α : F.op ⟶ G.op) : G ⟶ F := { app := λ X, (α.app (op X)).unop, naturality' := begin intros X Y f, have := congr_arg quiver.hom.unop (α.naturality f.op), dsimp at this, rw this, end } @[simp] lemma remove_op_id (F : C ⥤ D) : nat_trans.remove_op (𝟙 F.op) = 𝟙 F := rfl end section variables {F G H : C ⥤ Dᵒᵖ} /-- Given a natural transformation `α : F ⟶ G`, for `F G : C ⥤ Dᵒᵖ`, taking `unop` of each component gives a natural transformation `G.left_op ⟶ F.left_op`. -/ @[simps] protected def left_op (α : F ⟶ G) : G.left_op ⟶ F.left_op := { app := λ X, (α.app (unop X)).unop, naturality' := begin intros X Y f, dsimp, simp_rw [← unop_comp, α.naturality] end } @[simp] lemma left_op_id : (𝟙 F : F ⟶ F).left_op = 𝟙 F.left_op := rfl @[simp] lemma left_op_comp (α : F ⟶ G) (β : G ⟶ H) : (α ≫ β).left_op = β.left_op ≫ α.left_op := rfl /-- Given a natural transformation `α : F.left_op ⟶ G.left_op`, for `F G : C ⥤ Dᵒᵖ`, taking `op` of each component gives a natural transformation `G ⟶ F`. -/ @[simps] protected def remove_left_op (α : F.left_op ⟶ G.left_op) : G ⟶ F := { app := λ X, (α.app (op X)).op, naturality' := begin intros X Y f, have := congr_arg quiver.hom.op (α.naturality f.op), dsimp at this, erw this end } end section variables {F G H : Cᵒᵖ ⥤ D} /-- Given a natural transformation `α : F ⟶ G`, for `F G : Cᵒᵖ ⥤ D`, taking `op` of each component gives a natural transformation `G.right_op ⟶ F.right_op`. -/ @[simps] protected def right_op (α : F ⟶ G) : G.right_op ⟶ F.right_op := { app := λ X, (α.app _).op, naturality' := begin intros X Y f, dsimp, simp_rw [← op_comp, α.naturality] end } @[simp] lemma right_op_id : (𝟙 F : F ⟶ F).right_op = 𝟙 F.right_op := rfl @[simp] lemma right_op_comp (α : F ⟶ G) (β : G ⟶ H) : (α ≫ β).right_op = β.right_op ≫ α.right_op := rfl /-- Given a natural transformation `α : F.right_op ⟶ G.right_op`, for `F G : Cᵒᵖ ⥤ D`, taking `unop` of each component gives a natural transformation `G ⟶ F`. -/ @[simps] protected def remove_right_op (α : F.right_op ⟶ G.right_op) : G ⟶ F := { app := λ X, (α.app X.unop).unop, naturality' := begin intros X Y f, have := congr_arg quiver.hom.unop (α.naturality f.unop), dsimp at this, erw this, end } end end nat_trans namespace iso variables {X Y : C} /-- The opposite isomorphism. -/ @[simps] protected def op (α : X ≅ Y) : op Y ≅ op X := { hom := α.hom.op, inv := α.inv.op, hom_inv_id' := quiver.hom.unop_inj α.inv_hom_id, inv_hom_id' := quiver.hom.unop_inj α.hom_inv_id } /-- The isomorphism obtained from an isomorphism in the opposite category. -/ @[simps] def unop {X Y : Cᵒᵖ} (f : X ≅ Y) : Y.unop ≅ X.unop := { hom := f.hom.unop, inv := f.inv.unop, hom_inv_id' := by simp only [← unop_comp, f.inv_hom_id, unop_id], inv_hom_id' := by simp only [← unop_comp, f.hom_inv_id, unop_id] } @[simp] lemma unop_op {X Y : Cᵒᵖ} (f : X ≅ Y) : f.unop.op = f := by ext; refl @[simp] lemma op_unop {X Y : C} (f : X ≅ Y) : f.op.unop = f := by ext; refl end iso namespace nat_iso variables {D : Type u₂} [category.{v₂} D] variables {F G : C ⥤ D} /-- The natural isomorphism between opposite functors `G.op ≅ F.op` induced by a natural isomorphism between the original functors `F ≅ G`. -/ @[simps] protected def op (α : F ≅ G) : G.op ≅ F.op := { hom := nat_trans.op α.hom, inv := nat_trans.op α.inv, hom_inv_id' := begin ext, dsimp, rw ←op_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←op_comp, rw α.hom_inv_id_app, refl, end } /-- The natural isomorphism between functors `G ≅ F` induced by a natural isomorphism between the opposite functors `F.op ≅ G.op`. -/ @[simps] protected def remove_op (α : F.op ≅ G.op) : G ≅ F := { hom := nat_trans.remove_op α.hom, inv := nat_trans.remove_op α.inv, hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw α.hom_inv_id_app, refl, end } /-- The natural isomorphism between functors `G.unop ≅ F.unop` induced by a natural isomorphism between the original functors `F ≅ G`. -/ @[simps] protected def unop {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ≅ G) : G.unop ≅ F.unop := { hom := nat_trans.unop α.hom, inv := nat_trans.unop α.inv, hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw α.hom_inv_id_app, refl, end } end nat_iso namespace equivalence variables {D : Type u₂} [category.{v₂} D] /-- An equivalence between categories gives an equivalence between the opposite categories. -/ @[simps] def op (e : C ≌ D) : Cᵒᵖ ≌ Dᵒᵖ := { functor := e.functor.op, inverse := e.inverse.op, unit_iso := (nat_iso.op e.unit_iso).symm, counit_iso := (nat_iso.op e.counit_iso).symm, functor_unit_iso_comp' := λ X, by { apply quiver.hom.unop_inj, dsimp, simp, }, } /-- An equivalence between opposite categories gives an equivalence between the original categories. -/ @[simps] def unop (e : Cᵒᵖ ≌ Dᵒᵖ) : C ≌ D := { functor := e.functor.unop, inverse := e.inverse.unop, unit_iso := (nat_iso.unop e.unit_iso).symm, counit_iso := (nat_iso.unop e.counit_iso).symm, functor_unit_iso_comp' := λ X, by { apply quiver.hom.op_inj, dsimp, simp, }, } end equivalence /-- The equivalence between arrows of the form `A ⟶ B` and `B.unop ⟶ A.unop`. Useful for building adjunctions. Note that this (definitionally) gives variants ``` def op_equiv' (A : C) (B : Cᵒᵖ) : (opposite.op A ⟶ B) ≃ (B.unop ⟶ A) := op_equiv _ _ def op_equiv'' (A : Cᵒᵖ) (B : C) : (A ⟶ opposite.op B) ≃ (B ⟶ A.unop) := op_equiv _ _ def op_equiv''' (A B : C) : (opposite.op A ⟶ opposite.op B) ≃ (B ⟶ A) := op_equiv _ _ ``` -/ @[simps] def op_equiv (A B : Cᵒᵖ) : (A ⟶ B) ≃ (B.unop ⟶ A.unop) := { to_fun := λ f, f.unop, inv_fun := λ g, g.op, left_inv := λ _, rfl, right_inv := λ _, rfl } instance subsingleton_of_unop (A B : Cᵒᵖ) [subsingleton (unop B ⟶ unop A)] : subsingleton (A ⟶ B) := (op_equiv A B).subsingleton instance decidable_eq_of_unop (A B : Cᵒᵖ) [decidable_eq (unop B ⟶ unop A)] : decidable_eq (A ⟶ B) := (op_equiv A B).decidable_eq universes v variables {α : Type v} [preorder α] /-- Construct a morphism in the opposite of a preorder category from an inequality. -/ def op_hom_of_le {U V : αᵒᵖ} (h : unop V ≤ unop U) : U ⟶ V := h.hom.op lemma le_of_op_hom {U V : αᵒᵖ} (h : U ⟶ V) : unop V ≤ unop U := h.unop.le namespace functor variables (C) variables (D : Type u₂) [category.{v₂} D] /-- The equivalence of functor categories induced by `op` and `unop`. -/ @[simps] def op_unop_equiv : (C ⥤ D)ᵒᵖ ≌ Cᵒᵖ ⥤ Dᵒᵖ := { functor := op_hom _ _, inverse := op_inv _ _, unit_iso := nat_iso.of_components (λ F, F.unop.op_unop_iso.op) begin intros F G f, dsimp [op_unop_iso], rw [(show f = f.unop.op, by simp), ← op_comp, ← op_comp], congr' 1, tidy, end, counit_iso := nat_iso.of_components (λ F, F.unop_op_iso) (by tidy) }. /-- The equivalence of functor categories induced by `left_op` and `right_op`. -/ @[simps] def left_op_right_op_equiv : (Cᵒᵖ ⥤ D)ᵒᵖ ≌ (C ⥤ Dᵒᵖ) := { functor := { obj := λ F, F.unop.right_op, map := λ F G η, η.unop.right_op }, inverse := { obj := λ F, op F.left_op, map := λ F G η, η.left_op.op }, unit_iso := nat_iso.of_components (λ F, F.unop.right_op_left_op_iso.op) begin intros F G η, dsimp, rw [(show η = η.unop.op, by simp), ← op_comp, ← op_comp], congr' 1, tidy, end, counit_iso := nat_iso.of_components (λ F, F.left_op_right_op_iso) (by tidy) } end functor end category_theory
7dbc6b7d9c65049cba7cf283007bc08229d15d47
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/cc1.lean
a1391cdd24a615932d2fc7809d1443545a694b8d
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
2,150
lean
open tactic set_option pp.implicit true example (a b c d : nat) (f : nat → nat → nat) : a = b → b = c → d + (if b > 0 then a else b) = 0 → f (b + b) b ≠ f (a + c) c → false := by do intros, s ← cc_state.mk_using_hs, s^.pp >>= trace, t₁ ← to_expr `(f (b + b) b), t₂ ← to_expr `(f (a + c) c), b ← to_expr `(b), d ← to_expr `(d), guard (s^.inconsistent), guard (s^.eqc_size b = 3), guard (not (s^.in_singlenton_eqc b)), guard (s^.in_singlenton_eqc d), trace ">>> Equivalence roots", trace s^.roots, trace ">>> b's equivalence class", trace (s^.eqc_of b), pr ← s^.eqv_proof t₁ t₂, note `h pr, contradiction example (a b : nat) (f : nat → nat) : a = b → f a = f b := by cc example (a b : nat) (f : nat → nat) : a = b → f a ≠ f b → false := by cc example (a b : nat) (f : nat → nat) : a = b → f (f a) ≠ f (f b) → false := by cc example (a b c : nat) (f : nat → nat) : a = b → c = b → f (f a) ≠ f (f c) → false := by cc example (a b c : nat) (f : nat → nat → nat) : a = b → c = b → f (f a b) a ≠ f (f c c) c → false := by cc example (a b c : nat) (f : nat → nat → nat) : a = b → c = b → f (f a b) a = f (f c c) c := by cc example (a b c d : nat) : a == b → b = c → c == d → a == d := by cc example (a b c d : nat) : a = b → b = c → c == d → a == d := by cc example (a b c d : nat) : a = b → b == c → c == d → a == d := by cc example (a b c d : nat) : a == b → b == c → c = d → a == d := by cc example (a b c d : nat) : a == b → b = c → c = d → a == d := by cc example (a b c d : nat) : a = b → b = c → c = d → a == d := by cc example (a b c d : nat) : a = b → b == c → c = d → a == d := by cc constant f {α : Type} : α → α → α constant g : nat → nat example (a b c : nat) : a = b → g a == g b := by cc example (a b c : nat) : a = b → c = b → f (f a b) (g c) = f (f c a) (g b) := by cc example (a b c d e x y : nat) : a = b → a = x → b = y → c = d → c = e → c = b → a = e := by cc
4f9a46829e05c2e25f56b247eb7337f645a48b34
874a8d2247ab9a4516052498f80da2e32d0e3a48
/square_root_prime_v2.lean
bd31c1424ea006b2e07142e4dfa2b4baaa487e95
[]
no_license
AlexKontorovich/Spring2020Math492
378b36c643ee029f5ab91c1677889baa591f5e85
659108c5d864ff5c75b9b3b13b847aa5cff4348a
refs/heads/master
1,610,780,595,457
1,588,174,859,000
1,588,174,859,000
243,017,788
0
1
null
null
null
null
UTF-8
Lean
false
false
10,963
lean
import tactic import data.nat.prime import data.int.basic open classical -- HUMAN PROOF 1: --Claim: Let n > 1. If n has no positive PRIME factor less ≤ sqrt(n), then n is prime -- Proof by Contradiction: -- Suppose n is not prime. Then n has atleast two positive prime factors p1 and p2 such that -- n = p1p2*k for some positive integer k. By hypothesis p1 and p2 are > sqrt(n). Then -- n = p1p2*k ≥ p1p2 > n, and so n > n. Contradiction -- HUMAN PROOF 2: -- Claim: Let n > 1. If n has no positive PROPER factor less ≤ sqrt(n), then n is prime -- Proof my Contrapositive: -- Suppose that n is composite. Then n = a*b where a ≤ b and b < n. Hence a^2 ≤ ab = n. -- Hence a ≤ sqrt(n). --Important theorems adapted from the Natural Number Game------------------------------ theorem ge_iff_exists_add (a b: ℕ): a ≥ b ↔ ∃ (c: ℕ), a = b + c := begin apply le_iff_exists_add, -- Ok, maybe this theorem was a little bit silly :) end def greater (a b: ℕ): Prop := a ≥ b ∧ a ≠ b --axiom zero (a : ℕ): a < 1 ↔ a =0 lemma zero (a : ℕ): a < 1 ↔ a =0 := begin split, -- by library_search, exact nat.sub_eq_zero_of_le, intros h, linarith, end --axiom zero2 (a u : ℕ): u + a = u ↔ a = 0 lemma zero2 (a u : ℕ): u + a = u ↔ a = 0 := begin split, intros h, -- by library_search, exact (add_left_inj u).mp h, intros h1, -- by library_search, exact eq.trans (congr_arg (has_add.add u) h1) rfl, end theorem g_iff_exists_add (a b: ℕ): greater a b ↔ ∃ (c: ℕ), a = b + c ∧ c ≥ 1:= begin --Perhaps a little bit overkill rw greater, rw ge_iff_exists_add, rw ne_from_not_eq, split, { intro h, have h_left: ∃ (c : ℕ), a = b + c, from and.left h, have h_right: ¬a = b, from and.right h, cases h_left with u hu, use u, split, apply hu, by_contradiction, push_neg at a_1, rw zero at a_1, subst a_1, rw add_zero at hu, -- have h_right: a ≠ b, from and.right h, exact h_right hu, }, { intro h2, cases h2 with u hu, have hu_left: a = b+u, from and.left hu, split, use u, apply hu_left, by_contradiction, subst hu_left, rw zero2 at a_1, rw ← zero at a_1, have hu_right: u ≥ 1, from and.right hu, linarith, -- Thanks Olu :) } end theorem my_simp (u v a : ℕ): u*v + (a*a + u*a) = a*u + (u*v + a*a):= begin rw ← add_assoc, rw ← add_assoc, rw add_comm, simp, rw mul_comm, end ----------------------------------------------------------------------------------------- def dvd (m n: ℕ): Prop := ∃ k, n = m * k def prime (p : ℕ) : Prop := p ≥ 2 ∧ ∀ n, dvd n p → n = 1 ∨ n = p def composite (d : ℕ): Prop:= ∃ (a b: ℕ), d = a*b ∧ a ≤ b ∧ b < d lemma greater_than_not_zero (n : ℕ)(n ≥ 2): n ≠ 0:= begin exact lattice.ne_bot_of_gt H, end lemma dvd_n_less_than_n (u n : ℕ) (ha: dvd u n) (hb: u ≠ 1) (hc: u ≠ n) (hn : n ≠ 0) : u < n := begin refine lt_of_le_of_ne _ hc, rcases ha with ⟨k, rfl⟩, simpa using nat.mul_le_mul_left _ (_:1≤_), refine nat.pos_iff_ne_zero.2 (mt _ hn), rintro rfl, refl, end --- The grand unification lemma ---- lemma either_prime_or_composite (n:ℕ ) (ge: n≥ 2): (¬ (prime n) ↔ composite n) := begin split, { intros h, rw prime at h, rw composite, push_neg at h, cases h, { linarith, } , { cases h with u hu, let hu_left:= hu.1, rw dvd at hu_left, cases hu_left with k hk, have u_g_k : (u≤ k)∨ (u>k), { -- by library_search, exact le_or_lt u k, }, cases u_g_k, { use u, use k, split, exact hk, split, exact u_g_k, let hu_mid:= hu.2.1, have u_ge_1 : (u≥ 1), { by_contradiction, have u_zero: u=0, { linarith, }, have n_zero: n=0, { subst u_zero, simp at hk, exact hk, }, linarith, }, have u_ge_2 : (u≥ 2), { by_contradiction, have u_less_2 : u<2, { linarith, }, have u_eq_1: u=1, { linarith, }, -- by library_search, exact hu_mid u_eq_1, }, by_contradiction, have k_ge_n: k≥ n, { linarith, }, have uk_ge_2n: u*k≥ 2* n, { -- by library_search, exact canonically_ordered_semiring.mul_le_mul u_ge_2 k_ge_n, }, have n_ge_2n: n≥ 2*n, { linarith, }, have twon_gt_n: 2*n > n, { linarith, }, linarith, }, { use k, use u, split, rw mul_comm at hk, exact hk, split, --exact u_g_k, let hu_mid:= hu.2.1, have u_ge_1 : (u≥ 1), { by_contradiction, have u_zero: u=0, { linarith, }, have n_zero: n=0, { subst u_zero, simp at hk, exact hk, }, linarith, }, have u_ge_2 : (u≥ 2), { by_contradiction, have u_less_2 : u<2, { linarith, }, have u_eq_1: u=1, { linarith, }, -- by library_search, exact hu_mid u_eq_1, }, by_contradiction, have k_ge_n: k≥ n, { linarith, }, have uk_ge_2n: u*k≥ 2* n, { -- by library_search, exact canonically_ordered_semiring.mul_le_mul u_ge_2 k_ge_n, }, have n_ge_2n: n≥ 2*n, { linarith, }, have twon_gt_n: 2*n > n, { linarith, }, linarith, have ha: dvd u n, from and.left hu, have h2: u ≠ 1 ∧ u ≠ n, from and.right hu, have hc: u ≠ n, from and.right h2, have hb: u ≠ 1, from and.left h2, have hn: n ≠ 0, { exact lattice.ne_bot_of_gt ge, }, apply dvd_n_less_than_n, have h4: dvd u n, from and.left hu, apply h4, apply hb, apply hc, apply hn, }, } }, { intros h, rw composite at h, by_contradiction, rw prime at a, cases h with a1 ha1, cases ha1 with b hb, have h1: n = a1*b, from and.left hb, have temp: a1 ≤ b ∧ b < n, from and.right hb, have h2: a1 ≤ b, from and.left temp, have h3: b < n, from and.right temp, have hc := a.right b, have b_isnt_one: b ≠ 1, { by_contradiction, push_neg at a_1, subst a_1, rw mul_one at h1, linarith, }, have b_divides_n: dvd b n, { rw dvd, rw mul_comm at h1, use a1, rw h1, }, have b_is_trivial: b = 1 ∨ b = n, { exact hc b_divides_n, }, cases b_is_trivial, { exact b_isnt_one b_is_trivial, }, { linarith, }, }, end theorem ge_refl(x : ℕ) : x ≥ x := begin linarith, -- end theorem ge_cancel (a b : ℕ) (ha : a*b ≥ a) (hb: a ≥ 1) : b ≥ 1 := begin by library_search, --exact (le_mul_iff_one_le_right hb).mp ha, end theorem example1 (a b c :ℕ) (hba: b ≥ a) (hca: c ≥ a) : b*c ≥ a*a := begin exact canonically_ordered_semiring.mul_le_mul hba hca, -- by library_search, /- -/ end -- Adapted from the Natural Number Game--- lemma one_eq_succ_zero: 1 = nat.succ(0) := begin refl, -- OK maybe a little bit silly :) end lemma succ_eq_add_one (n : ℕ) : nat.succ n = n + 1 := begin exact rfl, -- by library_search, -- end ---------------------------------------------------------------------- lemma x_plus_stuff_plus_one_ge_x (x d : ℕ) : x + d + 1 ≥ x := -- Helps to prove my_lemma_helper begin linarith, /- -/ end lemma my_lemma_helper (x y: ℕ) : y+x ≥ x := begin linarith, /- -/ end lemma my_lemma (c x : ℕ) (hab: c >= 1): c * x >= x := begin exact nat.le_mul_of_pos_left hab, -- by library_search, /- -/ end theorem example2 (a b c : ℕ) (hba: c ≥ 1): a*b*c ≥ a*b := begin exact nat.le_mul_of_pos_right hba, -- by library_search, /- -/ end theorem example3 (a:ℕ) : ¬ a < a := begin linarith, /- -/ end lemma another_helper (u v : ℕ) : v ≤ u ↔ v*v ≤ v*u := begin cases v, { split, { intro h, simp, }, intro, linarith, -- exact zero_le u, }, { symmetry, apply mul_le_mul_left, simp, } end theorem square_root_prime2 (n : ℕ) (h1: composite n): ∃ (c d : ℕ), n = c*d ∧ c*c ≤ n := -- HUMAN PROOF 2 in Code :) begin rw composite at h1, cases h1 with v hv, cases hv with u hu, use v, use u, have hl: n = v*u, from and.left hu, rw hl, have hmr: v ≤ u ∧ u < n, from and.right hu, have hr: u < n, from and.right hmr, have hm: v ≤ u, from and.left hmr, rw another_helper at hm, split, refl, apply hm, end
c61861a80e65eff19814b0971fd0dffff618cdd1
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/measure_theory/integral/integrable_on.lean
f7c9c136d28edd16d61b3fe61ae71f0ea8d17f5f
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
20,875
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.function.l1_space import analysis.normed_space.indicator_function /-! # Functions integrable on a set and at a filter We define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like `integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`. Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite at `l`. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topological_space interval big_operators filter ennreal measure_theory variables {α β E F : Type*} [measurable_space α] section variables [topological_space β] {l l' : filter α} {f g : α → β} {μ ν : measure α} /-- A function `f` is strongly measurable at a filter `l` w.r.t. a measure `μ` if it is ae strongly measurable w.r.t. `μ.restrict s` for some `s ∈ l`. -/ def strongly_measurable_at_filter (f : α → β) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, ae_strongly_measurable f (μ.restrict s) @[simp] lemma strongly_measurable_at_bot {f : α → β} : strongly_measurable_at_filter f ⊥ μ := ⟨∅, mem_bot, by simp⟩ protected lemma strongly_measurable_at_filter.eventually (h : strongly_measurable_at_filter f l μ) : ∀ᶠ s in l.small_sets, ae_strongly_measurable f (μ.restrict s) := (eventually_small_sets' $ λ s t, ae_strongly_measurable.mono_set).2 h protected lemma strongly_measurable_at_filter.filter_mono (h : strongly_measurable_at_filter f l μ) (h' : l' ≤ l) : strongly_measurable_at_filter f l' μ := let ⟨s, hsl, hs⟩ := h in ⟨s, h' hsl, hs⟩ protected lemma measure_theory.ae_strongly_measurable.strongly_measurable_at_filter (h : ae_strongly_measurable f μ) : strongly_measurable_at_filter f l μ := ⟨univ, univ_mem, by rwa measure.restrict_univ⟩ lemma ae_strongly_measurable.strongly_measurable_at_filter_of_mem {s} (h : ae_strongly_measurable f (μ.restrict s)) (hl : s ∈ l) : strongly_measurable_at_filter f l μ := ⟨s, hl, h⟩ protected lemma measure_theory.strongly_measurable.strongly_measurable_at_filter (h : strongly_measurable f) : strongly_measurable_at_filter f l μ := h.ae_strongly_measurable.strongly_measurable_at_filter end namespace measure_theory section normed_add_comm_group lemma has_finite_integral_restrict_of_bounded [normed_add_comm_group E] {f : α → E} {s : set α} {μ : measure α} {C} (hs : μ s < ∞) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) : has_finite_integral f (μ.restrict s) := by haveI : is_finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩; exact has_finite_integral_of_bounded hf variables [normed_add_comm_group E] {f g : α → E} {s t : set α} {μ ν : measure α} /-- A function is `integrable_on` a set `s` if it is almost everywhere strongly measurable on `s` and if the integral of its pointwise norm over `s` is less than infinity. -/ def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop := integrable f (μ.restrict s) lemma integrable_on.integrable (h : integrable_on f s μ) : integrable f (μ.restrict s) := h @[simp] lemma integrable_on_empty : integrable_on f ∅ μ := by simp [integrable_on, integrable_zero_measure] @[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ := by rw [integrable_on, measure.restrict_univ] lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _ @[simp] lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ∞ := integrable_const_iff.trans $ by rw [measure.restrict_apply_univ] lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono_measure $ measure.restrict_mono hs hμ lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) : integrable_on f s μ := h.mono hst le_rfl lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono (subset.refl _) hμ lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) : integrable_on f s μ := h.integrable.mono_measure $ measure.restrict_mono_ae hst lemma integrable_on.congr_set_ae (h : integrable_on f t μ) (hst : s =ᵐ[μ] t) : integrable_on f s μ := h.mono_set_ae hst.le lemma integrable_on.congr_fun' (h : integrable_on f s μ) (hst : f =ᵐ[μ.restrict s] g) : integrable_on g s μ := integrable.congr h hst lemma integrable_on.congr_fun (h : integrable_on f s μ) (hst : eq_on f g s) (hs : measurable_set s) : integrable_on g s μ := h.congr_fun' ((ae_restrict_iff' hs).2 (eventually_of_forall hst)) lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ := h.mono_measure $ measure.restrict_le_self lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ := h lemma integrable_on.restrict (h : integrable_on f s μ) (hs : measurable_set s) : integrable_on f s (μ.restrict t) := by { rw [integrable_on, measure.restrict_restrict hs], exact h.mono_set (inter_subset_left _ _) } lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ := h.mono_set $ subset_union_left _ _ lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ := h.mono_set $ subset_union_right _ _ lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) : integrable_on f (s ∪ t) μ := (hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _ @[simp] lemma integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ := ⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩ @[simp] lemma integrable_on_singleton_iff {x : α} [measurable_singleton_class α] : integrable_on f {x} μ ↔ f x = 0 ∨ μ {x} < ∞ := begin have : f =ᵐ[μ.restrict {x}] (λ y, f x), { filter_upwards [ae_restrict_mem (measurable_set_singleton x)] with _ ha, simp only [mem_singleton_iff.1 ha], }, rw [integrable_on, integrable_congr this, integrable_const_iff], simp, end @[simp] lemma integrable_on_finite_Union {s : set β} (hs : s.finite) {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := begin apply hs.induction_on, { simp }, { intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] } end @[simp] lemma integrable_on_finset_Union {s : finset β} {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := integrable_on_finite_Union s.finite_to_set @[simp] lemma integrable_on_fintype_Union [fintype β] {t : β → set α} : integrable_on f (⋃ i, t i) μ ↔ ∀ i, integrable_on f (t i) μ := by simpa using @integrable_on_finset_Union _ _ _ _ _ f μ finset.univ t lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) : integrable_on f s (μ + ν) := by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν } @[simp] lemma integrable_on_add_measure : integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right le_rfl), h.mono_measure (measure.le_add_left le_rfl)⟩, λ h, h.1.add_measure h.2⟩ lemma _root_.measurable_embedding.integrable_on_map_iff [measurable_space β] {e : α → β} (he : measurable_embedding e) {f : β → E} {μ : measure α} {s : set β} : integrable_on f s (measure.map e μ) ↔ integrable_on (f ∘ e) (e ⁻¹' s) μ := by simp only [integrable_on, he.restrict_map, he.integrable_map_iff] lemma integrable_on_map_equiv [measurable_space β] (e : α ≃ᵐ β) {f : β → E} {μ : measure α} {s : set β} : integrable_on f s (measure.map e μ) ↔ integrable_on (f ∘ e) (e ⁻¹' s) μ := by simp only [integrable_on, e.restrict_map, integrable_map_equiv e] lemma measure_preserving.integrable_on_comp_preimage [measurable_space β] {e : α → β} {ν} (h₁ : measure_preserving e μ ν) (h₂ : measurable_embedding e) {f : β → E} {s : set β} : integrable_on (f ∘ e) (e ⁻¹' s) μ ↔ integrable_on f s ν := (h₁.restrict_preimage_emb h₂ s).integrable_comp_emb h₂ lemma measure_preserving.integrable_on_image [measurable_space β] {e : α → β} {ν} (h₁ : measure_preserving e μ ν) (h₂ : measurable_embedding e) {f : β → E} {s : set α} : integrable_on f (e '' s) ν ↔ integrable_on (f ∘ e) s μ := ((h₁.restrict_image_emb h₂ s).integrable_comp_emb h₂).symm lemma integrable_indicator_iff (hs : measurable_set s) : integrable (indicator s f) μ ↔ integrable_on f s μ := by simp [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator, lintegral_indicator _ hs, ae_strongly_measurable_indicator_iff hs] lemma integrable_on.indicator (h : integrable_on f s μ) (hs : measurable_set s) : integrable (indicator s f) μ := (integrable_indicator_iff hs).2 h lemma integrable.indicator (h : integrable f μ) (hs : measurable_set s) : integrable (indicator s f) μ := h.integrable_on.indicator hs lemma integrable_indicator_const_Lp {E} [normed_add_comm_group E] {p : ℝ≥0∞} {s : set α} (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : E) : integrable (indicator_const_Lp p hs hμs c) μ := begin rw [integrable_congr indicator_const_Lp_coe_fn, integrable_indicator_iff hs, integrable_on, integrable_const_iff, lt_top_iff_ne_top], right, simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply] using hμs, end lemma integrable_on_iff_integable_of_support_subset {f : α → E} {s : set α} (h1s : support f ⊆ s) (h2s : measurable_set s) : integrable_on f s μ ↔ integrable f μ := begin refine ⟨λ h, _, λ h, h.integrable_on⟩, rwa [← indicator_eq_self.2 h1s, integrable_indicator_iff h2s] end lemma integrable_on_Lp_of_measure_ne_top {E} [normed_add_comm_group E] {p : ℝ≥0∞} {s : set α} (f : Lp E p μ) (hp : 1 ≤ p) (hμs : μ s ≠ ∞) : integrable_on f s μ := begin refine mem_ℒp_one_iff_integrable.mp _, have hμ_restrict_univ : (μ.restrict s) set.univ < ∞, by simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply, lt_top_iff_ne_top], haveI hμ_finite : is_finite_measure (μ.restrict s) := ⟨hμ_restrict_univ⟩, exact ((Lp.mem_ℒp _).restrict s).mem_ℒp_of_exponent_le hp, end /-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.small_sets`. -/ def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, integrable_on f s μ variables {l l' : filter α} protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) : ∀ᶠ s in l.small_sets, integrable_on f s μ := iff.mpr (eventually_small_sets' $ λ s t hst ht, ht.mono_set hst) h lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) : integrable_at_filter f l μ := let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩ lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) : integrable_at_filter f (l ⊓ l') μ := hl.filter_mono inf_le_left lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) : integrable_at_filter f (l' ⊓ l) μ := hl.filter_mono inf_le_right @[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} : integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, rfl⟩, hf⟩, refine ⟨t, ht, _⟩, refine hf.integrable.mono_measure (λ v hv, _), simp only [measure.restrict_apply hv], refine measure_mono_ae (mem_of_superset hu $ λ x hx, _), exact λ ⟨hv, ht⟩, ⟨hv, ⟨ht, hx⟩⟩ end alias integrable_at_filter.inf_ae_iff ↔ integrable_at_filter.of_inf_ae _ /-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded above at `l`, then `f` is integrable at `l`. -/ lemma measure.finite_at_filter.integrable_at_filter {l : filter α} [is_measurably_generated l] (hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) (hf : l.is_bounded_under (≤) (norm ∘ f)) : integrable_at_filter f l μ := begin obtain ⟨C, hC⟩ : ∃ C, ∀ᶠ s in l.small_sets, ∀ x ∈ s, ∥f x∥ ≤ C, from hf.imp (λ C hC, eventually_small_sets.2 ⟨_, hC, λ t, id⟩), rcases (hfm.eventually.and (hμ.eventually.and hC)).exists_measurable_mem_of_small_sets with ⟨s, hsl, hsm, hfm, hμ, hC⟩, refine ⟨s, hsl, ⟨hfm, has_finite_integral_restrict_of_bounded hμ _⟩⟩, exact C, rw [ae_restrict_eq hsm, eventually_inf_principal], exact eventually_of_forall hC end lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae {l : filter α} [is_measurably_generated l] (hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) : integrable_at_filter f l μ := (hμ.inf_of_left.integrable_at_filter (hfm.filter_mono inf_le_left) hf.norm.is_bounded_under_le).of_inf_ae alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ← _root_.filter.tendsto.integrable_at_filter_ae lemma measure.finite_at_filter.integrable_at_filter_of_tendsto {l : filter α} [is_measurably_generated l] (hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f l (𝓝 b)) : integrable_at_filter f l μ := hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← _root_.filter.tendsto.integrable_at_filter lemma integrable_add_of_disjoint {f g : α → E} (h : disjoint (support f) (support g)) (hf : strongly_measurable f) (hg : strongly_measurable g) : integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ := begin refine ⟨λ hfg, ⟨_, _⟩, λ h, h.1.add h.2⟩, { rw ← indicator_add_eq_left h, exact hfg.indicator hf.measurable_set_support }, { rw ← indicator_add_eq_right h, exact hfg.indicator hg.measurable_set_support } end end normed_add_comm_group end measure_theory open measure_theory variables [normed_add_comm_group E] /-- A function which is continuous on a set `s` is almost everywhere measurable with respect to `μ.restrict s`. -/ lemma continuous_on.ae_measurable [topological_space α] [opens_measurable_space α] [measurable_space β] [topological_space β] [borel_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) : ae_measurable f (μ.restrict s) := begin nontriviality α, inhabit α, have : piecewise s f (λ _, f default) =ᵐ[μ.restrict s] f := piecewise_ae_eq_restrict hs, refine ⟨piecewise s f (λ _, f default), _, this.symm⟩, apply measurable_of_is_open, assume t ht, obtain ⟨u, u_open, hu⟩ : ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := _root_.continuous_on_iff'.1 hf t ht, rw [piecewise_preimage, set.ite, hu], exact (u_open.measurable_set.inter hs).union ((measurable_const ht.measurable_set).diff hs) end /-- A function which is continuous on a separable set `s` is almost everywhere strongly measurable with respect to `μ.restrict s`. -/ lemma continuous_on.ae_strongly_measurable_of_is_separable [topological_space α] [pseudo_metrizable_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) (h's : topological_space.is_separable s) : ae_strongly_measurable f (μ.restrict s) := begin letI := pseudo_metrizable_space_pseudo_metric α, borelize β, rw ae_strongly_measurable_iff_ae_measurable_separable, refine ⟨hf.ae_measurable hs, f '' s, hf.is_separable_image h's, _⟩, exact mem_of_superset (self_mem_ae_restrict hs) (subset_preimage_image _ _), end /-- A function which is continuous on a set `s` is almost everywhere strongly measurable with respect to `μ.restrict s` when either the source space or the target space is second-countable. -/ lemma continuous_on.ae_strongly_measurable [topological_space α] [topological_space β] [h : second_countable_topology_either α β] [opens_measurable_space α] [pseudo_metrizable_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) : ae_strongly_measurable f (μ.restrict s) := begin borelize β, refine ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨hf.ae_measurable hs, f '' s, _, mem_of_superset (self_mem_ae_restrict hs) (subset_preimage_image _ _)⟩, casesI h.out, { let f' : s → β := s.restrict f, have A : continuous f' := continuous_on_iff_continuous_restrict.1 hf, have B : is_separable (univ : set s) := is_separable_of_separable_space _, convert is_separable.image B A using 1, ext x, simp }, { exact is_separable_of_separable_space _ } end lemma continuous_on.integrable_at_nhds_within_of_is_separable [topological_space α] [pseudo_metrizable_space α] [opens_measurable_space α] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t) (h't : topological_space.is_separable t) (ha : a ∈ t) : integrable_at_filter f (𝓝[t] a) μ := begin haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _, exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_strongly_measurable_of_is_separable ht h't⟩ (μ.finite_at_nhds_within _ _), end lemma continuous_on.integrable_at_nhds_within [topological_space α] [second_countable_topology_either α E] [opens_measurable_space α] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t) (ha : a ∈ t) : integrable_at_filter f (𝓝[t] a) μ := begin haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _, exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_strongly_measurable ht⟩ (μ.finite_at_nhds_within _ _), end /-- If a function is continuous on an open set `s`, then it is strongly measurable at the filter `𝓝 x` for all `x ∈ s` if either the source space or the target space is second-countable. -/ lemma continuous_on.strongly_measurable_at_filter [topological_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] [second_countable_topology_either α β] {f : α → β} {s : set α} {μ : measure α} (hs : is_open s) (hf : continuous_on f s) : ∀ x ∈ s, strongly_measurable_at_filter f (𝓝 x) μ := λ x hx, ⟨s, is_open.mem_nhds hs hx, hf.ae_strongly_measurable hs.measurable_set⟩ lemma continuous_at.strongly_measurable_at_filter [topological_space α] [opens_measurable_space α] [second_countable_topology_either α E] {f : α → E} {s : set α} {μ : measure α} (hs : is_open s) (hf : ∀ x ∈ s, continuous_at f x) : ∀ x ∈ s, strongly_measurable_at_filter f (𝓝 x) μ := continuous_on.strongly_measurable_at_filter hs $ continuous_at.continuous_on hf lemma continuous.strongly_measurable_at_filter [topological_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] [second_countable_topology_either α β] {f : α → β} (hf : continuous f) (μ : measure α) (l : filter α) : strongly_measurable_at_filter f l μ := hf.strongly_measurable.strongly_measurable_at_filter /-- If a function is continuous on a measurable set `s`, then it is measurable at the filter `𝓝[s] x` for all `x`. -/ lemma continuous_on.strongly_measurable_at_filter_nhds_within {α β : Type*} [measurable_space α] [topological_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β] [second_countable_topology_either α β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) (x : α) : strongly_measurable_at_filter f (𝓝[s] x) μ := ⟨s, self_mem_nhds_within, hf.ae_strongly_measurable hs⟩
54bb6a32e0c45cf0cd2a2211979ed003793a6f53
ae9f8bf05de0928a4374adc7d6b36af3411d3400
/src/formal_ml/ennreal.lean
1e4073da93af575b8282cb8f593f8d7c968c41e3
[ "Apache-2.0" ]
permissive
NeoTim/formal-ml
bc42cf6beba9cd2ed56c1cd054ab4eb5402ed445
c9cbad2837104160a9832a29245471468748bb8d
refs/heads/master
1,671,549,160,900
1,601,362,989,000
1,601,362,989,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,095
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import data.real.ennreal import formal_ml.nat -- ennreal is a canonically_ordered_add_monoid -- ennreal is not a decidable_linear_ordered_semiring -- Otherwise (0 < c) → (c * a) ≤ (c * b) → (a ≤ b), -- but this does not hold for c =⊤, a = 1, b = 0. -- This is because ennreal is not an ordered_cancel_add_comm_monoid. -- Nor is it an ordered_cancel_comm_monoid -- This implies it is also not an ordered_semiring lemma ennreal_coe_eq_lift {a:ennreal} {b:nnreal}:a = b → (a.to_nnreal = b) := begin intro A1, have A2:(a.to_nnreal)=(b:ennreal).to_nnreal, { rw A1, }, rw ennreal.to_nnreal_coe at A2, exact A2, end /- This is one of those complicated inequalities that is probably too rare to justify a lemma. However, since it shows up, we give it the canonical name and move on. -/ lemma ennreal_le_to_nnreal_of_ennreal_le_of_ne_top {a:nnreal} {b:ennreal}: b≠ ⊤ → (a:ennreal) ≤ b → (a ≤ b.to_nnreal) := begin intros A1 A2, cases b, { simp at A1, exfalso, apply A1, }, { have A3:(b:ennreal) = (some b) := rfl, rw ← A3, rw (@ennreal.to_nnreal_coe b), rw ← ennreal.coe_le_coe, rw A3, apply A2, } end lemma ennreal_add_monoid_smul_def{n:ℕ} {c:ennreal}: n •ℕ c = ↑(n) * c := begin induction n, { simp, }, { simp, } end lemma ennreal_lt_add_ennreal_one (x:nnreal):(x:ennreal) < (1:ennreal) + (x:ennreal) := begin apply ennreal.coe_lt_coe.mpr, simp, apply canonically_ordered_semiring.zero_lt_one, end
d906e1946c22e938b76fd69808d1562fbcd3260d
367134ba5a65885e863bdc4507601606690974c1
/src/number_theory/pell.lean
95b335a4b979017a3964ebc7ccb955957a880b6e
[ "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
39,420
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.modeq import data.zsqrtd.basic /-! # Pell's equation and Matiyasevic's theorem This file solves Pell's equation, i.e. integer solutions to `x ^ 2 - d * y ^ 2 = 1` in the special case that `d = a ^ 2 - 1`. This is then applied to prove Matiyasevic's theorem that the power function is Diophantine, which is the last key ingredient in the solution to Hilbert's tenth problem. For the definition of Diophantine function, see `dioph.lean`. ## Main definition * `pell` is a function assigning to a natural number `n` the `n`-th solution to Pell's equation constructed recursively from the intial solution `(0,1)`. ## Main statements * `eq_pell` shows that every solution to Pell's equation is recursively obtained using `pell` * `matiyasevic` shows that a certain system of Diophantine equations has a solution if and only if the first variable is the `x`-component in a solution to Pell's equation - the key step towards Hilbert's tenth problem in Davis' version of Matiyasevic's theorem. * `eq_pow_of_pell` shows that the power function is Diophantine. ## Implementation notes The proof of Matiyasevic's theorem doesn't follow Matiyasevic's original account of using Fibonacci numbers but instead Davis' variant of using solutions to Pell's equation. ## References * [M. Carneiro, _A Lean formalization of Matiyasiv's theorem_][carneiro2018matiysevic] * [M. Davis, _Hilbert's tenth problem is unsolvable_][MR317916] ## Tags Pell's equation, Matiyasevic's theorem, Hilbert's tenth problem ## TODO * Please the unused arguments linter. * Provide solutions to Pell's equation for the case of arbitrary `d` (not just `d = a ^ 2 - 1` like in the current version) and furthermore also for `x ^ 2 - d * y ^ 2 = -1`. * Connect solutions to the continued fraction expansion of `√d`. -/ namespace pell open nat section parameters {a : ℕ} (a1 : 1 < a) include a1 private def d := a*a - 1 @[simp] theorem d_pos : 0 < d := nat.sub_pos_of_lt (mul_lt_mul a1 (le_of_lt a1) dec_trivial dec_trivial : 1*1<a*a) /-- The Pell sequences, i.e. the sequence of integer solutions to `x ^ 2 - d * y ^ 2 = 1`, where `d = a ^ 2 - 1`, defined together in mutual recursion. -/ -- TODO(lint): Fix double namespace issue @[nolint dup_namespace] def pell : ℕ → ℕ × ℕ := λn, nat.rec_on n (1, 0) (λn xy, (xy.1*a + d*xy.2, xy.1 + xy.2*a)) /-- The Pell `x` sequence. -/ def xn (n : ℕ) : ℕ := (pell n).1 /-- The Pell `y` sequence. -/ def yn (n : ℕ) : ℕ := (pell n).2 @[simp] theorem pell_val (n : ℕ) : pell n = (xn n, yn n) := show pell n = ((pell n).1, (pell n).2), from match pell n with (a, b) := rfl end @[simp] theorem xn_zero : xn 0 = 1 := rfl @[simp] theorem yn_zero : yn 0 = 0 := rfl @[simp] theorem xn_succ (n : ℕ) : xn (n+1) = xn n * a + d * yn n := rfl @[simp] theorem yn_succ (n : ℕ) : yn (n+1) = xn n + yn n * a := rfl @[simp] theorem xn_one : xn 1 = a := by simp @[simp] theorem yn_one : yn 1 = 1 := by simp /-- The Pell `x` sequence, considered as an integer sequence.-/ def xz (n : ℕ) : ℤ := xn n /-- The Pell `y` sequence, considered as an integer sequence.-/ def yz (n : ℕ) : ℤ := yn n /-- The element `a` such that `d = a ^ 2 - 1`, considered as an integer.-/ def az : ℤ := a theorem asq_pos : 0 < a*a := le_trans (le_of_lt a1) (by have := @nat.mul_le_mul_left 1 a a (le_of_lt a1); rwa mul_one at this) theorem dz_val : ↑d = az*az - 1 := have 1 ≤ a*a, from asq_pos, show ↑(a*a - 1) = _, by rw int.coe_nat_sub this; refl @[simp] theorem xz_succ (n : ℕ) : xz (n+1) = xz n * az + ↑d * yz n := rfl @[simp] theorem yz_succ (n : ℕ) : yz (n+1) = xz n + yz n * az := rfl /-- The Pell sequence can also be viewed as an element of `ℤ√d` -/ def pell_zd (n : ℕ) : ℤ√d := ⟨xn n, yn n⟩ @[simp] theorem pell_zd_re (n : ℕ) : (pell_zd n).re = xn n := rfl @[simp] theorem pell_zd_im (n : ℕ) : (pell_zd n).im = yn n := rfl /-- The property of being a solution to the Pell equation, expressed as a property of elements of `ℤ√d`. -/ def is_pell : ℤ√d → Prop | ⟨x, y⟩ := x*x - d*y*y = 1 theorem is_pell_nat {x y : ℕ} : is_pell ⟨x, y⟩ ↔ x*x - d*y*y = 1 := ⟨λh, int.coe_nat_inj (by rw int.coe_nat_sub (int.le_of_coe_nat_le_coe_nat $ int.le.intro_sub h); exact h), λh, show ((x*x : ℕ) - (d*y*y:ℕ) : ℤ) = 1, by rw [← int.coe_nat_sub $ le_of_lt $ nat.lt_of_sub_eq_succ h, h]; refl⟩ theorem is_pell_norm : Π {b : ℤ√d}, is_pell b ↔ b * b.conj = 1 | ⟨x, y⟩ := by simp [zsqrtd.ext, is_pell, mul_comm]; ring theorem is_pell_mul {b c : ℤ√d} (hb : is_pell b) (hc : is_pell c) : is_pell (b * c) := is_pell_norm.2 (by simp [mul_comm, mul_left_comm, zsqrtd.conj_mul, pell.is_pell_norm.1 hb, pell.is_pell_norm.1 hc]) theorem is_pell_conj : ∀ {b : ℤ√d}, is_pell b ↔ is_pell b.conj | ⟨x, y⟩ := by simp [is_pell, zsqrtd.conj] @[simp] theorem pell_zd_succ (n : ℕ) : pell_zd (n+1) = pell_zd n * ⟨a, 1⟩ := by simp [zsqrtd.ext] theorem is_pell_one : is_pell ⟨a, 1⟩ := show az*az-d*1*1=1, by simp [dz_val]; ring theorem is_pell_pell_zd : ∀ (n : ℕ), is_pell (pell_zd n) | 0 := rfl | (n+1) := let o := is_pell_one in by simp; exact pell.is_pell_mul (is_pell_pell_zd n) o @[simp] theorem pell_eqz (n : ℕ) : xz n * xz n - d * yz n * yz n = 1 := is_pell_pell_zd n @[simp] theorem pell_eq (n : ℕ) : xn n * xn n - d * yn n * yn n = 1 := let pn := pell_eqz n in have h : (↑(xn n * xn n) : ℤ) - ↑(d * yn n * yn n) = 1, by repeat {rw int.coe_nat_mul}; exact pn, have hl : d * yn n * yn n ≤ xn n * xn n, from int.le_of_coe_nat_le_coe_nat $ int.le.intro $ add_eq_of_eq_sub' $ eq.symm h, int.coe_nat_inj (by rw int.coe_nat_sub hl; exact h) instance dnsq : zsqrtd.nonsquare d := ⟨λn h, have n*n + 1 = a*a, by rw ← h; exact nat.succ_pred_eq_of_pos (asq_pos a1), have na : n < a, from nat.mul_self_lt_mul_self_iff.2 (by rw ← this; exact nat.lt_succ_self _), have (n+1)*(n+1) ≤ n*n + 1, by rw this; exact nat.mul_self_le_mul_self na, have n+n ≤ 0, from @nat.le_of_add_le_add_right (n*n + 1) _ _ (by ring at this ⊢; assumption), ne_of_gt d_pos $ by rwa nat.eq_zero_of_le_zero ((nat.le_add_left _ _).trans this) at h⟩ theorem xn_ge_a_pow : ∀ (n : ℕ), a^n ≤ xn n | 0 := le_refl 1 | (n+1) := by simp [pow_succ']; exact le_trans (nat.mul_le_mul_right _ (xn_ge_a_pow n)) (nat.le_add_right _ _) theorem n_lt_a_pow : ∀ (n : ℕ), n < a^n | 0 := nat.le_refl 1 | (n+1) := begin have IH := n_lt_a_pow n, have : a^n + a^n ≤ a^n * a, { rw ← mul_two, exact nat.mul_le_mul_left _ a1 }, simp [pow_succ'], refine lt_of_lt_of_le _ this, exact add_lt_add_of_lt_of_le IH (lt_of_le_of_lt (nat.zero_le _) IH) end theorem n_lt_xn (n) : n < xn n := lt_of_lt_of_le (n_lt_a_pow n) (xn_ge_a_pow n) theorem x_pos (n) : 0 < xn n := lt_of_le_of_lt (nat.zero_le n) (n_lt_xn n) lemma eq_pell_lem : ∀n (b:ℤ√d), 1 ≤ b → is_pell b → b ≤ pell_zd n → ∃n, b = pell_zd n | 0 b := λh1 hp hl, ⟨0, @zsqrtd.le_antisymm _ dnsq _ _ hl h1⟩ | (n+1) b := λh1 hp h, have a1p : (0:ℤ√d) ≤ ⟨a, 1⟩, from trivial, have am1p : (0:ℤ√d) ≤ ⟨a, -1⟩, from show (_:nat) ≤ _, by simp; exact nat.pred_le _, have a1m : (⟨a, 1⟩ * ⟨a, -1⟩ : ℤ√d) = 1, from is_pell_norm.1 is_pell_one, if ha : (⟨↑a, 1⟩ : ℤ√d) ≤ b then let ⟨m, e⟩ := eq_pell_lem n (b * ⟨a, -1⟩) (by rw ← a1m; exact mul_le_mul_of_nonneg_right ha am1p) (is_pell_mul hp (is_pell_conj.1 is_pell_one)) (by have t := mul_le_mul_of_nonneg_right h am1p; rwa [pell_zd_succ, mul_assoc, a1m, mul_one] at t) in ⟨m+1, by rw [show b = b * ⟨a, -1⟩ * ⟨a, 1⟩, by rw [mul_assoc, eq.trans (mul_comm _ _) a1m]; simp, pell_zd_succ, e]⟩ else suffices ¬1 < b, from ⟨0, show b = 1, from (or.resolve_left (lt_or_eq_of_le h1) this).symm⟩, λ h1l, by cases b with x y; exact have bm : (_*⟨_,_⟩ :ℤ√(d a1)) = 1, from pell.is_pell_norm.1 hp, have y0l : (0:ℤ√(d a1)) < ⟨x - x, y - -y⟩, from sub_lt_sub h1l $ λ(hn : (1:ℤ√(d a1)) ≤ ⟨x, -y⟩), by have t := mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1); rw [bm, mul_one] at t; exact h1l t, have yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩, from show (⟨x, y⟩ - ⟨x, -y⟩ : ℤ√(d a1)) < ⟨a, 1⟩ - ⟨a, -1⟩, from sub_lt_sub (by exact ha) $ λ(hn : (⟨x, -y⟩ : ℤ√(d a1)) ≤ ⟨a, -1⟩), by have t := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1)) a1p; rw [bm, one_mul, mul_assoc, eq.trans (mul_comm _ _) a1m, mul_one] at t; exact ha t, by simp at y0l; simp at yl2; exact match y, y0l, (yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩) with | 0, y0l, yl2 := y0l (le_refl 0) | (y+1 : ℕ), y0l, yl2 := yl2 (zsqrtd.le_of_le_le (le_refl 0) (let t := int.coe_nat_le_coe_nat_of_le (nat.succ_pos y) in add_le_add t t)) | -[1+y], y0l, yl2 := y0l trivial end theorem eq_pell_zd (b : ℤ√d) (b1 : 1 ≤ b) (hp : is_pell b) : ∃n, b = pell_zd n := let ⟨n, h⟩ := @zsqrtd.le_arch d b in eq_pell_lem n b b1 hp $ zsqrtd.le_trans h $ by rw zsqrtd.coe_nat_val; exact zsqrtd.le_of_le_le (int.coe_nat_le_coe_nat_of_le $ le_of_lt $ n_lt_xn _ _) (int.coe_zero_le _) /-- Every solution to Pell's equation is recursively obtained from the initial solution `(1,0)` using the recursion `pell`-/ theorem eq_pell {x y : ℕ} (hp : x*x - d*y*y = 1) : ∃n, x = xn n ∧ y = yn n := have (1:ℤ√d) ≤ ⟨x, y⟩, from match x, hp with | 0, (hp : 0 - _ = 1) := by rw nat.zero_sub at hp; contradiction | (x+1), hp := zsqrtd.le_of_le_le (int.coe_nat_le_coe_nat_of_le $ nat.succ_pos x) (int.coe_zero_le _) end, let ⟨m, e⟩ := eq_pell_zd ⟨x, y⟩ this (is_pell_nat.2 hp) in ⟨m, match x, y, e with ._, ._, rfl := ⟨rfl, rfl⟩ end⟩ theorem pell_zd_add (m) : ∀ n, pell_zd (m + n) = pell_zd m * pell_zd n | 0 := (mul_one _).symm | (n+1) := by rw[← add_assoc, pell_zd_succ, pell_zd_succ, pell_zd_add n, ← mul_assoc] theorem xn_add (m n) : xn (m + n) = xn m * xn n + d * yn m * yn n := by injection (pell_zd_add _ m n) with h _; repeat {rw ← int.coe_nat_add at h <|> rw ← int.coe_nat_mul at h}; exact int.coe_nat_inj h theorem yn_add (m n) : yn (m + n) = xn m * yn n + yn m * xn n := by injection (pell_zd_add _ m n) with _ h; repeat {rw ← int.coe_nat_add at h <|> rw ← int.coe_nat_mul at h}; exact int.coe_nat_inj h theorem pell_zd_sub {m n} (h : n ≤ m) : pell_zd (m - n) = pell_zd m * (pell_zd n).conj := let t := pell_zd_add n (m - n) in by rw [nat.add_sub_of_le h] at t; rw [t, mul_comm (pell_zd _ n) _, mul_assoc, (is_pell_norm _).1 (is_pell_pell_zd _ _), mul_one] theorem xz_sub {m n} (h : n ≤ m) : xz (m - n) = xz m * xz n - d * yz m * yz n := by injection (pell_zd_sub _ h) with h _; repeat {rw ← neg_mul_eq_mul_neg at h}; exact h theorem yz_sub {m n} (h : n ≤ m) : yz (m - n) = xz n * yz m - xz m * yz n := by injection (pell_zd_sub a1 h) with _ h; repeat {rw ← neg_mul_eq_mul_neg at h}; rw [add_comm, mul_comm] at h; exact h theorem xy_coprime (n) : (xn n).coprime (yn n) := nat.coprime_of_dvd' $ λk kp kx ky, let p := pell_eq n in by rw ← p; exact nat.dvd_sub (le_of_lt $ nat.lt_of_sub_eq_succ p) (dvd_mul_of_dvd_right kx _) (dvd_mul_of_dvd_right ky _) theorem y_increasing {m} : Π {n}, m < n → yn m < yn n | 0 h := absurd h $ nat.not_lt_zero _ | (n+1) h := have yn m ≤ yn n, from or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ h) (λhl, le_of_lt $ y_increasing hl) (λe, by rw e), by simp; refine lt_of_le_of_lt _ (nat.lt_add_of_pos_left $ x_pos a1 n); rw ← mul_one (yn a1 m); exact mul_le_mul this (le_of_lt a1) (nat.zero_le _) (nat.zero_le _) theorem x_increasing {m} : Π {n}, m < n → xn m < xn n | 0 h := absurd h $ nat.not_lt_zero _ | (n+1) h := have xn m ≤ xn n, from or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ h) (λhl, le_of_lt $ x_increasing hl) (λe, by rw e), by simp; refine lt_of_lt_of_le (lt_of_le_of_lt this _) (nat.le_add_right _ _); have t := nat.mul_lt_mul_of_pos_left a1 (x_pos a1 n); rwa mul_one at t theorem yn_ge_n : Π n, n ≤ yn n | 0 := nat.zero_le _ | (n+1) := show n < yn (n+1), from lt_of_le_of_lt (yn_ge_n n) (y_increasing $ nat.lt_succ_self n) theorem y_mul_dvd (n) : ∀k, yn n ∣ yn (n * k) | 0 := dvd_zero _ | (k+1) := by rw [nat.mul_succ, yn_add]; exact dvd_add (dvd_mul_left _ _) (dvd_mul_of_dvd_left (y_mul_dvd k) _) theorem y_dvd_iff (m n) : yn m ∣ yn n ↔ m ∣ n := ⟨λh, nat.dvd_of_mod_eq_zero $ (nat.eq_zero_or_pos _).resolve_right $ λhp, have co : nat.coprime (yn m) (xn (m * (n / m))), from nat.coprime.symm $ (xy_coprime _).coprime_dvd_right (y_mul_dvd m (n / m)), have m0 : 0 < m, from m.eq_zero_or_pos.resolve_left $ λe, by rw [e, nat.mod_zero] at hp; rw [e] at h; exact ne_of_lt (y_increasing a1 hp) (eq_zero_of_zero_dvd h).symm, by rw [← nat.mod_add_div n m, yn_add] at h; exact not_le_of_gt (y_increasing _ $ nat.mod_lt n m0) (nat.le_of_dvd (y_increasing _ hp) $ co.dvd_of_dvd_mul_right $ (nat.dvd_add_iff_right $ dvd_mul_of_dvd_right (y_mul_dvd _ _ _) _).2 h), λ⟨k, e⟩, by rw e; apply y_mul_dvd⟩ theorem xy_modeq_yn (n) : ∀k, xn (n * k) ≡ (xn n)^k [MOD (yn n)^2] ∧ yn (n * k) ≡ k * (xn n)^(k-1) * yn n [MOD (yn n)^3] | 0 := by constructor; simp | (k+1) := let ⟨hx, hy⟩ := xy_modeq_yn k in have L : xn (n * k) * xn n + d * yn (n * k) * yn n ≡ xn n^k * xn n + 0 [MOD yn n^2], from modeq.modeq_add (modeq.modeq_mul_right _ hx) $ modeq.modeq_zero_iff.2 $ by rw pow_succ'; exact mul_dvd_mul_right (dvd_mul_of_dvd_right (modeq.modeq_zero_iff.1 $ (hy.modeq_of_dvd_of_modeq $ by simp [pow_succ']).trans $ modeq.modeq_zero_iff.2 $ by simp [-mul_comm, -mul_assoc]) _) _, have R : xn (n * k) * yn n + yn (n * k) * xn n ≡ xn n^k * yn n + k * xn n^k * yn n [MOD yn n^3], from modeq.modeq_add (by rw pow_succ'; exact modeq.modeq_mul_right' _ hx) $ have k * xn n^(k - 1) * yn n * xn n = k * xn n^k * yn n, by clear _let_match; cases k with k; simp [pow_succ', mul_comm, mul_left_comm], by rw ← this; exact modeq.modeq_mul_right _ hy, by rw [nat.add_sub_cancel, nat.mul_succ, xn_add, yn_add, pow_succ' (xn _ n), nat.succ_mul, add_comm (k * xn _ n^k) (xn _ n^k), right_distrib]; exact ⟨L, R⟩ theorem ysq_dvd_yy (n) : yn n * yn n ∣ yn (n * yn n) := modeq.modeq_zero_iff.1 $ ((xy_modeq_yn n (yn n)).right.modeq_of_dvd_of_modeq $ by simp [pow_succ]).trans (modeq.modeq_zero_iff.2 $ by simp [mul_dvd_mul_left, mul_assoc]) theorem dvd_of_ysq_dvd {n t} (h : yn n * yn n ∣ yn t) : yn n ∣ t := have nt : n ∣ t, from (y_dvd_iff n t).1 $ dvd_of_mul_left_dvd h, n.eq_zero_or_pos.elim (λn0, by rw n0; rw n0 at nt; exact nt) $ λ(n0l : 0 < n), let ⟨k, ke⟩ := nt in have yn n ∣ k * (xn n)^(k-1), from nat.dvd_of_mul_dvd_mul_right (y_increasing n0l) $ modeq.modeq_zero_iff.1 $ by have xm := (xy_modeq_yn a1 n k).right; rw ← ke at xm; exact (xm.modeq_of_dvd_of_modeq $ by simp [pow_succ]).symm.trans (modeq.modeq_zero_iff.2 h), by rw ke; exact dvd_mul_of_dvd_right (((xy_coprime _ _).pow_left _).symm.dvd_of_dvd_mul_right this) _ theorem pell_zd_succ_succ (n) : pell_zd (n + 2) + pell_zd n = (2 * a : ℕ) * pell_zd (n + 1) := have (1:ℤ√d) + ⟨a, 1⟩ * ⟨a, 1⟩ = ⟨a, 1⟩ * (2 * a), by { rw zsqrtd.coe_nat_val, change (⟨_,_⟩:ℤ√(d a1))=⟨_,_⟩, rw dz_val, change az a1 with a, rw zsqrtd.ext, dsimp, split; ring }, by simpa [mul_add, mul_comm, mul_left_comm, add_comm] using congr_arg (* pell_zd a1 n) this theorem xy_succ_succ (n) : xn (n + 2) + xn n = (2 * a) * xn (n + 1) ∧ yn (n + 2) + yn n = (2 * a) * yn (n + 1) := begin have := pell_zd_succ_succ a1 n, unfold pell_zd at this, rw [← int.cast_coe_nat, zsqrtd.smul_val] at this, injection this with h₁ h₂, split; apply int.coe_nat_inj; [simpa using h₁, simpa using h₂] end theorem xn_succ_succ (n) : xn (n + 2) + xn n = (2 * a) * xn (n + 1) := (xy_succ_succ n).1 theorem yn_succ_succ (n) : yn (n + 2) + yn n = (2 * a) * yn (n + 1) := (xy_succ_succ n).2 theorem xz_succ_succ (n) : xz (n + 2) = (2 * a : ℕ) * xz (n + 1) - xz n := eq_sub_of_add_eq $ by delta xz; rw [← int.coe_nat_add, ← int.coe_nat_mul, xn_succ_succ] theorem yz_succ_succ (n) : yz (n + 2) = (2 * a : ℕ) * yz (n + 1) - yz n := eq_sub_of_add_eq $ by delta yz; rw [← int.coe_nat_add, ← int.coe_nat_mul, yn_succ_succ] theorem yn_modeq_a_sub_one : ∀ n, yn n ≡ n [MOD a-1] | 0 := by simp | 1 := by simp | (n+2) := modeq.modeq_add_cancel_right (yn_modeq_a_sub_one n) $ have 2*(n+1) = n+2+n, by ring, by rw [yn_succ_succ, ← this]; refine modeq.modeq_mul (modeq.modeq_mul_left 2 (_ : a ≡ 1 [MOD a-1])) (yn_modeq_a_sub_one (n+1)); exact (modeq.modeq_of_dvd $ by rw [int.coe_nat_sub $ le_of_lt a1]; apply dvd_refl).symm theorem yn_modeq_two : ∀ n, yn n ≡ n [MOD 2] | 0 := by simp | 1 := by simp | (n+2) := modeq.modeq_add_cancel_right (yn_modeq_two n) $ have 2*(n+1) = n+2+n, by ring, by rw [yn_succ_succ, ← this]; refine modeq.modeq_mul _ (yn_modeq_two (n+1)); exact modeq.trans (modeq.modeq_zero_iff.2 $ by simp) (modeq.modeq_zero_iff.2 $ by simp).symm lemma x_sub_y_dvd_pow_lem (y2 y1 y0 yn1 yn0 xn1 xn0 ay a2 : ℤ) : (a2 * yn1 - yn0) * ay + y2 - (a2 * xn1 - xn0) = y2 - a2 * y1 + y0 + a2 * (yn1 * ay + y1 - xn1) - (yn0 * ay + y0 - xn0) := by ring theorem x_sub_y_dvd_pow (y : ℕ) : ∀ n, (2*a*y - y*y - 1 : ℤ) ∣ yz n * (a - y) + ↑(y^n) - xz n | 0 := by simp [xz, yz, int.coe_nat_zero, int.coe_nat_one] | 1 := by simp [xz, yz, int.coe_nat_zero, int.coe_nat_one] | (n+2) := have (2*a*y - y*y - 1 : ℤ) ∣ ↑(y^(n + 2)) - ↑(2 * a) * ↑(y^(n + 1)) + ↑(y^n), from ⟨-↑(y^n), by simp [pow_succ, mul_add, int.coe_nat_mul, show ((2:ℕ):ℤ) = 2, from rfl, mul_comm, mul_left_comm]; ring ⟩, by rw [xz_succ_succ, yz_succ_succ, x_sub_y_dvd_pow_lem a1 ↑(y^(n+2)) ↑(y^(n+1)) ↑(y^n)]; exact dvd_sub (dvd_add this $ dvd_mul_of_dvd_right (x_sub_y_dvd_pow (n+1)) _) (x_sub_y_dvd_pow n) theorem xn_modeq_x2n_add_lem (n j) : xn n ∣ d * yn n * (yn n * xn j) + xn j := have h1 : d * yn n * (yn n * xn j) + xn j = (d * yn n * yn n + 1) * xn j, by simp [add_mul, mul_assoc], have h2 : d * yn n * yn n + 1 = xn n * xn n, by apply int.coe_nat_inj; repeat {rw int.coe_nat_add <|> rw int.coe_nat_mul}; exact add_eq_of_eq_sub' (eq.symm $ pell_eqz _ _), by rw h2 at h1; rw [h1, mul_assoc]; exact dvd_mul_right _ _ theorem xn_modeq_x2n_add (n j) : xn (2 * n + j) + xn j ≡ 0 [MOD xn n] := by rw [two_mul, add_assoc, xn_add, add_assoc]; exact show _ ≡ 0+0 [MOD xn a1 n], from modeq.modeq_add (modeq.modeq_zero_iff.2 $ dvd_mul_right (xn a1 n) (xn a1 (n + j))) $ by rw [yn_add, left_distrib, add_assoc]; exact show _ ≡ 0+0 [MOD xn a1 n], from modeq.modeq_add (modeq.modeq_zero_iff.2 $ dvd_mul_of_dvd_right (dvd_mul_right _ _) _) $ modeq.modeq_zero_iff.2 $ xn_modeq_x2n_add_lem _ _ _ lemma xn_modeq_x2n_sub_lem {n j} (h : j ≤ n) : xn (2 * n - j) + xn j ≡ 0 [MOD xn n] := have h1 : xz n ∣ ↑d * yz n * yz (n - j) + xz j, by rw [yz_sub _ h, mul_sub_left_distrib, sub_add_eq_add_sub]; exact dvd_sub (by delta xz; delta yz; repeat {rw ← int.coe_nat_add <|> rw ← int.coe_nat_mul}; rw mul_comm (xn a1 j) (yn a1 n); exact int.coe_nat_dvd.2 (xn_modeq_x2n_add_lem _ _ _)) (dvd_mul_of_dvd_right (dvd_mul_right _ _) _), by rw [two_mul, nat.add_sub_assoc h, xn_add, add_assoc]; exact show _ ≡ 0+0 [MOD xn a1 n], from modeq.modeq_add (modeq.modeq_zero_iff.2 $ dvd_mul_right _ _) $ modeq.modeq_zero_iff.2 $ int.coe_nat_dvd.1 $ by simpa [xz, yz] using h1 theorem xn_modeq_x2n_sub {n j} (h : j ≤ 2 * n) : xn (2 * n - j) + xn j ≡ 0 [MOD xn n] := (le_total j n).elim xn_modeq_x2n_sub_lem (λjn, have 2 * n - j + j ≤ n + j, by rw [nat.sub_add_cancel h, two_mul]; exact nat.add_le_add_left jn _, let t := xn_modeq_x2n_sub_lem (nat.le_of_add_le_add_right this) in by rwa [nat.sub_sub_self h, add_comm] at t) theorem xn_modeq_x4n_add (n j) : xn (4 * n + j) ≡ xn j [MOD xn n] := modeq.modeq_add_cancel_right (modeq.refl $ xn (2 * n + j)) $ by refine @modeq.trans _ _ 0 _ _ (by rw add_comm; exact (xn_modeq_x2n_add _ _ _).symm); rw [show 4*n = 2*n + 2*n, from right_distrib 2 2 n, add_assoc]; apply xn_modeq_x2n_add theorem xn_modeq_x4n_sub {n j} (h : j ≤ 2 * n) : xn (4 * n - j) ≡ xn j [MOD xn n] := have h' : j ≤ 2*n, from le_trans h (by rw nat.succ_mul; apply nat.le_add_left), modeq.modeq_add_cancel_right (modeq.refl $ xn (2 * n - j)) $ by refine @modeq.trans _ _ 0 _ _ (by rw add_comm; exact (xn_modeq_x2n_sub _ h).symm); rw [show 4*n = 2*n + 2*n, from right_distrib 2 2 n, nat.add_sub_assoc h']; apply xn_modeq_x2n_add theorem eq_of_xn_modeq_lem1 {i n} : Π {j}, i < j → j < n → xn i % xn n < xn j % xn n | 0 ij _ := absurd ij (nat.not_lt_zero _) | (j+1) ij jn := suffices xn j % xn n < xn (j + 1) % xn n, from (lt_or_eq_of_le (nat.le_of_succ_le_succ ij)).elim (λh, lt_trans (eq_of_xn_modeq_lem1 h (le_of_lt jn)) this) (λh, by rw h; exact this), by rw [nat.mod_eq_of_lt (x_increasing _ (nat.lt_of_succ_lt jn)), nat.mod_eq_of_lt (x_increasing _ jn)]; exact x_increasing _ (nat.lt_succ_self _) theorem eq_of_xn_modeq_lem2 {n} (h : 2 * xn n = xn (n + 1)) : a = 2 ∧ n = 0 := by rw [xn_succ, mul_comm] at h; exact have n = 0, from n.eq_zero_or_pos.resolve_right $ λnp, ne_of_lt (lt_of_le_of_lt (nat.mul_le_mul_left _ a1) (nat.lt_add_of_pos_right $ mul_pos (d_pos a1) (y_increasing a1 np))) h, by cases this; simp at h; exact ⟨h.symm, rfl⟩ theorem eq_of_xn_modeq_lem3 {i n} (npos : 0 < n) : Π {j}, i < j → j ≤ 2 * n → j ≠ n → ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2) → xn i % xn n < xn j % xn n | 0 ij _ _ _ := absurd ij (nat.not_lt_zero _) | (j+1) ij j2n jnn ntriv := have lem2 : ∀k > n, k ≤ 2*n → (↑(xn k % xn n) : ℤ) = xn n - xn (2 * n - k), from λk kn k2n, let k2nl := lt_of_add_lt_add_right $ show 2*n-k+k < n+k, by {rw nat.sub_add_cancel, rw two_mul; exact (add_lt_add_left kn n), exact k2n } in have xle : xn (2 * n - k) ≤ xn n, from le_of_lt $ x_increasing k2nl, suffices xn k % xn n = xn n - xn (2 * n - k), by rw [this, int.coe_nat_sub xle], by { rw ← nat.mod_eq_of_lt (nat.sub_lt (x_pos a1 n) (x_pos a1 (2 * n - k))), apply modeq.modeq_add_cancel_right (modeq.refl (xn a1 (2 * n - k))), rw [nat.sub_add_cancel xle], have t := xn_modeq_x2n_sub_lem a1 (le_of_lt k2nl), rw nat.sub_sub_self k2n at t, exact t.trans (modeq.modeq_zero_iff.2 $ dvd_refl _).symm }, (lt_trichotomy j n).elim (λ (jn : j < n), eq_of_xn_modeq_lem1 ij (lt_of_le_of_ne jn jnn)) $ λo, o.elim (λ (jn : j = n), by { cases jn, apply int.lt_of_coe_nat_lt_coe_nat, rw [lem2 (n+1) (nat.lt_succ_self _) j2n, show 2 * n - (n + 1) = n - 1, by rw[two_mul, ← nat.sub_sub, nat.add_sub_cancel]], refine lt_sub_left_of_add_lt (int.coe_nat_lt_coe_nat_of_lt _), cases (lt_or_eq_of_le $ nat.le_of_succ_le_succ ij) with lin ein, { rw nat.mod_eq_of_lt (x_increasing _ lin), have ll : xn a1 (n-1) + xn a1 (n-1) ≤ xn a1 n, { rw [← two_mul, mul_comm, show xn a1 n = xn a1 (n-1+1), by rw [nat.sub_add_cancel npos], xn_succ], exact le_trans (nat.mul_le_mul_left _ a1) (nat.le_add_right _ _) }, have npm : (n-1).succ = n := nat.succ_pred_eq_of_pos npos, have il : i ≤ n - 1, { apply nat.le_of_succ_le_succ, rw npm, exact lin }, cases lt_or_eq_of_le il with ill ile, { exact lt_of_lt_of_le (nat.add_lt_add_left (x_increasing a1 ill) _) ll }, { rw ile, apply lt_of_le_of_ne ll, rw ← two_mul, exact λe, ntriv $ let ⟨a2, s1⟩ := @eq_of_xn_modeq_lem2 _ a1 (n-1) (by rwa [nat.sub_add_cancel npos]) in have n1 : n = 1, from le_antisymm (nat.le_of_sub_eq_zero s1) npos, by rw [ile, a2, n1]; exact ⟨rfl, rfl, rfl, rfl⟩ } }, { rw [ein, nat.mod_self, add_zero], exact x_increasing _ (nat.pred_lt $ ne_of_gt npos) } }) (λ (jn : j > n), have lem1 : j ≠ n → xn j % xn n < xn (j + 1) % xn n → xn i % xn n < xn (j + 1) % xn n, from λjn s, (lt_or_eq_of_le (nat.le_of_succ_le_succ ij)).elim (λh, lt_trans (eq_of_xn_modeq_lem3 h (le_of_lt j2n) jn $ λ⟨a1, n1, i0, j2⟩, by rw [n1, j2] at j2n; exact absurd j2n dec_trivial) s) (λh, by rw h; exact s), lem1 (ne_of_gt jn) $ int.lt_of_coe_nat_lt_coe_nat $ by { rw [lem2 j jn (le_of_lt j2n), lem2 (j+1) (nat.le_succ_of_le jn) j2n], refine sub_lt_sub_left (int.coe_nat_lt_coe_nat_of_lt $ x_increasing _ _) _, rw [nat.sub_succ], exact nat.pred_lt (ne_of_gt $ nat.sub_pos_of_lt j2n) }) theorem eq_of_xn_modeq_le {i j n} (npos : 0 < n) (ij : i ≤ j) (j2n : j ≤ 2 * n) (h : xn i ≡ xn j [MOD xn n]) (ntriv : ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2)) : i = j := (lt_or_eq_of_le ij).resolve_left $ λij', if jn : j = n then by { refine ne_of_gt _ h, rw [jn, nat.mod_self], have x0 : 0 < xn a1 0 % xn a1 n := by rw [nat.mod_eq_of_lt (x_increasing a1 npos)]; exact dec_trivial, cases i with i, exact x0, rw jn at ij', exact x0.trans (eq_of_xn_modeq_lem3 _ npos (nat.succ_pos _) (le_trans ij j2n) (ne_of_lt ij') $ λ⟨a1, n1, _, i2⟩, by rw [n1, i2] at ij'; exact absurd ij' dec_trivial) } else ne_of_lt (eq_of_xn_modeq_lem3 npos ij' j2n jn ntriv) h theorem eq_of_xn_modeq {i j n} (npos : 0 < n) (i2n : i ≤ 2 * n) (j2n : j ≤ 2 * n) (h : xn i ≡ xn j [MOD xn n]) (ntriv : a = 2 → n = 1 → (i = 0 → j ≠ 2) ∧ (i = 2 → j ≠ 0)) : i = j := (le_total i j).elim (λij, eq_of_xn_modeq_le npos ij j2n h $ λ⟨a2, n1, i0, j2⟩, (ntriv a2 n1).left i0 j2) (λij, (eq_of_xn_modeq_le npos ij i2n h.symm $ λ⟨a2, n1, j0, i2⟩, (ntriv a2 n1).right i2 j0).symm) theorem eq_of_xn_modeq' {i j n} (ipos : 0 < i) (hin : i ≤ n) (j4n : j ≤ 4 * n) (h : xn j ≡ xn i [MOD xn n]) : j = i ∨ j + i = 4 * n := have i2n : i ≤ 2*n, by apply le_trans hin; rw two_mul; apply nat.le_add_left, have npos : 0 < n, from lt_of_lt_of_le ipos hin, (le_or_gt j (2 * n)).imp (λj2n : j ≤ 2 * n, eq_of_xn_modeq npos j2n i2n h $ λa2 n1, ⟨λj0 i2, by rw [n1, i2] at hin; exact absurd hin dec_trivial, λj2 i0, ne_of_gt ipos i0⟩) (λj2n : 2 * n < j, suffices i = 4*n - j, by rw [this, nat.add_sub_of_le j4n], have j42n : 4*n - j ≤ 2*n, from @nat.le_of_add_le_add_right j _ _ $ by rw [nat.sub_add_cancel j4n, show 4*n = 2*n + 2*n, from right_distrib 2 2 n]; exact nat.add_le_add_left (le_of_lt j2n) _, eq_of_xn_modeq npos i2n j42n (h.symm.trans $ let t := xn_modeq_x4n_sub j42n in by rwa [nat.sub_sub_self j4n] at t) (λa2 n1, ⟨λi0, absurd i0 (ne_of_gt ipos), λi2, by { rw [n1, i2] at hin, exact absurd hin dec_trivial }⟩)) theorem modeq_of_xn_modeq {i j n} (ipos : 0 < i) (hin : i ≤ n) (h : xn j ≡ xn i [MOD xn n]) : j ≡ i [MOD 4 * n] ∨ j + i ≡ 0 [MOD 4 * n] := let j' := j % (4 * n) in have n4 : 0 < 4 * n, from mul_pos dec_trivial (lt_of_lt_of_le ipos hin), have jl : j' < 4 * n, from nat.mod_lt _ n4, have jj : j ≡ j' [MOD 4 * n], by delta modeq; rw nat.mod_eq_of_lt jl, have ∀j q, xn (j + 4 * n * q) ≡ xn j [MOD xn n], begin intros j q, induction q with q IH, { simp }, rw[nat.mul_succ, ← add_assoc, add_comm], exact modeq.trans (xn_modeq_x4n_add _ _ _) IH end, or.imp (λ(ji : j' = i), by rwa ← ji) (λ(ji : j' + i = 4 * n), (modeq.modeq_add jj (modeq.refl _)).trans $ by rw ji; exact modeq.modeq_zero_iff.2 (dvd_refl _)) (eq_of_xn_modeq' ipos hin (le_of_lt jl) $ (modeq.symm (by rw ← nat.mod_add_div j (4*n); exact this j' _)).trans h) end theorem xy_modeq_of_modeq {a b c} (a1 : 1 < a) (b1 : 1 < b) (h : a ≡ b [MOD c]) : ∀ n, xn a1 n ≡ xn b1 n [MOD c] ∧ yn a1 n ≡ yn b1 n [MOD c] | 0 := by constructor; refl | 1 := by simp; exact ⟨h, modeq.refl 1⟩ | (n+2) := ⟨ modeq.modeq_add_cancel_right (xy_modeq_of_modeq n).left $ by rw [xn_succ_succ a1, xn_succ_succ b1]; exact modeq.modeq_mul (modeq.modeq_mul_left _ h) (xy_modeq_of_modeq (n+1)).left, modeq.modeq_add_cancel_right (xy_modeq_of_modeq n).right $ by rw [yn_succ_succ a1, yn_succ_succ b1]; exact modeq.modeq_mul (modeq.modeq_mul_left _ h) (xy_modeq_of_modeq (n+1)).right⟩ theorem matiyasevic {a k x y} : (∃ a1 : 1 < a, xn a1 k = x ∧ yn a1 k = y) ↔ 1 < a ∧ k ≤ y ∧ (x = 1 ∧ y = 0 ∨ ∃ (u v s t b : ℕ), x * x - (a * a - 1) * y * y = 1 ∧ u * u - (a * a - 1) * v * v = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ 1 < b ∧ b ≡ 1 [MOD 4 * y] ∧ b ≡ a [MOD u] ∧ 0 < v ∧ y * y ∣ v ∧ s ≡ x [MOD u] ∧ t ≡ k [MOD 4 * y]) := ⟨λ⟨a1, hx, hy⟩, by rw [← hx, ← hy]; refine ⟨a1, (nat.eq_zero_or_pos k).elim (λk0, by rw k0; exact ⟨le_refl _, or.inl ⟨rfl, rfl⟩⟩) (λkpos, _)⟩; exact let x := xn a1 k, y := yn a1 k, m := 2 * (k * y), u := xn a1 m, v := yn a1 m in have ky : k ≤ y, from yn_ge_n a1 k, have yv : y * y ∣ v, from dvd_trans (ysq_dvd_yy a1 k) $ (y_dvd_iff _ _ _).2 $ dvd_mul_left _ _, have uco : nat.coprime u (4 * y), from have 2 ∣ v, from modeq.modeq_zero_iff.1 $ (yn_modeq_two _ _).trans $ modeq.modeq_zero_iff.2 (dvd_mul_right _ _), have nat.coprime u 2, from (xy_coprime a1 m).coprime_dvd_right this, (this.mul_right this).mul_right $ (xy_coprime _ _).coprime_dvd_right (dvd_of_mul_left_dvd yv), let ⟨b, ba, bm1⟩ := modeq.chinese_remainder uco a 1 in have m1 : 1 < m, from have 0 < k * y, from mul_pos kpos (y_increasing a1 kpos), nat.mul_le_mul_left 2 this, have vp : 0 < v, from y_increasing a1 (lt_trans zero_lt_one m1), have b1 : 1 < b, from have xn a1 1 < u, from x_increasing a1 m1, have a < u, by simp at this; exact this, lt_of_lt_of_le a1 $ by delta modeq at ba; rw nat.mod_eq_of_lt this at ba; rw ← ba; apply nat.mod_le, let s := xn b1 k, t := yn b1 k in have sx : s ≡ x [MOD u], from (xy_modeq_of_modeq b1 a1 ba k).left, have tk : t ≡ k [MOD 4 * y], from have 4 * y ∣ b - 1, from int.coe_nat_dvd.1 $ by rw int.coe_nat_sub (le_of_lt b1); exact modeq.dvd_of_modeq bm1.symm, modeq.modeq_of_dvd_of_modeq this $ yn_modeq_a_sub_one _ _, ⟨ky, or.inr ⟨u, v, s, t, b, pell_eq _ _, pell_eq _ _, pell_eq _ _, b1, bm1, ba, vp, yv, sx, tk⟩⟩, λ⟨a1, ky, o⟩, ⟨a1, match o with | or.inl ⟨x1, y0⟩ := by rw y0 at ky; rw [nat.eq_zero_of_le_zero ky, x1, y0]; exact ⟨rfl, rfl⟩ | or.inr ⟨u, v, s, t, b, xy, uv, st, b1, rem⟩ := match x, y, eq_pell a1 xy, u, v, eq_pell a1 uv, s, t, eq_pell b1 st, rem, ky with | ._, ._, ⟨i, rfl, rfl⟩, ._, ._, ⟨n, rfl, rfl⟩, ._, ._, ⟨j, rfl, rfl⟩, ⟨(bm1 : b ≡ 1 [MOD 4 * yn a1 i]), (ba : b ≡ a [MOD xn a1 n]), (vp : 0 < yn a1 n), (yv : yn a1 i * yn a1 i ∣ yn a1 n), (sx : xn b1 j ≡ xn a1 i [MOD xn a1 n]), (tk : yn b1 j ≡ k [MOD 4 * yn a1 i])⟩, (ky : k ≤ yn a1 i) := (nat.eq_zero_or_pos i).elim (λi0, by simp [i0] at ky; rw [i0, ky]; exact ⟨rfl, rfl⟩) $ λipos, suffices i = k, by rw this; exact ⟨rfl, rfl⟩, by clear _x o rem xy uv st _match _match _fun_match; exact have iln : i ≤ n, from le_of_not_gt $ λhin, not_lt_of_ge (nat.le_of_dvd vp (dvd_of_mul_left_dvd yv)) (y_increasing a1 hin), have yd : 4 * yn a1 i ∣ 4 * n, from mul_dvd_mul_left _ $ dvd_of_ysq_dvd a1 yv, have jk : j ≡ k [MOD 4 * yn a1 i], from have 4 * yn a1 i ∣ b - 1, from int.coe_nat_dvd.1 $ by rw int.coe_nat_sub (le_of_lt b1); exact modeq.dvd_of_modeq bm1.symm, (modeq.modeq_of_dvd_of_modeq this (yn_modeq_a_sub_one b1 _)).symm.trans tk, have ki : k + i < 4 * yn a1 i, from lt_of_le_of_lt (add_le_add ky (yn_ge_n a1 i)) $ by rw ← two_mul; exact nat.mul_lt_mul_of_pos_right dec_trivial (y_increasing a1 ipos), have ji : j ≡ i [MOD 4 * n], from have xn a1 j ≡ xn a1 i [MOD xn a1 n], from (xy_modeq_of_modeq b1 a1 ba j).left.symm.trans sx, (modeq_of_xn_modeq a1 ipos iln this).resolve_right $ λ (ji : j + i ≡ 0 [MOD 4 * n]), not_le_of_gt ki $ nat.le_of_dvd (lt_of_lt_of_le ipos $ nat.le_add_left _ _) $ modeq.modeq_zero_iff.1 $ (modeq.modeq_add jk.symm (modeq.refl i)).trans $ modeq.modeq_of_dvd_of_modeq yd ji, by have : i % (4 * yn a1 i) = k % (4 * yn a1 i) := (modeq.modeq_of_dvd_of_modeq yd ji).symm.trans jk; rwa [nat.mod_eq_of_lt (lt_of_le_of_lt (nat.le_add_left _ _) ki), nat.mod_eq_of_lt (lt_of_le_of_lt (nat.le_add_right _ _) ki)] at this end end⟩⟩ lemma eq_pow_of_pell_lem {a y k} (a1 : 1 < a) (ypos : 0 < y) : 0 < k → y^k < a → (↑(y^k) : ℤ) < 2*a*y - y*y - 1 := have y < a → a + (y*y + 1) ≤ 2*a*y, begin intro ya, induction y with y IH, exact absurd ypos (lt_irrefl _), cases nat.eq_zero_or_pos y with y0 ypos, { rw y0, simpa [two_mul], }, { rw [nat.mul_succ, nat.mul_succ, nat.succ_mul y], have : y + nat.succ y ≤ 2 * a, { change y + y < 2 * a, rw ← two_mul, exact mul_lt_mul_of_pos_left (nat.lt_of_succ_lt ya) dec_trivial }, have := add_le_add (IH ypos (nat.lt_of_succ_lt ya)) this, convert this using 1, ring } end, λk0 yak, lt_of_lt_of_le (int.coe_nat_lt_coe_nat_of_lt yak) $ by rw sub_sub; apply le_sub_right_of_add_le; apply int.coe_nat_le_coe_nat_of_le; have y1 := nat.pow_le_pow_of_le_right ypos k0; simp at y1; exact this (lt_of_le_of_lt y1 yak) theorem eq_pow_of_pell {m n k} : (n^k = m ↔ k = 0 ∧ m = 1 ∨ 0 < k ∧ (n = 0 ∧ m = 0 ∨ 0 < n ∧ ∃ (w a t z : ℕ) (a1 : 1 < a), xn a1 k ≡ yn a1 k * (a - n) + m [MOD t] ∧ 2 * a * n = t + (n * n + 1) ∧ m < t ∧ n ≤ w ∧ k ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)) := ⟨λe, by rw ← e; refine (nat.eq_zero_or_pos k).elim (λk0, by rw k0; exact or.inl ⟨rfl, rfl⟩) (λkpos, or.inr ⟨kpos, _⟩); refine (nat.eq_zero_or_pos n).elim (λn0, by rw [n0, zero_pow kpos]; exact or.inl ⟨rfl, rfl⟩) (λnpos, or.inr ⟨npos, _⟩); exact let w := _root_.max n k in have nw : n ≤ w, from le_max_left _ _, have kw : k ≤ w, from le_max_right _ _, have wpos : 0 < w, from lt_of_lt_of_le npos nw, have w1 : 1 < w + 1, from nat.succ_lt_succ wpos, let a := xn w1 w in have a1 : 1 < a, from x_increasing w1 wpos, let x := xn a1 k, y := yn a1 k in let ⟨z, ze⟩ := show w ∣ yn w1 w, from modeq.modeq_zero_iff.1 $ modeq.trans (yn_modeq_a_sub_one w1 w) (modeq.modeq_zero_iff.2 $ dvd_refl _) in have nt : (↑(n^k) : ℤ) < 2 * a * n - n * n - 1, from eq_pow_of_pell_lem a1 npos kpos $ calc n^k ≤ n^w : nat.pow_le_pow_of_le_right npos kw ... < (w + 1)^w : nat.pow_lt_pow_of_lt_left (nat.lt_succ_of_le nw) wpos ... ≤ a : xn_ge_a_pow w1 w, let ⟨t, te⟩ := int.eq_coe_of_zero_le $ le_trans (int.coe_zero_le _) $ le_of_lt nt in have na : n ≤ a, from le_trans nw $ le_of_lt $ n_lt_xn w1 w, have tm : x ≡ y * (a - n) + n^k [MOD t], begin apply modeq.modeq_of_dvd, rw [int.coe_nat_add, int.coe_nat_mul, int.coe_nat_sub na, ← te], exact x_sub_y_dvd_pow a1 n k end, have ta : 2 * a * n = t + (n * n + 1), from int.coe_nat_inj $ by rw [int.coe_nat_add, ← te, sub_sub]; repeat {rw int.coe_nat_add <|> rw int.coe_nat_mul}; rw [int.coe_nat_one, sub_add_cancel]; refl, have mt : n^k < t, from int.lt_of_coe_nat_lt_coe_nat $ by rw ← te; exact nt, have zp : a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1, by rw ← ze; exact pell_eq w1 w, ⟨w, a, t, z, a1, tm, ta, mt, nw, kw, zp⟩, λo, match o with | or.inl ⟨k0, m1⟩ := by rw [k0, m1]; refl | or.inr ⟨kpos, or.inl ⟨n0, m0⟩⟩ := by rw [n0, m0, zero_pow kpos] | or.inr ⟨kpos, or.inr ⟨npos, w, a, t, z, (a1 : 1 < a), (tm : xn a1 k ≡ yn a1 k * (a - n) + m [MOD t]), (ta : 2 * a * n = t + (n * n + 1)), (mt : m < t), (nw : n ≤ w), (kw : k ≤ w), (zp : a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)⟩⟩ := have wpos : 0 < w, from lt_of_lt_of_le npos nw, have w1 : 1 < w + 1, from nat.succ_lt_succ wpos, let ⟨j, xj, yj⟩ := eq_pell w1 zp in by clear _match o _let_match; exact have jpos : 0 < j, from (nat.eq_zero_or_pos j).resolve_left $ λj0, have a1 : a = 1, by rw j0 at xj; exact xj, have 2 * n = t + (n * n + 1), by rw a1 at ta; exact ta, have n1 : n = 1, from have n * n < n * 2, by rw [mul_comm n 2, this]; apply nat.le_add_left, have n ≤ 1, from nat.le_of_lt_succ $ lt_of_mul_lt_mul_left this (nat.zero_le _), le_antisymm this npos, by rw n1 at this; rw ← @nat.add_right_cancel 0 2 t this at mt; exact nat.not_lt_zero _ mt, have wj : w ≤ j, from nat.le_of_dvd jpos $ modeq.modeq_zero_iff.1 $ (yn_modeq_a_sub_one w1 j).symm.trans $ modeq.modeq_zero_iff.2 ⟨z, yj.symm⟩, have nt : (↑(n^k) : ℤ) < 2 * a * n - n * n - 1, from eq_pow_of_pell_lem a1 npos kpos $ calc n^k ≤ n^j : nat.pow_le_pow_of_le_right npos (le_trans kw wj) ... < (w + 1)^j : nat.pow_lt_pow_of_lt_left (nat.lt_succ_of_le nw) jpos ... ≤ xn w1 j : xn_ge_a_pow w1 j ... = a : xj.symm, have na : n ≤ a, by rw xj; exact le_trans (le_trans nw wj) (le_of_lt $ n_lt_xn _ _), have te : (t : ℤ) = 2 * ↑a * ↑n - ↑n * ↑n - 1, by rw sub_sub; apply eq_sub_of_add_eq; apply (int.coe_nat_eq_coe_nat_iff _ _).2; exact ta.symm, have xn a1 k ≡ yn a1 k * (a - n) + n^k [MOD t], by have := x_sub_y_dvd_pow a1 n k; rw [← te, ← int.coe_nat_sub na] at this; exact modeq.modeq_of_dvd this, have n^k % t = m % t, from modeq.modeq_add_cancel_left (modeq.refl _) (this.symm.trans tm), by rw ← te at nt; rwa [nat.mod_eq_of_lt (int.lt_of_coe_nat_lt_coe_nat nt), nat.mod_eq_of_lt mt] at this end⟩ end pell
ca2432b85f6e800737e33a5fdfc58bdab48961b5
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/eq15.lean
de98b67232d60b42d11e78cd727fc22e3f7f62fa
[ "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
401
lean
open list set_option pp.implicit true definition app {A : Type} : list A → list A → list A | nil l := l | (h :: t) l := h :: (app t l) theorem app_nil {A : Type} (l : list A) : app nil l = l := rfl theorem app_cons {A : Type} (h : A) (t l : list A) : app (h :: t) l = h :: (app t l) := rfl example : app ((1:nat) :: 2 :: nil) (3 :: 4 :: 5 :: nil) = (1 :: 2 :: 3 :: 4 :: 5 :: nil) := rfl
8e1fa4ce63074304328c89b6cef0789260557b29
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/fun_like/basic.lean
c250c6d4e5a279fe9d64acbca659571127af990e
[ "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
7,298
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import logic.function.basic import tactic.lint import tactic.norm_cast /-! # Typeclass for a type `F` with an injective map to `A → B` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/541 > Any changes to this file require a corresponding PR to mathlib4. This typeclass is primarily for use by homomorphisms like `monoid_hom` and `linear_map`. ## Basic usage of `fun_like` A typical type of morphisms should be declared as: ``` structure my_hom (A B : Type*) [my_class A] [my_class B] := (to_fun : A → B) (map_op' : ∀ {x y : A}, to_fun (my_class.op x y) = my_class.op (to_fun x) (to_fun y)) namespace my_hom variables (A B : Type*) [my_class A] [my_class B] -- This instance is optional if you follow the "morphism class" design below: instance : fun_like (my_hom A B) A (λ _, B) := { coe := my_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (my_hom A B) (λ _, A → B) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : my_hom A B} : f.to_fun = (f : A → B) := rfl @[ext] theorem ext {f g : my_hom A B} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h /-- Copy of a `my_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : my_hom A B) (f' : A → B) (h : f' = ⇑f) : my_hom A B := { to_fun := f', map_op' := h.symm ▸ f.map_op' } end my_hom ``` This file will then provide a `has_coe_to_fun` instance and various extensionality and simp lemmas. ## Morphism classes extending `fun_like` The `fun_like` design provides further benefits if you put in a bit more work. The first step is to extend `fun_like` to create a class of those types satisfying the axioms of your new type of morphisms. Continuing the example above: ``` section set_option old_structure_cmd true /-- `my_hom_class F A B` states that `F` is a type of `my_class.op`-preserving morphisms. You should extend this class when you extend `my_hom`. -/ class my_hom_class (F : Type*) (A B : out_param $ Type*) [my_class A] [my_class B] extends fun_like F A (λ _, B) := (map_op : ∀ (f : F) (x y : A), f (my_class.op x y) = my_class.op (f x) (f y)) end @[simp] lemma map_op {F A B : Type*} [my_class A] [my_class B] [my_hom_class F A B] (f : F) (x y : A) : f (my_class.op x y) = my_class.op (f x) (f y) := my_hom_class.map_op -- You can replace `my_hom.fun_like` with the below instance: instance : my_hom_class (my_hom A B) A B := { coe := my_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_op := my_hom.map_op' } -- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here] ``` The second step is to add instances of your new `my_hom_class` for all types extending `my_hom`. Typically, you can just declare a new class analogous to `my_hom_class`: ``` structure cooler_hom (A B : Type*) [cool_class A] [cool_class B] extends my_hom A B := (map_cool' : to_fun cool_class.cool = cool_class.cool) section set_option old_structure_cmd true class cooler_hom_class (F : Type*) (A B : out_param $ Type*) [cool_class A] [cool_class B] extends my_hom_class F A B := (map_cool : ∀ (f : F), f cool_class.cool = cool_class.cool) end @[simp] lemma map_cool {F A B : Type*} [cool_class A] [cool_class B] [cooler_hom_class F A B] (f : F) : f cool_class.cool = cool_class.cool := my_hom_class.map_op -- You can also replace `my_hom.fun_like` with the below instance: instance : cool_hom_class (cool_hom A B) A B := { coe := cool_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_op := cool_hom.map_op', map_cool := cool_hom.map_cool' } -- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here] ``` Then any declaration taking a specific type of morphisms as parameter can instead take the class you just defined: ``` -- Compare with: lemma do_something (f : my_hom A B) : sorry := sorry lemma do_something {F : Type*} [my_hom_class F A B] (f : F) : sorry := sorry ``` This means anything set up for `my_hom`s will automatically work for `cool_hom_class`es, and defining `cool_hom_class` only takes a constant amount of effort, instead of linearly increasing the work per `my_hom`-related declaration. -/ -- This instance should have low priority, to ensure we follow the chain -- `fun_like → has_coe_to_fun` attribute [instance, priority 10] coe_fn_trans /-- The class `fun_like F α β` expresses that terms of type `F` have an injective coercion to functions from `α` to `β`. This typeclass is used in the definition of the homomorphism typeclasses, such as `zero_hom_class`, `mul_hom_class`, `monoid_hom_class`, .... -/ class fun_like (F : Sort*) (α : out_param Sort*) (β : out_param $ α → Sort*) := (coe : F → Π a : α, β a) (coe_injective' : function.injective coe) section dependent /-! ### `fun_like F α β` where `β` depends on `a : α` -/ variables (F α : Sort*) (β : α → Sort*) namespace fun_like variables {F α β} [i : fun_like F α β] include i @[priority 100, -- Give this a priority between `coe_fn_trans` and the default priority nolint dangerous_instance] -- `α` and `β` are out_params, so this instance should not be dangerous instance : has_coe_to_fun F (λ _, Π a : α, β a) := { coe := fun_like.coe } @[simp] lemma coe_eq_coe_fn : (fun_like.coe : F → Π a : α, β a) = coe_fn := rfl theorem coe_injective : function.injective (coe_fn : F → Π a : α, β a) := fun_like.coe_injective' @[simp, norm_cast] theorem coe_fn_eq {f g : F} : (f : Π a : α, β a) = (g : Π a : α, β a) ↔ f = g := ⟨λ h, @coe_injective _ _ _ i _ _ h, λ h, by cases h; refl⟩ theorem ext' {f g : F} (h : (f : Π a : α, β a) = (g : Π a : α, β a)) : f = g := coe_injective h theorem ext'_iff {f g : F} : f = g ↔ ((f : Π a : α, β a) = (g : Π a : α, β a)) := coe_fn_eq.symm theorem ext (f g : F) (h : ∀ (x : α), f x = g x) : f = g := coe_injective (funext h) theorem ext_iff {f g : F} : f = g ↔ (∀ x, f x = g x) := coe_fn_eq.symm.trans function.funext_iff protected lemma congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x := congr_fun (congr_arg _ h₁) x lemma ne_iff {f g : F} : f ≠ g ↔ ∃ a, f a ≠ g a := ext_iff.not.trans not_forall lemma exists_ne {f g : F} (h : f ≠ g) : ∃ x, f x ≠ g x := ne_iff.mp h /-- This is not an instance to avoid slowing down every single `subsingleton` typeclass search.-/ lemma subsingleton_cod [∀ a, subsingleton (β a)] : subsingleton F := ⟨λ f g, coe_injective $ subsingleton.elim _ _⟩ end fun_like end dependent section non_dependent /-! ### `fun_like F α (λ _, β)` where `β` does not depend on `a : α` -/ variables {F α β : Sort*} [i : fun_like F α (λ _, β)] include i namespace fun_like protected lemma congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y := congr (congr_arg _ h₁) h₂ protected lemma congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y := congr_arg _ h₂ end fun_like end non_dependent
5e08beb811f87933b15722f2d59fdab487779fa7
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/init/wf.hlean
82c688a6e0c9d7ea45404c77e0e19070879f4826
[ "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
8,303
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.relation init.tactic init.funext open eq inductive acc.{l₁ l₂} {A : Type.{l₁}} (R : A → A → Type.{l₂}) : A → Type.{max l₁ l₂} := intro : ∀x, (∀ y, R y x → acc R y) → acc R x namespace acc variables {A : Type} {R : A → A → Type} definition acc_eq {a : A} (H₁ H₂ : acc R a) : H₁ = H₂ := begin induction H₁ with a K₁ IH₁, induction H₂ with a K₂ IH₂, apply eq.ap (intro a), apply eq_of_homotopy, intro a, apply eq_of_homotopy, intro r, apply IH₁ end definition inv {x y : A} (H₁ : acc R x) (H₂ : R y x) : acc R y := acc.rec_on H₁ (λ x₁ ac₁ iH H₂, ac₁ y H₂) H₂ -- dependent elimination for acc protected definition drec [recursor] {C : Π (a : A), acc R a → Type} (h₁ : Π (x : A) (acx : Π (y : A), R y x → acc R y), (Π (y : A) (ryx : R y x), C y (acx y ryx)) → C x (acc.intro x acx)) {a : A} (h₂ : acc R a) : C a h₂ := acc.rec h₁ h₂ end acc inductive well_founded [class] {A : Type} (R : A → A → Type) : Type := intro : (Π a, acc R a) → well_founded R namespace well_founded definition apply [coercion] {A : Type} {R : A → A → Type} (wf : well_founded R) : Πa, acc R a := take a, well_founded.rec_on wf (λp, p) a section parameters {A : Type} {R : A → A → Type} local infix `≺`:50 := R hypothesis [Hwf : well_founded R] theorem recursion {C : A → Type} (a : A) (H : Πx, (Πy, y ≺ x → C y) → C x) : C a := acc.rec_on (Hwf a) (λ x₁ ac₁ iH, H x₁ iH) theorem induction {C : A → Type} (a : A) (H : Πx, (Πy, y ≺ x → C y) → C x) : C a := recursion a H variable {C : A → Type} variable F : Πx, (Πy, y ≺ x → C y) → C x definition fix_F (x : A) (a : acc R x) : C x := acc.rec_on a (λ x₁ ac₁ iH, F x₁ iH) theorem fix_F_eq (x : A) (r : acc R x) : fix_F F x r = F x (λ (y : A) (p : y ≺ x), fix_F F y (acc.inv r p)) := begin induction r using acc.drec, reflexivity -- proof is star due to proof irrelevance end end variables {A : Type} {C : A → Type} {R : A → A → Type} -- Well-founded fixpoint definition fix [Hwf : well_founded R] (F : Πx, (Πy, R y x → C y) → C x) (x : A) : C x := fix_F F x (Hwf x) -- Well-founded fixpoint satisfies fixpoint equation theorem fix_eq [Hwf : well_founded R] (F : Πx, (Πy, R y x → C y) → C x) (x : A) : fix F x = F x (λy h, fix F y) := begin refine fix_F_eq F x (Hwf x) ⬝ _, apply ap (F x), apply eq_of_homotopy, intro a, apply eq_of_homotopy, intro r, apply ap (fix_F F a), apply acc.acc_eq end end well_founded open well_founded -- Empty relation is well-founded definition empty.wf {A : Type} : well_founded empty_relation := well_founded.intro (λ (a : A), acc.intro a (λ (b : A) (lt : empty), empty.rec _ lt)) -- Subrelation of a well-founded relation is well-founded namespace subrelation section universe variable u parameters {A : Type} {R Q : A → A → Type} parameters (H₁ : subrelation Q R) parameters (H₂ : well_founded R) definition accessible {a : A} (ac : acc R a) : acc Q a := using H₁, begin induction ac with x ax ih, constructor, exact λ (y : A) (lt : Q y x), ih y (H₁ lt) end definition wf : well_founded Q := using H₂, well_founded.intro (λ a, accessible proof (@apply A R H₂ a) qed) end end subrelation -- The inverse image of a well-founded relation is well-founded namespace inv_image section parameters {A B : Type} {R : B → B → Type} parameters (f : A → B) parameters (H : well_founded R) private definition acc_aux {b : B} (ac : acc R b) : Π x, f x = b → acc (inv_image R f) x := begin induction ac with x acx ih, intro z e, constructor, intro y lt, subst x, exact ih (f y) lt y rfl end definition accessible {a : A} (ac : acc R (f a)) : acc (inv_image R f) a := acc_aux ac a rfl definition wf : well_founded (inv_image R f) := well_founded.intro (λ a, accessible (H (f a))) end end inv_image -- The transitive closure of a well-founded relation is well-founded namespace tc section parameters {A : Type} {R : A → A → Type} local notation `R⁺` := tc R definition accessible {z} (ac: acc R z) : acc R⁺ z := begin induction ac with x acx ih, constructor, intro y rel, induction rel with a b rab a b c rab rbc ih₁ ih₂, {exact ih a rab}, {exact acc.inv (ih₂ acx ih) rab} end definition wf (H : well_founded R) : well_founded R⁺ := well_founded.intro (λ a, accessible (H a)) end end tc namespace nat -- less-than is well-founded definition lt.wf [instance] : well_founded (lt : ℕ → ℕ → Type₀) := begin constructor, intro n, induction n with n IH, { constructor, intros n H, exfalso, exact !not_lt_zero H}, { constructor, intros m H, have aux : ∀ {n₁} (hlt : m < n₁), succ n = n₁ → acc lt m, begin intros n₁ hlt, induction hlt, { intro p, injection p with q, exact q ▸ IH}, { intro p, injection p with q, exact (acc.inv (q ▸ IH) a)} end, apply aux H rfl}, end definition measure {A : Type} : (A → ℕ) → A → A → Type₀ := inv_image lt definition measure.wf {A : Type} (f : A → ℕ) : well_founded (measure f) := inv_image.wf f lt.wf end nat namespace prod open well_founded prod.ops section variables {A B : Type} variable (Ra : A → A → Type) variable (Rb : B → B → Type) -- Lexicographical order based on Ra and Rb inductive lex : A × B → A × B → Type := | left : ∀{a₁ b₁} a₂ b₂, Ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂) | right : ∀a {b₁ b₂}, Rb b₁ b₂ → lex (a, b₁) (a, b₂) -- Relational product based on Ra and Rb inductive rprod : A × B → A × B → Type := intro : ∀{a₁ b₁ a₂ b₂}, Ra a₁ a₂ → Rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂) end section parameters {A B : Type} parameters {Ra : A → A → Type} {Rb : B → B → Type} local infix `≺`:50 := lex Ra Rb definition lex.accessible {a} (aca : acc Ra a) (acb : ∀b, acc Rb b): ∀b, acc (lex Ra Rb) (a, b) := acc.rec_on aca (λxa aca (iHa : ∀y, Ra y xa → ∀b, acc (lex Ra Rb) (y, b)), λb, acc.rec_on (acb b) (λxb acb (iHb : ∀y, Rb y xb → acc (lex Ra Rb) (xa, y)), acc.intro (xa, xb) (λp (lt : p ≺ (xa, xb)), have aux : xa = xa → xb = xb → acc (lex Ra Rb) p, from @prod.lex.rec_on A B Ra Rb (λp₁ p₂ h, pr₁ p₂ = xa → pr₂ p₂ = xb → acc (lex Ra Rb) p₁) p (xa, xb) lt (λa₁ b₁ a₂ b₂ (H : Ra a₁ a₂) (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a₁, b₁), from have Ra₁ : Ra a₁ xa, from eq.rec_on eq₂ H, iHa a₁ Ra₁ b₁) (λa b₁ b₂ (H : Rb b₁ b₂) (eq₂ : a = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a, b₁), from have Rb₁ : Rb b₁ xb, from eq.rec_on eq₃ H, have eq₂' : xa = a, from eq.rec_on eq₂ rfl, eq.rec_on eq₂' (iHb b₁ Rb₁)), aux rfl rfl))) -- The lexicographical order of well founded relations is well-founded definition lex.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (lex Ra Rb) := well_founded.intro (λp, destruct p (λa b, lex.accessible (Ha a) (well_founded.apply Hb) b)) -- Relational product is a subrelation of the lex definition rprod.sub_lex : ∀ a b, rprod Ra Rb a b → lex Ra Rb a b := λa b H, prod.rprod.rec_on H (λ a₁ b₁ a₂ b₂ H₁ H₂, lex.left Rb a₂ b₂ H₁) -- The relational product of well founded relations is well-founded definition rprod.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (rprod Ra Rb) := subrelation.wf (rprod.sub_lex) (lex.wf Ha Hb) end end prod
ac40afec6ccec983a2de36581a165666496d062a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/deriv/support.lean
adb9f0637a7ad54d7c174ba0a5872961be7c5f0b
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,217
lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import analysis.calculus.deriv.basic /-! # Support of the derivative of a function > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove that the (topological) support of a function includes the support of its derivative. As a corollary, we show that the derivative of a function with compact support has compact support. ## Keywords derivative, support -/ universes u v variables {𝕜 : Type u} [nontrivially_normed_field 𝕜] variables {E : Type v} [normed_add_comm_group E] [normed_space 𝕜 E] variables {f : 𝕜 → E} /-! ### Support of derivatives -/ section support open function lemma support_deriv_subset : support (deriv f) ⊆ tsupport f := begin intros x, rw [← not_imp_not], intro h2x, rw [not_mem_tsupport_iff_eventually_eq] at h2x, exact nmem_support.mpr (h2x.deriv_eq.trans (deriv_const x 0)) end lemma has_compact_support.deriv (hf : has_compact_support f) : has_compact_support (deriv f) := hf.mono' support_deriv_subset end support
efa2f2343d04d06dae1779ece6d1841a6baa884a
82e44445c70db0f03e30d7be725775f122d72f3e
/src/measure_theory/tactic.lean
eca41146a3f572a24fe5d3450dfed6e4d5a2ea72
[ "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,428
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import tactic.auto_cases import tactic.tidy import tactic.with_local_reducibility import tactic.show_term import measure_theory.measure_space_def /-! # Tactics for measure theory Currently we have one domain-specific tactic for measure theory: `measurability`. This tactic is to a large extent a copy of the `continuity` tactic by Reid Barton. -/ /-! ### `measurability` tactic Automatically solve goals of the form `measurable f`, `ae_measurable f μ` and `measurable_set s`. Mark lemmas with `@[measurability]` to add them to the set of lemmas used by `measurability`. Note: `to_additive` doesn't know yet how to copy the attribute to the additive version. -/ /-- User attribute used to mark tactics used by `measurability`. -/ @[user_attribute] meta def measurability : user_attribute := { name := `measurability, descr := "lemmas usable to prove (ae)-measurability" } /- Mark some measurability lemmas already defined in `measure_theory.measurable_space_def` and `measure_theory.measure_space_def` -/ attribute [measurability] measurable_id measurable_id' ae_measurable_id ae_measurable_id' measurable_const ae_measurable_const ae_measurable.measurable_mk measurable_set.empty measurable_set.univ measurable_set.compl subsingleton.measurable_set measurable_set.Union measurable_set.Inter measurable_set.Union_Prop measurable_set.Inter_Prop measurable_set.union measurable_set.inter measurable_set.diff measurable_set.symm_diff measurable_set.ite measurable_set.cond measurable_set.disjointed measurable_set.const measurable_set.insert measurable_set_eq set.finite.measurable_set finset.measurable_set set.countable.measurable_set measurable_space.measurable_set_top namespace tactic /-- Tactic to apply `measurable.comp` when appropriate. Applying `measurable.comp` is not always a good idea, so we have some extra logic here to try to avoid bad cases. * If the function we're trying to prove measurable is actually constant, and that constant is a function application `f z`, then measurable.comp would produce new goals `measurable f`, `measurable (λ _, z)`, which is silly. We avoid this by failing if we could apply `measurable_const`. * measurable.comp will always succeed on `measurable (λ x, f x)` and produce new goals `measurable (λ x, x)`, `measurable f`. We detect this by failing if a new goal can be closed by applying measurable_id. -/ meta def apply_measurable.comp : tactic unit := `[fail_if_success { exact measurable_const }; refine measurable.comp _ _; fail_if_success { exact measurable_id }] /-- Tactic to apply `measurable.comp_ae_measurable` when appropriate. Applying `measurable.comp_ae_measurable` is not always a good idea, so we have some extra logic here to try to avoid bad cases. * If the function we're trying to prove measurable is actually constant, and that constant is a function application `f z`, then `measurable.comp_ae_measurable` would produce new goals `measurable f`, `ae_measurable (λ _, z) μ`, which is silly. We avoid this by failing if we could apply `ae_measurable_const`. * `measurable.comp_ae_measurable` will always succeed on `ae_measurable (λ x, f x) μ` and can produce new goals (`measurable (λ x, x)`, `ae_measurable f μ`) or (`measurable f`, `ae_measurable (λ x, x) μ`). We detect those by failing if a new goal can be closed by applying `measurable_id` or `ae_measurable_id`. -/ meta def apply_measurable.comp_ae_measurable : tactic unit := `[fail_if_success { exact ae_measurable_const }; refine measurable.comp_ae_measurable _ _; fail_if_success { exact measurable_id }; fail_if_success { exact ae_measurable_id }] /-- We don't want the intro1 tactic to apply to a goal of the form `measurable f`, `ae_measurable f μ` or `measurable_set s`. This tactic tests the target to see if it matches that form. -/ meta def goal_is_not_measurable : tactic unit := do t ← tactic.target, match t with | `(measurable %%l) := failed | `(ae_measurable %%l %%r) := failed | `(measurable_set %%l) := failed | _ := skip end /-- List of tactics used by `measurability` internally. -/ meta def measurability_tactics (md : transparency := semireducible) : list (tactic string) := [ propositional_goal >> apply_assumption >> pure "apply_assumption", goal_is_not_measurable >> intro1 >>= λ ns, pure ("intro " ++ ns.to_string), apply_rules [``(measurability)] 50 { md := md } >> pure "apply_rules measurability", apply_measurable.comp >> pure "refine measurable.comp _ _", apply_measurable.comp_ae_measurable >> pure "refine measurable.comp_ae_measurable _ _", `[ refine measurable.ae_measurable _ ] >> pure "refine measurable.ae_measurable _" ] namespace interactive setup_tactic_parser /-- Solve goals of the form `measurable f`, `ae_measurable f μ` or `measurable_set s`. `measurability?` reports back the proof term it found. -/ meta def measurability (bang : parse $ optional (tk "!")) (trace : parse $ optional (tk "?")) (cfg : tidy.cfg := {}) : tactic unit := let md := if bang.is_some then semireducible else reducible, measurability_core := tactic.tidy { tactics := measurability_tactics md, ..cfg }, trace_fn := if trace.is_some then show_term else id in trace_fn measurability_core /-- Version of `measurability` for use with auto_param. -/ meta def measurability' : tactic unit := measurability none none {} /-- `measurability` solves goals of the form `measurable f`, `ae_measurable f μ` or `measurable_set s` by applying lemmas tagged with the `measurability` user attribute. You can also use `measurability!`, which applies lemmas with `{ md := semireducible }`. The default behaviour is more conservative, and only unfolds `reducible` definitions when attempting to match lemmas with the goal. `measurability?` reports back the proof term it found. -/ add_tactic_doc { name := "measurability / measurability'", category := doc_category.tactic, decl_names := [`tactic.interactive.measurability, `tactic.interactive.measurability'], tags := ["lemma application"] } end interactive end tactic