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
e3d39a61a2b026035c43b2473c31709d29ec6e3f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/type_equations.lean
45529bce7b3971d1386b82e3f1e149069580dd42
[ "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
1,582
lean
open nat inductive Expr | zero : Expr | one : Expr | add : Expr → Expr → Expr namespace Expr inductive direct_subterm : Expr → Expr → Prop | add_1 : ∀ e₁ e₂ : Expr, direct_subterm e₁ (add e₁ e₂) | add_2 : ∀ e₁ e₂ : Expr, direct_subterm e₂ (add e₁ e₂) theorem direct_subterm_wf : well_founded direct_subterm := begin constructor, intro e, induction e, repeat { constructor, intros y hlt, cases hlt; assumption }, end inductive tc {α : Sort*} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → tc a b | trans : ∀ a b c, tc a b → tc b c → tc a c -- The transitive closure of a well-founded relation is well-founded -- (moved to mathlib) namespace tc section parameters {α : Sort*} {r : α → α → Prop} local notation `r⁺` := tc r lemma accessible {z : α} (ac : acc r z) : acc (tc r) z := acc.rec_on ac (λ x acx ih, acc.intro x (λ y rel, tc.rec_on rel (λ a b rab acx ih, ih a rab) (λ a b c rab rbc ih₁ ih₂ acx ih, acc.inv (ih₂ acx ih) rab) acx ih)) lemma wf (h : well_founded r) : well_founded r⁺ := ⟨λ a, accessible (h.apply a)⟩ end end tc definition subterm := tc direct_subterm theorem subterm_wf : well_founded subterm := tc.wf direct_subterm_wf local infix (name := add) `+` := Expr.add set_option pp.notation false definition ev : Expr → nat | zero := 0 | one := 1 | ((a : Expr) + b) := has_add.add (ev a) (ev b) definition foo : Expr := add zero (add one one) example : ev foo = 2 := rfl end Expr
1bc1ff6512c0721913523d3b5e93f9cf483a486e
26b8b0964ca8e1c2e203585ba5940f83fe05e48a
/src/tidy/congr_struct.lean
3013260d118c30122ba99b17e7aa72f2018599eb
[]
no_license
jcommelin/lean-tidy
ef3cd32a3804221d93f0dff9e180bb2c52f4b143
9cecf497e90db64b5ea140ad6ae1603976dcd402
refs/heads/master
1,585,129,919,276
1,533,512,680,000
1,533,512,680,000
143,677,361
0
0
null
1,616,803,481,000
1,533,530,576,000
Lean
UTF-8
Lean
false
false
3,288
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .applicable open tactic namespace tactic open expr /-- Given a fully applied structure type `ty` with fields `f1`...`fn`, synthesize the proof `∀ x : ty, ty.mk x.f1 ... x.fn = x`. The proof can be extracted into a new definition using ``` def ty.eta := by mk_struct_eta ```(ty) >>= exact ``` -/ meta def mk_struct_eta (ty : expr) : tactic expr := do (const n ls) ← pure ty.get_app_fn | fail "not a structure", env ← get_env, fields ← env.structure_fields n <|> fail "not a structure", [ctor] ← pure $ env.constructors_of n, let ctor := (const ctor ls).mk_app ty.get_app_args, x ← mk_local_def `x ty, fields ← fields.mmap $ λ f, to_expr (pexpr.mk_field_macro (pexpr.of_expr x) f), proof_ty ← mk_app ``eq [ctor.mk_app fields, x], prod.snd <$> ((pis [x] proof_ty) >>= λ e, solve_aux e (do x ← intro `_, cases x, reflexivity)) end tactic namespace tactic.interactive open expr tactic private meta def common_app_prefix : expr → expr → tactic expr | (app e₁ e₁') (app e₂ e₂') := (is_def_eq e₁ e₂ *> pure e₁) <|> common_app_prefix e₁ e₂ | e₁ e₂ := fail "no common head symbol" /-- Given a goal of form `f a₁ ... aₙ == f a₁' ... aₙ'`, this tactic breaks it down to subgoals `a₁ == a₁'`, ... Subgoals provable by reflexivity are dispensed automatically. The goal can also be a homogenous equality. New subgoals will use homogenous equalities where possible. -/ meta def congr_args : tactic unit := do tgt ← target, (lhs, rhs) ← match tgt with | `(%%lhs = %%rhs) := pure (lhs, rhs) | `(%%lhs == %%rhs) := pure (lhs, rhs) | _ := fail "goal is not an equality" end, pre ← common_app_prefix lhs rhs, l ← mk_hcongr_lemma pre, tactic.apply l.proof, all_goals $ try refl /-- Given a goal that equates two structure values, this tactic breaks it down to subgoals equating each pair of fields. -/ meta def congr_struct : tactic unit := do `(%%lhs = %%rhs) ← target | fail "goal is not an equality", ty ← infer_type lhs, eta ← mk_struct_eta ty, apply ``(@eq.rec _ _ (λ lhs, lhs = %%rhs) _ _ %%(app eta lhs)), `(%%new_lhs = %%rhs) ← target, apply ``(@eq.rec _ _ (λ rhs, %%new_lhs = rhs) _ _ %%(app eta rhs)), congr_args end tactic.interactive -- congr_struct needs various helper lemmas. @[applicable] lemma heq_prop { α β : Prop } { a : α } { b : β } ( h : α = β ) : a == b := begin induction h, reflexivity end @[applicable] theorem {u v w z} funext_prop_001 { α : Type u } { β : Type v } { Z : α → β → Type w } { X : Π ( a : α ) ( b : β ) ( g : Z a b ), Type z } { p q r s : Π ( a : α ) ( b : β ) ( g : Z a b ), X a b g } ( h1 : p = r ) ( h2 : q = s ) : (∀ ( a : α ) ( b : β ) ( g : Z a b ), p a b g = q a b g ) = (∀ ( a : α ) ( b : β ) ( g : Z a b), r a b g = s a b g ) := begin induction h1, induction h2, reflexivity end
9b1a37bbbea16c8e2832491353a55e35e7e740d0
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/print_meta.lean
9fda7678f55975abc05364878c6401f7168edd5b
[ "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
20
lean
#print tactic.intro
87be2cb8db72dba8e27cce81a8448760d55720d0
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/padics/padic_numbers.lean
c8ff40e5667e47073f9e8e595c1846430b1301a0
[ "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
38,158
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 data.padics.padic_norm import analysis.normed_space.basic /-! # p-adic numbers This file defines the p-adic numbers (rationals) `ℚ_p` as the completion of `ℚ` with respect to the p-adic norm. We show that the p-adic norm on ℚ extends to `ℚ_p`, that `ℚ` is embedded in `ℚ_p`, and that `ℚ_p` is Cauchy complete. ## Important definitions * `padic` : the type of p-adic numbers * `padic_norm_e` : the rational valued p-adic norm on `ℚ_p` ## Notation We introduce the notation `ℚ_[p]` for the p-adic numbers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (prime p)]` as a type class argument. We use the same concrete Cauchy sequence construction that is used to construct ℝ. `ℚ_p` inherits a field structure from this construction. The extension of the norm on ℚ to `ℚ_p` is *not* analogous to extending the absolute value to ℝ, and hence the proof that `ℚ_p` is complete is different from the proof that ℝ is complete. A small special-purpose simplification tactic, `padic_index_simp`, is used to manipulate sequence indices in the proof that the norm extends. `padic_norm_e` is the rational-valued p-adic norm on `ℚ_p`. To instantiate `ℚ_p` as a normed field, we must cast this into a ℝ-valued norm. The `ℝ`-valued norm, using notation `∥ ∥` from normed spaces, is the canonical representation of this norm. `simp` prefers `padic_norm` to `padic_norm_e` when possible. Since `padic_norm_e` and `∥ ∥` have different types, `simp` does not rewrite one to the other. Coercions from `ℚ` to `ℚ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation, cauchy, completion, p-adic completion -/ noncomputable theory open_locale classical open nat multiplicity padic_norm cau_seq cau_seq.completion metric /-- The type of Cauchy sequences of rationals with respect to the p-adic norm. -/ @[reducible] def padic_seq (p : ℕ) := cau_seq _ (padic_norm p) namespace padic_seq section variables {p : ℕ} [fact p.prime] /-- The p-adic norm of the entries of a nonzero Cauchy sequence of rationals is eventually constant. -/ lemma stationary {f : cau_seq ℚ (padic_norm p)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, N ≤ m → N ≤ n → padic_norm p (f n) = padic_norm p (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm p (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this, ⟨N2, hN2⟩ := cau_seq.cauchy₂ f hε in ⟨ max N1 N2, λ n m hn hm, have padic_norm p (f n - f m) < ε, from hN2 _ _ (max_le_iff.1 hn).2 (max_le_iff.1 hm).2, have padic_norm p (f n - f m) < padic_norm p (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm p (f n - f m) < max (padic_norm p (f n)) (padic_norm p (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ←padic_norm.neg p (f m) at hne, have hnam := add_eq_max_of_ne p hne, rw [padic_norm.neg, max_comm] at hnam, rw [←hnam, sub_eq_add_neg, add_comm] at this, apply _root_.lt_irrefl _ this end ⟩ /-- For all n ≥ stationary_point f hf, the p-adic norm of f n is the same. -/ def stationary_point {f : padic_seq p} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq p} (hf : ¬ f ≈ 0) : ∀ {m n}, stationary_point hf ≤ m → stationary_point hf ≤ n → padic_norm p (f n) = padic_norm p (f m) := classical.some_spec $ stationary hf /-- Since the norm of the entries of a Cauchy sequence is eventually stationary, we can lift the norm to sequences. -/ def norm (f : padic_seq p) : ℚ := if hf : f ≈ 0 then 0 else padic_norm p (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq p) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf (le_refl _) hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} [fact p.prime] lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq p} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm p k ∧ k ≠ 0 := have heq : f.norm = padic_norm p (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm p) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ (const (padic_norm p) q) ≈ 0 := λ h : lim_zero (const (padic_norm p) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq p) : 0 ≤ f.norm := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v2 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max (stationary_point hf) (max v2 v3))) := begin apply stationary_point_spec hf, { apply le_max_left }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max (stationary_point hf) v3))) := begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_left _ v3 }, { apply le_max_right } }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_right {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v2 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max v2 (stationary_point hf)))) := begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_right v2 }, { apply le_max_right } }, { apply le_refl } end end embedding section valuation open cau_seq variables {p : ℕ} [fact p.prime] /-! ### Valuation on `padic_seq` -/ /-- The `p`-adic valuation on `ℚ` lifts to `padic_seq p`. `valuation f` is defined to be the valuation of the (`ℚ`-valued) stationary point of `f`. -/ def valuation (f : padic_seq p) : ℤ := if hf : f ≈ 0 then 0 else padic_val_rat p (f (stationary_point hf)) lemma norm_eq_pow_val {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm = p^(-f.valuation : ℤ) := begin rw [norm, valuation, dif_neg hf, dif_neg hf, padic_norm, if_neg], intro H, apply cau_seq.not_lim_zero_of_not_congr_zero hf, intros ε hε, use (stationary_point hf), intros n hn, rw stationary_point_spec hf (le_refl _) hn, simpa [H] using hε, end lemma val_eq_iff_norm_eq {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : f.valuation = g.valuation ↔ f.norm = g.norm := begin rw [norm_eq_pow_val hf, norm_eq_pow_val hg, ← neg_inj, fpow_inj], { exact_mod_cast (fact.out p.prime).pos }, { exact_mod_cast (fact.out p.prime).ne_one }, end end valuation end padic_seq section open padic_seq private meta def index_simp_core (hh hf hg : expr) (at_ : interactive.loc := interactive.loc.ns [none]) : tactic unit := do [v1, v2, v3] ← [hh, hf, hg].mmap (λ n, tactic.mk_app ``stationary_point [n] <|> return n), e1 ← tactic.mk_app ``lift_index_left_left [hh, v2, v3] <|> return `(true), e2 ← tactic.mk_app ``lift_index_left [hf, v1, v3] <|> return `(true), e3 ← tactic.mk_app ``lift_index_right [hg, v1, v2] <|> return `(true), sl ← [e1, e2, e3].mfoldl (λ s e, simp_lemmas.add s e) simp_lemmas.mk, when at_.include_goal (tactic.simp_target sl >> tactic.skip), hs ← at_.get_locals, hs.mmap' (tactic.simp_hyp sl []) /-- This is a special-purpose tactic that lifts padic_norm (f (stationary_point f)) to padic_norm (f (max _ _ _)). -/ meta def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list) (at_ : interactive.parse interactive.types.location) : tactic unit := do [h, f, g] ← l.mmap tactic.i_to_expr, index_simp_core h f g at_ end namespace padic_seq section embedding open cau_seq variables {p : ℕ} [hp : fact p.prime] include hp lemma norm_mul (f g : padic_seq p) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp only [hf, hg, norm, dif_pos, zero_mul] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp only [hf, hg, norm, dif_pos, mul_zero] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.mul end lemma eq_zero_iff_equiv_zero (f : padic_seq p) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq p) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm p) q) = padic_norm p q := if hq : q = 0 then have (const (padic_norm p) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm p) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm p) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_values_discrete (a : padic_seq p) (ha : ¬ a ≈ 0) : (∃ (z : ℤ), a.norm = ↑p ^ (-z)) := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.values_discrete p hk' lemma norm_one : norm (1 : padic_seq p) = 1 := have h1 : ¬ (1 : padic_seq p) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.1.one_lt] private lemma norm_eq_of_equiv_aux {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm p (f (stationary_point hf)) ≠ padic_norm p (g (stationary_point hg))) (hlt : padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf))) : false := begin have hpn : 0 < padic_norm p (f (stationary_point hf)) - padic_norm p (g (stationary_point hg)), from sub_pos_of_lt hlt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hi : N ≤ i, from le_max_left _ _, have hN' := hN _ hi, padic_index_simp [N, hf, hg] at hN' h hlt, have hpne : padic_norm p (f i) ≠ padic_norm p (-(g i)), by rwa [ ←padic_norm.neg p (g i)] at h, let hpnem := add_eq_max_of_ne p hpne, have hpeq : padic_norm p ((f - g) i) = max (padic_norm p (f i)) (padic_norm p (g i)), { rwa padic_norm.neg at hpnem }, rw [hpeq, max_eq_left_of_lt hlt] at hN', have : padic_norm p (f i) < padic_norm p (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm p (f (stationary_point hf)) = padic_norm p (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf)))) with hlt hnlt, { exact norm_eq_of_equiv_aux hf hg hfg h hlt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hnlt, apply h } end theorem norm_equiv {f g : padic_seq p} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq p} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max (f.norm) (g.norm) := begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq p) : (f + g).norm ≤ max (f.norm) (g.norm) := if hfg : f + g ≈ 0 then have 0 ≤ max (f.norm) (g.norm), from le_max_left_of_le (norm_nonneg _), by simpa only [hfg, norm, ne.def, le_max_iff, cau_seq.add_apply, not_true, dif_pos] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa only [sub_zero, add_sub_cancel] using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max (f.norm) (g.norm) = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa only [add_sub_cancel', sub_zero] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max (f.norm) (g.norm) = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp only [hf, hg, norm, dif_pos] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp only [h, forall_const, eq_self_iff_true]) hg, begin simp only [hg, hf, norm, dif_neg, not_false_iff], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm p (f (stationary_point hf)) = padic_norm p (f i), { apply stationary_point_spec, apply le_max_left, apply le_refl }, have hpg : padic_norm p (g (stationary_point hg)) = padic_norm p (g i), { apply stationary_point_spec, apply le_max_right, apply le_refl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq p) : (-a).norm = a.norm := norm_eq $ by simp lemma norm_eq_of_add_equiv_zero {f g : padic_seq p} (h : f + g ≈ 0) : f.norm = g.norm := have lim_zero (f + g - 0), from h, have f ≈ -g, from show lim_zero (f - (-g)), by simpa only [sub_zero, sub_neg_eq_add], have f.norm = (-g).norm, from norm_equiv this, by simpa only [norm_neg] using this lemma add_eq_max_of_ne {f g : padic_seq p} (hfgne : f.norm ≠ g.norm) : (f + g).norm = max f.norm g.norm := have hfg : ¬f + g ≈ 0, from mt norm_eq_of_add_equiv_zero hfgne, if hf : f ≈ 0 then have lim_zero (f - 0), from hf, have f + g ≈ g, from show lim_zero ((f + g) - g), by simpa only [sub_zero, add_sub_cancel], have h1 : (f+g).norm = g.norm, from norm_equiv this, have h2 : f.norm = 0, from (norm_zero_iff _).2 hf, by rw [h1, h2]; rw max_eq_right (norm_nonneg _) else if hg : g ≈ 0 then have lim_zero (g - 0), from hg, have f + g ≈ f, from show lim_zero ((f + g) - f), by rw [add_sub_cancel']; simpa only [sub_zero], have h1 : (f+g).norm = f.norm, from norm_equiv this, have h2 : g.norm = 0, from (norm_zero_iff _).2 hg, by rw [h1, h2]; rw max_eq_left (norm_nonneg _) else begin unfold norm at ⊢ hfgne, split_ifs at ⊢ hfgne, padic_index_simp [hfg, hf, hg] at ⊢ hfgne, exact padic_norm.add_eq_max_of_ne p hfgne end end embedding end padic_seq /-- The p-adic numbers `Q_[p]` are the Cauchy completion of `ℚ` with respect to the p-adic norm. -/ def padic (p : ℕ) [fact p.prime] := @cau_seq.completion.Cauchy _ _ _ _ (padic_norm p) _ notation `ℚ_[` p `]` := padic p namespace padic section completion variables {p : ℕ} [fact p.prime] /-- The discrete field structure on `ℚ_p` is inherited from the Cauchy completion construction. -/ instance field : field (ℚ_[p]) := cau_seq.completion.field instance : inhabited ℚ_[p] := ⟨0⟩ -- short circuits instance : has_zero ℚ_[p] := by apply_instance instance : has_one ℚ_[p] := by apply_instance instance : has_add ℚ_[p] := by apply_instance instance : has_mul ℚ_[p] := by apply_instance instance : has_sub ℚ_[p] := by apply_instance instance : has_neg ℚ_[p] := by apply_instance instance : has_div ℚ_[p] := by apply_instance instance : add_comm_group ℚ_[p] := by apply_instance instance : comm_ring ℚ_[p] := by apply_instance /-- Builds the equivalence class of a Cauchy sequence of rationals. -/ def mk : padic_seq p → ℚ_[p] := quotient.mk end completion section completion variables (p : ℕ) [fact p.prime] lemma mk_eq {f g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq /-- Embeds the rational numbers in the p-adic numbers. -/ def of_rat : ℚ → ℚ_[p] := cau_seq.completion.of_rat @[simp] lemma of_rat_add : ∀ (x y : ℚ), of_rat p (x + y) = of_rat p x + of_rat p y := cau_seq.completion.of_rat_add @[simp] lemma of_rat_neg : ∀ (x : ℚ), of_rat p (-x) = -of_rat p x := cau_seq.completion.of_rat_neg @[simp] lemma of_rat_mul : ∀ (x y : ℚ), of_rat p (x * y) = of_rat p x * of_rat p y := cau_seq.completion.of_rat_mul @[simp] lemma of_rat_sub : ∀ (x y : ℚ), of_rat p (x - y) = of_rat p x - of_rat p y := cau_seq.completion.of_rat_sub @[simp] lemma of_rat_div : ∀ (x y : ℚ), of_rat p (x / y) = of_rat p x / of_rat p y := cau_seq.completion.of_rat_div @[simp] lemma of_rat_one : of_rat p 1 = 1 := rfl @[simp] lemma of_rat_zero : of_rat p 0 = 0 := rfl lemma cast_eq_of_rat_of_nat (n : ℕ) : (↑n : ℚ_[p]) = of_rat p n := begin induction n with n ih, { refl }, { simpa using ih } end lemma cast_eq_of_rat_of_int (n : ℤ) : ↑n = of_rat p n := by induction n; simp [cast_eq_of_rat_of_nat] lemma cast_eq_of_rat : ∀ (q : ℚ), (↑q : ℚ_[p]) = of_rat p q | ⟨n, d, h1, h2⟩ := show ↑n / ↑d = _, from have (⟨n, d, h1, h2⟩ : ℚ) = rat.mk n d, from rat.num_denom', by simp [this, rat.mk_eq_div, of_rat_div, cast_eq_of_rat_of_int, cast_eq_of_rat_of_nat] @[norm_cast] lemma coe_add : ∀ {x y : ℚ}, (↑(x + y) : ℚ_[p]) = ↑x + ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_neg : ∀ {x : ℚ}, (↑(-x) : ℚ_[p]) = -↑x := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_mul : ∀ {x y : ℚ}, (↑(x * y) : ℚ_[p]) = ↑x * ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_sub : ∀ {x y : ℚ}, (↑(x - y) : ℚ_[p]) = ↑x - ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_div : ∀ {x y : ℚ}, (↑(x / y) : ℚ_[p]) = ↑x / ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_one : (↑1 : ℚ_[p]) = 1 := rfl @[norm_cast] lemma coe_zero : (↑0 : ℚ_[p]) = 0 := rfl lemma const_equiv {q r : ℚ} : const (padic_norm p) q ≈ const (padic_norm p) r ↔ q = r := ⟨ λ heq : lim_zero (const (padic_norm p) (q - r)), eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ lemma of_rat_eq {q r : ℚ} : of_rat p q = of_rat p r ↔ q = r := ⟨(const_equiv p).1 ∘ quotient.eq.1, λ h, by rw h⟩ @[norm_cast] lemma coe_inj {q r : ℚ} : (↑q : ℚ_[p]) = ↑r ↔ q = r := by simp [cast_eq_of_rat, of_rat_eq] instance : char_zero ℚ_[p] := ⟨λ m n, by { rw ← rat.cast_coe_nat, norm_cast, exact id }⟩ end completion end padic /-- The rational-valued p-adic norm on `ℚ_p` is lifted from the norm on Cauchy sequences. The canonical form of this function is the normed space instance, with notation `∥ ∥`. -/ def padic_norm_e {p : ℕ} [hp : fact p.prime] : ℚ_[p] → ℚ := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _ namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} [fact p.prime] lemma defn (f : padic_seq p) {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin simp only [padic.cast_eq_of_rat], change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contradiction h, cases cauchy₂ f hε with N hN, have : ∀ N, ∃ i ≥ N, ε ≤ (f - const _ (f i)).norm, by simpa only [not_forall, not_exists, not_lt] using h, rcases this N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm p) (f i)) ≈ 0, { intro h, unfold padic_seq.norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold padic_seq.norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases decidable.em (N ≤ stationary_point hne) with hgen hngen, { apply hN; assumption }, { have := stationary_point_spec hne (le_refl _) (le_of_not_le hngen), rw ←this, apply hN, apply le_refl, assumption } end protected lemma nonneg (q : ℚ_[p]) : 0 ≤ padic_norm_e q := quotient.induction_on q $ norm_nonneg lemma zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl lemma zero_iff (q : ℚ_[p]) : padic_norm_e q = 0 ↔ q = 0 := quotient.induction_on q $ by simpa only [zero_def, quotient.eq] using norm_zero_iff @[simp] protected lemma zero : padic_norm_e (0 : ℚ_[p]) = 0 := (zero_iff _).2 rfl /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ @[simp] protected lemma one' : padic_norm_e (1 : ℚ_[p]) = 1 := norm_one @[simp] protected lemma neg (q : ℚ_[p]) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q $ norm_neg /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem nonarchimedean' (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem add_eq_max_of_ne' {q r : ℚ_[p]} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ λ _ _, padic_seq.add_eq_max_of_ne lemma triangle_ineq (x y z : ℚ_[p]) : padic_norm_e (x - z) ≤ padic_norm_e (x - y) + padic_norm_e (y - z) := calc padic_norm_e (x - z) = padic_norm_e ((x - y) + (y - z)) : by rw sub_add_sub_cancel ... ≤ max (padic_norm_e (x - y)) (padic_norm_e (y - z)) : padic_norm_e.nonarchimedean' _ _ ... ≤ padic_norm_e (x - y) + padic_norm_e (y - z) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma add (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ (padic_norm_e q) + (padic_norm_e r) := calc padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean' _ _ ... ≤ (padic_norm_e q) + (padic_norm_e r) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma mul' (q r : ℚ_[p]) : padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) := quotient.induction_on₂ q r $ norm_mul instance : is_absolute_value (@padic_norm_e p _) := { abv_nonneg := padic_norm_e.nonneg, abv_eq_zero := zero_iff, abv_add := padic_norm_e.add, abv_mul := padic_norm_e.mul' } @[simp] lemma eq_padic_norm' (q : ℚ) : padic_norm_e (padic.of_rat p q) = padic_norm p q := norm_const _ protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = p ^ (-n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_values_discrete f this lemma sub_rev (q r : ℚ_[p]) : padic_norm_e (q - r) = padic_norm_e (r - q) := by rw ←(padic_norm_e.neg); simp end embedding end padic_norm_e namespace padic section complete open padic_seq padic theorem rat_dense' {p : ℕ} [fact p.prime] (q : ℚ_[p]) {ε : ℚ} (hε : 0 < ε) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm p (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin simp only [padic.cast_eq_of_rat], change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm p) (q' N)) ≈ 0) with heq hne', { simpa only [heq, padic_seq.norm, dif_pos] }, { simp only [padic_seq.norm, dif_neg hne'], change padic_norm p (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (stationary_point hne' ≤ N) with hle hle, { have := eq.symm (this (le_refl _) hle), simp only [const_apply, sub_apply, padic_norm.zero, sub_self] at this, simpa only [this] }, { apply hN, apply le_of_lt, apply lt_of_not_ge, apply hle, apply le_refl }} end⟩ variables {p : ℕ} [fact p.prime] (f : cau_seq _ (@padic_norm_e p _)) open classical private lemma div_nat_pos (n : ℕ) : 0 < (1 / ((n + 1): ℚ)) := div_pos zero_lt_one (by exact_mod_cast succ_pos _) /-- `lim_seq f`, for `f` a Cauchy sequence of `p`-adic numbers, is a sequence of rationals with the same limit point as `f`. -/ def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense' (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - ((lim_seq f) i : ℚ_[p])) < ε := begin refine (exists_nat_gt (1/ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense' (f i) (div_nat_pos i)), refine lt_of_lt_of_le h ((div_le_iff' $ by exact_mod_cast succ_pos _).mpr _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact (div_le_iff hε).mp (le_trans (le_of_lt hN) (by exact_mod_cast hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm p) (lim_seq f) := assume ε hε, have hε3 : 0 < ε / 3, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, suffices : padic_norm_e ((↑(lim_seq f j) - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring_nf at this ⊢, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat], exact_mod_cast this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { field_simp [this], simp only [bit0, bit1, mul_add, mul_one] }, rw this, apply add_lt_add, { suffices : padic_norm_e ((↑(lim_seq f j) - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa only [sub_add_sub_cancel], apply lt_of_le_of_lt, { apply padic_norm_e.add }, { apply add_lt_add, { rw [padic_norm_e.sub_rev], apply_mod_cast hN, exact le_of_max_le_left hj }, { apply hN2, exact le_of_max_le_right hj, apply le_max_right }}}, { apply_mod_cast hN, apply le_max_left }}} end private def lim' : padic_seq p := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[p] := ⟦lim' f⟧ theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, let ⟨N, hN⟩ := exi_rat_seq_conv f (show 0 < ε / 2, from div_pos hε (by norm_num)), ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (show 0 < ε / 2, from div_pos hε (by norm_num)) in begin existsi max N N2, intros i hi, suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < ε, { ring_nf at this; exact this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : ε = ε / 2 + ε / 2, by rw ←(add_self_div_two ε); simp, rw this, apply add_lt_add, { apply hN2, exact le_of_max_le_right hi }, { rw_mod_cast [padic_norm_e.sub_rev], apply hN, exact le_of_max_le_left hi }}} end ⟩ end complete section normed_space variables (p : ℕ) [fact p.prime] instance : has_dist ℚ_[p] := ⟨λ x y, padic_norm_e (x - y)⟩ instance : metric_space ℚ_[p] := { dist_self := by simp [dist], dist_comm := λ x y, by unfold dist; rw ←padic_norm_e.neg (x - y); simp, dist_triangle := begin intros, unfold dist, exact_mod_cast padic_norm_e.triangle_ineq _ _ _, end, eq_of_dist_eq_zero := begin unfold dist, intros _ _ h, apply eq_of_sub_eq_zero, apply (padic_norm_e.zero_iff _).1, exact_mod_cast h end } instance : has_norm ℚ_[p] := ⟨λ x, padic_norm_e x⟩ instance : normed_field ℚ_[p] := { dist_eq := λ _ _, rfl, norm_mul' := by simp [has_norm.norm, padic_norm_e.mul'] } instance is_absolute_value : is_absolute_value (λ a : ℚ_[p], ∥a∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ _, norm_eq_zero, abv_add := norm_add_le, abv_mul := by simp [has_norm.norm, padic_norm_e.mul'] } theorem rat_dense {p : ℕ} {hp : fact p.prime} (q : ℚ_[p]) {ε : ℝ} (hε : 0 < ε) : ∃ r : ℚ, ∥q - r∥ < ε := let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨r, hr⟩ := rat_dense' q (by simpa using hε'l) in ⟨r, lt_trans (by simpa [has_norm.norm] using hr) hε'r⟩ end normed_space end padic namespace padic_norm_e section normed_space variables {p : ℕ} [hp : fact p.prime] include hp @[simp] protected lemma mul (q r : ℚ_[p]) : ∥q * r∥ = ∥q∥ * ∥r∥ := by simp [has_norm.norm, padic_norm_e.mul'] protected lemma is_norm (q : ℚ_[p]) : ↑(padic_norm_e q) = ∥q∥ := rfl theorem nonarchimedean (q r : ℚ_[p]) : ∥q + r∥ ≤ max (∥q∥) (∥r∥) := begin unfold has_norm.norm, exact_mod_cast nonarchimedean' _ _ end theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ∥q∥ ≠ ∥r∥) : ∥q+r∥ = max (∥q∥) (∥r∥) := begin unfold has_norm.norm, apply_mod_cast add_eq_max_of_ne', intro h', apply h, unfold has_norm.norm, exact_mod_cast h' end @[simp] lemma eq_padic_norm (q : ℚ) : ∥(↑q : ℚ_[p])∥ = padic_norm p q := begin unfold has_norm.norm, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat] end instance : nondiscrete_normed_field ℚ_[p] := { non_trivial := ⟨padic.of_rat p (p⁻¹), begin have h0 : p ≠ 0 := ne_of_gt (hp.1.pos), have h1 : 1 < p := hp.1.one_lt, rw [← padic.cast_eq_of_rat, eq_padic_norm], simp only [padic_norm, inv_eq_zero], simp only [if_neg] {discharger := `[exact_mod_cast h0]}, norm_cast, simp only [padic_val_rat.inv] {discharger := `[exact_mod_cast h0]}, rw [neg_neg, padic_val_rat.padic_val_rat_self h1], erw _root_.pow_one, exact_mod_cast h1, end⟩ } @[simp] lemma norm_p : ∥(p : ℚ_[p])∥ = p⁻¹ := begin have p₀ : p ≠ 0 := hp.1.ne_zero, have p₁ : p ≠ 1 := hp.1.ne_one, simp [p₀, p₁, norm, padic_norm, padic_val_rat, fpow_neg, padic.cast_eq_of_rat_of_nat], end lemma norm_p_lt_one : ∥(p : ℚ_[p])∥ < 1 := begin rw [norm_p, inv_eq_one_div, div_lt_iff, one_mul], { exact_mod_cast hp.1.one_lt }, { exact_mod_cast hp.1.pos } end @[simp] lemma norm_p_pow (n : ℤ) : ∥(p^n : ℚ_[p])∥ = p^-n := by rw [normed_field.norm_fpow, norm_p]; field_simp protected theorem image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ∥q∥ = ↑((↑p : ℚ) ^ (-n)) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (padic_seq.ne_zero_iff_nequiv_zero f).1 hf, let ⟨n, hn⟩ := padic_seq.norm_values_discrete f this in ⟨n, congr_arg coe hn⟩ protected lemma is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ∥q∥ = ↑q' := if h : q = 0 then ⟨0, by simp [h]⟩ else let ⟨n, hn⟩ := padic_norm_e.image h in ⟨_, hn⟩ /--`rat_norm q`, for a `p`-adic number `q` is the `p`-adic norm of `q`, as rational number. The lemma `padic_norm_e.eq_rat_norm` asserts `∥q∥ = rat_norm q`. -/ def rat_norm (q : ℚ_[p]) : ℚ := classical.some (padic_norm_e.is_rat q) lemma eq_rat_norm (q : ℚ_[p]) : ∥q∥ = rat_norm q := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one : ∀ {q : ℚ} (hq : ¬ p ∣ q.denom), ∥(q : ℚ_[p])∥ ≤ 1 | ⟨n, d, hn, hd⟩ := λ hq : ¬ p ∣ d, if hnz : n = 0 then have (⟨n, d, hn, hd⟩ : ℚ) = 0, from rat.zero_iff_num_zero.mpr hnz, by norm_num [this] else begin have hnz' : { rat . num := n, denom := d, pos := hn, cop := hd } ≠ 0, from mt rat.zero_iff_num_zero.1 hnz, rw [padic_norm_e.eq_padic_norm], norm_cast, rw [padic_norm.eq_fpow_of_nonzero p hnz', padic_val_rat_def p hnz'], have h : (multiplicity p d).get _ = 0, by simp [multiplicity_eq_zero_of_not_dvd, hq], simp only, norm_cast, rw_mod_cast [h, sub_zero], apply fpow_le_one_of_nonpos, { exact_mod_cast le_of_lt hp.1.one_lt, }, { apply neg_nonpos_of_nonneg, norm_cast, simp, } end theorem norm_int_le_one (z : ℤ) : ∥(z : ℚ_[p])∥ ≤ 1 := suffices ∥((z : ℚ) : ℚ_[p])∥ ≤ 1, by simpa, norm_rat_le_one $ by simp [hp.1.ne_one] lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k := begin split, { intro h, contrapose! h, apply le_of_eq, rw eq_comm, calc ∥(k : ℚ_[p])∥ = ∥((k : ℚ) : ℚ_[p])∥ : by { norm_cast } ... = padic_norm p k : padic_norm_e.eq_padic_norm _ ... = 1 : _, rw padic_norm, split_ifs with H, { exfalso, apply h, norm_cast at H, rw H, apply dvd_zero }, { norm_cast at H ⊢, convert fpow_zero _, simp only [neg_eq_zero], rw padic_val_rat.padic_val_rat_of_int _ hp.1.ne_one H, norm_cast, rw [← enat.coe_inj, enat.coe_get, enat.coe_zero], apply multiplicity.multiplicity_eq_zero_of_not_dvd h } }, { rintro ⟨x, rfl⟩, push_cast, rw padic_norm_e.mul, calc _ ≤ ∥(p : ℚ_[p])∥ * 1 : mul_le_mul (le_refl _) (by simpa using norm_int_le_one _) (norm_nonneg _) (norm_nonneg _) ... < 1 : _, { rw [mul_one, padic_norm_e.norm_p], apply inv_lt_one, exact_mod_cast hp.1.one_lt }, }, end lemma norm_int_le_pow_iff_dvd (k : ℤ) (n : ℕ) : ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k := begin have : (p : ℝ) ^ (-n : ℤ) = ↑((p ^ (-n : ℤ) : ℚ)), {simp}, rw [show (k : ℚ_[p]) = ((k : ℚ) : ℚ_[p]), by norm_cast, eq_padic_norm, this], norm_cast, rw padic_norm.dvd_iff_norm_le, end lemma eq_of_norm_add_lt_right {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_left) h end normed_space end padic_norm_e namespace padic variables {p : ℕ} [fact p.prime] set_option eqn_compiler.zeta true instance complete : cau_seq.is_complete ℚ_[p] norm := begin split, intro f, have cau_seq_norm_e : is_cau_seq padic_norm_e f, { intros ε hε, let h := is_cau f ε (by exact_mod_cast hε), unfold norm at h, apply_mod_cast h }, cases padic.complete' ⟨f, cau_seq_norm_e⟩ with q hq, existsi q, intros ε hε, cases exists_rat_btwn hε with ε' hε', norm_cast at hε', cases hq ε' hε'.1 with N hN, existsi N, intros i hi, let h := hN i hi, unfold norm, rw_mod_cast [cau_seq.sub_apply, padic_norm_e.sub_rev], refine lt_trans _ hε'.2, exact_mod_cast hN i hi end lemma padic_norm_e_lim_le {f : cau_seq ℚ_[p] norm} {a : ℝ} (ha : 0 < a) (hf : ∀ i, ∥f i∥ ≤ a) : ∥f.lim∥ ≤ a := let ⟨N, hN⟩ := setoid.symm (cau_seq.equiv_lim f) _ ha in calc ∥f.lim∥ = ∥f.lim - f N + f N∥ : by simp ... ≤ max (∥f.lim - f N∥) (∥f N∥) : padic_norm_e.nonarchimedean _ _ ... ≤ a : max_le (le_of_lt (hN _ (le_refl _))) (hf _) /-! ### Valuation on `ℚ_[p]` -/ /-- `padic.valuation` lifts the p-adic valuation on rationals to `ℚ_[p]`. -/ def valuation : ℚ_[p] → ℤ := quotient.lift (@padic_seq.valuation p _) (λ f g h, begin by_cases hf : f ≈ 0, { have hg : g ≈ 0, from setoid.trans (setoid.symm h) hf, simp [hf, hg, padic_seq.valuation] }, { have hg : ¬ g ≈ 0, from (λ hg, hf (setoid.trans h hg)), rw padic_seq.val_eq_iff_norm_eq hf hg, exact padic_seq.norm_equiv h }, end) @[simp] lemma valuation_zero : valuation (0 : ℚ_[p]) = 0 := dif_pos ((const_equiv p).2 rfl) @[simp] lemma valuation_one : valuation (1 : ℚ_[p]) = 0 := begin change dite (cau_seq.const (padic_norm p) 1 ≈ _) _ _ = _, have h : ¬ cau_seq.const (padic_norm p) 1 ≈ 0, { assume H, erw const_equiv p at H, exact one_ne_zero H }, rw dif_neg h, simp, end lemma norm_eq_pow_val {x : ℚ_[p]} : x ≠ 0 → ∥x∥ = p^(-x.valuation) := begin apply quotient.induction_on' x, clear x, intros f hf, change (padic_seq.norm _ : ℝ) = (p : ℝ) ^ -padic_seq.valuation _, rw padic_seq.norm_eq_pow_val, change ↑((p : ℚ) ^ -padic_seq.valuation f) = (p : ℝ) ^ -padic_seq.valuation f, { rw rat.cast_fpow, congr' 1, norm_cast }, { apply cau_seq.not_lim_zero_of_not_congr_zero, contrapose! hf, apply quotient.sound, simpa using hf, } end @[simp] lemma valuation_p : valuation (p : ℚ_[p]) = 1 := begin have h : (1 : ℝ) < p := by exact_mod_cast (fact.out p.prime).one_lt, rw ← neg_inj, apply (fpow_strict_mono h).injective, dsimp only, rw ← norm_eq_pow_val, { simp }, { exact_mod_cast (fact.out p.prime).ne_zero } end end padic
0aeb21ef394d5fdf8e90b62b3b8e2c7fd8407f21
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/constructions/finite_products_of_binary_products.lean
d0d2128b0e85603e6f5048d7c59f92b866573f3f
[ "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
13,685
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.preserves.shapes.binary_products import category_theory.limits.preserves.shapes.products import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.finite_products import category_theory.pempty import logic.equiv.fin /-! # Constructing finite products from binary products and terminal. If a category has binary products and a terminal object then it has finite products. If a functor preserves binary products and the terminal object then it preserves finite products. # TODO Provide the dual results. Show the analogous results for functors which reflect or create (co)limits. -/ universes v u u' noncomputable theory open category_theory category_theory.category category_theory.limits namespace category_theory variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] variables {D : Type u'} [category.{v} D] /-- Given `n+1` objects of `C`, a fan for the last `n` with point `c₁.X` and a binary fan on `c₁.X` and `f 0`, we can build a fan for all `n+1`. In `extend_fan_is_limit` we show that if the two given fans are limits, then this fan is also a limit. -/ @[simps {rhs_md := semireducible}] def extend_fan {n : ℕ} {f : ulift (fin (n+1)) → C} (c₁ : fan (λ (i : ulift (fin n)), f ⟨i.down.succ⟩)) (c₂ : binary_fan (f ⟨0⟩) c₁.X) : fan f := fan.mk c₂.X begin rintro ⟨i⟩, revert i, refine fin.cases _ _, { apply c₂.fst }, { intro i, apply c₂.snd ≫ c₁.π.app (ulift.up i) }, end /-- Show that if the two given fans in `extend_fan` are limits, then the constructed fan is also a limit. -/ def extend_fan_is_limit {n : ℕ} (f : ulift (fin (n+1)) → C) {c₁ : fan (λ (i : ulift (fin n)), f ⟨i.down.succ⟩)} {c₂ : binary_fan (f ⟨0⟩) c₁.X} (t₁ : is_limit c₁) (t₂ : is_limit c₂) : is_limit (extend_fan c₁ c₂) := { lift := λ s, begin apply (binary_fan.is_limit.lift' t₂ (s.π.app ⟨0⟩) _).1, apply t₁.lift ⟨_, discrete.nat_trans (λ i, s.π.app ⟨i.down.succ⟩)⟩ end, fac' := λ s, begin rintro ⟨j⟩, apply fin.induction_on j, { apply (binary_fan.is_limit.lift' t₂ _ _).2.1 }, { rintro i -, dsimp only [extend_fan_π_app], rw [fin.cases_succ, ← assoc, (binary_fan.is_limit.lift' t₂ _ _).2.2, t₁.fac], refl } end, uniq' := λ s m w, begin apply binary_fan.is_limit.hom_ext t₂, { rw (binary_fan.is_limit.lift' t₂ _ _).2.1, apply w ⟨0⟩ }, { rw (binary_fan.is_limit.lift' t₂ _ _).2.2, apply t₁.uniq ⟨_, _⟩, rintro ⟨j⟩, rw assoc, dsimp only [discrete.nat_trans_app], rw ← w ⟨j.succ⟩, dsimp only [extend_fan_π_app], rw fin.cases_succ } end } section variables [has_binary_products.{v} C] [has_terminal C] /-- If `C` has a terminal object and binary products, then it has a product for objects indexed by `ulift (fin n)`. This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_product_ulift_fin : Π (n : ℕ) (f : ulift.{v} (fin n) → C), has_product f | 0 := λ f, begin letI : has_limits_of_shape (discrete (ulift.{v} (fin 0))) C := has_limits_of_shape_of_equivalence (discrete.equivalence.{v} (equiv.ulift.trans fin_zero_equiv').symm), apply_instance, end | (n+1) := λ f, begin haveI := has_product_ulift_fin n, apply has_limit.mk ⟨_, extend_fan_is_limit f (limit.is_limit.{v} _) (limit.is_limit _)⟩, end /-- If `C` has a terminal object and binary products, then it has limits of shape `discrete (ulift (fin n))` for any `n : ℕ`. This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_limits_of_shape_ulift_fin (n : ℕ) : has_limits_of_shape (discrete (ulift.{v} (fin n))) C := { has_limit := λ K, begin letI := has_product_ulift_fin n K.obj, let : discrete.functor K.obj ≅ K := discrete.nat_iso (λ i, iso.refl _), apply has_limit_of_iso this, end } /-- If `C` has a terminal object and binary products, then it has finite products. -/ lemma has_finite_products_of_has_binary_and_terminal : has_finite_products C := ⟨λ J 𝒥₁ 𝒥₂, begin resetI, let e := fintype.equiv_fin J, apply has_limits_of_shape_of_equivalence (discrete.equivalence (e.trans equiv.ulift.symm)).symm, refine has_limits_of_shape_ulift_fin (fintype.card J), end⟩ end section preserves variables (F : C ⥤ D) variables [preserves_limits_of_shape (discrete.{v} walking_pair) F] variables [preserves_limits_of_shape (discrete.{v} pempty) F] variables [has_finite_products.{v} C] /-- If `F` preserves the terminal object and binary products, then it preserves products indexed by `ulift (fin n)` for any `n`. -/ noncomputable def preserves_fin_of_preserves_binary_and_terminal : Π (n : ℕ) (f : ulift.{v} (fin n) → C), preserves_limit (discrete.functor f) F | 0 := λ f, begin letI : preserves_limits_of_shape (discrete (ulift (fin 0))) F := preserves_limits_of_shape_of_equiv.{v v} (discrete.equivalence (equiv.ulift.trans fin_zero_equiv').symm) _, apply_instance, end | (n+1) := begin haveI := preserves_fin_of_preserves_binary_and_terminal n, intro f, refine preserves_limit_of_preserves_limit_cone (extend_fan_is_limit f (limit.is_limit.{v} _) (limit.is_limit _)) _, apply (is_limit_map_cone_fan_mk_equiv _ _ _).symm _, let := extend_fan_is_limit (λ i, F.obj (f i)) (is_limit_of_has_product_of_preserves_limit F _) (is_limit_of_has_binary_product_of_preserves_limit F _ _), refine is_limit.of_iso_limit this _, apply cones.ext _ _, apply iso.refl _, rintro ⟨j⟩, apply fin.induction_on j, { apply (category.id_comp _).symm }, { rintro i -, dsimp only [extend_fan_π_app, iso.refl_hom, fan.mk_π_app], rw [fin.cases_succ, fin.cases_succ], change F.map _ ≫ _ = 𝟙 _ ≫ _, rw [id_comp, ←F.map_comp], refl } end /-- If `F` preserves the terminal object and binary products, then it preserves limits of shape `discrete (ulift (fin n))`. -/ def preserves_ulift_fin_of_preserves_binary_and_terminal (n : ℕ) : preserves_limits_of_shape (discrete (ulift (fin n))) F := { preserves_limit := λ K, begin let : discrete.functor K.obj ≅ K := discrete.nat_iso (λ i, iso.refl _), haveI := preserves_fin_of_preserves_binary_and_terminal F n K.obj, apply preserves_limit_of_iso_diagram F this, end } /-- If `F` preserves the terminal object and binary products then it preserves finite products. -/ def preserves_finite_products_of_preserves_binary_and_terminal (J : Type v) [fintype J] : preserves_limits_of_shape.{v} (discrete J) F := begin classical, let e := fintype.equiv_fin J, haveI := preserves_ulift_fin_of_preserves_binary_and_terminal F (fintype.card J), apply preserves_limits_of_shape_of_equiv.{v v} (discrete.equivalence (e.trans equiv.ulift.symm)).symm, end end preserves /-- Given `n+1` objects of `C`, a cofan for the last `n` with point `c₁.X` and a binary cofan on `c₁.X` and `f 0`, we can build a cofan for all `n+1`. In `extend_cofan_is_colimit` we show that if the two given cofans are colimits, then this cofan is also a colimit. -/ @[simps {rhs_md := semireducible}] def extend_cofan {n : ℕ} {f : ulift (fin (n+1)) → C} (c₁ : cofan (λ (i : ulift (fin n)), f ⟨i.down.succ⟩)) (c₂ : binary_cofan (f ⟨0⟩) c₁.X) : cofan f := cofan.mk c₂.X begin rintro ⟨i⟩, revert i, refine fin.cases _ _, { apply c₂.inl }, { intro i, apply c₁.ι.app (ulift.up i) ≫ c₂.inr }, end /-- Show that if the two given cofans in `extend_cofan` are colimits, then the constructed cofan is also a colimit. -/ def extend_cofan_is_colimit {n : ℕ} (f : ulift (fin (n+1)) → C) {c₁ : cofan (λ (i : ulift (fin n)), f ⟨i.down.succ⟩)} {c₂ : binary_cofan (f ⟨0⟩) c₁.X} (t₁ : is_colimit c₁) (t₂ : is_colimit c₂) : is_colimit (extend_cofan c₁ c₂) := { desc := λ s, begin apply (binary_cofan.is_colimit.desc' t₂ (s.ι.app ⟨0⟩) _).1, apply t₁.desc ⟨_, discrete.nat_trans (λ i, s.ι.app ⟨i.down.succ⟩)⟩ end, fac' := λ s, begin rintro ⟨j⟩, apply fin.induction_on j, { apply (binary_cofan.is_colimit.desc' t₂ _ _).2.1 }, { rintro i -, dsimp only [extend_cofan_ι_app], rw [fin.cases_succ, assoc, (binary_cofan.is_colimit.desc' t₂ _ _).2.2, t₁.fac], refl } end, uniq' := λ s m w, begin apply binary_cofan.is_colimit.hom_ext t₂, { rw (binary_cofan.is_colimit.desc' t₂ _ _).2.1, apply w ⟨0⟩ }, { rw (binary_cofan.is_colimit.desc' t₂ _ _).2.2, apply t₁.uniq ⟨_, _⟩, rintro ⟨j⟩, dsimp only [discrete.nat_trans_app], rw ← w ⟨j.succ⟩, dsimp only [extend_cofan_ι_app], rw [fin.cases_succ, assoc], } end } section variables [has_binary_coproducts.{v} C] [has_initial C] /-- If `C` has an initial object and binary coproducts, then it has a coproduct for objects indexed by `ulift (fin n)`. This is a helper lemma for `has_cofinite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_coproduct_ulift_fin : Π (n : ℕ) (f : ulift.{v} (fin n) → C), has_coproduct f | 0 := λ f, begin letI : has_colimits_of_shape (discrete (ulift.{v} (fin 0))) C := has_colimits_of_shape_of_equivalence (discrete.equivalence.{v} (equiv.ulift.trans fin_zero_equiv').symm), apply_instance, end | (n+1) := λ f, begin haveI := has_coproduct_ulift_fin n, apply has_colimit.mk ⟨_, extend_cofan_is_colimit f (colimit.is_colimit.{v} _) (colimit.is_colimit _)⟩, end /-- If `C` has an initial object and binary coproducts, then it has colimits of shape `discrete (ulift (fin n))` for any `n : ℕ`. This is a helper lemma for `has_cofinite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_colimits_of_shape_ulift_fin (n : ℕ) : has_colimits_of_shape (discrete (ulift.{v} (fin n))) C := { has_colimit := λ K, begin letI := has_coproduct_ulift_fin n K.obj, let : K ≅ discrete.functor K.obj := discrete.nat_iso (λ i, iso.refl _), apply has_colimit_of_iso this, end } /-- If `C` has an initial object and binary coproducts, then it has finite coproducts. -/ lemma has_finite_coproducts_of_has_binary_and_terminal : has_finite_coproducts C := ⟨λ J 𝒥₁ 𝒥₂, begin resetI, let e := fintype.equiv_fin J, apply has_colimits_of_shape_of_equivalence (discrete.equivalence (e.trans equiv.ulift.symm)).symm, refine has_colimits_of_shape_ulift_fin (fintype.card J), end⟩ end section preserves variables (F : C ⥤ D) variables [preserves_colimits_of_shape (discrete.{v} walking_pair) F] variables [preserves_colimits_of_shape (discrete.{v} pempty) F] variables [has_finite_coproducts.{v} C] /-- If `F` preserves the initial object and binary coproducts, then it preserves products indexed by `ulift (fin n)` for any `n`. -/ noncomputable def preserves_fin_of_preserves_binary_and_initial : Π (n : ℕ) (f : ulift.{v} (fin n) → C), preserves_colimit (discrete.functor f) F | 0 := λ f, begin letI : preserves_colimits_of_shape (discrete (ulift (fin 0))) F := preserves_colimits_of_shape_of_equiv.{v v} (discrete.equivalence (equiv.ulift.trans fin_zero_equiv').symm) _, apply_instance, end | (n+1) := begin haveI := preserves_fin_of_preserves_binary_and_initial n, intro f, refine preserves_colimit_of_preserves_colimit_cocone (extend_cofan_is_colimit f (colimit.is_colimit.{v} _) (colimit.is_colimit _)) _, apply (is_colimit_map_cocone_cofan_mk_equiv _ _ _).symm _, let := extend_cofan_is_colimit (λ i, F.obj (f i)) (is_colimit_of_has_coproduct_of_preserves_colimit F _) (is_colimit_of_has_binary_coproduct_of_preserves_colimit F _ _), refine is_colimit.of_iso_colimit this _, apply cocones.ext _ _, apply iso.refl _, rintro ⟨j⟩, apply fin.induction_on j, { apply category.comp_id }, { rintro i -, dsimp only [extend_cofan_ι_app, iso.refl_hom, cofan.mk_ι_app], rw [fin.cases_succ, fin.cases_succ], erw [comp_id, ←F.map_comp], refl, } end /-- If `F` preserves the initial object and binary coproducts, then it preserves colimits of shape `discrete (ulift (fin n))`. -/ def preserves_ulift_fin_of_preserves_binary_and_initial (n : ℕ) : preserves_colimits_of_shape (discrete (ulift (fin n))) F := { preserves_colimit := λ K, begin let : discrete.functor K.obj ≅ K := discrete.nat_iso (λ i, iso.refl _), haveI := preserves_fin_of_preserves_binary_and_initial F n K.obj, apply preserves_colimit_of_iso_diagram F this, end } /-- If `F` preserves the initial object and binary coproducts then it preserves finite products. -/ def preserves_finite_coproducts_of_preserves_binary_and_initial (J : Type v) [fintype J] : preserves_colimits_of_shape.{v} (discrete J) F := begin classical, let e := fintype.equiv_fin J, haveI := preserves_ulift_fin_of_preserves_binary_and_initial F (fintype.card J), apply preserves_colimits_of_shape_of_equiv.{v v} (discrete.equivalence (e.trans equiv.ulift.symm)).symm, end end preserves end category_theory
6048bb9a95638c33fff470f3c5c222cd0ff557d8
5aaed23ab7202c675981a8ecc309d1f3ea53fa63
/src/2012_q3.lean
666c343dd28856b9481cc8f12dd2099adfc79772
[]
no_license
jalex-stark/mathcamp-QQuiz-lean
d1cedba0ae1ff078022c6b9f6e5090b97ee4cc27
fd17c0cfe6c7a0b2f283cf33bed1403279c8e04a
refs/heads/master
1,668,476,432,896
1,594,602,972,000
1,594,602,972,000
279,175,371
0
0
null
null
null
null
UTF-8
Lean
false
false
2,369
lean
import tactic import data.nat.modeq noncomputable theory open_locale classical -- Let p be an odd prime. variables {p : ℕ} [fact p.prime] -- A group of p campers sit around a circle, -- and are labeled with the integers 1,2,...,p in clockwise order. -- The camper with label 1 yells out the number 1. -- The camper sitting next to this camper in clockwise order yells out 2. -- The camper two spots in clockwise order from the camper who yelled out 2 yells out 3. -- This process continues: the camper seated n spots (in clockwise order) from the camper who yelled out n must yell out n+1. -- A camper gets a cookie anytime she or he yells out a number. lemma arithmetic1 (a b : ℕ) (hb : 1 < b) : a % b < b := sorry structure camper_state (campers : Type*) := (head : campers) (count : ℕ) (cookies : campers → ℕ) def initial_state : camper_state (fin p) := begin refine {head := _, count := 0, cookies := λ x, 0}, refine ⟨1, _⟩, apply nat.prime.one_lt, assumption, end def update : camper_state (fin p) → camper_state (fin p) := begin intro s, refine {head := _, count := s.count + 1, cookies := λ x, if x = s.head then s.cookies x + 1 else s.cookies x }, refine ⟨ (s.head + s.count) % p, _ ⟩, apply arithmetic1, refine nat.prime.one_lt _inst_1, end def seq_state : ℕ → camper_state (fin p) | 0 := initial_state | (n+1) := update (seq_state n) -- Show that there is a camper who never gets a cookie. def sad_camper (a : fin p) : Prop := ∀ n, (seq_state n).cookies a = 0 := theorem exists_sad_camper : ∃ a : fin p, sad_camper a := sorry -- Of the campers who do get cookies, is there one who at some point has at least ten more cookies than the others? def max_cookie_camper (a : fin p) : Prop := ∀ n, ∀ b ≠ a, 10 < (seq_state n).cookies a - (seq_state n).cookies b -- prove the following statement or its negation theorem exists_max_cookie_camper : ∃ a : fin p, max_cookie_camper a := sorry -- Of the campers who do get cookies, is there one who at some point has at least ten fewer cookies than the others? def min_cookie_camper (a : fin p) : Prop := ∀ n, ∀ b ≠ a, sad_camper b ∨ 10 < (seq_state n).cookies b - (seq_state n).cookies a -- prove the following statement or its negation theorem exists_min_cookie_camper : ∃ a : fin p, min_cookie_camper a := sorry
1d4a4a282e2fcde3ac1ec33a410b17a52427da56
4fa161becb8ce7378a709f5992a594764699e268
/src/analysis/calculus/fderiv.lean
4094b71f7ccb695171686fa567f53030ecdf564d
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
102,513
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, Yury Kudryashov -/ import analysis.calculus.tangent_cone /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` 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` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results 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 * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) * inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. The simplifier is set up to prove automatically that some functions are differentiable, or differentiable at a point (but not differentiable on a set or within a set at a point, as checking automatically that the good domains are mapped one to the other when using composition is not something the simplifier can easily do). This means that one can write `example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`. If there are divisions, one needs to supply to the simplifier proofs that the denominators do not vanish, as in ```lean example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x := by simp [h] ``` Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be differentiable, in `analysis.special_functions.trigonometric`. The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general complicated multidimensional linear maps), but it will compute one-dimensional derivatives, see `deriv.lean`. ## Implementation details 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 𝕜 f s x` (where `𝕜` 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 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 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. To make sure that the simplifier can prove automatically that functions are differentiable, we tag many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable functions is differentiable, as well as their product, their cartesian product, and so on. A notable exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are differentiable, then their composition also is: `simp` would always be able to match this lemma, by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`), we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding some boilerplate lemmas, but these can also be useful in their own right. Tests for this ability of the simplifier (with more examples) are provided in `tests/differentiable.lean`. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set open_locale topological_space classical noncomputable theory section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] 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] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = nhds_within x s` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (nhds_within x s) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] 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. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (nhds_within x s), { conv in (nhds_within x s) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (nhds_within x s) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- `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 𝕜 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 𝕜 s x, f' y = f₁' y, { rintros y ⟨c, d, dtop, clim, cdlim⟩, exact tendsto_nhds_unique (by simp) (h.lim at_top dtop clim cdlim) (h₁.lim at_top dtop clim cdlim) }, have B : ∀y ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 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 𝕜 (tangent_cone_at 𝕜 s x)) : set E), f' y = f₁' y, { assume y hy, let K := {y | f' y = f₁' y}, have : (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ K := B, have : closure (submodule.span 𝕜 (tangent_cone_at 𝕜 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 }, rw H.1 at C, ext y, exact C y (mem_univ _) end theorem unique_diff_on.eq (H : unique_diff_on 𝕜 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 section fderiv_properties /-! ### Basic properties of the derivative -/ 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 (𝓝 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.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 (λ _, 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) (𝓝 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)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin split, { assume H, have : tendsto (λ (z : E), z + x) (𝓝 0) (𝓝 (0 + x)), from tendsto_id.add tendsto_const_nhds, rw [zero_add] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel', add_comm z] }, { assume H, have : tendsto (λ (z : E), z - x) (𝓝 x) (𝓝 (x - x)), from tendsto_id.sub tendsto_const_nhds, rw [sub_self] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel'_right] } end 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₁ := h.mono hst 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 ≤ 𝓝 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 inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : 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 } lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma 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.is_O.congr_of_sub.2 (f'.is_O_sub _ _) protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) : has_fderiv_at f f' x := begin rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff], exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc)) end protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_nhds hU, dsimp only [], rw [← mul_smul, mul_inv_cancel hy, one_smul] end 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_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ nhds_within x s) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 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 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at } lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp [mem_closure_iff_nhds_within_ne_bot] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ nhds_within x s) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 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 (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto_le_left hL _), rw ← sub_self x, exact tendsto_id.sub 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 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 𝕜 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 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) : continuous_at f x := hf.has_fderiv_at.continuous_at lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) : is_O (λ p : E × E, p.1 - p.2) (λ p : E × E, f p.1 - f p.2) (𝓝 (x, x)) := ((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) lemma has_fderiv_at_filter.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_fderiv_at_filter f (f' : E →L[𝕜] F) x L) : is_O (λ x', x' - x) (λ x', f x' - f x) L := ((f'.is_O_sub_rev _ _).trans (hf.trans_is_O (f'.is_O_sub_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) end continuous section congr /-! ### congr properties of the derivative -/ theorem has_strict_fderiv_at_congr_of_mem_sets (h : ∀ᶠ y in 𝓝 x, f₀ y = f₁ y) (h' : ∀ y, f₀' y = f₁' y) : has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x := begin refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall _ $ λ _, rfl), rintros p ⟨hp₁, hp₂⟩, simp only [*] end theorem has_strict_fderiv_at.congr_of_mem_sets (h : has_strict_fderiv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f y = f₁ y) : has_strict_fderiv_at f₁ f' x := (has_strict_fderiv_at_congr_of_mem_sets h₁ (λ _, rfl)).1 h theorem has_fderiv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : ∀ᶠ x in L, 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 := is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall _ $ λ _, rfl) lemma has_fderiv_at_filter.congr_of_mem_sets (h : has_fderiv_at_filter f f' x L) (hL : ∀ᶠ x in L, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (has_fderiv_at_filter_congr_of_mem_sets hx hL $ λ _, rfl).2 h 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_of_mem_sets (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr_of_mem_nhds_within (h : has_fderiv_within_at f f' s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_mem_sets h h₁ hx lemma has_fderiv_at.congr_of_mem_nhds (h : has_fderiv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f₁ y = f y) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_mem_nhds_within (h : differentiable_within_at 𝕜 f s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_mem_nhds_within h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_mem_nhds (h : differentiable_at 𝕜 f x) (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_at hL (mem_of_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma fderiv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_mem_sets hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_mem_nhds_within (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply fderiv_within_congr_of_mem_nhds_within hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma fderiv_congr_of_mem_nhds (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := (mem_of_nhds hL : _), rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact fderiv_within_congr_of_mem_nhds_within unique_diff_within_at_univ hL A end end congr section id /-! ### Derivative of the identity -/ theorem has_strict_fderiv_at_id (x : E) : has_strict_fderiv_at id (id 𝕜 E) x := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id 𝕜 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) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x := has_fderiv_at_filter_id _ _ @[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at @[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at @[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id @[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E := has_fderiv_at.fderiv (has_fderiv_at_id x) lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id 𝕜 E := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] 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[𝕜] 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[𝕜] F) x := has_fderiv_at_filter_const _ _ _ @[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end @[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter @[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end @[simp]protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 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 𝕜 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 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 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 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section composition /-! ### Derivative of the composition of two functions 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[𝕜] 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_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (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[𝕜] 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_tendsto (le_refl _), 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₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (nhds_within x s) ≤ nhds_within (f x) (f '' s) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (f x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] 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[𝕜] 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_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) /-- The chain rule for derivatives in the sense of strict differentiability. -/ protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x := ((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $ by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) : differentiable 𝕜 (f^[n]) := nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf) protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s) (hs : maps_to f s s) (n : ℕ) : differentiable_on 𝕜 (f^[n]) s := nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs) variable {x} protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_fderiv_at_filter (f^[n]) (f'^n) x L := begin induction n with n ihn, { exact has_fderiv_at_filter_id x L }, { change has_fderiv_at_filter (f^[n] ∘ f) (f'^(n+1)) x L, rw [pow_succ'], refine has_fderiv_at_filter.comp x _ hf, rw hx, exact ihn.mono hL } end protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_fderiv_at (f^[n]) (f'^n) x := begin refine hf.iterate _ hx n, convert hf.continuous_at, exact hx.symm end protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_fderiv_within_at (f^[n]) (f'^n) s x := begin refine hf.iterate _ hx n, convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩, exacts [hx.symm, tendsto_le_left inf_le_right (tendsto_principal_principal.2 hs)] end protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_fderiv_at (f^[n]) (f'^n) x := begin induction n with n ihn, { exact has_strict_fderiv_at_id x }, { change has_strict_fderiv_at (f^[n] ∘ f) (f'^(n+1)) x, rw [pow_succ'], refine has_strict_fderiv_at.comp x _ hf, rwa hx } end protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x) (hx : f x = x) (n : ℕ) : differentiable_at 𝕜 (f^[n]) x := exists.elim hf $ λ f' hf, (hf.iterate hx n).differentiable_at protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : differentiable_within_at 𝕜 (f^[n]) s x := exists.elim hf $ λ f' hf, (hf.iterate hx hs n).differentiable_within_at end composition section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ section prod variables {f₂ : E → G} {f₂' : E →L[𝕜] G} protected lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod_left hf₂ 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 := hf₁.prod_left hf₂ 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 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ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 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) @[simp] lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = continuous_linear_map.prod (fderiv 𝕜 f₁ x) (fderiv 𝕜 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 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = continuous_linear_map.prod (fderiv_within 𝕜 f₁ s x) (fderiv_within 𝕜 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 prod section fst variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_fst : has_strict_fderiv_at prod.fst (fst 𝕜 E F) p := (fst 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := has_strict_fderiv_at_fst.comp x h lemma has_fderiv_at_filter_fst {L : filter (E × F)} : has_fderiv_at_filter prod.fst (fst 𝕜 E F) p L := (fst 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_fst.comp x h lemma has_fderiv_at_fst : has_fderiv_at prod.fst (fst 𝕜 E F) p := has_fderiv_at_filter_fst protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := h.fst lemma has_fderiv_within_at_fst {s : set (E × F)} : has_fderiv_within_at prod.fst (fst 𝕜 E F) s p := has_fderiv_at_filter_fst protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x := h.fst lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p := has_fderiv_at_fst.differentiable_at @[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).1) x := differentiable_at_fst.comp x h lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) := λ x, differentiable_at_fst @[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).1) := differentiable_fst.comp h lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p := differentiable_at_fst.differentiable_within_at protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x := differentiable_at_fst.comp_differentiable_within_at x h lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s := differentiable_fst.differentiable_on protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).1) s := differentiable_fst.comp_differentiable_on h lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.fst.fderiv lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F := has_fderiv_within_at_fst.fderiv_within hs lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.fst.fderiv_within hs end fst section snd variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_snd : has_strict_fderiv_at prod.snd (snd 𝕜 E F) p := (snd 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := has_strict_fderiv_at_snd.comp x h lemma has_fderiv_at_filter_snd {L : filter (E × F)} : has_fderiv_at_filter prod.snd (snd 𝕜 E F) p L := (snd 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_snd.comp x h lemma has_fderiv_at_snd : has_fderiv_at prod.snd (snd 𝕜 E F) p := has_fderiv_at_filter_snd protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := h.snd lemma has_fderiv_within_at_snd {s : set (E × F)} : has_fderiv_within_at prod.snd (snd 𝕜 E F) s p := has_fderiv_at_filter_snd protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x := h.snd lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p := has_fderiv_at_snd.differentiable_at @[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).2) x := differentiable_at_snd.comp x h lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) := λ x, differentiable_at_snd @[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).2) := differentiable_snd.comp h lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p := differentiable_at_snd.differentiable_within_at protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x := differentiable_at_snd.comp_differentiable_within_at x h lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s := differentiable_snd.differentiable_on protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).2) s := differentiable_snd.comp_differentiable_on h lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.snd.fderiv lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F := has_fderiv_within_at_snd.fderiv_within hs lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.snd.fderiv_within hs end snd section prod_map variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G) -- TODO (Lean 3.8): use `prod.map f f₂`` protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1) (hf₂ : has_strict_fderiv_at f₂ f₂' p.2) : has_strict_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd) protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1) (hf₂ : has_fderiv_at f₂ f₂' p.2) : has_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd) @[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1) (hf₂ : differentiable_at 𝕜 f₂ p.2) : differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p := (hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd) end prod_map end cartesian_product section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by simp; abel 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; abel 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 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) @[simp] lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.add_const c).fderiv_within hxs lemma fderiv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.add_const c).fderiv theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_add c).fderiv_within hxs lemma fderiv_const_add (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := (hf.has_fderiv_at.const_add c).fderiv end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)} theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) : has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := begin dsimp [has_strict_fderiv_at] at *, convert is_o.sum h, simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply] end theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) : has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := begin dsimp [has_fderiv_at_filter] at *, convert is_o.sum h, simp [continuous_linear_map.sum_apply] end theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) : has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_fderiv_at_filter.sum h theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) : has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_fderiv_at_filter.sum h theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x := has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $ λ i hi, (h i hi).has_fderiv_within_at @[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x := has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) : differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s := λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx @[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) : differentiable 𝕜 (λ y, ∑ i in u, A i y) := λ x, differentiable_at.sum $ λ i hi, h i hi x theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) := (has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) := (has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv end sum section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h 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 := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h 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 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at @[simp] lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := h.has_fderiv_within_at.neg.fderiv_within hxs lemma fderiv_neg (h : differentiable_at 𝕜 f x) : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := h.has_fderiv_at.neg.fderiv end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := hf.add hg.neg 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 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) @[simp] lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.sub_const c).fderiv_within hxs lemma fderiv_sub_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.sub_const c).fderiv theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_sub c).fderiv_within hxs lemma fderiv_const_sub (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := (hf.has_fderiv_at.const_sub c).fderiv end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)), { ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 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 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 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 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/ variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf 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'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf 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'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) @[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } 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 := by { convert hc.smul hd, ext z, apply mul_comm } 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 := by { convert hc.smul hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) @[simp] lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x) theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s) theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma continuous_linear_equiv.has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma continuous_linear_equiv.has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma continuous_linear_equiv.has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma continuous_linear_equiv.differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma continuous_linear_equiv.differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma continuous_linear_equiv.fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma continuous_linear_equiv.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma continuous_linear_equiv.differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma continuous_linear_equiv.differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma continuous_linear_equiv.comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma continuous_linear_equiv.comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma continuous_linear_equiv.comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma continuous_linear_equiv.comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma continuous_linear_equiv.comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma continuous_linear_equiv.comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma continuous_linear_equiv.comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma continuous_linear_equiv.comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma continuous_linear_equiv.comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin replace hg := hg.prod_map' hg, replace hfg := hfg.prod_mk_nhds hfg, have : is_O (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2)) (λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)) (𝓝 (a, a)), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall _ $ λ _, rfl)).trans_is_O _, { rintros p ⟨hp1, hp2⟩, simp [hp1, hp2] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall _ $ λ _, rfl) (hfg.mono _), rintros p ⟨hp1, hp2⟩, simp only [(∘), hp1, hp2] } end /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin have : is_O (λ x : F, g x - g a - f'.symm (x - a)) (λ x : F, f' (g x - g a) - (x - a)) (𝓝 a), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall _ $ λ _, rfl)).trans_is_O _, { rintros p hp, simp [hp, hfg.self_of_nhds] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall _ $ λ _, rfl) (hfg.mono _), rintros p hp, simp only [(∘), hp, hfg.self_of_nhds] } end end section /- 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. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : closure (range f') = univ) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin have B : ∀v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E), f' v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F), { assume v hv, apply submodule.span_induction hv, { exact λ w hw, submodule.subset_span (h.maps_to_tangent_cone hw) }, { simp }, { assume w₁ w₂ hw₁ hw₂, rw continuous_linear_map.map_add, exact submodule.add_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) hw₁ hw₂ }, { assume a w hw, rw continuous_linear_map.map_smul, exact submodule.smul_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) _ hw } }, rw [unique_diff_within_at, ← univ_subset_iff], split, show f x ∈ closure (f '' s), from h.continuous_within_at.mem_closure_image hs.2, show univ ⊆ closure ↑(submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))), from calc univ ⊆ closure (range f') : univ_subset_iff.2 h' ... = closure (f' '' univ) : by rw image_univ ... = closure (f' '' (closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : by rw hs.1 ... ⊆ closure (closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : closure_mono (image_closure_subset_closure_image f'.cont) ... = closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E)) : closure_closure ... ⊆ closure (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F) : closure_mono (image_subset_iff.mpr B) end lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin apply h.unique_diff_within_at hs, have : set.range (e' : E →L[𝕜] F) = univ := e'.to_linear_equiv.to_equiv.range_eq_univ, rw [this, closure_univ] end lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := begin split, { assume hs x hx, have A : s = e '' (e.symm '' s) := (equiv.symm_image_image (e.symm.to_linear_equiv.to_equiv) s).symm, have B : e.symm '' s = e⁻¹' s := equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s, rw [A, B, (e.apply_symm_apply x).symm], refine has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e e.has_fderiv_within_at (hs _ _), rwa [mem_preimage, e.apply_symm_apply x] }, { assume hs x hx, have : e ⁻¹' s = e.symm '' s := (equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s).symm, rw [this, (e.symm_apply_apply x).symm], exact has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e.symm e.symm.has_fderiv_within_at (hs _ hx) }, end end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] {F : Type*} [normed_group F] [normed_space 𝕜' F] {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} local attribute [instance] normed_space.restrict_scalars lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars
20bc2359e71bd58ed0c3571780feb8351467a568
246309748072bf9f8da313401699689ebbecd94d
/src/group_theory/submonoid/operations.lean
391406e374baf765ada903c896d272d9660656bc
[ "Apache-2.0" ]
permissive
YJMD/mathlib
b703a641e5f32a996f7842f7c0043bab2b462ee2
7310eab9fa8c1b1229dca42682f1fa6bfb7dbbf9
refs/heads/master
1,670,714,479,314
1,599,035,445,000
1,599,035,445,000
292,279,930
0
0
null
1,599,050,561,000
1,599,050,560,000
null
UTF-8
Lean
false
false
19,727
lean
import group_theory.submonoid.basic import data.equiv.mul_add import algebra.group.prod import algebra.group.inj_surj /-! # Operations on `submonoid`s In this file we define various operations on `submonoid`s and `monoid_hom`s. ## Main definitions ### Conversion between multiplicative and additive definitions * `submonoid.to_add_submonoid`, `submonoid.of_add_submonoid`, `add_submonoid.to_submonoid`, `add_submonoid.of_submonoid`: convert between multiplicative and additive submonoids of `M`, `multiplicative M`, and `additive M`. * `submonoid.add_submonoid_equiv`: equivalence between `submonoid M` and `add_submonoid (additive M)`. ### (Commutative) monoid structure on a submonoid * `submonoid.to_monoid`, `submonoid.to_comm_monoid`: a submonoid inherits a (commutative) monoid structure. ### Operations on submonoids * `submonoid.comap`: preimage of a submonoid under a monoid homomorphism as a submonoid of the domain; * `submonoid.map`: image of a submonoid under a monoid homomorphism as a submonoid of the codomain; * `submonoid.prod`: product of two submonoids `s : submonoid M` and `t : submonoid N` as a submonoid of `M × N`; ### Monoid homomorphisms between submonoid * `submonoid.subtype`: embedding of a submonoid into the ambient monoid. * `submonoid.inclusion`: given two submonoids `S`, `T` such that `S ≤ T`, `S.inclusion T` is the inclusion of `S` into `T` as a monoid homomorphism; * `mul_equiv.submonoid_congr`: converts a proof of `S = T` into a monoid isomorphism between `S` and `T`. * `submonoid.prod_equiv`: monoid isomorphism between `s.prod t` and `s × t`; ### Operations on `monoid_hom`s * `monoid_hom.mrange`: range of a monoid homomorphism as a submonoid of the codomain; * `monoid_hom.mrestrict`: restrict a monoid homomorphism to a submonoid; * `monoid_hom.cod_mrestrict`: restrict the codomain of a monoid homomorphism to a submonoid; * `monoid_hom.mrange_restrict`: restrict a monoid homomorphism to its range; ## Tags submonoid, range, product, map, comap -/ variables {M N P : Type*} [monoid M] [monoid N] [monoid P] (S : submonoid M) /-! ### Conversion to/from `additive`/`multiplicative` -/ /-- Map from submonoids of monoid `M` to `add_submonoid`s of `additive M`. -/ def submonoid.to_add_submonoid {M : Type*} [monoid M] (S : submonoid M) : add_submonoid (additive M) := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Map from `add_submonoid`s of `additive M` to submonoids of `M`. -/ def submonoid.of_add_submonoid {M : Type*} [monoid M] (S : add_submonoid (additive M)) : submonoid M := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from `add_submonoid`s of `add_monoid M` to submonoids of `multiplicative M`. -/ def add_submonoid.to_submonoid {M : Type*} [add_monoid M] (S : add_submonoid M) : submonoid (multiplicative M) := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from submonoids of `multiplicative M` to `add_submonoid`s of `add_monoid M`. -/ def add_submonoid.of_submonoid {M : Type*} [add_monoid M] (S : submonoid (multiplicative M)) : add_submonoid M := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Submonoids of monoid `M` are isomorphic to additive submonoids of `additive M`. -/ def submonoid.add_submonoid_equiv (M : Type*) [monoid M] : submonoid M ≃ add_submonoid (additive M) := { to_fun := submonoid.to_add_submonoid, inv_fun := submonoid.of_add_submonoid, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace submonoid open set /-! ### `comap` and `map` -/ /-- The preimage of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The preimage of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def comap (f : M →* N) (S : submonoid N) : submonoid M := { carrier := (f ⁻¹' S), one_mem' := show f 1 ∈ S, by rw f.map_one; exact S.one_mem, mul_mem' := λ a b ha hb, show f (a * b) ∈ S, by rw f.map_mul; exact S.mul_mem ha hb } @[simp, to_additive] lemma coe_comap (S : submonoid N) (f : M →* N) : (S.comap f : set M) = f ⁻¹' S := rfl @[simp, to_additive] lemma mem_comap {S : submonoid N} {f : M →* N} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl @[to_additive] lemma comap_comap (S : submonoid P) (g : N →* P) (f : M →* N) : (S.comap g).comap f = S.comap (g.comp f) := rfl @[to_additive, simp] lemma comap_id (S : submonoid P) : S.comap (monoid_hom.id _) = S := ext (by simp) /-- The image of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The image of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def map (f : M →* N) (S : submonoid M) : submonoid N := { carrier := (f '' S), one_mem' := ⟨1, S.one_mem, f.map_one⟩, mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, S.mul_mem hx hy, by rw f.map_mul; refl⟩ end } @[simp, to_additive] lemma coe_map (f : M →* N) (S : submonoid M) : (S.map f : set N) = f '' S := rfl @[simp, to_additive] lemma mem_map {f : M →* N} {S : submonoid M} {y : N} : y ∈ S.map f ↔ ∃ x ∈ S, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : M →* N) : (S.map f).map g = S.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : M →* N} {S : submonoid M} {T : submonoid N} : S.map f ≤ T ↔ S ≤ T.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : M →* N) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap @[to_additive] lemma map_le_of_le_comap {T : submonoid N} {f : M →* N} : S ≤ T.comap f → S.map f ≤ T := (gc_map_comap f).l_le @[to_additive] lemma le_comap_of_map_le {T : submonoid N} {f : M →* N} : S.map f ≤ T → S ≤ T.comap f := (gc_map_comap f).le_u @[to_additive] lemma le_comap_map {f : M →* N} : S ≤ (S.map f).comap f := (gc_map_comap f).le_u_l _ @[to_additive] lemma map_comap_le {S : submonoid N} {f : M →* N} : (S.comap f).map f ≤ S := (gc_map_comap f).l_u_le _ @[to_additive] lemma monotone_map {f : M →* N} : monotone (map f) := (gc_map_comap f).monotone_l @[to_additive] lemma monotone_comap {f : M →* N} : monotone (comap f) := (gc_map_comap f).monotone_u @[simp, to_additive] lemma map_comap_map {f : M →* N} : ((S.map f).comap f).map f = S.map f := congr_fun ((gc_map_comap f).l_u_l_eq_l) _ @[simp, to_additive] lemma comap_map_comap {S : submonoid N} {f : M →* N} : ((S.comap f).map f).comap f = S.comap f := congr_fun ((gc_map_comap f).u_l_u_eq_u) _ @[to_additive] lemma map_sup (S T : submonoid M) (f : M →* N) : (S ⊔ T).map f = S.map f ⊔ T.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : M →* N) (s : ι → submonoid M) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (S T : submonoid N) (f : M →* N) : (S ⊓ T).comap f = S.comap f ⊓ T.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : M →* N) (s : ι → submonoid N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : M →* N) : (⊥ : submonoid M).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : M →* N) : (⊤ : submonoid N).comap f = ⊤ := (gc_map_comap f).u_top @[simp, to_additive] lemma map_id (S : submonoid M) : S.map (monoid_hom.id M) = S := ext (λ x, ⟨λ ⟨_, h, rfl⟩, h, λ h, ⟨_, h, rfl⟩⟩) section galois_coinsertion variables {ι : Type*} {f : M →* N} (hf : function.injective f) include hf /-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/ def gci_map_comap : galois_coinsertion (map f) (comap f) := (gc_map_comap f).to_galois_coinsertion (λ S x, by simp [mem_comap, mem_map, hf.eq_iff]) lemma comap_map_eq_of_injective (S : submonoid M) : (S.map f).comap f = S := (gci_map_comap hf).u_l_eq _ lemma comap_surjective_of_injective : function.surjective (comap f) := (gci_map_comap hf).u_surjective lemma map_injective_of_injective : function.injective (map f) := (gci_map_comap hf).l_injective lemma comap_inf_map_of_injective (S T : submonoid M) : (S.map f ⊓ T.map f).comap f = S ⊓ T := (gci_map_comap hf).u_inf_l _ _ lemma comap_infi_map_of_injective (S : ι → submonoid M) : (⨅ i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ lemma comap_sup_map_of_injective (S T : submonoid M) : (S.map f ⊔ T.map f).comap f = S ⊔ T := (gci_map_comap hf).u_sup_l _ _ lemma comap_supr_map_of_injective (S : ι → submonoid M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ lemma map_le_map_iff_of_injective {S T : submonoid M} : S.map f ≤ T.map f ↔ S ≤ T := (gci_map_comap hf).l_le_l_iff lemma map_strict_mono_of_injective : strict_mono (map f) := (gci_map_comap hf).strict_mono_l end galois_coinsertion section galois_insertion variables {ι : Type*} {f : M →* N} (hf : function.surjective f) include hf /-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/ def gi_map_comap : galois_insertion (map f) (comap f) := (gc_map_comap f).to_galois_insertion (λ S x h, let ⟨y, hy⟩ := hf x in mem_map.2 ⟨y, by simp [hy, h]⟩) lemma map_comap_eq_of_surjective (S : submonoid N) : (S.comap f).map f = S := (gi_map_comap hf).l_u_eq _ lemma map_surjective_of_surjective : function.surjective (map f) := (gi_map_comap hf).l_surjective lemma comap_injective_of_surjective : function.injective (comap f) := (gi_map_comap hf).u_injective lemma map_inf_comap_of_surjective (S T : submonoid N) : (S.comap f ⊓ T.comap f).map f = S ⊓ T := (gi_map_comap hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (S : ι → submonoid N) : (⨅ i, (S i).comap f).map f = infi S := (gi_map_comap hf).l_infi_u _ lemma map_sup_comap_of_surjective (S T : submonoid N) : (S.comap f ⊔ T.comap f).map f = S ⊔ T := (gi_map_comap hf).l_sup_u _ _ lemma map_supr_comap_of_surjective (S : ι → submonoid N) : (⨆ i, (S i).comap f).map f = supr S := (gi_map_comap hf).l_supr_u _ lemma comap_le_comap_iff_of_surjective {S T : submonoid N} : S.comap f ≤ T.comap f ↔ S ≤ T := (gi_map_comap hf).u_le_u_iff lemma comap_strict_mono_of_surjective : strict_mono (comap f) := (gi_map_comap hf).strict_mono_u end galois_insertion /-- A submonoid of a monoid inherits a multiplication. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an addition."] instance has_mul : has_mul S := ⟨λ a b, ⟨a.1 * b.1, S.mul_mem a.2 b.2⟩⟩ /-- A submonoid of a monoid inherits a 1. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."] instance has_one : has_one S := ⟨⟨_, S.one_mem⟩⟩ @[simp, to_additive] lemma coe_mul (x y : S) : (↑(x * y) : M) = ↑x * ↑y := rfl @[simp, to_additive] lemma coe_one : ((1 : S) : M) = 1 := rfl attribute [norm_cast] coe_mul coe_one attribute [norm_cast] add_submonoid.coe_add add_submonoid.coe_zero /-- A submonoid of a monoid inherits a monoid structure. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an `add_monoid` structure."] instance to_monoid {M : Type*} [monoid M] (S : submonoid M) : monoid S := S.coe_injective.monoid coe rfl (λ _ _, rfl) /-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `add_comm_monoid` is an `add_comm_monoid`."] instance to_comm_monoid {M} [comm_monoid M] (S : submonoid M) : comm_monoid S := S.coe_injective.comm_monoid coe rfl (λ _ _, rfl) /-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/ @[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."] def subtype : S →* M := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑S.subtype = coe := rfl /-- Given `submonoid`s `s`, `t` of monoids `M`, `N` respectively, `s × t` as a submonoid of `M × N`. -/ @[to_additive prod "Given `add_submonoid`s `s`, `t` of `add_monoid`s `A`, `B` respectively, `s × t` as an `add_submonoid` of `A × B`."] def prod (s : submonoid M) (t : submonoid N) : submonoid (M × N) := { carrier := (s : set M).prod t, one_mem' := ⟨s.one_mem, t.one_mem⟩, mul_mem' := λ p q hp hq, ⟨s.mul_mem hp.1 hq.1, t.mul_mem hp.2 hq.2⟩ } @[to_additive coe_prod] lemma coe_prod (s : submonoid M) (t : submonoid N) : (s.prod t : set (M × N)) = (s : set M).prod (t : set N) := rfl @[to_additive mem_prod] lemma mem_prod {s : submonoid M} {t : submonoid N} {p : M × N} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[to_additive prod_mono] lemma prod_mono {s₁ s₂ : submonoid M} {t₁ t₂ : submonoid N} (hs : s₁ ≤ s₂) (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht @[to_additive prod_top] lemma prod_top (s : submonoid M) : s.prod (⊤ : submonoid N) = s.comap (monoid_hom.fst M N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (s : submonoid N) : (⊤ : submonoid M).prod s = s.comap (monoid_hom.snd M N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : submonoid M).prod (⊤ : submonoid N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : submonoid M).prod (⊥ : submonoid N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- The product of submonoids is isomorphic to their product as monoids. -/ @[to_additive prod_equiv "The product of additive submonoids is isomorphic to their product as additive monoids"] def prod_equiv (s : submonoid M) (t : submonoid N) : s.prod t ≃* s × t := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } open monoid_hom @[to_additive] lemma map_inl (s : submonoid M) : s.map (inl M N) = s.prod ⊥ := ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨hx, set.mem_singleton 1⟩, λ ⟨hps, hp1⟩, ⟨p.1, hps, prod.ext rfl $ (set.eq_of_mem_singleton hp1).symm⟩⟩ @[to_additive] lemma map_inr (s : submonoid N) : s.map (inr M N) = prod ⊥ s := ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨set.mem_singleton 1, hx⟩, λ ⟨hp1, hps⟩, ⟨p.2, hps, prod.ext (set.eq_of_mem_singleton hp1).symm rfl⟩⟩ @[simp, to_additive prod_bot_sup_bot_prod] lemma prod_bot_sup_bot_prod (s : submonoid M) (t : submonoid N) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono (le_refl s) bot_le) (prod_mono bot_le (le_refl t))) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem _ ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set.mem_singleton 1⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set.mem_singleton 1, hp.2⟩) end submonoid namespace monoid_hom open submonoid /-- The range of a monoid homomorphism is a submonoid. -/ @[to_additive "The range of an `add_monoid_hom` is an `add_submonoid`."] def mrange (f : M →* N) : submonoid N := (⊤ : submonoid M).map f @[simp, to_additive] lemma coe_mrange (f : M →* N) : (f.mrange : set N) = set.range f := set.image_univ @[simp, to_additive] lemma mem_mrange {f : M →* N} {y : N} : y ∈ f.mrange ↔ ∃ x, f x = y := by simp [mrange] @[to_additive] lemma map_mrange (g : N →* P) (f : M →* N) : f.mrange.map g = (g.comp f).mrange := (⊤ : submonoid M).map_map g f @[to_additive] lemma mrange_top_iff_surjective {N} [monoid N] {f : M →* N} : f.mrange = (⊤ : submonoid N) ↔ function.surjective f := submonoid.ext'_iff.trans $ iff.trans (by rw [coe_mrange, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid hom is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` hom is the whole of the codomain."] lemma mrange_top_of_surjective {N} [monoid N] (f : M →* N) (hf : function.surjective f) : f.mrange = (⊤ : submonoid N) := mrange_top_iff_surjective.2 hf @[to_additive] lemma mrange_eq_map (f : M →* N) : f.mrange = map f ⊤ := rfl @[to_additive] lemma mclosure_preimage_le (f : M →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set."] lemma map_mclosure (f : M →* N) (s : set M) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (mclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) /-- Restriction of a monoid hom to a submonoid of the domain. -/ @[to_additive "Restriction of an add_monoid hom to an `add_submonoid` of the domain."] def mrestrict {N : Type*} [monoid N] (f : M →* N) (S : submonoid M) : S →* N := f.comp S.subtype @[simp, to_additive] lemma mrestrict_apply {N : Type*} [monoid N] (f : M →* N) (x : S) : f.mrestrict S x = f x := rfl /-- Restriction of a monoid hom to a submonoid of the codomain. -/ @[to_additive "Restriction of an `add_monoid` hom to an `add_submonoid` of the codomain."] def cod_mrestrict (f : M →* N) (S : submonoid N) (h : ∀ x, f x ∈ S) : M →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- Restriction of a monoid hom to its range interpreted as a submonoid. -/ @[to_additive "Restriction of an `add_monoid` hom to its range interpreted as a submonoid."] def mrange_restrict {N} [monoid N] (f : M →* N) : M →* f.mrange := f.cod_mrestrict f.mrange $ λ x, ⟨x, submonoid.mem_top x, rfl⟩ @[simp, to_additive] lemma coe_mrange_restrict {N} [monoid N] (f : M →* N) (x : M) : (f.mrange_restrict x : N) = f x := rfl end monoid_hom namespace submonoid open monoid_hom @[to_additive] lemma mrange_inl : (inl M N).mrange = prod ⊤ ⊥ := map_inl ⊤ @[to_additive] lemma mrange_inr : (inr M N).mrange = prod ⊥ ⊤ := map_inr ⊤ @[to_additive] lemma mrange_inl' : (inl M N).mrange = comap (snd M N) ⊥ := mrange_inl.trans (top_prod _) @[to_additive] lemma mrange_inr' : (inr M N).mrange = comap (fst M N) ⊥ := mrange_inr.trans (prod_top _) @[simp, to_additive] lemma mrange_fst : (fst M N).mrange = ⊤ := (fst M N).mrange_top_of_surjective $ @prod.fst_surjective _ _ ⟨1⟩ @[simp, to_additive] lemma mrange_snd : (snd M N).mrange = ⊤ := (snd M N).mrange_top_of_surjective $ @prod.snd_surjective _ _ ⟨1⟩ @[simp, to_additive] lemma mrange_inl_sup_mrange_inr : (inl M N).mrange ⊔ (inr M N).mrange = ⊤ := by simp only [mrange_inl, mrange_inr, prod_bot_sup_bot_prod, top_prod_top] /-- The monoid hom associated to an inclusion of submonoids. -/ @[to_additive "The `add_monoid` hom associated to an inclusion of submonoids."] def inclusion {S T : submonoid M} (h : S ≤ T) : S →* T := S.subtype.cod_mrestrict _ (λ x, h x.2) @[simp, to_additive] lemma range_subtype (s : submonoid M) : s.subtype.mrange = s := ext' $ (coe_mrange _).trans $ subtype.range_coe end submonoid namespace mul_equiv variables {S} {T : submonoid M} /-- Makes the identity isomorphism from a proof that two submonoids of a multiplicative monoid are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two submonoids of an additive monoid are equal."] def submonoid_congr (h : S = T) : S ≃* T := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ submonoid.ext'_iff.1 h } end mul_equiv
20de416589c8cae7429d31ffa42375343b4adc73
e0b0b1648286e442507eb62344760d5cd8d13f2d
/stage0/src/Lean/Elab/Match.lean
1f93e5a1c5f3e42f5675d55eab15d7e1f3cdbb26
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
53,114
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.CollectFVars import Lean.Meta.Match.MatchPatternAttr import Lean.Meta.Match.Match import Lean.Meta.SortLocalDecls import Lean.Meta.GeneralizeVars import Lean.Elab.SyntheticMVars import Lean.Elab.App import Lean.Parser.Term namespace Lean.Elab.Term open Meta open Lean.Parser.Term /- This modules assumes "match"-expressions use the following syntax. ```lean def matchDiscr := leading_parser optional (try (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser def «match» := leading_parser:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` -/ structure MatchAltView where ref : Syntax patterns : Array Syntax rhs : Syntax deriving Inhabited private def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar := $discr; $rhs) withMacroExpansion stx newStx <| elabTerm newStx expectedType? private def elabDiscrsWitMatchType (discrStxs : Array Syntax) (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr × Bool) := do let mut discrs := #[] let mut i := 0 let mut matchType := matchType let mut isDep := false for discrStx in discrStxs do i := i + 1 matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let discr ← fullApproxDefEq <| elabTermEnsuringType discrStx[1] d trace[Elab.match] "discr #{i} {discr} : {d}" if b.hasLooseBVars then isDep := true matchType ← b.instantiate1 discr discrs := discrs.push discr | _ => throwError "invalid type provided to match-expression, function type with arity #{discrStxs.size} expected" pure (discrs, isDep) private def mkUserNameFor (e : Expr) : TermElabM Name := do match e with /- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/ | Expr.fvar fvarId _ => mkFreshUserName ((← getLocalDecl fvarId).userName) | _ => mkFreshBinderName /-- Return true iff `n` is an auxiliary variable created by `expandNonAtomicDiscrs?` -/ def isAuxDiscrName (n : Name) : Bool := n.hasMacroScopes && n.eraseMacroScopes == `_discr /- We treat `@x` as atomic to avoid unnecessary extra local declarations from being inserted into the local context. Recall that `expandMatchAltsIntoMatch` uses `@` modifier. Thus this is kind of discriminant is quite common. Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression. This can happen due to error recovery. Example ``` example : (p ∨ p) → p := fun h => match ``` If we don't abort, the elaborator loops because we will keep trying to expand ``` match ``` into ``` let d := <Syntax.missing>; match ``` Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/ def isAtomicDiscr? (discr : Syntax) : TermElabM (Option Expr) := do match discr with | `($x:ident) => isLocalIdent? x | `(@$x:ident) => isLocalIdent? x | _ => if discr.isMissing then throwAbortTerm else return none -- See expandNonAtomicDiscrs? private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do let term := discr[1] match (← isAtomicDiscr? term) with | some e@(Expr.fvar fvarId _) => let localDecl ← getLocalDecl fvarId if !isAuxDiscrName localDecl.userName then pure e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?` else pure localDecl.value | _ => throwErrorAt discr "unexpected discriminant" structure ElabMatchTypeAndDiscsResult where discrs : Array Expr matchType : Expr /- `true` when performing dependent elimination. We use this to decide whether we optimize the "match unit" case. See `isMatchUnit?`. -/ isDep : Bool alts : Array MatchAltView private def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr) : TermElabM ElabMatchTypeAndDiscsResult := do let numDiscrs := discrStxs.size if matchOptType.isNone then let rec loop (i : Nat) (discrs : Array Expr) (matchType : Expr) (isDep : Bool) (matchAltViews : Array MatchAltView) := do match i with | 0 => return { discrs := discrs.reverse, matchType := matchType, isDep := isDep, alts := matchAltViews } | i+1 => let discrStx := discrStxs[i] let discr ← elabAtomicDiscr discrStx let discr ← instantiateMVars discr let discrType ← inferType discr let discrType ← instantiateMVars discrType let matchTypeBody ← kabstract matchType discr let isDep := isDep || matchTypeBody.hasLooseBVars let userName ← mkUserNameFor discr if discrStx[0].isNone then loop i (discrs.push discr) (Lean.mkForall userName BinderInfo.default discrType matchTypeBody) isDep matchAltViews else let identStx := discrStx[0][0] withLocalDeclD userName discrType fun x => do let eqType ← mkEq discr x withLocalDeclD identStx.getId eqType fun h => do let matchTypeBody := matchTypeBody.instantiate1 x let matchType ← mkForallFVars #[x, h] matchTypeBody let refl ← mkEqRefl discr let discrs := (discrs.push refl).push discr let matchAltViews := matchAltViews.map fun altView => { altView with patterns := altView.patterns.insertAt (i+1) identStx } loop i discrs matchType isDep matchAltViews loop discrStxs.size (discrs := #[]) (isDep := false) expectedType matchAltViews else let matchTypeStx := matchOptType[0][1] let matchType ← elabType matchTypeStx let (discrs, isDep) ← elabDiscrsWitMatchType discrStxs matchType expectedType return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews } def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do matchAlts.mapM fun matchAlt => do let patterns ← matchAlt.patterns.mapM expandMacros pure { matchAlt with patterns := patterns } private def getMatchGeneralizing? : Syntax → Option Bool | `(match (generalizing := true) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some true | `(match (generalizing := false) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some false | _ => none /- Given `stx` a match-expression, return its alternatives. -/ private def getMatchAlts : Syntax → Array MatchAltView | `(match $[$gen]? $discrs,* $[: $ty?]? with $alts:matchAlt*) => alts.filterMap fun alt => match alt with | `(matchAltExpr| | $patterns,* => $rhs) => some { ref := alt, patterns := patterns, rhs := rhs } | _ => none | _ => #[] inductive PatternVar where | localVar (userName : Name) -- anonymous variables (`_`) are encoded using metavariables | anonymousVar (mvarId : MVarId) instance : ToString PatternVar := ⟨fun | PatternVar.localVar x => toString x | PatternVar.anonymousVar mvarId => s!"?m{mvarId}"⟩ builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind /-- Create an auxiliary Syntax node wrapping a fresh metavariable id. We use this kind of Syntax for representing `_` occurring in patterns. The metavariables are created before we elaborate the patterns into `Expr`s. -/ private def mkMVarSyntax : TermElabM Syntax := do let mvarId ← mkFreshId return Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]] /-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/ private def getMVarSyntaxMVarId (stx : Syntax) : MVarId := stx[0].getKind open Meta.Match (mkInaccessible inaccessible?) /-- The elaboration function for `Syntax` created using `mkMVarSyntax`. It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/ @[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? => return mkInaccessible <| mkMVar (getMVarSyntaxMVarId stx) @[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return mkInaccessible e /- Patterns define new local variables. This module collect them and preprocess `_` occurring in patterns. Recall that an `_` may represent anonymous variables or inaccessible terms that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`. After we elaborate the pattern, if the metavariable remains unassigned, we transform it into a regular pattern variable. Otherwise, it becomes an inaccessible term. Macros occurring in patterns are expanded before the `collectPatternVars` method is executed. The following kinds of Syntax are handled by this module - Constructor applications - Applications of functions tagged with the `[matchPattern]` attribute - Identifiers - Anonymous constructors - Structure instances - Inaccessible terms - Named patterns - Tuple literals - Type ascriptions - Literals: num, string and char -/ namespace CollectPatternVars structure State where found : NameSet := {} vars : Array PatternVar := #[] abbrev M := StateRefT State TermElabM private def throwCtorExpected {α} : M α := throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected" private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat := forallBoundedTelescope ctorVal.type ctorVal.numParams fun ps _ => do let mut result := 0 for p in ps do let localDecl ← getLocalDecl p.fvarId! if localDecl.binderInfo.isExplicit then result := result+1 pure result private def throwInvalidPattern {α} : M α := throwError "invalid pattern" /- An application in a pattern can be 1- A constructor application The elaborator assumes fields are accessible and inductive parameters are not accessible. 2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`. The elaborator assumes implicit arguments are not accessible and explicit ones are accessible. -/ structure Context where funId : Syntax ctorVal? : Option ConstructorVal -- It is `some`, if constructor application explicit : Bool ellipsis : Bool paramDecls : Array (Name × BinderInfo) -- parameters names and binder information paramDeclIdx : Nat := 0 namedArgs : Array NamedArg args : List Arg newArgs : Array Syntax := #[] deriving Inhabited private def isDone (ctx : Context) : Bool := ctx.paramDeclIdx ≥ ctx.paramDecls.size private def finalize (ctx : Context) : M Syntax := do if ctx.namedArgs.isEmpty && ctx.args.isEmpty then let fStx ← `(@$(ctx.funId):ident) return Syntax.mkApp fStx ctx.newArgs else throwError "too many arguments" private def isNextArgAccessible (ctx : Context) : Bool := let i := ctx.paramDeclIdx match ctx.ctorVal? with | some ctorVal => i ≥ ctorVal.numParams -- For constructor applications only fields are accessible | none => if h : i < ctx.paramDecls.size then -- For `[matchPattern]` applications, only explicit parameters are accessible. let d := ctx.paramDecls.get ⟨i, h⟩ d.2.isExplicit else false private def getNextParam (ctx : Context) : (Name × BinderInfo) × Context := let i := ctx.paramDeclIdx let d := ctx.paramDecls[i] (d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 }) private def processVar (idStx : Syntax) : M Syntax := do unless idStx.isIdent do throwErrorAt idStx "identifier expected" let id := idStx.getId unless id.eraseMacroScopes.isAtomic do throwError "invalid pattern variable, must be atomic" if (← get).found.contains id then throwError "invalid pattern, variable '{id}' occurred more than once" modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id } return idStx private def nameToPattern : Name → TermElabM Syntax | Name.anonymous => `(Name.anonymous) | Name.str p s _ => do let p ← nameToPattern p; `(Name.str $p $(quote s) _) | Name.num p n _ => do let p ← nameToPattern p; `(Name.num $p $(quote n) _) private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax := match stx[0].isNameLit? with | some val => nameToPattern val | none => throwIllFormedSyntax private def doubleQuotedNameToPattern (stx : Syntax) : TermElabM Syntax := do match stx[1].isNameLit? with | some val => nameToPattern (← resolveGlobalConstNoOverloadWithInfo stx[1] val) | none => throwIllFormedSyntax partial def collect (stx : Syntax) : M Syntax := withRef stx <| withFreshMacroScope do let k := stx.getKind if k == identKind then processId stx else if k == ``Lean.Parser.Term.app then processCtorApp stx else if k == ``Lean.Parser.Term.anonymousCtor then let elems ← stx[1].getArgs.mapSepElemsM collect return stx.setArg 1 <| mkNullNode elems else if k == ``Lean.Parser.Term.structInst then /- ``` leading_parser "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group (structInstField >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" ``` -/ let withMod := stx[1] unless withMod.isNone do throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns" let fields ← stx[2].getArgs.mapM fun p => do -- p is of the form (group (structInstField >> optional ", ")) let field := p[0] -- leading_parser structInstLVal >> " := " >> termParser let newVal ← collect field[2] let field := field.setArg 2 newVal pure <| field.setArg 0 field return stx.setArg 2 <| mkNullNode fields else if k == ``Lean.Parser.Term.hole then let r ← mkMVarSyntax modify fun s => { s with vars := s.vars.push <| PatternVar.anonymousVar <| getMVarSyntaxMVarId r } return r else if k == ``Lean.Parser.Term.paren then let arg := stx[1] if arg.isNone then return stx -- `()` else let t := arg[0] let s := arg[1] if s.isNone || s[0].getKind == ``Lean.Parser.Term.typeAscription then -- Ignore `s`, since it empty or it is a type ascription let t ← collect t let arg := arg.setArg 0 t return stx.setArg 1 arg else return stx else if k == ``Lean.Parser.Term.explicitUniv then processCtor stx[0] else if k == ``Lean.Parser.Term.namedPattern then /- Recall that def namedPattern := check... >> trailing_parser "@" >> termParser -/ let id := stx[0] discard <| processVar id let pat := stx[2] let pat ← collect pat `(_root_.namedPattern $id $pat) else if k == ``Lean.Parser.Term.binop then let lhs ← collect stx[2] let rhs ← collect stx[3] return stx.setArg 2 lhs |>.setArg 3 rhs else if k == ``Lean.Parser.Term.inaccessible then return stx else if k == strLitKind then return stx else if k == numLitKind then return stx else if k == scientificLitKind then return stx else if k == charLitKind then return stx else if k == ``Lean.Parser.Term.quotedName then /- Quoted names have an elaboration function associated with them, and they will not be macro expanded. Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum` instead of the constructors `Name.str` and `Name.num` -/ quotedNameToPattern stx else if k == ``Lean.Parser.Term.doubleQuotedName then /- Similar to previous case -/ doubleQuotedNameToPattern stx else if k == choiceKind then throwError "invalid pattern, notation is ambiguous" else throwInvalidPattern where processCtorApp (stx : Syntax) : M Syntax := do let (f, namedArgs, args, ellipsis) ← expandApp stx true processCtorAppCore f namedArgs args ellipsis processCtor (stx : Syntax) : M Syntax := do processCtorAppCore stx #[] #[] false /- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/ processId (stx : Syntax) : M Syntax := do match (← resolveId? stx "pattern" (withInfo := true)) with | none => processVar stx | some f => match f with | Expr.const fName _ _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => processCtor stx | some _ => if hasMatchPatternAttribute (← getEnv) fName then processCtor stx else processVar stx | none => throwCtorExpected | _ => processVar stx pushNewArg (accessible : Bool) (ctx : Context) (arg : Arg) : M Context := do match arg with | Arg.stx stx => let stx ← if accessible then collect stx else pure stx return { ctx with newArgs := ctx.newArgs.push stx } | _ => unreachable! processExplicitArg (accessible : Bool) (ctx : Context) : M Context := do match ctx.args with | [] => if ctx.ellipsis then pushNewArg accessible ctx (Arg.stx (← `(_))) else throwError "explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}" | arg::args => pushNewArg accessible { ctx with args := args } arg processImplicitArg (accessible : Bool) (ctx : Context) : M Context := do if ctx.explicit then processExplicitArg accessible ctx else pushNewArg accessible ctx (Arg.stx (← `(_))) processCtorAppContext (ctx : Context) : M Syntax := do if isDone ctx then finalize ctx else let accessible := isNextArgAccessible ctx let (d, ctx) := getNextParam ctx match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.1 with | some idx => let arg := ctx.namedArgs[idx] let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx } let ctx ← pushNewArg accessible ctx arg.val processCtorAppContext ctx | none => let ctx ← match d.2 with | BinderInfo.implicit => processImplicitArg accessible ctx | BinderInfo.instImplicit => processImplicitArg accessible ctx | _ => processExplicitArg accessible ctx processCtorAppContext ctx processCtorAppCore (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do let args := args.toList let (fId, explicit) ← match f with | `($fId:ident) => pure (fId, false) | `(@$fId:ident) => pure (fId, true) | _ => throwError "identifier expected" let some (Expr.const fName _ _) ← resolveId? fId "pattern" (withInfo := true) | throwCtorExpected let fInfo ← getConstInfo fName let paramDecls ← forallTelescopeReducing fInfo.type fun xs _ => xs.mapM fun x => do let d ← getFVarLocalDecl x return (d.userName, d.binderInfo) match fInfo with | ConstantInfo.ctorInfo val => processCtorAppContext { funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } | _ => if hasMatchPatternAttribute (← getEnv) fName then processCtorAppContext { funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } else throwCtorExpected def main (alt : MatchAltView) : M MatchAltView := do let patterns ← alt.patterns.mapM fun p => do trace[Elab.match] "collecting variables at pattern: {p}" collect p return { alt with patterns := patterns } end CollectPatternVars private def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do let (alt, s) ← (CollectPatternVars.main alt).run {} return (s.vars, alt) /- Return the pattern variables in the given pattern. Remark: this method is not used by the main `match` elaborator, but in the precheck hook and other macros (e.g., at `Do.lean`). -/ def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do let patternStx ← liftMacroM <| expandMacros patternStx let (_, s) ← (CollectPatternVars.collect patternStx).run {} return s.vars def getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do let collect : CollectPatternVars.M Unit := do for pattern in patterns do discard <| CollectPatternVars.collect (← liftMacroM <| expandMacros pattern) let (_, s) ← collect.run {} return s.vars def getPatternVarNames (pvars : Array PatternVar) : Array Name := pvars.filterMap fun | PatternVar.localVar x => some x | _ => none open Lean.Elab.Term.Quotation in @[builtinQuotPrecheck Lean.Parser.Term.match] def precheckMatch : Precheck | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do discrs.forM precheck for (pats, rhs) in patss.zip rhss do let vars ← try getPatternsVars pats catch | _ => return -- can happen in case of pattern antiquotations Quotation.withNewLocals (getPatternVarNames vars) <| precheck rhs | _ => throwUnsupportedSyntax /- We convert the collected `PatternVar`s intro `PatternVarDecl` -/ inductive PatternVarDecl where /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable when it is not assigned during pattern elaboration. -/ | anonymousVar (mvarId : MVarId) (fvarId : FVarId) | localVar (fvarId : FVarId) private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α := let rec loop (i : Nat) (decls : Array PatternVarDecl) := do if h : i < pVars.size then match pVars.get ⟨i, h⟩ with | PatternVar.anonymousVar mvarId => let type ← mkFreshTypeMVar let userName ← mkFreshBinderName withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!)) | PatternVar.localVar userName => let type ← mkFreshTypeMVar withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!)) else /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`. Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/ decls.forM fun decl => match decl with | PatternVarDecl.anonymousVar mvarId fvarId => do let type ← inferType (mkFVar fvarId) discard <| mkFreshExprMVarWithId mvarId type | _ => pure () k decls loop 0 #[] /- Remark: when performing dependent pattern matching, we often had to write code such as ```lean def Vec.map' (f : α → β) (xs : Vec α n) : Vec β n := match n, xs with | _, nil => nil | _, cons a as => cons (f a) (map' f as) ``` We had to include `n` and the `_`s because the type of `xs` depends on `n`. Moreover, `nil` and `cons a as` have different types. This was quite tedious. So, we have implemented an automatic "discriminant refinement procedure". The procedure is based on the observation that we get a type error whenenver we forget to include `_`s and the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant is an indexed family, and add their indices as new discriminants. The current implementation, adds indices as they are found, and does not try to "sort" the new discriminants. If the refinement process fails, we report the original error message. -/ /- Auxiliary structure for storing an type mismatch exception when processing the pattern #`idx` of some alternative. -/ structure PatternElabException where ex : Exception idx : Nat private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr × Expr) := withReader (fun ctx => { ctx with implicitLambda := false }) do let mut patterns := #[] let mut matchType := matchType for idx in [:patternStxs.size] do let patternStx := patternStxs[idx] matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let pattern ← try liftM <| withSynthesize <| withoutErrToSorry <| elabTermEnsuringType patternStx d catch ex => -- Wrap the type mismatch exception for the "discriminant refinement" feature. throwThe PatternElabException { ex := ex, idx := idx } matchType := b.instantiate1 pattern patterns := patterns.push pattern | _ => throwError "unexpected match type" return (patterns, matchType) def finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do let mut decls := #[] for pdecl in patternVarDecls do match pdecl with | PatternVarDecl.localVar fvarId => let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | PatternVarDecl.anonymousVar mvarId fvarId => let e ← instantiateMVars (mkMVar mvarId); trace[Elab.match] "finalizePatternDecls: mvarId: {mvarId} := {e}, fvar: {mkFVar fvarId}" match e with | Expr.mvar newMVarId _ => /- Metavariable was not assigned, or assigned to another metavariable. So, we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/ assignExprMVar newMVarId (mkFVar fvarId) trace[Elab.match] "finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}" let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | _ => pure () /- We perform a topological sort (dependecies) on `decls` because the pattern elaboration process may produce a sequence where a declaration d₁ may occur after d₂ when d₂ depends on d₁. -/ sortLocalDecls decls open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult) namespace ToDepElimPattern structure State where found : NameSet := {} localDecls : Array LocalDecl newLocals : NameSet := {} abbrev M := StateRefT State TermElabM private def alreadyVisited (fvarId : FVarId) : M Bool := do let s ← get return s.found.contains fvarId private def markAsVisited (fvarId : FVarId) : M Unit := modify fun s => { s with found := s.found.insert fvarId } private def throwInvalidPattern {α} (e : Expr) : M α := throwError "invalid pattern {indentExpr e}" /- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/ private def mkLocalDeclFor (mvar : Expr) : M Pattern := do let mvarId := mvar.mvarId! let s ← get match (← getExprMVarAssignment? mvarId) with | some val => return Pattern.inaccessible val | none => let fvarId ← mkFreshId let type ← inferType mvar /- HACK: `fvarId` is not in the scope of `mvarId` If this generates problems in the future, we should update the metavariable declarations. -/ assignExprMVar mvarId (mkFVar fvarId) let userName ← mkFreshBinderName let newDecl := LocalDecl.cdecl arbitrary fvarId userName type BinderInfo.default; modify fun s => { s with newLocals := s.newLocals.insert fvarId, localDecls := match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with | none => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar` | some i => s.localDecls.insertAt i newDecl } return Pattern.var fvarId partial def main (e : Expr) : M Pattern := do let isLocalDecl (fvarId : FVarId) : M Bool := do return (← get).localDecls.any fun d => d.fvarId == fvarId let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do if (← alreadyVisited fvarId) then return Pattern.inaccessible e else markAsVisited fvarId return Pattern.var e.fvarId! let mkInaccessible (e : Expr) : M Pattern := do match e with | Expr.fvar fvarId _ => if (← isLocalDecl fvarId) then mkPatternVar fvarId e else return Pattern.inaccessible e | _ => return Pattern.inaccessible e match inaccessible? e with | some t => mkInaccessible t | none => match e.arrayLit? with | some (α, lits) => return Pattern.arrayLit α (← lits.mapM main) | none => if e.isAppOfArity `namedPattern 3 then let p ← main <| e.getArg! 2 match e.getArg! 1 with | Expr.fvar fvarId _ => return Pattern.as fvarId p | _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if e.isNatLit || e.isStringLit || e.isCharLit then return Pattern.val e else if e.isFVar then let fvarId := e.fvarId! unless (← isLocalDecl fvarId) do throwInvalidPattern e mkPatternVar fvarId e else if e.isMVar then mkLocalDeclFor e else let newE ← whnf e if newE != e then main newE else matchConstCtor e.getAppFn (fun _ => throwInvalidPattern e) fun v us => do let args := e.getAppArgs unless args.size == v.numParams + v.numFields do throwInvalidPattern e let params := args.extract 0 v.numParams let fields := args.extract v.numParams args.size let fields ← fields.mapM main return Pattern.ctor v.name us params.toList fields.toList end ToDepElimPattern def withDepElimPatterns {α} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl → Array Pattern → TermElabM α) : TermElabM α := do let (patterns, s) ← (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls } let localDecls ← s.localDecls.mapM fun d => instantiateLocalDeclMVars d /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/ let lctx ← getLCtx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do k localDecls patterns private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr) (k : AltLHS → Expr → TermElabM α) : ExceptT PatternElabException TermElabM α := do let (patterns, matchType) ← withSynthesize <| elabPatterns patternStxs matchType id (α := TermElabM α) do let localDecls ← finalizePatternDecls patternVarDecls let patterns ← patterns.mapM (instantiateMVars ·) withDepElimPatterns localDecls patterns fun localDecls patterns => k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType private def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : ExceptT PatternElabException TermElabM (AltLHS × Expr) := withRef alt.ref do let (patternVars, alt) ← collectPatternVars alt trace[Elab.match] "patternVars: {patternVars}" withPatternVars patternVars fun patternVarDecls => do withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do let rhs ← elabTermEnsuringType alt.rhs matchType let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr let rhs ← if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs trace[Elab.match] "rhs: {rhs}" return (altLHS, rhs) /-- Collect indices for the "discriminant refinement feature". This method is invoked when we detect a type mismatch at a pattern #`idx` of some alternative. -/ private def getIndicesToInclude (discrs : Array Expr) (idx : Nat) : TermElabM (Array Expr) := do let discrType ← whnfD (← inferType discrs[idx]) matchConstInduct discrType.getAppFn (fun _ => return #[]) fun info _ => do let mut result := #[] let args := discrType.getAppArgs for arg in args[info.numParams : args.size] do unless (← discrs.anyM fun discr => isDefEq discr arg) do result := result.push arg return result /-- "Generalize" variables that depend on the discriminants. Remarks and limitations: - If `matchType` is a proposition, then we generalize even when the user did not provide `(generalizing := true)`. Motivation: users should have control about the actual `match`-expressions in their programs. - We currently do not generalize let-decls. - We abort generalization if the new `matchType` is type incorrect. - Only discriminants that are free variables are considered during specialization. - We "generalize" by adding new discriminants and pattern variables. We do not "clear" the generalized variables, but they become inaccessible since they are shadowed by the patterns variables. We assume this is ok since this is the exact behavior users would get if they had written it by hand. Recall there is no `clear` in term mode. -/ private def generalize (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (generalizing? : Option Bool) : TermElabM (Array Expr × Expr × Array MatchAltView × Bool) := do let gen ← match generalizing? with | some g => pure g | _ => isProp matchType if !gen then return (discrs, matchType, altViews, false) else let ysFVarIds ← getFVarsToGeneralize discrs /- let-decls are currently being ignored by the generalizer. -/ let ysFVarIds ← ysFVarIds.filterM fun fvarId => return !(← getLocalDecl fvarId).isLet if ysFVarIds.isEmpty then return (discrs, matchType, altViews, false) else let ys := ysFVarIds.map mkFVar -- trace[Meta.debug] "ys: {ys}, discrs: {discrs}" let matchType' ← forallBoundedTelescope matchType discrs.size fun ds type => do let type ← mkForallFVars ys type let (discrs', ds') := Array.unzip <| Array.zip discrs ds |>.filter fun (di, d) => di.isFVar let type := type.replaceFVars discrs' ds' mkForallFVars ds type -- trace[Meta.debug] "matchType': {matchType'}" if (← isTypeCorrect matchType') then let discrs := discrs ++ ys let altViews ← altViews.mapM fun altView => do let patternVars ← getPatternsVars altView.patterns -- We traverse backwards because we want to keep the most recent names. -- For example, if `ys` contains `#[h, h]`, we want to make sure `mkFreshUsername is applied to the first `h`, -- since it is already shadowed by the second. let ysUserNames ← ys.foldrM (init := #[]) fun ys ysUserNames => do let yDecl ← getLocalDecl ys.fvarId! let mut yUserName := yDecl.userName if ysUserNames.contains yUserName then yUserName ← mkFreshUserName yUserName -- Explicitly provided pattern variables shadow `y` else if patternVars.any fun | PatternVar.localVar x => x == yUserName | _ => false then yUserName ← mkFreshUserName yUserName return ysUserNames.push yUserName let ysIds ← ysUserNames.reverse.mapM fun n => return mkIdentFrom (← getRef) n return { altView with patterns := altView.patterns ++ ysIds } return (discrs, matchType', altViews, true) else return (discrs, matchType, altViews, true) private partial def elabMatchAltViews (generalizing? : Option Bool) (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do loop discrs matchType altViews none where /- "Discriminant refinement" main loop. `first?` contains the first error message we found before updated the `discrs`. -/ loop (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState × Exception)) : TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do let s ← saveState let (discrs', matchType', altViews', refined) ← generalize discrs matchType altViews generalizing? match ← altViews'.mapM (fun altView => elabMatchAltView altView matchType') |>.run with | Except.ok alts => return (discrs', matchType', alts, first?.isSome || refined) | Except.error { idx := idx, ex := ex } => let indices ← getIndicesToInclude discrs idx if indices.isEmpty then throwEx (← updateFirst first? ex) else let first ← updateFirst first? ex s.restore let indices ← collectDeps indices discrs let matchType ← try updateMatchType indices matchType catch ex => throwEx first let altViews ← addWildcardPatterns indices.size altViews let discrs := indices ++ discrs loop discrs matchType altViews first throwEx {α} (p : SavedState × Exception) : TermElabM α := do p.1.restore; throw p.2 updateFirst (first? : Option (SavedState × Exception)) (ex : Exception) : TermElabM (SavedState × Exception) := do match first? with | none => return (← saveState, ex) | some first => return first containsFVar (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => e.isFVar && e.fvarId! == fvarId /- Update `indices` by including any free variable `x` s.t. - Type of some `discr` depends on `x`. - Type of `x` depends on some free variable in `indices`. If we don't include these extra variables in indices, then `updateMatchType` will generate a type incorrect term. For example, suppose `discr` contains `h : @HEq α a α b`, and `indices` is `#[α, b]`, and `matchType` is `@HEq α a α b → B`. `updateMatchType indices matchType` produces the type `(α' : Type) → (b : α') → @HEq α' a α' b → B` which is type incorrect because we have `a : α`. The method `collectDeps` will include `a` into `indices`. This method does not handle dependencies among non-free variables. We rely on the type checking method `check` at `updateMatchType`. -/ collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do let mut s : CollectFVars.State := {} for discr in discrs do s := collectFVars s (← instantiateMVars (← inferType discr)) let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar let indicesFVar := indicesFVar.map Expr.fvarId! let mut toAdd := #[] for fvarId in s.fvarSet.toList do unless containsFVar discrs fvarId || containsFVar indices fvarId do let localDecl ← getLocalDecl fvarId let mctx ← getMCtx for indexFVarId in indicesFVar do if mctx.localDeclDependsOn localDecl indexFVarId then toAdd := toAdd.push fvarId let lctx ← getLCtx let indicesFVar := (indicesFVar ++ toAdd).qsort fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index return indicesFVar.map mkFVar ++ indicesNonFVar updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do let matchType ← indices.foldrM (init := matchType) fun index matchType => do let indexType ← inferType index let matchTypeBody ← kabstract matchType index let userName ← mkUserNameFor index return Lean.mkForall userName BinderInfo.default indexType matchTypeBody check matchType return matchType addWildcardPatterns (num : Nat) (altViews : Array MatchAltView) : TermElabM (Array MatchAltView) := do let hole := mkHole (← getRef) let wildcards := mkArray num hole return altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns } def mkMatcher (elimName : Name) (matchType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : TermElabM MatcherResult := Meta.Match.mkMatcher elimName matchType numDiscrs lhss register_builtin_option match.ignoreUnusedAlts : Bool := { defValue := false descr := "if true, do not generate error if an alternative is not used" } def reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do unless result.counterExamples.isEmpty do withHeadRefOnly <| logError m!"missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}" unless match.ignoreUnusedAlts.get (← getOptions) || result.unusedAltIdxs.isEmpty do let mut i := 0 for alt in altLHSS do if result.unusedAltIdxs.contains i then withRef alt.ref do logError "redundant alternative" i := i + 1 /-- If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]` Otherwise, return none. -/ private def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do assert! altLHSS.length == rhss.size match altLHSS with | [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] => /- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/ match rhss[0] with | Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b | _ => return none | _ => return none private def elabMatchAux (generalizing? : Option Bool) (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr) : TermElabM Expr := do let mut generalizing? := generalizing? if !matchOptType.isNone then if generalizing? == some true then throwError "the '(generalizing := true)' parameter is not supported when the 'match' type is explicitly provided" generalizing? := some false let (discrs, matchType, altLHSS, isDep, rhss) ← commitIfDidNotPostpone do let ⟨discrs, matchType, isDep, altViews⟩ ← elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType let matchAlts ← liftMacroM <| expandMacrosInPatterns altViews trace[Elab.match] "matchType: {matchType}" let (discrs, matchType, alts, refined) ← elabMatchAltViews generalizing? discrs matchType matchAlts let isDep := isDep || refined /- We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be able to elaborate examples such as: ``` def f (x : Nat) : Option Nat := none def g (xs : List (Nat × Nat)) : IO Unit := xs.forM fun x => match f x.fst with | _ => pure () ``` If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because the type of `x` is only available after we proces the last argument of `List.forM`. We apply pending default types to make sure we can process examples such as ``` let (a, b) := (0, 0) ``` -/ synthesizeSyntheticMVarsUsingDefault let rhss := alts.map Prod.snd let matchType ← instantiateMVars matchType let altLHSS ← alts.toList.mapM fun alt => do let altLHS ← Match.instantiateAltLHSMVars alt.1 /- Remark: we try to postpone before throwing an error. The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed. The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here. Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here. ``` def bad (ps : Array (Nat × Nat)) : Array (Nat × Nat) := (ps.filter fun (p : Prod _ _) => match p with | (x, y) => x == 0) ++ ps ``` When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet because `Array.filter` has type `{α : Type u_1} → (α → Bool) → (as : Array α) → optParam Nat 0 → optParam Nat (Array.size as) → Array α` However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`. -/ withRef altLHS.ref do for d in altLHS.fvarDecls do if d.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}" for p in altLHS.patterns do if p.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}" pure altLHS return (discrs, matchType, altLHSS, isDep, rhss) if let some r ← if isDep then pure none else isMatchUnit? altLHSS rhss then return r else let numDiscrs := discrs.size let matcherName ← mkAuxName `match let matcherResult ← mkMatcher matcherName matchType numDiscrs altLHSS let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType reportMatcherResultErrors altLHSS matcherResult let r := mkApp matcherResult.matcher motive let r := mkAppN r discrs let r := mkAppN r rhss trace[Elab.match] "result: {r}" return r private def getDiscrs (matchStx : Syntax) : Array Syntax := matchStx[2].getSepArgs private def getMatchOptType (matchStx : Syntax) : Syntax := matchStx[3] private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) := let matchOptType := getMatchOptType matchStx; if matchOptType.isNone then do let discrs := getDiscrs matchStx; let allLocal ← discrs.allM fun discr => Option.isSome <$> isAtomicDiscr? discr[1] if allLocal then return none else -- We use `foundFVars` to make sure the discriminants are distinct variables. -- See: code for computing "matchType" at `elabMatchTypeAndDiscrs` let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) (foundFVars : NameSet) := do match discrs with | [] => let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", "); pure (matchStx.setArg 2 discrs) | discr :: discrs => -- Recall that -- matchDiscr := leading_parser optional (ident >> ":") >> termParser let term := discr[1] let addAux : TermElabM Syntax := withFreshMacroScope do let d ← `(_discr); unless isAuxDiscrName d.getId do -- Use assertion? throwError "unexpected internal auxiliary discriminant name" let discrNew := discr.setArg 1 d; let r ← loop discrs (discrsNew.push discrNew) foundFVars `(let _discr := $term; $r) match (← isAtomicDiscr? term) with | some x => if x.isFVar then loop discrs (discrsNew.push discr) (foundFVars.insert x.fvarId!) else addAux | none => addAux return some (← loop discrs.toList #[] {}) else -- We do not pull non atomic discriminants when match type is provided explicitly by the user return none private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do -- We don't wait for the discriminants types when match type is provided by user if getMatchOptType matchStx |>.isNone then let discrs := getDiscrs matchStx for discr in discrs do let term := discr[1] match (← isAtomicDiscr? term) with | none => throwErrorAt discr "unexpected discriminant" -- see `expandNonAtomicDiscrs? | some d => let dType ← inferType d trace[Elab.match] "discr {d} : {dType}" tryPostponeIfMVar dType /- We (try to) elaborate a `match` only when the expected type is available. If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type of a discriminant is not available. That is, it is of the form `(?m ...)`. We use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables. This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances. Suppose, we are trying to elaborate ``` match g x with | ... => ... ``` `expandNonAtomicDiscrs?` converts it intro ``` let _discr := g x match _discr with | ... => ... ``` Thus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`. Note that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`. This elaboration technique is needed to elaborate terms such as: ```lean xs.filter fun (a, b) => a > b ``` which are syntax sugar for ```lean List.filter (fun p => match p with | (a, b) => a > b) xs ``` When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet. -/ private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? tryPostponeIfDiscrTypeIsMVar matchStx match expectedType? with | some expectedType => return expectedType | none => mkFreshTypeMVar /- ``` leading_parser:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`. -/ private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← waitExpectedTypeAndDiscrs stx expectedType? let discrStxs := (getDiscrs stx).map fun d => d let gen? := getMatchGeneralizing? stx let altViews := getMatchAlts stx let matchOptType := getMatchOptType stx elabMatchAux gen? discrStxs altViews matchOptType expectedType private def isPatternVar (stx : Syntax) : TermElabM Bool := do match (← resolveId? stx "pattern") with | none => isAtomicIdent stx | some f => match f with | Expr.const fName _ _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => return false | some _ => return !hasMatchPatternAttribute (← getEnv) fName | _ => isAtomicIdent stx | _ => isAtomicIdent stx where isAtomicIdent (stx : Syntax) : Bool := stx.isIdent && stx.getId.eraseMacroScopes.isAtomic -- leading_parser "match " >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts @[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => do match stx with | `(match $discr:term with | $y:ident => $rhs:term) => if (← isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType? | _ => elabMatchDefault stx expectedType? where elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do match (← expandNonAtomicDiscrs? stx) with | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | none => let discrs := getDiscrs stx; let matchOptType := getMatchOptType stx; if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then throwErrorAt matchOptType "match expected type should not be provided when discriminants with equality proofs are used" elabMatchCore stx expectedType? builtin_initialize registerTraceClass `Elab.match -- leading_parser:leadPrec "nomatch " >> termParser @[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => do match stx with | `(nomatch $discrExpr) => match ← isLocalIdent? discrExpr with | some _ => let expectedType ← waitExpectedType expectedType? let discr := Syntax.node ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr] elabMatchAux none #[discr] #[] mkNullNode expectedType | _ => let stxNew ← `(let _discr := $discrExpr; nomatch _discr) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | _ => throwUnsupportedSyntax end Lean.Elab.Term
dd2112a21644b36b8e4afcbcae3076a4f20c99de
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/compiler/strictOrSimp.lean
bccd4f1a2b6b0d05a24bfbd8f63083c635278b54
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
223
lean
partial def spin : Nat → Bool | n := spin (n) @[inline] def C : Nat := 0 def f (b : Nat) := if strictOr (C == 0) (spin b) then "hello" else "world" def main (xs : List String) : IO Unit := IO.println (f xs.head.toNat)
5e151eece9cea8c2d6b66c93a637beef7ab732e6
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/polynomial/scale_roots_auto.lean
e58b3fe18f36cbdc311b34d214067930a6d523c3
[]
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,692
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Devon Tuma -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.polynomial.basic import Mathlib.ring_theory.non_zero_divisors import Mathlib.PostPort universes u_3 u_4 u_1 u_2 namespace Mathlib /-- `scale_roots p s` is a polynomial with root `r * s` for each root `r` of `p`. -/ def scale_roots {R : Type u_3} [comm_ring R] (p : polynomial R) (s : R) : polynomial R := finsupp.on_finset (finsupp.support p) (fun (i : ℕ) => polynomial.coeff p i * s ^ (polynomial.nat_degree p - i)) sorry @[simp] theorem coeff_scale_roots {R : Type u_3} [comm_ring R] (p : polynomial R) (s : R) (i : ℕ) : polynomial.coeff (scale_roots p s) i = polynomial.coeff p i * s ^ (polynomial.nat_degree p - i) := rfl theorem coeff_scale_roots_nat_degree {R : Type u_3} [comm_ring R] (p : polynomial R) (s : R) : polynomial.coeff (scale_roots p s) (polynomial.nat_degree p) = polynomial.leading_coeff p := sorry @[simp] theorem zero_scale_roots {R : Type u_3} [comm_ring R] (s : R) : scale_roots 0 s = 0 := sorry theorem scale_roots_ne_zero {R : Type u_3} [comm_ring R] {p : polynomial R} (hp : p ≠ 0) (s : R) : scale_roots p s ≠ 0 := sorry theorem support_scale_roots_le {R : Type u_3} [comm_ring R] (p : polynomial R) (s : R) : finsupp.support (scale_roots p s) ≤ finsupp.support p := sorry theorem support_scale_roots_eq {R : Type u_3} [comm_ring R] (p : polynomial R) {s : R} (hs : s ∈ non_zero_divisors R) : finsupp.support (scale_roots p s) = finsupp.support p := sorry @[simp] theorem degree_scale_roots {R : Type u_3} [comm_ring R] (p : polynomial R) {s : R} : polynomial.degree (scale_roots p s) = polynomial.degree p := sorry @[simp] theorem nat_degree_scale_roots {R : Type u_3} [comm_ring R] (p : polynomial R) (s : R) : polynomial.nat_degree (scale_roots p s) = polynomial.nat_degree p := sorry theorem monic_scale_roots_iff {R : Type u_3} [comm_ring R] {p : polynomial R} (s : R) : polynomial.monic (scale_roots p s) ↔ polynomial.monic p := sorry theorem scale_roots_eval₂_eq_zero {R : Type u_3} {S : Type u_4} [comm_ring R] [comm_ring S] {p : polynomial S} (f : S →+* R) {r : R} {s : S} (hr : polynomial.eval₂ f r p = 0) : polynomial.eval₂ f (coe_fn f s * r) (scale_roots p s) = 0 := sorry theorem scale_roots_aeval_eq_zero {R : Type u_3} {S : Type u_4} [comm_ring R] [comm_ring S] [algebra S R] {p : polynomial S} {r : R} {s : S} (hr : coe_fn (polynomial.aeval r) p = 0) : coe_fn (polynomial.aeval (coe_fn (algebra_map S R) s * r)) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero (algebra_map S R) hr theorem scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero {A : Type u_1} {K : Type u_2} [integral_domain A] [field K] {p : polynomial A} {f : A →+* K} (hf : function.injective ⇑f) {r : A} {s : A} (hr : polynomial.eval₂ f (coe_fn f r / coe_fn f s) p = 0) (hs : s ∈ non_zero_divisors A) : polynomial.eval₂ f (coe_fn f r) (scale_roots p s) = 0 := sorry theorem scale_roots_aeval_eq_zero_of_aeval_div_eq_zero {A : Type u_1} {K : Type u_2} [integral_domain A] [field K] [algebra A K] (inj : function.injective ⇑(algebra_map A K)) {p : polynomial A} {r : A} {s : A} (hr : coe_fn (polynomial.aeval (coe_fn (algebra_map A K) r / coe_fn (algebra_map A K) s)) p = 0) (hs : s ∈ non_zero_divisors A) : coe_fn (polynomial.aeval (coe_fn (algebra_map A K) r)) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero inj hr hs end Mathlib
528feaab3d678bb4d1eab85c7a865a4465b6d505
3863d2564418bccb1859e057bf5a4ef240e75fd7
/hott/types/univ.hlean
f60e2fdc0e4ca2b6989d54cfab339893c213c75a
[ "Apache-2.0" ]
permissive
JacobGross/lean
118bbb067ff4d4af48a266face2c7eb9868fa91c
eb26087df940c54337cb807b4bc6d345d1fc1085
refs/heads/master
1,582,735,011,532
1,462,557,826,000
1,462,557,826,000
46,451,196
0
0
null
1,462,557,826,000
1,447,885,161,000
C++
UTF-8
Lean
false
false
4,920
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about the universe -/ -- see also init.ua import .bool .trunc .lift .pullback open is_trunc bool lift unit eq pi equiv sum sigma fiber prod pullback is_equiv sigma.ops pointed namespace univ universe variables u v variables {A B : Type.{u}} {a : A} {b : B} /- Pathovers -/ definition eq_of_pathover_ua {f : A ≃ B} (p : a =[ua f] b) : f a = b := !cast_ua⁻¹ ⬝ tr_eq_of_pathover p definition pathover_ua {f : A ≃ B} (p : f a = b) : a =[ua f] b := pathover_of_tr_eq (!cast_ua ⬝ p) definition pathover_ua_equiv (f : A ≃ B) : (a =[ua f] b) ≃ (f a = b) := equiv.MK eq_of_pathover_ua pathover_ua abstract begin intro p, unfold [pathover_ua,eq_of_pathover_ua], rewrite [to_right_inv !pathover_equiv_tr_eq, inv_con_cancel_left] end end abstract begin intro p, unfold [pathover_ua,eq_of_pathover_ua], rewrite [con_inv_cancel_left, to_left_inv !pathover_equiv_tr_eq] end end /- Properties which can be disproven for the universe -/ definition not_is_set_type0 : ¬is_set Type₀ := assume H : is_set Type₀, absurd !is_set.elim eq_bnot_ne_idp definition not_is_set_type : ¬is_set Type.{u} := assume H : is_set Type, absurd (is_trunc_is_embedding_closed lift !trunc_index.minus_one_le_succ) not_is_set_type0 definition not_double_negation_elimination0 : ¬Π(A : Type₀), ¬¬A → A := begin intro f, have u : ¬¬bool, by exact (λg, g tt), let H1 := apd f eq_bnot, note H2 := apo10 H1 u, have p : eq_bnot ▸ u = u, from !is_prop.elim, rewrite p at H2, note H3 := eq_of_pathover_ua H2, esimp at H3, --TODO: use apply ... at after #700 exact absurd H3 (bnot_ne (f bool u)), end definition not_double_negation_elimination : ¬Π(A : Type), ¬¬A → A := begin intro f, apply not_double_negation_elimination0, intro A nna, refine down (f _ _), intro na, have ¬A, begin intro a, exact absurd (up a) na end, exact absurd this nna end definition not_excluded_middle : ¬Π(A : Type), A + ¬A := begin intro f, apply not_double_negation_elimination, intro A nna, induction (f A) with a na, exact a, exact absurd na nna end definition characteristic_map [unfold 2] {B : Type.{u}} (p : Σ(A : Type.{max u v}), A → B) (b : B) : Type.{max u v} := by induction p with A f; exact fiber f b definition characteristic_map_inv [unfold 2] {B : Type.{u}} (P : B → Type.{max u v}) : Σ(A : Type.{max u v}), A → B := ⟨(Σb, P b), pr1⟩ definition sigma_arrow_equiv_arrow_univ [constructor] (B : Type.{u}) : (Σ(A : Type.{max u v}), A → B) ≃ (B → Type.{max u v}) := begin fapply equiv.MK, { exact characteristic_map}, { exact characteristic_map_inv}, { intro P, apply eq_of_homotopy, intro b, esimp, apply ua, apply fiber_pr1}, { intro p, induction p with A f, fapply sigma_eq: esimp, { apply ua, apply sigma_fiber_equiv }, { apply arrow_pathover_constant_right, intro v, rewrite [-cast_def _ v, cast_ua_fn], esimp [sigma_fiber_equiv,equiv.trans,equiv.symm,sigma_comm_equiv,comm_equiv_unc], induction v with b w, induction w with a p, esimp, exact p⁻¹}} end definition is_object_classifier (f : A → B) : pullback_square (pointed_fiber f) (fiber f) f pType.carrier := pullback_square.mk (λa, idp) (is_equiv_of_equiv_of_homotopy (calc A ≃ Σb, fiber f b : sigma_fiber_equiv ... ≃ Σb (v : ΣX, X = fiber f b), v.1 : sigma_equiv_sigma_right (λb, !sigma_equiv_of_is_contr_left) ... ≃ Σb X (p : X = fiber f b), X : sigma_equiv_sigma_right (λb, !sigma_assoc_equiv) ... ≃ Σb X (x : X), X = fiber f b : sigma_equiv_sigma_right (λb, sigma_equiv_sigma_right (λX, !comm_equiv_nondep)) ... ≃ Σb (v : ΣX, X), v.1 = fiber f b : sigma_equiv_sigma_right (λb, !sigma_assoc_equiv⁻¹ᵉ) ... ≃ Σb (Y : Type*), Y = fiber f b : sigma_equiv_sigma_right (λb, sigma_equiv_sigma (pType.sigma_char)⁻¹ᵉ (λv, sigma.rec_on v (λx y, equiv.refl))) ... ≃ Σ(Y : Type*) b, Y = fiber f b : sigma_comm_equiv ... ≃ pullback pType.carrier (fiber f) : !pullback.sigma_char⁻¹ᵉ ) proof λb, idp qed) end univ
fa7ea32d23ae2d1c61f93385f37bcc6bb94f52c8
e514e8b939af519a1d5e9b30a850769d058df4e9
/src/tactic/rewrite_search/tracer/default.lean
9a34db99c5b6293c85e5cdb3bd6bd57cbd8dada7
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
26
lean
import .unit import .graph
31b7ad23e2f7697ee5a5c5e3b6aaed8225e1d279
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/control/lawful_fix.lean
0c1a46d66ca99e262ba55a6e0ff07c8face6ca95
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,808
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.stream.init import tactic.apply import control.fix import order.omega_complete_partial_order /-! # Lawful fixed point operators > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This module defines the laws required of a `has_fix` instance, using the theory of omega complete partial orders (ωCPO). Proofs of the lawfulness of all `has_fix` instances in `control.fix` are provided. ## Main definition * class `lawful_fix` -/ universes u v open_locale classical variables {α : Type*} {β : α → Type*} open omega_complete_partial_order /-- Intuitively, a fixed point operator `fix` is lawful if it satisfies `fix f = f (fix f)` for all `f`, but this is inconsistent / uninteresting in most cases due to the existence of "exotic" functions `f`, such as the function that is defined iff its argument is not, familiar from the halting problem. Instead, this requirement is limited to only functions that are `continuous` in the sense of `ω`-complete partial orders, which excludes the example because it is not monotone (making the input argument less defined can make `f` more defined). -/ class lawful_fix (α : Type*) [omega_complete_partial_order α] extends has_fix α := (fix_eq : ∀ {f : α →o α}, continuous f → has_fix.fix f = f (has_fix.fix f)) lemma lawful_fix.fix_eq' {α} [omega_complete_partial_order α] [lawful_fix α] {f : α → α} (hf : continuous' f) : has_fix.fix f = f (has_fix.fix f) := lawful_fix.fix_eq (hf.to_bundled _) namespace part open part nat nat.upto namespace fix variables (f : (Π a, part $ β a) →o (Π a, part $ β a)) lemma approx_mono' {i : ℕ} : fix.approx f i ≤ fix.approx f (succ i) := begin induction i, dsimp [approx], apply @bot_le _ _ _ (f ⊥), intro, apply f.monotone, apply i_ih end lemma approx_mono ⦃i j : ℕ⦄ (hij : i ≤ j) : approx f i ≤ approx f j := begin induction j with j ih, { cases hij, exact le_rfl }, cases hij, { exact le_rfl }, exact le_trans (ih ‹_›) (approx_mono' f) end lemma mem_iff (a : α) (b : β a) : b ∈ part.fix f a ↔ ∃ i, b ∈ approx f i a := begin by_cases h₀ : ∃ (i : ℕ), (approx f i a).dom, { simp only [part.fix_def f h₀], split; intro hh, exact ⟨_,hh⟩, have h₁ := nat.find_spec h₀, rw [dom_iff_mem] at h₁, cases h₁ with y h₁, replace h₁ := approx_mono' f _ _ h₁, suffices : y = b, subst this, exact h₁, cases hh with i hh, revert h₁, generalize : (succ (nat.find h₀)) = j, intro, wlog case : i ≤ j, { cases le_total i j with H H; [skip, symmetry]; apply_assumption; assumption }, replace hh := approx_mono f case _ _ hh, apply part.mem_unique h₁ hh }, { simp only [fix_def' ⇑f h₀, not_exists, false_iff, not_mem_none], simp only [dom_iff_mem, not_exists] at h₀, intro, apply h₀ } end lemma approx_le_fix (i : ℕ) : approx f i ≤ part.fix f := assume a b hh, by { rw [mem_iff f], exact ⟨_,hh⟩ } lemma exists_fix_le_approx (x : α) : ∃ i, part.fix f x ≤ approx f i x := begin by_cases hh : ∃ i b, b ∈ approx f i x, { rcases hh with ⟨i,b,hb⟩, existsi i, intros b' h', have hb' := approx_le_fix f i _ _ hb, obtain rfl := part.mem_unique h' hb', exact hb }, { simp only [not_exists] at hh, existsi 0, intros b' h', simp only [mem_iff f] at h', cases h' with i h', cases hh _ _ h' } end include f /-- The series of approximations of `fix f` (see `approx`) as a `chain` -/ def approx_chain : chain (Π a, part $ β a) := ⟨approx f, approx_mono f⟩ lemma le_f_of_mem_approx {x} : x ∈ approx_chain f → x ≤ f x := begin simp only [(∈), forall_exists_index], rintro i rfl, apply approx_mono' end lemma approx_mem_approx_chain {i} : approx f i ∈ approx_chain f := stream.mem_of_nth_eq rfl end fix open fix variables {α} variables (f : (Π a, part $ β a) →o (Π a, part $ β a)) open omega_complete_partial_order open part (hiding ωSup) nat open nat.upto omega_complete_partial_order lemma fix_eq_ωSup : part.fix f = ωSup (approx_chain f) := begin apply le_antisymm, { intro x, cases exists_fix_le_approx f x with i hx, transitivity' approx f i.succ x, { transitivity', apply hx, apply approx_mono' f }, apply' le_ωSup_of_le i.succ, dsimp [approx], refl', }, { apply ωSup_le _ _ _, simp only [fix.approx_chain, order_hom.coe_fun_mk], intros y x, apply approx_le_fix f }, end lemma fix_le {X : Π a, part $ β a} (hX : f X ≤ X) : part.fix f ≤ X := begin rw fix_eq_ωSup f, apply ωSup_le _ _ _, simp only [fix.approx_chain, order_hom.coe_fun_mk], intros i, induction i, dsimp [fix.approx], apply' bot_le, transitivity' f X, apply f.monotone i_ih, apply hX end variables {f} (hc : continuous f) include hc lemma fix_eq : part.fix f = f (part.fix f) := begin rw [fix_eq_ωSup f,hc], apply le_antisymm, { apply ωSup_le_ωSup_of_le _, intros i, existsi [i], intro x, -- intros x y hx, apply le_f_of_mem_approx _ ⟨i, rfl⟩, }, { apply ωSup_le_ωSup_of_le _, intros i, existsi i.succ, refl', } end end part namespace part /-- `to_unit` as a monotone function -/ @[simps] def to_unit_mono (f : part α →o part α) : (unit → part α) →o (unit → part α) := { to_fun := λ x u, f (x u), monotone' := λ x y (h : x ≤ y) u, f.monotone $ h u } lemma to_unit_cont (f : part α →o part α) (hc : continuous f) : continuous (to_unit_mono f) | c := begin ext ⟨⟩ : 1, dsimp [omega_complete_partial_order.ωSup], erw [hc, chain.map_comp], refl end instance : lawful_fix (part α) := ⟨λ f hc, show part.fix (to_unit_mono f) () = _, by rw part.fix_eq (to_unit_cont f hc); refl⟩ end part open sigma namespace pi instance {β} : lawful_fix (α → part β) := ⟨λ f, part.fix_eq⟩ variables {γ : Π a : α, β a → Type*} section monotone variables (α β γ) /-- `sigma.curry` as a monotone function. -/ @[simps] def monotone_curry [∀ x y, preorder $ γ x y] : (Π x : Σ a, β a, γ x.1 x.2) →o (Π a (b : β a), γ a b) := { to_fun := curry, monotone' := λ x y h a b, h ⟨a,b⟩ } /-- `sigma.uncurry` as a monotone function. -/ @[simps] def monotone_uncurry [∀ x y, preorder $ γ x y] : (Π a (b : β a), γ a b) →o (Π x : Σ a, β a, γ x.1 x.2) := { to_fun := uncurry, monotone' := λ x y h a, h a.1 a.2 } variables [∀ x y, omega_complete_partial_order $ γ x y] open omega_complete_partial_order.chain lemma continuous_curry : continuous $ monotone_curry α β γ := λ c, by { ext x y, dsimp [curry,ωSup], rw [map_comp,map_comp], refl } lemma continuous_uncurry : continuous $ monotone_uncurry α β γ := λ c, by { ext x y, dsimp [uncurry,ωSup], rw [map_comp,map_comp], refl } end monotone open has_fix instance [has_fix $ Π x : sigma β, γ x.1 x.2] : has_fix (Π x (y : β x), γ x y) := ⟨ λ f, curry (fix $ uncurry ∘ f ∘ curry) ⟩ variables [∀ x y, omega_complete_partial_order $ γ x y] section curry variables {f : (Π x (y : β x), γ x y) →o (Π x (y : β x), γ x y)} variables (hc : continuous f) lemma uncurry_curry_continuous : continuous $ (monotone_uncurry α β γ).comp $ f.comp $ monotone_curry α β γ := continuous_comp _ _ (continuous_comp _ _ (continuous_curry _ _ _) hc) (continuous_uncurry _ _ _) end curry instance pi.lawful_fix' [lawful_fix $ Π x : sigma β, γ x.1 x.2] : lawful_fix (Π x y, γ x y) := { fix_eq := λ f hc, begin dsimp [fix], conv { to_lhs, erw [lawful_fix.fix_eq (uncurry_curry_continuous hc)] }, refl, end, } end pi
d0456aee0395a3481387850f3aa17c9c9052e5f3
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/init/default.hlean
f083de41e7594ff8fe8f2805b375a65b1177f492
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
973
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jakob von Raumer, Floris van Doorn -/ prelude import init.datatypes init.reserved_notation init.tactic init.logic import init.bool init.num init.relation init.wf import init.types init.connectives import init.trunc init.path init.equiv init.util import init.ua init.funext import init.hedberg init.nat init.hit init.pathover namespace core export bool unit export empty (hiding elim) export sum (hiding elim) export sigma (hiding pr1 pr2) export [notation] prod export [notation] nat export eq (idp idpath concat inverse transport ap ap10 cast tr_inv homotopy ap11 apd refl) export [declaration] function export equiv (to_inv to_right_inv to_left_inv) export is_equiv (inv right_inv left_inv adjointify) export [abbreviation] [declaration] is_trunc (trunctype hprop.mk hset.mk) end core
cfb37a732f164c274b634fb3adad9bf45e652276
3f7026ea8bef0825ca0339a275c03b911baef64d
/test/examples.lean
5861909dc73d8d531dfe683f70c9556c6b5ff150
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
4,801
lean
import tactic data.stream.basic data.set.basic data.finset data.multiset category.traversable.derive open tactic universe u variable {α : Type} example (s t u : set ℕ) (h : s ⊆ t ∩ u) (h' : u ⊆ s) : u ⊆ s → true := begin dunfold has_subset.subset has_inter.inter at *, -- trace_state, intro1, triv end example (s t u : set ℕ) (h : s ⊆ t ∩ u) (h' : u ⊆ s) : u ⊆ s → true := begin delta has_subset.subset has_inter.inter at *, -- trace_state, intro1, triv end example (x y z : ℕ) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 := begin simp at *, -- trace_state, rw [←h, ←h'] end example (x y z : ℕ) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 := begin simp at *, simp [h] at h', simp [*] end def my_id (x : α) := x def my_id_def (x : α) : my_id x = x := rfl example (x y z : ℕ) (h'' : true) (h : 0 + my_id y = x) (h' : 0 + y = z) : x = z + 0 := begin simp [my_id_def] at *, simp [h] at h', simp [*] end @[simp] theorem mem_set_of {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl -- TODO: write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := begin dsimp [subset_def, union_def] at *, intros x h, cases h; back_chaining_using_hs end theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := begin dsimp [subset_def, inter_def] at *, intros x h, split; back_chaining_using_hs end /- extensionality -/ example : true := begin have : ∀ (s₀ s₁ : set ℤ), s₀ = s₁, { intros, ext1, guard_target x ∈ s₀ ↔ x ∈ s₁, admit }, have : ∀ (s₀ s₁ : finset ℕ), s₀ = s₁, { intros, ext1, guard_target a ∈ s₀ ↔ a ∈ s₁, admit }, have : ∀ (s₀ s₁ : multiset ℕ), s₀ = s₁, { intros, ext1, guard_target multiset.count a s₀ = multiset.count a s₁, admit }, have : ∀ (s₀ s₁ : list ℕ), s₀ = s₁, { intros, ext1, guard_target list.nth s₀ n = list.nth s₁ n, admit }, have : ∀ (s₀ s₁ : stream ℕ), s₀ = s₁, { intros, ext1, guard_target stream.nth n s₀ = stream.nth n s₁, admit }, have : ∀ n (s₀ s₁ : array n ℕ), s₀ = s₁, { intros, ext1, guard_target array.read s₀ i = array.read s₁ i, admit }, trivial end /- choice -/ example (h : ∀n m : ℕ, ∃i j, m = n + i ∨ m + j = n) : true := begin choose i j h using h, guard_hyp i := ℕ → ℕ → ℕ, guard_hyp j := ℕ → ℕ → ℕ, guard_hyp h := ∀ (n m : ℕ), m = n + i n m ∨ m + j n m = n, trivial end example (h : ∀n m : ℕ, ∃i, ∀n:ℕ, ∃j, m = n + i ∨ m + j = n) : true := begin choose i j h using h, guard_hyp i := ℕ → ℕ → ℕ, guard_hyp j := ℕ → ℕ → ℕ → ℕ, guard_hyp h := ∀ (n m k : ℕ), m = k + i n m ∨ m + j n m k = k, trivial end -- Test `simp only [exists_prop]` gets applied after choosing. -- Because of this simp, we need a non-rfl goal example (h : ∀ n, ∃ k ≥ 0, n = k) : ∀ x : ℕ, 1 = 1 := begin choose u hu using h, guard_hyp hu := ∀ n, u n ≥ 0 ∧ n = u n, intro, refl end /- refine_struct -/ section refine_struct variables {α} [_inst : monoid α] include _inst example : true := begin have : group α, { refine_struct { .._inst }, guard_tags _field inv group, admit, guard_tags _field mul_left_inv group, admit, }, trivial end end refine_struct /- traversable -/ open tactic.interactive run_cmd do lawful_traversable_derive_handler' `test ``(is_lawful_traversable) ``list -- the above creates local instances of `traversable` and `is_lawful_traversable` -- for `list` -- do not put in instances because they are not universe polymorphic @[derive [traversable, is_lawful_traversable]] structure my_struct (α : Type) := (y : ℤ) @[derive [traversable, is_lawful_traversable]] inductive either (α : Type u) | left : α → ℤ → either | right : α → either @[derive [traversable, is_lawful_traversable]] structure my_struct2 (α : Type u) : Type u := (x : α) (y : ℤ) (η : list α) (k : list (list α)) @[derive [traversable, is_lawful_traversable]] inductive rec_data3 (α : Type u) : Type u | nil : rec_data3 | cons : ℕ → α → rec_data3 → rec_data3 → rec_data3 @[derive traversable] meta structure meta_struct (α : Type u) : Type u := (x : α) (y : ℤ) (z : list α) (k : list (list α)) (w : expr)
e37548cbaeb3fa88fcbe219fd045920e2ee9303b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/geometry/manifold/algebra/structures.lean
6cf64d15133c59813513d369442ed56fcf678012
[ "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,754
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import geometry.manifold.algebra.lie_group /-! # Smooth structures In this file we define smooth structures that build on Lie groups. We prefer using the term smooth instead of Lie mainly because Lie ring has currently another use in mathematics. -/ open_locale manifold section smooth_ring variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] set_option old_structure_cmd true set_option default_priority 100 -- see Note [default priority] /-- A smooth semiring is a semiring where addition and multiplication are smooth. -/ -- See note [Design choices about smooth algebraic structures] class smooth_semiring (I : model_with_corners 𝕜 E H) (R : Type*) [semiring R] [topological_space R] [charted_space H R] extends has_smooth_add I R, has_smooth_mul I R : Prop /-- A smooth ring is a ring where the ring operations are smooth. -/ -- See note [Design choices about smooth algebraic structures] class smooth_ring (I : model_with_corners 𝕜 E H) (R : Type*) [ring R] [topological_space R] [charted_space H R] extends lie_add_group I R, has_smooth_mul I R : Prop instance smooth_ring.to_smooth_semiring {I : model_with_corners 𝕜 E H} {R : Type*} [ring R] [topological_space R] [charted_space H R] [t : smooth_ring I R] : smooth_semiring I R := { ..t } end smooth_ring instance field_smooth_ring {𝕜 : Type*} [nondiscrete_normed_field 𝕜] : smooth_ring 𝓘(𝕜) 𝕜 := { smooth_mul := begin rw smooth_iff, refine ⟨continuous_mul, λ x y, _⟩, simp only [prod.mk.eta] with mfld_simps, rw times_cont_diff_on_univ, exact times_cont_diff_mul, end, ..normed_space_lie_add_group } variables {𝕜 R E H : Type*} [topological_space R] [topological_space H] [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [charted_space H R] (I : model_with_corners 𝕜 E H) /-- A smooth semiring is a topological semiring. This is not an instance for technical reasons, see note [Design choices about smooth algebraic structures]. -/ lemma topological_semiring_of_smooth [semiring R] [smooth_semiring I R] : topological_semiring R := { .. has_continuous_mul_of_smooth I, .. has_continuous_add_of_smooth I } /-- A smooth ring is a topological ring. This is not an instance for technical reasons, see note [Design choices about smooth algebraic structures]. -/ lemma topological_ring_of_smooth [ring R] [smooth_ring I R] : topological_ring R := { .. has_continuous_mul_of_smooth I, .. topological_add_group_of_lie_add_group I }
043ada1cd4bf2ee97d3d11ed64441324fa738581
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/subobject/mono_over.lean
8e33233d2b6e53735f325c6ce6e19d274347c7bb
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
13,488
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Scott Morrison -/ import category_theory.currying import category_theory.limits.over import category_theory.limits.shapes.images import category_theory.adjunction.reflective /-! # Monomorphisms over a fixed object As preparation for defining `subobject X`, we set up the theory for `mono_over X := {f : over X // mono f.hom}`. Here `mono_over X` is a thin category (a pair of objects has at most one morphism between them), so we can think of it as a preorder. However as it is not skeletal, it is not yet a partial order. `subobject X` will be defined as the skeletalization of `mono_over X`. We provide * `def pullback [has_pullbacks C] (f : X ⟶ Y) : mono_over Y ⥤ mono_over X` * `def map (f : X ⟶ Y) [mono f] : mono_over X ⥤ mono_over Y` * `def «exists» [has_images C] (f : X ⟶ Y) : mono_over X ⥤ mono_over Y` and prove their basic properties and relationships. ## Notes This development originally appeared in Bhavik Mehta's "Topos theory for Lean" repository, and was ported to mathlib by Scott Morrison. -/ universes v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory open category_theory category_theory.category category_theory.limits variables {C : Type u₁} [category.{v₁} C] {X Y Z : C} variables {D : Type u₂} [category.{v₂} D] /-- The category of monomorphisms into `X` as a full subcategory of the over category. This isn't skeletal, so it's not a partial order. Later we define `subobject X` as the quotient of this by isomorphisms. -/ @[derive [category]] def mono_over (X : C) := {f : over X // mono f.hom} namespace mono_over /-- Construct a `mono_over X`. -/ @[simps] def mk' {X A : C} (f : A ⟶ X) [hf : mono f] : mono_over X := { val := over.mk f, property := hf } /-- The inclusion from monomorphisms over X to morphisms over X. -/ def forget (X : C) : mono_over X ⥤ over X := full_subcategory_inclusion _ instance : has_coe (mono_over X) C := { coe := λ Y, Y.val.left, } @[simp] lemma forget_obj_left {f} : ((forget X).obj f).left = (f : C) := rfl @[simp] lemma mk'_coe' {X A : C} (f : A ⟶ X) [hf : mono f] : (mk' f : C) = A := rfl /-- Convenience notation for the underlying arrow of a monomorphism over X. -/ abbreviation arrow (f : mono_over X) : (f : C) ⟶ X := ((forget X).obj f).hom @[simp] lemma mk'_arrow {X A : C} (f : A ⟶ X) [hf : mono f] : (mk' f).arrow = f := rfl @[simp] lemma forget_obj_hom {f} : ((forget X).obj f).hom = f.arrow := rfl instance : full (forget X) := full_subcategory.full _ instance : faithful (forget X) := full_subcategory.faithful _ instance mono (f : mono_over X) : mono f.arrow := f.property /-- The category of monomorphisms over X is a thin category, which makes defining its skeleton easy. -/ instance is_thin {X : C} (f g : mono_over X) : subsingleton (f ⟶ g) := ⟨begin intros h₁ h₂, ext1, erw [← cancel_mono g.arrow, over.w h₁, over.w h₂], end⟩ @[reassoc] lemma w {f g : mono_over X} (k : f ⟶ g) : k.left ≫ g.arrow = f.arrow := over.w _ /-- Convenience constructor for a morphism in monomorphisms over `X`. -/ abbreviation hom_mk {f g : mono_over X} (h : f.val.left ⟶ g.val.left) (w : h ≫ g.arrow = f.arrow) : f ⟶ g := over.hom_mk h w /-- Convenience constructor for an isomorphism in monomorphisms over `X`. -/ @[simps] def iso_mk {f g : mono_over X} (h : f.val.left ≅ g.val.left) (w : h.hom ≫ g.arrow = f.arrow) : f ≅ g := { hom := hom_mk h.hom w, inv := hom_mk h.inv (by rw [h.inv_comp_eq, w]) } /-- If `f : mono_over X`, then `mk' f.arrow` is of course just `f`, but not definitionally, so we package it as an isomorphism. -/ @[simp] def mk'_arrow_iso {X : C} (f : mono_over X) : (mk' f.arrow) ≅ f := iso_mk (iso.refl _) (by simp) /-- Lift a functor between over categories to a functor between `mono_over` categories, given suitable evidence that morphisms are taken to monomorphisms. -/ @[simps] def lift {Y : D} (F : over Y ⥤ over X) (h : ∀ (f : mono_over Y), mono (F.obj ((mono_over.forget Y).obj f)).hom) : mono_over Y ⥤ mono_over X := { obj := λ f, ⟨_, h f⟩, map := λ _ _ k, (mono_over.forget X).preimage ((mono_over.forget Y ⋙ F).map k), } /-- Isomorphic functors `over Y ⥤ over X` lift to isomorphic functors `mono_over Y ⥤ mono_over X`. -/ def lift_iso {Y : D} {F₁ F₂ : over Y ⥤ over X} (h₁ h₂) (i : F₁ ≅ F₂) : lift F₁ h₁ ≅ lift F₂ h₂ := fully_faithful_cancel_right (mono_over.forget X) (iso_whisker_left (mono_over.forget Y) i) /-- `mono_over.lift` commutes with composition of functors. -/ def lift_comp {X Z : C} {Y : D} (F : over X ⥤ over Y) (G : over Y ⥤ over Z) (h₁ h₂) : lift F h₁ ⋙ lift G h₂ ≅ lift (F ⋙ G) (λ f, h₂ ⟨_, h₁ f⟩) := fully_faithful_cancel_right (mono_over.forget _) (iso.refl _) /-- `mono_over.lift` preserves the identity functor. -/ def lift_id : lift (𝟭 (over X)) (λ f, f.2) ≅ 𝟭 _ := fully_faithful_cancel_right (mono_over.forget _) (iso.refl _) @[simp] lemma lift_comm (F : over Y ⥤ over X) (h : ∀ (f : mono_over Y), mono (F.obj ((mono_over.forget Y).obj f)).hom) : lift F h ⋙ mono_over.forget X = mono_over.forget Y ⋙ F := rfl @[simp] lemma lift_obj_arrow {Y : D} (F : over Y ⥤ over X) (h : ∀ (f : mono_over Y), mono (F.obj ((mono_over.forget Y).obj f)).hom) (f : mono_over Y) : ((lift F h).obj f).arrow = (F.obj ((forget Y).obj f)).hom := rfl /-- Monomorphisms over an object `f : over A` in an over category are equivalent to monomorphisms over the source of `f`. -/ def slice {A : C} {f : over A} (h₁ h₂) : mono_over f ≌ mono_over f.left := { functor := mono_over.lift f.iterated_slice_equiv.functor h₁, inverse := mono_over.lift f.iterated_slice_equiv.inverse h₂, unit_iso := mono_over.lift_id.symm ≪≫ mono_over.lift_iso _ _ f.iterated_slice_equiv.unit_iso ≪≫ (mono_over.lift_comp _ _ _ _).symm, counit_iso := mono_over.lift_comp _ _ _ _ ≪≫ mono_over.lift_iso _ _ f.iterated_slice_equiv.counit_iso ≪≫ mono_over.lift_id } section pullback variables [has_pullbacks C] /-- When `C` has pullbacks, a morphism `f : X ⟶ Y` induces a functor `mono_over Y ⥤ mono_over X`, by pulling back a monomorphism along `f`. -/ def pullback (f : X ⟶ Y) : mono_over Y ⥤ mono_over X := mono_over.lift (over.pullback f) begin intro g, apply @pullback.snd_of_mono _ _ _ _ _ _ _ _ _, change mono g.arrow, apply_instance, end /-- pullback commutes with composition (up to a natural isomorphism) -/ def pullback_comp (f : X ⟶ Y) (g : Y ⟶ Z) : pullback (f ≫ g) ≅ pullback g ⋙ pullback f := lift_iso _ _ (over.pullback_comp _ _) ≪≫ (lift_comp _ _ _ _).symm /-- pullback preserves the identity (up to a natural isomorphism) -/ def pullback_id : pullback (𝟙 X) ≅ 𝟭 _ := lift_iso _ _ over.pullback_id ≪≫ lift_id @[simp] lemma pullback_obj_left (f : X ⟶ Y) (g : mono_over Y) : (((pullback f).obj g) : C) = limits.pullback g.arrow f := rfl @[simp] lemma pullback_obj_arrow (f : X ⟶ Y) (g : mono_over Y) : ((pullback f).obj g).arrow = pullback.snd := rfl end pullback section map attribute [instance] mono_comp /-- We can map monomorphisms over `X` to monomorphisms over `Y` by post-composition with a monomorphism `f : X ⟶ Y`. -/ def map (f : X ⟶ Y) [mono f] : mono_over X ⥤ mono_over Y := lift (over.map f) (λ g, by apply mono_comp g.arrow f) /-- `mono_over.map` commutes with composition (up to a natural isomorphism). -/ def map_comp (f : X ⟶ Y) (g : Y ⟶ Z) [mono f] [mono g] : map (f ≫ g) ≅ map f ⋙ map g := lift_iso _ _ (over.map_comp _ _) ≪≫ (lift_comp _ _ _ _).symm /-- `mono_over.map` preserves the identity (up to a natural isomorphism). -/ def map_id : map (𝟙 X) ≅ 𝟭 _ := lift_iso _ _ over.map_id ≪≫ lift_id @[simp] lemma map_obj_left (f : X ⟶ Y) [mono f] (g : mono_over X) : (((map f).obj g) : C) = g.val.left := rfl @[simp] lemma map_obj_arrow (f : X ⟶ Y) [mono f] (g : mono_over X) : ((map f).obj g).arrow = g.arrow ≫ f := rfl instance full_map (f : X ⟶ Y) [mono f] : full (map f) := { preimage := λ g h e, begin refine hom_mk e.left _, rw [← cancel_mono f, assoc], apply w e, end } instance faithful_map (f : X ⟶ Y) [mono f] : faithful (map f) := {}. /-- Isomorphic objects have equivalent `mono_over` categories. -/ @[simps] def map_iso {A B : C} (e : A ≅ B) : mono_over A ≌ mono_over B := { functor := map e.hom, inverse := map e.inv, unit_iso := ((map_comp _ _).symm ≪≫ eq_to_iso (by simp) ≪≫ map_id).symm, counit_iso := ((map_comp _ _).symm ≪≫ eq_to_iso (by simp) ≪≫ map_id) } section variables (X) /-- An equivalence of categories `e` between `C` and `D` induces an equivalence between `mono_over X` and `mono_over (e.functor.obj X)` whenever `X` is an object of `C`. -/ @[simps] def congr (e : C ≌ D) : mono_over X ≌ mono_over (e.functor.obj X) := { functor := lift (over.post e.functor) $ λ f, by { dsimp, apply_instance }, inverse := (lift (over.post e.inverse) $ λ f, by { dsimp, apply_instance }) ⋙ (map_iso (e.unit_iso.symm.app X)).functor, unit_iso := nat_iso.of_components (λ Y, iso_mk (e.unit_iso.app Y) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ Y, iso_mk (e.counit_iso.app Y) (by tidy)) (by tidy) } end section variable [has_pullbacks C] /-- `map f` is left adjoint to `pullback f` when `f` is a monomorphism -/ def map_pullback_adj (f : X ⟶ Y) [mono f] : map f ⊣ pullback f := adjunction.restrict_fully_faithful (forget X) (forget Y) (over.map_pullback_adj f) (iso.refl _) (iso.refl _) /-- `mono_over.map f` followed by `mono_over.pullback f` is the identity. -/ def pullback_map_self (f : X ⟶ Y) [mono f] : map f ⋙ pullback f ≅ 𝟭 _ := (as_iso (mono_over.map_pullback_adj f).unit).symm end end map section image variables (f : X ⟶ Y) [has_image f] /-- The `mono_over Y` for the image inclusion for a morphism `f : X ⟶ Y`. -/ def image_mono_over (f : X ⟶ Y) [has_image f] : mono_over Y := mono_over.mk' (image.ι f) @[simp] lemma image_mono_over_arrow (f : X ⟶ Y) [has_image f] : (image_mono_over f).arrow = image.ι f := rfl end image section image variables [has_images C] /-- Taking the image of a morphism gives a functor `over X ⥤ mono_over X`. -/ @[simps] def image : over X ⥤ mono_over X := { obj := λ f, image_mono_over f.hom, map := λ f g k, begin apply (forget X).preimage _, apply over.hom_mk _ _, refine image.lift {I := image _, m := image.ι g.hom, e := k.left ≫ factor_thru_image g.hom}, apply image.lift_fac, end } /-- `mono_over.image : over X ⥤ mono_over X` is left adjoint to `mono_over.forget : mono_over X ⥤ over X` -/ def image_forget_adj : image ⊣ forget X := adjunction.mk_of_hom_equiv { hom_equiv := λ f g, { to_fun := λ k, begin apply over.hom_mk (factor_thru_image f.hom ≫ k.left) _, change (factor_thru_image f.hom ≫ k.left) ≫ _ = f.hom, rw [assoc, over.w k], apply image.fac end, inv_fun := λ k, begin refine over.hom_mk _ _, refine image.lift {I := g.val.left, m := g.arrow, e := k.left, fac' := over.w k}, apply image.lift_fac, end, left_inv := λ k, subsingleton.elim _ _, right_inv := λ k, begin ext1, change factor_thru_image _ ≫ image.lift _ = _, rw [← cancel_mono g.arrow, assoc, image.lift_fac, image.fac f.hom], exact (over.w k).symm, end } } instance : is_right_adjoint (forget X) := { left := image, adj := image_forget_adj } instance reflective : reflective (forget X) := {}. /-- Forgetting that a monomorphism over `X` is a monomorphism, then taking its image, is the identity functor. -/ def forget_image : forget X ⋙ image ≅ 𝟭 (mono_over X) := as_iso (adjunction.counit image_forget_adj) end image section «exists» variables [has_images C] /-- In the case where `f` is not a monomorphism but `C` has images, we can still take the "forward map" under it, which agrees with `mono_over.map f`. -/ def «exists» (f : X ⟶ Y) : mono_over X ⥤ mono_over Y := forget _ ⋙ over.map f ⋙ image instance faithful_exists (f : X ⟶ Y) : faithful («exists» f) := {}. /-- When `f : X ⟶ Y` is a monomorphism, `exists f` agrees with `map f`. -/ def exists_iso_map (f : X ⟶ Y) [mono f] : «exists» f ≅ map f := nat_iso.of_components begin intro Z, suffices : (forget _).obj ((«exists» f).obj Z) ≅ (forget _).obj ((map f).obj Z), apply preimage_iso this, apply over.iso_mk _ _, apply image_mono_iso_source (Z.arrow ≫ f), apply image_mono_iso_source_hom_self, end begin intros Z₁ Z₂ g, ext1, change image.lift ⟨_, _, _, _⟩ ≫ (image_mono_iso_source (Z₂.arrow ≫ f)).hom = (image_mono_iso_source (Z₁.arrow ≫ f)).hom ≫ g.left, rw [← cancel_mono (Z₂.arrow ≫ f), assoc, assoc, w_assoc g, image_mono_iso_source_hom_self, image_mono_iso_source_hom_self], apply image.lift_fac, end /-- `exists` is adjoint to `pullback` when images exist -/ def exists_pullback_adj (f : X ⟶ Y) [has_pullbacks C] : «exists» f ⊣ pullback f := adjunction.restrict_fully_faithful (forget X) (𝟭 _) ((over.map_pullback_adj f).comp _ _ image_forget_adj) (iso.refl _) (iso.refl _) end «exists» end mono_over end category_theory
ff9c8424866cc3da6a2c6c97b0d1384fab9853bd
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/locally_convex/with_seminorms.lean
6afbaf2ddc9d28c46775e2fd6a3af0596abad34d
[ "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
20,571
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll, Anatole Dedecker -/ import analysis.seminorm import analysis.locally_convex.bounded /-! # Topology induced by a family of seminorms ## Main definitions * `seminorm_family.basis_sets`: The set of open seminorm balls for a family of seminorms. * `seminorm_family.module_filter_basis`: A module filter basis formed by the open balls. * `seminorm.is_bounded`: A linear map `f : E →ₗ[𝕜] F` is bounded iff every seminorm in `F` can be bounded by a finite number of seminorms in `E`. ## Main statements * `continuous_from_bounded`: A bounded linear map `f : E →ₗ[𝕜] F` is continuous. * `seminorm_family.to_locally_convex_space`: A space equipped with a family of seminorms is locally convex. ## TODO Show that for any locally convex space there exist seminorms that induce the topology. ## Tags seminorm, locally convex -/ open normed_field set seminorm topological_space open_locale big_operators nnreal pointwise topological_space variables {𝕜 E F G ι ι' : Type*} section filter_basis variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] variables (𝕜 E ι) /-- An abbreviation for indexed families of seminorms. This is mainly to allow for dot-notation. -/ abbreviation seminorm_family := ι → seminorm 𝕜 E variables {𝕜 E ι} namespace seminorm_family /-- The sets of a filter basis for the neighborhood filter of 0. -/ def basis_sets (p : seminorm_family 𝕜 E ι) : set (set E) := ⋃ (s : finset ι) r (hr : 0 < r), singleton $ ball (s.sup p) (0 : E) r variables (p : seminorm_family 𝕜 E ι) lemma basis_sets_iff {U : set E} : U ∈ p.basis_sets ↔ ∃ (i : finset ι) r (hr : 0 < r), U = ball (i.sup p) 0 r := by simp only [basis_sets, mem_Union, mem_singleton_iff] lemma basis_sets_mem (i : finset ι) {r : ℝ} (hr : 0 < r) : (i.sup p).ball 0 r ∈ p.basis_sets := (basis_sets_iff _).mpr ⟨i,_,hr,rfl⟩ lemma basis_sets_singleton_mem (i : ι) {r : ℝ} (hr : 0 < r) : (p i).ball 0 r ∈ p.basis_sets := (basis_sets_iff _).mpr ⟨{i},_,hr, by rw finset.sup_singleton⟩ lemma basis_sets_nonempty [nonempty ι] : p.basis_sets.nonempty := begin let i := classical.arbitrary ι, refine set.nonempty_def.mpr ⟨(p i).ball 0 1, _⟩, exact p.basis_sets_singleton_mem i zero_lt_one, end lemma basis_sets_intersect (U V : set E) (hU : U ∈ p.basis_sets) (hV : V ∈ p.basis_sets) : ∃ (z : set E) (H : z ∈ p.basis_sets), z ⊆ U ∩ V := begin classical, rcases p.basis_sets_iff.mp hU with ⟨s, r₁, hr₁, hU⟩, rcases p.basis_sets_iff.mp hV with ⟨t, r₂, hr₂, hV⟩, use ((s ∪ t).sup p).ball 0 (min r₁ r₂), refine ⟨p.basis_sets_mem (s ∪ t) (lt_min_iff.mpr ⟨hr₁, hr₂⟩), _⟩, rw [hU, hV, ball_finset_sup_eq_Inter _ _ _ (lt_min_iff.mpr ⟨hr₁, hr₂⟩), ball_finset_sup_eq_Inter _ _ _ hr₁, ball_finset_sup_eq_Inter _ _ _ hr₂], exact set.subset_inter (set.Inter₂_mono' $ λ i hi, ⟨i, finset.subset_union_left _ _ hi, ball_mono $ min_le_left _ _⟩) (set.Inter₂_mono' $ λ i hi, ⟨i, finset.subset_union_right _ _ hi, ball_mono $ min_le_right _ _⟩), end lemma basis_sets_zero (U) (hU : U ∈ p.basis_sets) : (0 : E) ∈ U := begin rcases p.basis_sets_iff.mp hU with ⟨ι', r, hr, hU⟩, rw [hU, mem_ball_zero, map_zero], exact hr, end lemma basis_sets_add (U) (hU : U ∈ p.basis_sets) : ∃ (V : set E) (H : V ∈ p.basis_sets), V + V ⊆ U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, use (s.sup p).ball 0 (r/2), refine ⟨p.basis_sets_mem s (div_pos hr zero_lt_two), _⟩, refine set.subset.trans (ball_add_ball_subset (s.sup p) (r/2) (r/2) 0 0) _, rw [hU, add_zero, add_halves'], end lemma basis_sets_neg (U) (hU' : U ∈ p.basis_sets) : ∃ (V : set E) (H : V ∈ p.basis_sets), V ⊆ (λ (x : E), -x) ⁻¹' U := begin rcases p.basis_sets_iff.mp hU' with ⟨s, r, hr, hU⟩, rw [hU, neg_preimage, neg_ball (s.sup p), neg_zero], exact ⟨U, hU', eq.subset hU⟩, end /-- The `add_group_filter_basis` induced by the filter basis `seminorm_basis_zero`. -/ protected def add_group_filter_basis [nonempty ι] : add_group_filter_basis E := add_group_filter_basis_of_comm p.basis_sets p.basis_sets_nonempty p.basis_sets_intersect p.basis_sets_zero p.basis_sets_add p.basis_sets_neg lemma basis_sets_smul_right (v : E) (U : set E) (hU : U ∈ p.basis_sets) : ∀ᶠ (x : 𝕜) in 𝓝 0, x • v ∈ U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, rw [hU, filter.eventually_iff], simp_rw [(s.sup p).mem_ball_zero, map_smul_eq_mul], by_cases h : 0 < (s.sup p) v, { simp_rw (lt_div_iff h).symm, rw ←_root_.ball_zero_eq, exact metric.ball_mem_nhds 0 (div_pos hr h) }, simp_rw [le_antisymm (not_lt.mp h) (map_nonneg _ v), mul_zero, hr], exact is_open.mem_nhds is_open_univ (mem_univ 0), end variables [nonempty ι] lemma basis_sets_smul (U) (hU : U ∈ p.basis_sets) : ∃ (V : set 𝕜) (H : V ∈ 𝓝 (0 : 𝕜)) (W : set E) (H : W ∈ p.add_group_filter_basis.sets), V • W ⊆ U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, refine ⟨metric.ball 0 r.sqrt, metric.ball_mem_nhds 0 (real.sqrt_pos.mpr hr), _⟩, refine ⟨(s.sup p).ball 0 r.sqrt, p.basis_sets_mem s (real.sqrt_pos.mpr hr), _⟩, refine set.subset.trans (ball_smul_ball (s.sup p) r.sqrt r.sqrt) _, rw [hU, real.mul_self_sqrt (le_of_lt hr)], end lemma basis_sets_smul_left (x : 𝕜) (U : set E) (hU : U ∈ p.basis_sets) : ∃ (V : set E) (H : V ∈ p.add_group_filter_basis.sets), V ⊆ (λ (y : E), x • y) ⁻¹' U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, rw hU, by_cases h : x ≠ 0, { rw [(s.sup p).smul_ball_preimage 0 r x h, smul_zero], use (s.sup p).ball 0 (r / ∥x∥), exact ⟨p.basis_sets_mem s (div_pos hr (norm_pos_iff.mpr h)), subset.rfl⟩ }, refine ⟨(s.sup p).ball 0 r, p.basis_sets_mem s hr, _⟩, simp only [not_ne_iff.mp h, subset_def, mem_ball_zero, hr, mem_univ, map_zero, implies_true_iff, preimage_const_of_mem, zero_smul], end /-- The `module_filter_basis` induced by the filter basis `seminorm_basis_zero`. -/ protected def module_filter_basis : module_filter_basis 𝕜 E := { to_add_group_filter_basis := p.add_group_filter_basis, smul' := p.basis_sets_smul, smul_left' := p.basis_sets_smul_left, smul_right' := p.basis_sets_smul_right } lemma filter_eq_infi (p : seminorm_family 𝕜 E ι) : p.module_filter_basis.to_filter_basis.filter = ⨅ i, (𝓝 0).comap (p i) := begin refine le_antisymm (le_infi $ λ i, _) _, { rw p.module_filter_basis.to_filter_basis.has_basis.le_basis_iff (metric.nhds_basis_ball.comap _), intros ε hε, refine ⟨(p i).ball 0 ε, _, _⟩, { rw ← (finset.sup_singleton : _ = p i), exact p.basis_sets_mem {i} hε, }, { rw [id, (p i).ball_zero_eq_preimage_ball] } }, { rw p.module_filter_basis.to_filter_basis.has_basis.ge_iff, rintros U (hU : U ∈ p.basis_sets), rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, rfl⟩, rw [id, seminorm.ball_finset_sup_eq_Inter _ _ _ hr, s.Inter_mem_sets], exact λ i hi, filter.mem_infi_of_mem i ⟨metric.ball 0 r, metric.ball_mem_nhds 0 hr, eq.subset ((p i).ball_zero_eq_preimage_ball).symm⟩, }, end end seminorm_family end filter_basis section bounded namespace seminorm variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F] -- Todo: This should be phrased entirely in terms of the von Neumann bornology. /-- The proposition that a linear map is bounded between spaces with families of seminorms. -/ def is_bounded (p : ι → seminorm 𝕜 E) (q : ι' → seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : Prop := ∀ i, ∃ s : finset ι, ∃ C : ℝ≥0, C ≠ 0 ∧ (q i).comp f ≤ C • s.sup p lemma is_bounded_const (ι' : Type*) [nonempty ι'] {p : ι → seminorm 𝕜 E} {q : seminorm 𝕜 F} (f : E →ₗ[𝕜] F) : is_bounded p (λ _ : ι', q) f ↔ ∃ (s : finset ι) C : ℝ≥0, C ≠ 0 ∧ q.comp f ≤ C • s.sup p := by simp only [is_bounded, forall_const] lemma const_is_bounded (ι : Type*) [nonempty ι] {p : seminorm 𝕜 E} {q : ι' → seminorm 𝕜 F} (f : E →ₗ[𝕜] F) : is_bounded (λ _ : ι, p) q f ↔ ∀ i, ∃ C : ℝ≥0, C ≠ 0 ∧ (q i).comp f ≤ C • p := begin split; intros h i, { rcases h i with ⟨s, C, hC, h⟩, exact ⟨C, hC, le_trans h (smul_le_smul (finset.sup_le (λ _ _, le_rfl)) le_rfl)⟩ }, use [{classical.arbitrary ι}], simp only [h, finset.sup_singleton], end lemma is_bounded_sup {p : ι → seminorm 𝕜 E} {q : ι' → seminorm 𝕜 F} {f : E →ₗ[𝕜] F} (hf : is_bounded p q f) (s' : finset ι') : ∃ (C : ℝ≥0) (s : finset ι), 0 < C ∧ (s'.sup q).comp f ≤ C • (s.sup p) := begin classical, obtain rfl | hs' := s'.eq_empty_or_nonempty, { exact ⟨1, ∅, zero_lt_one, by simp [seminorm.bot_eq_zero]⟩ }, choose fₛ fC hf using hf, use [s'.card • s'.sup fC, finset.bUnion s' fₛ], split, { refine nsmul_pos _ (ne_of_gt (finset.nonempty.card_pos hs')), cases finset.nonempty.bex hs' with j hj, exact lt_of_lt_of_le (zero_lt_iff.mpr (and.elim_left (hf j))) (finset.le_sup hj) }, have hs : ∀ i : ι', i ∈ s' → (q i).comp f ≤ s'.sup fC • ((finset.bUnion s' fₛ).sup p) := begin intros i hi, refine le_trans (and.elim_right (hf i)) (smul_le_smul _ (finset.le_sup hi)), exact finset.sup_mono (finset.subset_bUnion_of_mem fₛ hi), end, refine le_trans (comp_mono f (finset_sup_le_sum q s')) _, simp_rw [←pullback_apply, add_monoid_hom.map_sum, pullback_apply], refine le_trans (finset.sum_le_sum hs) _, rw [finset.sum_const, smul_assoc], exact le_rfl, end end seminorm end bounded section topology variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [nonempty ι] /-- The proposition that the topology of `E` is induced by a family of seminorms `p`. -/ structure with_seminorms (p : seminorm_family 𝕜 E ι) [t : topological_space E] : Prop := (topology_eq_with_seminorms : t = p.module_filter_basis.topology) lemma seminorm_family.with_seminorms_eq {p : seminorm_family 𝕜 E ι} [t : topological_space E] (hp : with_seminorms p) : t = p.module_filter_basis.topology := hp.1 variables [topological_space E] variables {p : seminorm_family 𝕜 E ι} lemma with_seminorms.has_basis (hp : with_seminorms p) : (𝓝 (0 : E)).has_basis (λ (s : set E), s ∈ p.basis_sets) id := begin rw (congr_fun (congr_arg (@nhds E) hp.1) 0), exact add_group_filter_basis.nhds_zero_has_basis _, end end topology section topological_add_group variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] variables [topological_space E] [topological_add_group E] variables [nonempty ι] lemma seminorm_family.with_seminorms_of_nhds (p : seminorm_family 𝕜 E ι) (h : 𝓝 (0 : E) = p.module_filter_basis.to_filter_basis.filter) : with_seminorms p := begin refine ⟨topological_add_group.ext (by apply_instance) (p.add_group_filter_basis.is_topological_add_group) _⟩, rw add_group_filter_basis.nhds_zero_eq, exact h, end lemma seminorm_family.with_seminorms_of_has_basis (p : seminorm_family 𝕜 E ι) (h : (𝓝 (0 : E)).has_basis (λ (s : set E), s ∈ p.basis_sets) id) : with_seminorms p := p.with_seminorms_of_nhds $ filter.has_basis.eq_of_same_basis h p.add_group_filter_basis.to_filter_basis.has_basis lemma seminorm_family.with_seminorms_iff_nhds_eq_infi (p : seminorm_family 𝕜 E ι) : with_seminorms p ↔ (𝓝 0 : filter E) = ⨅ i, (𝓝 0).comap (p i) := begin rw ← p.filter_eq_infi, refine ⟨λ h, _, p.with_seminorms_of_nhds⟩, rw h.topology_eq_with_seminorms, exact add_group_filter_basis.nhds_zero_eq _, end end topological_add_group section normed_space /-- The topology of a `normed_space 𝕜 E` is induced by the seminorm `norm_seminorm 𝕜 E`. -/ lemma norm_with_seminorms (𝕜 E) [normed_field 𝕜] [seminormed_add_comm_group E] [normed_space 𝕜 E] : with_seminorms (λ (_ : fin 1), norm_seminorm 𝕜 E) := begin let p : seminorm_family 𝕜 E (fin 1) := λ _, norm_seminorm 𝕜 E, refine ⟨topological_add_group.ext normed_top_group (p.add_group_filter_basis.is_topological_add_group) _⟩, refine filter.has_basis.eq_of_same_basis metric.nhds_basis_ball _, rw ←ball_norm_seminorm 𝕜 E, refine filter.has_basis.to_has_basis p.add_group_filter_basis.nhds_zero_has_basis _ (λ r hr, ⟨(norm_seminorm 𝕜 E).ball 0 r, p.basis_sets_singleton_mem 0 hr, rfl.subset⟩), rintros U (hU : U ∈ p.basis_sets), rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, use [r, hr], rw [hU, id.def], by_cases h : s.nonempty, { rw finset.sup_const h }, rw [finset.not_nonempty_iff_eq_empty.mp h, finset.sup_empty, ball_bot _ hr], exact set.subset_univ _, end end normed_space section nontrivially_normed_field variables [nontrivially_normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [nonempty ι] variables {p : seminorm_family 𝕜 E ι} variables [topological_space E] lemma with_seminorms.is_vonN_bounded_iff_finset_seminorm_bounded {s : set E} (hp : with_seminorms p) : bornology.is_vonN_bounded 𝕜 s ↔ ∀ I : finset ι, ∃ r (hr : 0 < r), ∀ (x ∈ s), I.sup p x < r := begin rw (hp.has_basis).is_vonN_bounded_basis_iff, split, { intros h I, simp only [id.def] at h, specialize h ((I.sup p).ball 0 1) (p.basis_sets_mem I zero_lt_one), rcases h with ⟨r, hr, h⟩, cases normed_field.exists_lt_norm 𝕜 r with a ha, specialize h a (le_of_lt ha), rw [seminorm.smul_ball_zero (lt_trans hr ha), mul_one] at h, refine ⟨∥a∥, lt_trans hr ha, _⟩, intros x hx, specialize h hx, exact (finset.sup I p).mem_ball_zero.mp h }, intros h s' hs', rcases p.basis_sets_iff.mp hs' with ⟨I, r, hr, hs'⟩, rw [id.def, hs'], rcases h I with ⟨r', hr', h'⟩, simp_rw ←(I.sup p).mem_ball_zero at h', refine absorbs.mono_right _ h', exact (finset.sup I p).ball_zero_absorbs_ball_zero hr, end lemma bornology.is_vonN_bounded_iff_seminorm_bounded {s : set E} (hp : with_seminorms p) : bornology.is_vonN_bounded 𝕜 s ↔ ∀ i : ι, ∃ r (hr : 0 < r), ∀ (x ∈ s), p i x < r := begin rw hp.is_vonN_bounded_iff_finset_seminorm_bounded, split, { intros hI i, convert hI {i}, rw [finset.sup_singleton] }, intros hi I, by_cases hI : I.nonempty, { choose r hr h using hi, have h' : 0 < I.sup' hI r := by { rcases hI.bex with ⟨i, hi⟩, exact lt_of_lt_of_le (hr i) (finset.le_sup' r hi) }, refine ⟨I.sup' hI r, h', λ x hx, finset_sup_apply_lt h' (λ i hi, _)⟩, refine lt_of_lt_of_le (h i x hx) _, simp only [finset.le_sup'_iff, exists_prop], exact ⟨i, hi, (eq.refl _).le⟩ }, simp only [finset.not_nonempty_iff_eq_empty.mp hI, finset.sup_empty, coe_bot, pi.zero_apply, exists_prop], exact ⟨1, zero_lt_one, λ _ _, zero_lt_one⟩, end end nontrivially_normed_field section continuous_bounded namespace seminorm variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F] variables [nonempty ι] [nonempty ι'] lemma continuous_from_bounded {p : seminorm_family 𝕜 E ι} {q : seminorm_family 𝕜 F ι'} [uniform_space E] [uniform_add_group E] (hp : with_seminorms p) [uniform_space F] [uniform_add_group F] (hq : with_seminorms q) (f : E →ₗ[𝕜] F) (hf : seminorm.is_bounded p q f) : continuous f := begin refine continuous_of_continuous_at_zero f _, rw [continuous_at_def, f.map_zero, hp.1], intros U hU, rw [hq.1, add_group_filter_basis.nhds_zero_eq, filter_basis.mem_filter_iff] at hU, rcases hU with ⟨V, hV : V ∈ q.basis_sets, hU⟩, rcases q.basis_sets_iff.mp hV with ⟨s₂, r, hr, hV⟩, rw hV at hU, rw [p.add_group_filter_basis.nhds_zero_eq, filter_basis.mem_filter_iff], rcases (seminorm.is_bounded_sup hf s₂) with ⟨C, s₁, hC, hf⟩, refine ⟨(s₁.sup p).ball 0 (r/C), p.basis_sets_mem _ (div_pos hr (nnreal.coe_pos.mpr hC)), _⟩, refine subset.trans _ (preimage_mono hU), simp_rw [←linear_map.map_zero f, ←ball_comp], refine subset.trans _ (ball_antitone hf), rw ball_smul (s₁.sup p) hC, end lemma cont_with_seminorms_normed_space (F) [seminormed_add_comm_group F] [normed_space 𝕜 F] [uniform_space E] [uniform_add_group E] {p : ι → seminorm 𝕜 E} (hp : with_seminorms p) (f : E →ₗ[𝕜] F) (hf : ∃ (s : finset ι) C : ℝ≥0, C ≠ 0 ∧ (norm_seminorm 𝕜 F).comp f ≤ C • s.sup p) : continuous f := begin rw ←seminorm.is_bounded_const (fin 1) at hf, exact continuous_from_bounded hp (norm_with_seminorms 𝕜 F) f hf, end lemma cont_normed_space_to_with_seminorms (E) [seminormed_add_comm_group E] [normed_space 𝕜 E] [uniform_space F] [uniform_add_group F] {q : ι → seminorm 𝕜 F} (hq : with_seminorms q) (f : E →ₗ[𝕜] F) (hf : ∀ i : ι, ∃ C : ℝ≥0, C ≠ 0 ∧ (q i).comp f ≤ C • (norm_seminorm 𝕜 E)) : continuous f := begin rw ←seminorm.const_is_bounded (fin 1) at hf, exact continuous_from_bounded (norm_with_seminorms 𝕜 E) hq f hf, end end seminorm end continuous_bounded section locally_convex_space open locally_convex_space variables [nonempty ι] [normed_field 𝕜] [normed_space ℝ 𝕜] [add_comm_group E] [module 𝕜 E] [module ℝ E] [is_scalar_tower ℝ 𝕜 E] [topological_space E] [topological_add_group E] lemma seminorm_family.to_locally_convex_space {p : seminorm_family 𝕜 E ι} (hp : with_seminorms p) : locally_convex_space ℝ E := begin apply of_basis_zero ℝ E id (λ s, s ∈ p.basis_sets), { rw [hp.1, add_group_filter_basis.nhds_eq _, add_group_filter_basis.N_zero], exact filter_basis.has_basis _ }, { intros s hs, change s ∈ set.Union _ at hs, simp_rw [set.mem_Union, set.mem_singleton_iff] at hs, rcases hs with ⟨I, r, hr, rfl⟩, exact convex_ball _ _ _ } end end locally_convex_space section normed_space variables (𝕜) [normed_field 𝕜] [normed_space ℝ 𝕜] [seminormed_add_comm_group E] /-- Not an instance since `𝕜` can't be inferred. See `normed_space.to_locally_convex_space` for a slightly weaker instance version. -/ lemma normed_space.to_locally_convex_space' [normed_space 𝕜 E] [module ℝ E] [is_scalar_tower ℝ 𝕜 E] : locally_convex_space ℝ E := seminorm_family.to_locally_convex_space (norm_with_seminorms 𝕜 E) /-- See `normed_space.to_locally_convex_space'` for a slightly stronger version which is not an instance. -/ instance normed_space.to_locally_convex_space [normed_space ℝ E] : locally_convex_space ℝ E := normed_space.to_locally_convex_space' ℝ end normed_space section topological_constructions variables [normed_field 𝕜] [add_comm_group F] [module 𝕜 F] [add_comm_group E] [module 𝕜 E] /-- The family of seminorms obtained by composing each seminorm by a linear map. -/ def seminorm_family.comp (q : seminorm_family 𝕜 F ι) (f : E →ₗ[𝕜] F) : seminorm_family 𝕜 E ι := λ i, (q i).comp f lemma seminorm_family.comp_apply (q : seminorm_family 𝕜 F ι) (i : ι) (f : E →ₗ[𝕜] F) : q.comp f i = (q i).comp f := rfl lemma seminorm_family.finset_sup_comp (q : seminorm_family 𝕜 F ι) (s : finset ι) (f : E →ₗ[𝕜] F) : (s.sup q).comp f = s.sup (q.comp f) := begin ext x, rw [seminorm.comp_apply, seminorm.finset_sup_apply, seminorm.finset_sup_apply], refl end variables [topological_space F] [topological_add_group F] lemma linear_map.with_seminorms_induced [hι : nonempty ι] {q : seminorm_family 𝕜 F ι} (hq : with_seminorms q) (f : E →ₗ[𝕜] F) : @with_seminorms 𝕜 E ι _ _ _ _ (q.comp f) (induced f infer_instance) := begin letI : topological_space E := induced f infer_instance, letI : topological_add_group E := topological_add_group_induced f, rw [(q.comp f).with_seminorms_iff_nhds_eq_infi, nhds_induced, map_zero, q.with_seminorms_iff_nhds_eq_infi.mp hq, filter.comap_infi], refine infi_congr (λ i, _), exact filter.comap_comap end lemma inducing.with_seminorms [hι : nonempty ι] {q : seminorm_family 𝕜 F ι} (hq : with_seminorms q) [topological_space E] {f : E →ₗ[𝕜] F} (hf : inducing f) : with_seminorms (q.comp f) := begin rw hf.induced, exact f.with_seminorms_induced hq end end topological_constructions
e0dfef8c4b22112134efe173d1fdac9b4993e7eb
c777c32c8e484e195053731103c5e52af26a25d1
/src/field_theory/krull_topology.lean
0901d5e87b26ae24dcc14cc06abf6db55bec7379
[ "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
13,096
lean
/- Copyright (c) 2022 Sebastian Monnet. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Monnet -/ import field_theory.galois import topology.algebra.filter_basis import topology.algebra.open_subgroup import tactic.by_contra /-! # Krull topology We define the Krull topology on `L ≃ₐ[K] L` for an arbitrary field extension `L/K`. In order to do this, we first define a `group_filter_basis` on `L ≃ₐ[K] L`, whose sets are `E.fixing_subgroup` for all intermediate fields `E` with `E/K` finite dimensional. ## Main Definitions - `finite_exts K L`. Given a field extension `L/K`, this is the set of intermediate fields that are finite-dimensional over `K`. - `fixed_by_finite K L`. Given a field extension `L/K`, `fixed_by_finite K L` is the set of subsets `Gal(L/E)` of `Gal(L/K)`, where `E/K` is finite - `gal_basis K L`. Given a field extension `L/K`, this is the filter basis on `L ≃ₐ[K] L` whose sets are `Gal(L/E)` for intermediate fields `E` with `E/K` finite. - `gal_group_basis K L`. This is the same as `gal_basis K L`, but with the added structure that it is a group filter basis on `L ≃ₐ[K] L`, rather than just a filter basis. - `krull_topology K L`. Given a field extension `L/K`, this is the topology on `L ≃ₐ[K] L`, induced by the group filter basis `gal_group_basis K L`. ## Main Results - `krull_topology_t2 K L`. For an integral field extension `L/K`, the topology `krull_topology K L` is Hausdorff. - `krull_topology_totally_disconnected K L`. For an integral field extension `L/K`, the topology `krull_topology K L` is totally disconnected. ## Notations - In docstrings, we will write `Gal(L/E)` to denote the fixing subgroup of an intermediate field `E`. That is, `Gal(L/E)` is the subgroup of `L ≃ₐ[K] L` consisting of automorphisms that fix every element of `E`. In particular, we distinguish between `L ≃ₐ[E] L` and `Gal(L/E)`, since the former is defined to be a subgroup of `L ≃ₐ[K] L`, while the latter is a group in its own right. ## Implementation Notes - `krull_topology K L` is defined as an instance for type class inference. -/ open_locale classical /-- Mapping intermediate fields along algebra equivalences preserves the partial order -/ lemma intermediate_field.map_mono {K L M : Type*} [field K] [field L] [field M] [algebra K L] [algebra K M] {E1 E2 : intermediate_field K L} (e : L ≃ₐ[K] M) (h12 : E1 ≤ E2) : E1.map e.to_alg_hom ≤ E2.map e.to_alg_hom := set.image_subset e h12 /-- Mapping intermediate fields along the identity does not change them -/ lemma intermediate_field.map_id {K L : Type*} [field K] [field L] [algebra K L] (E : intermediate_field K L) : E.map (alg_hom.id K L) = E := set_like.coe_injective $ set.image_id _ /-- Mapping a finite dimensional intermediate field along an algebra equivalence gives a finite-dimensional intermediate field. -/ instance im_finite_dimensional {K L : Type*} [field K] [field L] [algebra K L] {E : intermediate_field K L} (σ : L ≃ₐ[K] L) [finite_dimensional K E]: finite_dimensional K (E.map σ.to_alg_hom) := linear_equiv.finite_dimensional (intermediate_field.intermediate_field_map σ E).to_linear_equiv /-- Given a field extension `L/K`, `finite_exts K L` is the set of intermediate field extensions `L/E/K` such that `E/K` is finite -/ def finite_exts (K : Type*) [field K] (L : Type*) [field L] [algebra K L] : set (intermediate_field K L) := {E | finite_dimensional K E} /-- Given a field extension `L/K`, `fixed_by_finite K L` is the set of subsets `Gal(L/E)` of `L ≃ₐ[K] L`, where `E/K` is finite -/ def fixed_by_finite (K L : Type*) [field K] [field L] [algebra K L]: set (subgroup (L ≃ₐ[K] L)) := intermediate_field.fixing_subgroup '' (finite_exts K L) /-- For an field extension `L/K`, the intermediate field `K` is finite-dimensional over `K` -/ lemma intermediate_field.finite_dimensional_bot (K L : Type*) [field K] [field L] [algebra K L] : finite_dimensional K (⊥ : intermediate_field K L) := finite_dimensional_of_rank_eq_one intermediate_field.rank_bot /-- This lemma says that `Gal(L/K) = L ≃ₐ[K] L` -/ lemma intermediate_field.fixing_subgroup.bot {K L : Type*} [field K] [field L] [algebra K L] : intermediate_field.fixing_subgroup (⊥ : intermediate_field K L) = ⊤ := begin ext f, refine ⟨λ _, subgroup.mem_top _, λ _, _⟩, rintro ⟨x, hx : x ∈ (⊥ : intermediate_field K L)⟩, rw intermediate_field.mem_bot at hx, rcases hx with ⟨y, rfl⟩, exact f.commutes y, end /-- If `L/K` is a field extension, then we have `Gal(L/K) ∈ fixed_by_finite K L` -/ lemma top_fixed_by_finite {K L : Type*} [field K] [field L] [algebra K L] : ⊤ ∈ fixed_by_finite K L := ⟨⊥, intermediate_field.finite_dimensional_bot K L, intermediate_field.fixing_subgroup.bot⟩ /-- If `E1` and `E2` are finite-dimensional intermediate fields, then so is their compositum. This rephrases a result already in mathlib so that it is compatible with our type classes -/ lemma finite_dimensional_sup {K L: Type*} [field K] [field L] [algebra K L] (E1 E2 : intermediate_field K L) (h1 : finite_dimensional K E1) (h2 : finite_dimensional K E2) : finite_dimensional K ↥(E1 ⊔ E2) := by exactI intermediate_field.finite_dimensional_sup E1 E2 /-- An element of `L ≃ₐ[K] L` is in `Gal(L/E)` if and only if it fixes every element of `E`-/ lemma intermediate_field.mem_fixing_subgroup_iff {K L : Type*} [field K] [field L] [algebra K L] (E : intermediate_field K L) (σ : (L ≃ₐ[K] L)) : σ ∈ E.fixing_subgroup ↔∀ (x : L), x ∈ E → σ x = x := ⟨λ hσ x hx, hσ ⟨x, hx⟩, λ h ⟨x, hx⟩, h x hx⟩ /-- The map `E ↦ Gal(L/E)` is inclusion-reversing -/ lemma intermediate_field.fixing_subgroup.antimono {K L : Type*} [field K] [field L] [algebra K L] {E1 E2 : intermediate_field K L} (h12 : E1 ≤ E2) : E2.fixing_subgroup ≤ E1.fixing_subgroup := begin rintro σ hσ ⟨x, hx⟩, exact hσ ⟨x, h12 hx⟩, end /-- Given a field extension `L/K`, `gal_basis K L` is the filter basis on `L ≃ₐ[K] L` whose sets are `Gal(L/E)` for intermediate fields `E` with `E/K` finite dimensional -/ def gal_basis (K L : Type*) [field K] [field L] [algebra K L] : filter_basis (L ≃ₐ[K] L) := { sets := subgroup.carrier '' (fixed_by_finite K L), nonempty := ⟨⊤, ⊤, top_fixed_by_finite, rfl⟩, inter_sets := begin rintros X Y ⟨H1, ⟨E1, h_E1, rfl⟩, rfl⟩ ⟨H2, ⟨E2, h_E2, rfl⟩, rfl⟩, use (intermediate_field.fixing_subgroup (E1 ⊔ E2)).carrier, refine ⟨⟨_, ⟨_, finite_dimensional_sup E1 E2 h_E1 h_E2, rfl⟩, rfl⟩, _⟩, rw set.subset_inter_iff, exact ⟨intermediate_field.fixing_subgroup.antimono le_sup_left, intermediate_field.fixing_subgroup.antimono le_sup_right⟩, end } /-- A subset of `L ≃ₐ[K] L` is a member of `gal_basis K L` if and only if it is the underlying set of `Gal(L/E)` for some finite subextension `E/K`-/ lemma mem_gal_basis_iff (K L : Type*) [field K] [field L] [algebra K L] (U : set (L ≃ₐ[K] L)) : U ∈ gal_basis K L ↔ U ∈ subgroup.carrier '' (fixed_by_finite K L) := iff.rfl /-- For a field extension `L/K`, `gal_group_basis K L` is the group filter basis on `L ≃ₐ[K] L` whose sets are `Gal(L/E)` for finite subextensions `E/K` -/ def gal_group_basis (K L : Type*) [field K] [field L] [algebra K L] : group_filter_basis (L ≃ₐ[K] L) := { to_filter_basis := gal_basis K L, one' := λ U ⟨H, hH, h2⟩, h2 ▸ H.one_mem, mul' := λ U hU, ⟨U, hU, begin rcases hU with ⟨H, hH, rfl⟩, rintros x ⟨a, b, haH, hbH, rfl⟩, exact H.mul_mem haH hbH, end⟩, inv' := λ U hU, ⟨U, hU, begin rcases hU with ⟨H, hH, rfl⟩, exact λ _, H.inv_mem', end⟩, conj' := begin rintros σ U ⟨H, ⟨E, hE, rfl⟩, rfl⟩, let F : intermediate_field K L := E.map (σ.symm.to_alg_hom), refine ⟨F.fixing_subgroup.carrier, ⟨⟨F.fixing_subgroup, ⟨F, _, rfl⟩, rfl⟩, λ g hg, _⟩⟩, { apply im_finite_dimensional σ.symm, exact hE }, change σ * g * σ⁻¹ ∈ E.fixing_subgroup, rw intermediate_field.mem_fixing_subgroup_iff, intros x hx, change σ (g (σ⁻¹ x)) = x, have h_in_F : σ⁻¹ x ∈ F := ⟨x, hx, by {dsimp, rw ← alg_equiv.inv_fun_eq_symm, refl }⟩, have h_g_fix : g (σ⁻¹ x) = σ⁻¹ x, { rw [subgroup.mem_carrier, intermediate_field.mem_fixing_subgroup_iff F g] at hg, exact hg (σ⁻¹ x) h_in_F }, rw h_g_fix, change σ (σ⁻¹ x) = x, exact alg_equiv.apply_symm_apply σ x, end } /-- For a field extension `L/K`, `krull_topology K L` is the topological space structure on `L ≃ₐ[K] L` induced by the group filter basis `gal_group_basis K L` -/ instance krull_topology (K L : Type*) [field K] [field L] [algebra K L] : topological_space (L ≃ₐ[K] L) := group_filter_basis.topology (gal_group_basis K L) /-- For a field extension `L/K`, the Krull topology on `L ≃ₐ[K] L` makes it a topological group. -/ instance (K L : Type*) [field K] [field L] [algebra K L] : topological_group (L ≃ₐ[K] L) := group_filter_basis.is_topological_group (gal_group_basis K L) section krull_t2 open_locale topology filter /-- Let `L/E/K` be a tower of fields with `E/K` finite. Then `Gal(L/E)` is an open subgroup of `L ≃ₐ[K] L`. -/ lemma intermediate_field.fixing_subgroup_is_open {K L : Type*} [field K] [field L] [algebra K L] (E : intermediate_field K L) [finite_dimensional K E] : is_open (E.fixing_subgroup : set (L ≃ₐ[K] L)) := begin have h_basis : E.fixing_subgroup.carrier ∈ (gal_group_basis K L) := ⟨E.fixing_subgroup, ⟨E, ‹_›, rfl⟩, rfl⟩, have h_nhd := group_filter_basis.mem_nhds_one (gal_group_basis K L) h_basis, exact subgroup.is_open_of_mem_nhds _ h_nhd end /-- Given a tower of fields `L/E/K`, with `E/K` finite, the subgroup `Gal(L/E) ≤ L ≃ₐ[K] L` is closed. -/ lemma intermediate_field.fixing_subgroup_is_closed {K L : Type*} [field K] [field L] [algebra K L] (E : intermediate_field K L) [finite_dimensional K E] : is_closed (E.fixing_subgroup : set (L ≃ₐ[K] L)) := open_subgroup.is_closed ⟨E.fixing_subgroup, E.fixing_subgroup_is_open⟩ /-- If `L/K` is an algebraic extension, then the Krull topology on `L ≃ₐ[K] L` is Hausdorff. -/ lemma krull_topology_t2 {K L : Type*} [field K] [field L] [algebra K L] (h_int : algebra.is_integral K L) : t2_space (L ≃ₐ[K] L) := { t2 := λ f g hfg, begin let φ := f⁻¹ * g, cases (fun_like.exists_ne hfg) with x hx, have hφx : φ x ≠ x, { apply ne_of_apply_ne f, change f (f.symm (g x)) ≠ f x, rw [alg_equiv.apply_symm_apply f (g x), ne_comm], exact hx }, let E : intermediate_field K L := intermediate_field.adjoin K {x}, let h_findim : finite_dimensional K E := intermediate_field.adjoin.finite_dimensional (h_int x), let H := E.fixing_subgroup, have h_basis : (H : set (L ≃ₐ[K] L)) ∈ gal_group_basis K L := ⟨H, ⟨E, ⟨h_findim, rfl⟩⟩, rfl⟩, have h_nhd := group_filter_basis.mem_nhds_one (gal_group_basis K L) h_basis, rw mem_nhds_iff at h_nhd, rcases h_nhd with ⟨W, hWH, hW_open, hW_1⟩, refine ⟨left_coset f W, left_coset g W, ⟨hW_open.left_coset f, hW_open.left_coset g, ⟨1, hW_1, mul_one _⟩, ⟨1, hW_1, mul_one _⟩, _⟩⟩, rw set.disjoint_left, rintro σ ⟨w1, hw1, h⟩ ⟨w2, hw2, rfl⟩, rw [eq_inv_mul_iff_mul_eq.symm, ← mul_assoc, mul_inv_eq_iff_eq_mul.symm] at h, have h_in_H : w1 * w2⁻¹ ∈ H := H.mul_mem (hWH hw1) (H.inv_mem (hWH hw2)), rw h at h_in_H, change φ ∈ E.fixing_subgroup at h_in_H, rw intermediate_field.mem_fixing_subgroup_iff at h_in_H, specialize h_in_H x, have hxE : x ∈ E, { apply intermediate_field.subset_adjoin, apply set.mem_singleton }, exact hφx (h_in_H hxE), end } end krull_t2 section totally_disconnected /-- If `L/K` is an algebraic field extension, then the Krull topology on `L ≃ₐ[K] L` is totally disconnected. -/ lemma krull_topology_totally_disconnected {K L : Type*} [field K] [field L] [algebra K L] (h_int : algebra.is_integral K L) : is_totally_disconnected (set.univ : set (L ≃ₐ[K] L)) := begin apply is_totally_disconnected_of_clopen_set, intros σ τ h_diff, have hστ : σ⁻¹ * τ ≠ 1, { rwa [ne.def, inv_mul_eq_one] }, rcases (fun_like.exists_ne hστ) with ⟨x, hx : (σ⁻¹ * τ) x ≠ x⟩, let E := intermediate_field.adjoin K ({x} : set L), haveI := intermediate_field.adjoin.finite_dimensional (h_int x), refine ⟨left_coset σ E.fixing_subgroup, ⟨E.fixing_subgroup_is_open.left_coset σ, E.fixing_subgroup_is_closed.left_coset σ⟩, ⟨1, E.fixing_subgroup.one_mem', mul_one σ⟩, _⟩, simp only [mem_left_coset_iff, set_like.mem_coe, intermediate_field.mem_fixing_subgroup_iff, not_forall], exact ⟨x, intermediate_field.mem_adjoin_simple_self K x, hx⟩, end end totally_disconnected
c3557b8970aefaae0e62bd073f83852d88fd9d86
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/polynomial/ring_division.lean
1290e691633f7e52069179cdd6da56891f1d25f4
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,849
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker, Johan Commelin -/ import data.polynomial.algebra_map import data.polynomial.degree.lemmas import data.polynomial.div /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_ring variables [comm_ring R] {p q : polynomial R} variables [comm_ring S] lemma nat_degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.nat_degree := nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj lemma degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.degree := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj) lemma aeval_mod_by_monic_eq_self_of_root [algebra R S] {p q : polynomial R} (hq : q.monic) {x : S} (hx : aeval x q = 0) : aeval x (p %ₘ q) = aeval x p := eval₂_mod_by_monic_eq_self_of_root hq hx end comm_ring section no_zero_divisors variables [comm_ring R] [no_zero_divisors R] {p q : polynomial R} instance : no_zero_divisors (polynomial R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], refine eq_zero_or_eq_zero_of_mul_eq_zero _, rw [← leading_coeff_zero, ← leading_coeff_mul, h], end } lemma nat_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul] @[simp] lemma nat_degree_pow (p : polynomial R) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a := by simp_rw [is_root, eval_mul, mul_eq_zero] lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := root_mul.1 h lemma degree_le_mul_left (p : polynomial R) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) theorem nat_degree_le_of_dvd {p q : polynomial R} (h1 : p ∣ q) (h2 : q ≠ 0) : p.nat_degree ≤ q.nat_degree := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _ end end no_zero_divisors section integral_domain variables [integral_domain R] {p q : polynomial R} instance : integral_domain (polynomial R) := { ..polynomial.no_zero_divisors, ..polynomial.nontrivial, ..polynomial.comm_ring } lemma nat_trailing_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : (p * q).nat_trailing_degree = p.nat_trailing_degree + q.nat_trailing_degree := begin simp only [←nat.sub_eq_of_eq_add (nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree _)], rw [reverse_mul_of_domain, nat_degree_mul hp hq, nat_degree_mul (mt reverse_eq_zero.mp hp) (mt reverse_eq_zero.mp hq), reverse_nat_degree, reverse_nat_degree, ←nat.sub_sub, nat.add_comm, nat.add_sub_assoc (nat.sub_le _ _), add_comm, nat.add_sub_assoc (nat.sub_le _ _)], end section roots open multiset lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : polynomial R) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : units (polynomial R)) : degree (u : polynomial R) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ theorem prime_X_sub_C (r : R) : prime (X - C r) := ⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C, λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩ theorem prime_X : prime (X : polynomial R) := by { convert (prime_X_sub_C (0 : R)), simp } lemma monic.prime_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : prime p := have p = X - C (- p.coeff 0), by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1, this.symm ▸ prime_X_sub_C _ theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) := (prime_X_sub_C r).irreducible theorem irreducible_X : irreducible (X : polynomial R) := prime.irreducible prime_X lemma monic.irreducible_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : irreducible p := (hm.prime_of_degree_eq_one hp1).irreducible theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q := begin obtain ⟨u, hu⟩ := hpq, unfold monic at hp hq, rw eq_C_of_degree_le_zero (le_of_eq $ degree_coe_units _) at hu, rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq, rwa [hq, C_1, mul_one] at hu end @[simp] lemma root_multiplicity_zero {x : R} : root_multiplicity x 0 = 0 := dif_pos rfl lemma root_multiplicity_eq_zero {p : polynomial R} {x : R} (h : ¬ is_root p x) : root_multiplicity x p = 0 := begin rw root_multiplicity_eq_multiplicity, split_ifs, { refl }, rw [← enat.coe_inj, enat.coe_get, multiplicity.multiplicity_eq_zero_of_not_dvd, nat.cast_zero], intro hdvd, exact h (dvd_iff_is_root.mp hdvd) end lemma root_multiplicity_pos {p : polynomial R} (hp : p ≠ 0) {x : R} : 0 < root_multiplicity x p ↔ is_root p x := begin rw [← dvd_iff_is_root, root_multiplicity_eq_multiplicity, dif_neg hp, ← enat.coe_lt_coe, enat.coe_get], exact multiplicity.dvd_iff_multiplicity_pos end lemma root_multiplicity_mul {p q : polynomial R} {x : R} (hpq : p * q ≠ 0) : root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q := begin have hp : p ≠ 0 := left_ne_zero_of_mul hpq, have hq : q ≠ 0 := right_ne_zero_of_mul hpq, rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq, root_multiplicity_eq_multiplicity p, dif_neg hp, root_multiplicity_eq_multiplicity q, dif_neg hq, multiplicity.mul' (prime_X_sub_C x)], end lemma root_multiplicity_X_sub_C_self {x : R} : root_multiplicity x (X - C x) = 1 := by rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x), multiplicity.get_multiplicity_self] lemma root_multiplicity_X_sub_C {x y : R} : root_multiplicity x (X - C y) = if x = y then 1 else 0 := begin split_ifs with hxy, { rw hxy, exact root_multiplicity_X_sub_C_self }, exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy)) end /-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/ lemma root_multiplicity_X_sub_C_pow (a : R) (n : ℕ) : root_multiplicity a ((X - C a) ^ n) = n := begin induction n with n hn, { refine root_multiplicity_eq_zero _, simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] }, have hzero := (ne_zero_of_monic (monic_pow (monic_X_sub_C a) n.succ)), rw pow_succ (X - C a) n at hzero ⊢, simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add] end /-- If `(X - a) ^ n` divides a polynomial `p` then the multiplicity of `a` as root of `p` is at least `n`. -/ lemma root_multiplicity_of_dvd {p : polynomial R} {a : R} {n : ℕ} (hzero : p ≠ 0) (h : (X - C a) ^ n ∣ p) : n ≤ root_multiplicity a p := begin obtain ⟨q, hq⟩ := exists_eq_mul_right_of_dvd h, rw hq at hzero, simp only [hq, root_multiplicity_mul hzero, root_multiplicity_X_sub_C_pow, ge_iff_le, _root_.zero_le, le_add_iff_nonneg_right], end /-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/ lemma root_multiplicity_add {p q : polynomial R} (a : R) (hzero : p + q ≠ 0) : min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) := begin refine root_multiplicity_of_dvd hzero _, have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a, have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a, exact min_pow_dvd_add hdivp hdivq end lemma exists_multiset_roots : ∀ {p : polynomial R} (hp : p ≠ 0), ∃ s : multiset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ a, s.count a = root_multiplicity a p | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_multiset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨x ::ₘ t, calc (card (x ::ₘ t) : with_bot ℕ) = t.card + 1 : by exact_mod_cast card_cons _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add (le_refl (1 : with_bot ℕ)) htd, begin assume a, conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx }, rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero x) hdiv0), root_multiplicity_X_sub_C, ← htr a], split_ifs with ha, { rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] }, { rw [count_cons_of_ne ha, zero_add] }, end⟩ else ⟨0, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a multiset containing all the roots of `p`, including their multiplicities. -/ noncomputable def roots (p : polynomial R) : multiset R := if h : p = 0 then ∅ else classical.some (exists_multiset_roots h) @[simp] lemma roots_zero : (0 : polynomial R).roots = 0 := dif_pos rfl lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_multiset_roots hp0)).1 end lemma card_roots' {p : polynomial R} (hp0 : p ≠ 0) : p.roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) lemma card_roots_sub_C {p : polynomial R} {a : R} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot ℕ) ≤ degree p := calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : polynomial R} {a : R} (hp0 : 0 < degree p) : (p - C a).roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (λ h, by simp [*, lt_irrefl] at *))) @[simp] lemma count_roots (hp : p ≠ 0) : p.roots.count a = root_multiplicity a p := by { rw [roots, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a } @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by rw [← count_pos, count_roots hp, root_multiplicity_pos hp] lemma eq_zero_of_infinite_is_root (p : polynomial R) (h : set.infinite {x | is_root p x}) : p = 0 := begin by_contradiction hp, apply h, convert p.roots.to_finset.finite_to_set using 1, ext1 r, simp only [mem_roots hp, multiset.mem_to_finset, set.mem_set_of_eq, finset.mem_coe] end lemma exists_max_root [linear_order R] (p : polynomial R) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x ≤ x₀ := set.exists_upper_bound_image _ _ $ not_not.mp (mt (eq_zero_of_infinite_is_root p) hp) lemma exists_min_root [linear_order R] (p : polynomial R) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x₀ ≤ x := set.exists_lower_bound_image _ _ $ not_not.mp (mt (eq_zero_of_infinite_is_root p) hp) lemma eq_of_infinite_eval_eq {R : Type*} [integral_domain R] (p q : polynomial R) (h : set.infinite {x | eval x p = eval x q}) : p = q := begin rw [← sub_eq_zero], apply eq_zero_of_infinite_is_root, simpa only [is_root, eval_sub, sub_eq_zero] end lemma roots_mul {p q : polynomial R} (hpq : p * q ≠ 0) : (p * q).roots = p.roots + q.roots := multiset.ext.mpr $ λ r, by rw [count_add, count_roots hpq, count_roots (left_ne_zero_of_mul hpq), count_roots (right_ne_zero_of_mul hpq), root_multiplicity_mul hpq] @[simp] lemma mem_roots_sub_C {p : polynomial R} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) @[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = {r} := begin ext s, rw [count_roots (X_sub_C_ne_zero r), root_multiplicity_X_sub_C], split_ifs with h, { rw [h, count_singleton_self] }, { rw [singleton_eq_cons, count_cons_of_ne h, count_zero] } end @[simp] lemma roots_C (x : R) : (C x).roots = 0 := if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ λ r, have h : C x ≠ 0, from λ h, H $ C_inj.1 $ h.symm ▸ C_0.symm, have not_root : ¬ is_root (C x) r := mt (λ (h : eval r (C x) = 0), trans eval_C.symm h) H, by rw [count_roots h, count_zero, root_multiplicity_eq_zero not_root] @[simp] lemma roots_one : (1 : polynomial R).roots = ∅ := roots_C 1 lemma roots_list_prod (L : list (polynomial R)) : ((0 : polynomial R) ∉ L) → L.prod.roots = (L : multiset (polynomial R)).bind roots := list.rec_on L (λ _, roots_one) $ λ hd tl ih H, begin rw [list.mem_cons_iff, not_or_distrib] at H, rw [list.prod_cons, roots_mul (mul_ne_zero (ne.symm H.1) $ list.prod_ne_zero H.2), ← multiset.cons_coe, multiset.cons_bind, ih H.2] end lemma roots_multiset_prod (m : multiset (polynomial R)) : (0 : polynomial R) ∉ m → m.prod.roots = m.bind roots := by { rcases m with ⟨L⟩, simpa only [coe_prod, quot_mk_to_coe''] using roots_list_prod L } lemma roots_prod {ι : Type*} (f : ι → polynomial R) (s : finset ι) : s.prod f ≠ 0 → (s.prod f).roots = s.val.bind (λ i, roots (f i)) := begin rcases s with ⟨m, hm⟩, simpa [multiset.prod_eq_zero_iff, bind_map] using roots_multiset_prod (m.map f) end lemma roots_prod_X_sub_C (s : finset R) : (s.prod (λ a, X - C a)).roots = s.val := (roots_prod (λ a, X - C a) s (prod_ne_zero_iff.mpr (λ a _, X_sub_C_ne_zero a))).trans (by simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id']) lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : polynomial R) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial R) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial R) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a section nth_roots /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots (n : ℕ) (a : R) : multiset R := roots ((X : polynomial R) ^ n - C a) @[simp] lemma mem_nth_roots {n : ℕ} (hn : 0 < n) {a x : R} : x ∈ nth_roots n a ↔ x ^ n = a := by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero] @[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 := by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C] lemma card_nth_roots (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : polynomial R) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, card_zero] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by { rw [hn, pow_zero, ← C_1, ← ring_hom.map_sub ], exact degree_C_le })) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) /-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/ def nth_roots_finset (n : ℕ) (R : Type*) [integral_domain R] : finset R := multiset.to_finset (nth_roots n (1 : R)) @[simp] lemma mem_nth_roots_finset {n : ℕ} (h : 0 < n) {x : R} : x ∈ nth_roots_finset n R ↔ x ^ (n : ℕ) = 1 := by rw [nth_roots_finset, mem_to_finset, mem_nth_roots h] end nth_roots lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := if hp0 : p = 0 then by simp [hp0] else calc coeff (p.comp q) (nat_degree p * nat_degree q) = p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) : by rw [comp, eval₂, coeff_sum] ... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) : finset.sum_eq_single _ begin assume b hbs hbp, have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]), have : coeff p b ≠ 0, by rwa mem_support_iff at hbs, refine coeff_eq_zero_of_degree_lt _, erw [degree_mul, degree_C this, degree_pow, zero_add, degree_eq_nat_degree hq0, ← with_bot.coe_nsmul, nsmul_eq_mul, with_bot.coe_lt_coe, nat.cast_id, mul_lt_mul_right (pos_iff_ne_zero.mpr hqd0)], exact lt_of_le_of_ne (le_nat_degree_of_ne_zero this) hbp, end begin intro h, contrapose! hp0, rw mem_support_iff at h, push_neg at h, rwa ← leading_coeff_eq_zero, end ... = _ : have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p), by rw [leading_coeff, nat_degree_pow], by rw [coeff_C_mul, this, leading_coeff_pow] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := le_antisymm nat_degree_comp_le (if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul] else if hqd0 : nat_degree q = 0 then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree, by rw [eq_C_of_degree_le_zero this]; simp else le_nat_degree_of_ne_zero $ have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero], calc coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p : coeff_comp_degree_mul_degree hqd0 ... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0))) lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl lemma units_coeff_zero_smul (c : units (polynomial R)) (p : polynomial R) : (c : polynomial R).coeff 0 • p = c * p := by rw [←polynomial.C_mul', ←polynomial.eq_C_of_degree_eq_zero (degree_coe_units c)] @[simp] lemma nat_degree_coe_units (u : units (polynomial R)) : nat_degree (u : polynomial R) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma comp_eq_zero_iff : p.comp q = 0 ↔ p = 0 ∨ (p.eval (q.coeff 0) = 0 ∧ q = C (q.coeff 0)) := begin split, { intro h, have key : p.nat_degree = 0 ∨ q.nat_degree = 0, { rw [←mul_eq_zero, ←nat_degree_comp, h, nat_degree_zero] }, replace key := or.imp eq_C_of_nat_degree_eq_zero eq_C_of_nat_degree_eq_zero key, cases key, { rw [key, C_comp] at h, exact or.inl (key.trans h) }, { rw [key, comp_C, C_eq_zero] at h, exact or.inr ⟨h, key⟩ }, }, { exact λ h, or.rec (λ h, by rw [h, zero_comp]) (λ h, by rw [h.2, comp_C, h.1, C_0]) h }, end lemma zero_of_eval_zero [infinite R] (p : polynomial R) (h : ∀ x, p.eval x = 0) : p = 0 := by classical; by_contradiction hp; exact fintype.false ⟨p.roots.to_finset, λ x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩ lemma funext [infinite R] {p q : polynomial R} (ext : ∀ r : R, p.eval r = q.eval r) : p = q := begin rw ← sub_eq_zero, apply zero_of_eval_zero, intro x, rw [eval_sub, sub_eq_zero, ext], end /-- The set of distinct roots of `p` in `E`. If you have a non-separable polynomial, use `polynomial.roots` for the multiset where multiple roots have the appropriate multiplicity. -/ def root_set (p : polynomial R) (S) [integral_domain S] [algebra R S] : set S := (p.map (algebra_map R S)).roots.to_finset lemma root_set_def (p : polynomial R) (S) [integral_domain S] [algebra R S] : p.root_set S = (p.map (algebra_map R S)).roots.to_finset := rfl @[simp] lemma root_set_zero (S) [integral_domain S] [algebra R S] : (0 : polynomial R).root_set S = ∅ := by rw [root_set_def, polynomial.map_zero, roots_zero, to_finset_zero, finset.coe_empty] @[simp] lemma root_set_C [integral_domain S] [algebra R S] (a : R) : (C a).root_set S = ∅ := by rw [root_set_def, map_C, roots_C, multiset.to_finset_zero, finset.coe_empty] instance root_set_fintype {R : Type*} [integral_domain R] (p : polynomial R) (S : Type*) [integral_domain S] [algebra R S] : fintype (p.root_set S) := finset_coe.fintype _ lemma root_set_finite {R : Type*} [integral_domain R] (p : polynomial R) (S : Type*) [integral_domain S] [algebra R S] : (p.root_set S).finite := ⟨polynomial.root_set_fintype p S⟩ end roots theorem is_unit_iff {f : polynomial R} : is_unit f ↔ ∃ r : R, is_unit r ∧ C r = f := ⟨λ hf, ⟨f.coeff 0, is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) ▸ hf, (eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩, λ ⟨r, hr, hrf⟩, hrf ▸ is_unit_C.2 hr⟩ lemma coeff_coe_units_zero_ne_zero (u : units (polynomial R)) : coeff (u : polynomial R) 0 ≠ 0 := begin conv in (0) { rw [← nat_degree_coe_units u] }, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.is_unit_or_is_unit hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) /-- Division by a monic polynomial doesn't change the leading coefficient. -/ lemma leading_coeff_div_by_monic_of_monic {R : Type u} [integral_domain R] {p q : polynomial R} (hmonic : q.monic) (hdegree : q.degree ≤ p.degree) : (p /ₘ q).leading_coeff = p.leading_coeff := begin have hp := mod_by_monic_add_div p hmonic, have hzero : (p /ₘ q) ≠ 0, { intro h, exact not_lt_of_le hdegree ((div_by_monic_eq_zero_iff hmonic (monic.ne_zero hmonic)).1 h) }, have deglt : (p %ₘ q).degree < (q * (p /ₘ q)).degree, { rw degree_mul, refine lt_of_lt_of_le (degree_mod_by_monic_lt p hmonic (monic.ne_zero hmonic)) _, rw [degree_eq_nat_degree (monic.ne_zero hmonic), degree_eq_nat_degree hzero], norm_cast, simp only [zero_le, le_add_iff_nonneg_right] }, have hrew := (leading_coeff_add_of_degree_lt deglt), rw leading_coeff_mul q (p /ₘ q) at hrew, simp only [hmonic, one_mul, monic.leading_coeff] at hrew, nth_rewrite 1 ← hp, exact hrew.symm end lemma eq_of_monic_of_dvd_of_nat_degree_le (hp : p.monic) (hq : q.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = p := begin obtain ⟨r, hr⟩ := hdiv, have rzero : r ≠ 0, { intro h, simpa [h, monic.ne_zero hq] using hr }, rw [hr, nat_degree_mul (monic.ne_zero hp) rzero] at hdeg, have hdegeq : p.nat_degree + r.nat_degree = p.nat_degree, { suffices hdegle : p.nat_degree ≤ p.nat_degree + r.nat_degree, { exact le_antisymm hdeg hdegle }, exact nat.le.intro rfl }, replace hdegeq := eq_C_of_nat_degree_eq_zero (((@add_right_inj _ _ p.nat_degree) _ 0).1 hdegeq), suffices hlead : 1 = r.leading_coeff, { have hcoeff := leading_coeff_C (r.coeff 0), rw [← hdegeq, ← hlead] at hcoeff, rw [← hcoeff, C_1] at hdegeq, rwa [hdegeq, mul_one] at hr }, have hprod : q.leading_coeff = p.leading_coeff * r.leading_coeff, { simp only [hr, leading_coeff_mul] }, rwa [monic.leading_coeff hp, monic.leading_coeff hq, one_mul] at hprod end end integral_domain section variables [semiring R] [integral_domain S] (φ : R →+* S) lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map (f : polynomial R) (hf : is_unit (leading_coeff f)) (H : is_unit (map φ f)) : is_unit f := begin have dz := degree_eq_zero_of_is_unit H, rw degree_map_eq_of_leading_coeff_ne_zero at dz, { rw eq_C_of_degree_eq_zero dz, refine is_unit.map (C.to_monoid_hom : R →* polynomial R) _, convert hf, rw (degree_eq_iff_nat_degree_eq _).1 dz, rintro rfl, simpa using H, }, { intro h, have u : is_unit (φ f.leading_coeff) := is_unit.map φ.to_monoid_hom hf, rw h at u, simpa using u, } end end section variables [integral_domain R] [integral_domain S] (φ : R →+* S) /-- A polynomial over an integral domain `R` is irreducible if it is monic and irreducible after mapping into an integral domain `S`. A special case of this lemma is that a polynomial over `ℤ` is irreducible if it is monic and irreducible over `ℤ/pℤ` for some prime `p`. -/ lemma monic.irreducible_of_irreducible_map (f : polynomial R) (h_mon : monic f) (h_irr : irreducible (map φ f)) : irreducible f := begin fsplit, { intro h, exact h_irr.not_unit (is_unit.map (map_ring_hom φ).to_monoid_hom h), }, { intros a b h, have q := (leading_coeff_mul a b).symm, rw ←h at q, dsimp [monic] at h_mon, rw h_mon at q, have au : is_unit a.leading_coeff := is_unit_of_mul_eq_one _ _ q, rw mul_comm at q, have bu : is_unit b.leading_coeff := is_unit_of_mul_eq_one _ _ q, clear q h_mon, have h' := congr_arg (map φ) h, simp only [map_mul] at h', cases h_irr.is_unit_or_is_unit h' with w w, { left, exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ au w, }, { right, exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ bu w, }, } end end end polynomial namespace is_integral_domain variables {R : Type*} [comm_ring R] /-- Lift evidence that `is_integral_domain R` to `is_integral_domain (polynomial R)`. -/ lemma polynomial (h : is_integral_domain R) : is_integral_domain (polynomial R) := @integral_domain.to_is_integral_domain _ (@polynomial.integral_domain _ (h.to_integral_domain _)) end is_integral_domain
49dca3745d952123be40d893f53ca008c9883d64
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/order/filter/bases.lean
2e9640e39be985f1353b228c3e8512a4aaedc38c
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,160
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.basic import data.set.countable /-! # Filter bases A filter basis `B : filter_basis α` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. Compared to filters, filter bases do not require that any set containing an element of `B` belongs to `B`. A filter basis `B` can be used to construct `B.filter : filter α` such that a set belongs to `B.filter` if and only if it contains an element of `B`. Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → set α`, the proposition `h : filter.is_basis p s` makes sure the range of `s` bounded by `p` (ie. `s '' set_of p`) defines a filter basis `h.filter_basis`. If one already has a filter `l` on `α`, `filter.has_basis l p s` (where `p : ι → Prop` and `s : ι → set α` as above) means that a set belongs to `l` if and only if it contains some `s i` with `p i`. It implies `h : filter.is_basis p s`, and `l = h.filter_basis.filter`. The point of this definition is that checking statements involving elements of `l` often reduces to checking them on the basis elements. We define a function `has_basis.index (h : filter.has_basis l p s) (t) (ht : t ∈ l)` that returns some index `i` such that `p i` and `s i ⊆ t`. This function can be useful to avoid manual destruction of `h.mem_iff.mpr ht` using `cases` or `let`. This file also introduces more restricted classes of bases, involving monotonicity or countability. In particular, for `l : filter α`, `l.is_countably_generated` means there is a countable set of sets which generates `s`. This is reformulated in term of bases, and consequences are derived. ## Main statements * `has_basis.mem_iff`, `has_basis.mem_of_superset`, `has_basis.mem_of_mem` : restate `t ∈ f` in terms of a basis; * `basis_sets` : all sets of a filter form a basis; * `has_basis.inf`, `has_basis.inf_principal`, `has_basis.prod`, `has_basis.prod_self`, `has_basis.map`, `has_basis.comap` : combinators to construct filters of `l ⊓ l'`, `l ⊓ 𝓟 t`, `l ×ᶠ l'`, `l ×ᶠ l`, `l.map f`, `l.comap f` respectively; * `has_basis.le_iff`, `has_basis.ge_iff`, has_basis.le_basis_iff` : restate `l ≤ l'` in terms of bases. * `has_basis.tendsto_right_iff`, `has_basis.tendsto_left_iff`, `has_basis.tendsto_iff` : restate `tendsto f l l'` in terms of bases. * `is_countably_generated_iff_exists_antimono_basis` : proves a filter is countably generated if and only if it admis a basis parametrized by a decreasing sequence of sets indexed by `ℕ`. * `tendsto_iff_seq_tendsto ` : an abstract version of "sequentially continuous implies continuous". ## Implementation notes As with `Union`/`bUnion`/`sUnion`, there are three different approaches to filter bases: * `has_basis l s`, `s : set (set α)`; * `has_basis l s`, `s : ι → set α`; * `has_basis l p s`, `p : ι → Prop`, `s : ι → set α`. We use the latter one because, e.g., `𝓝 x` in an `emetric_space` or in a `metric_space` has a basis of this form. The other two can be emulated using `s = id` or `p = λ _, true`. With this approach sometimes one needs to `simp` the statement provided by the `has_basis` machinery, e.g., `simp only [exists_prop, true_and]` or `simp only [forall_const]` can help with the case `p = λ _, true`. -/ open set filter open_locale filter classical variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} {ι' : Type*} /-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure filter_basis (α : Type*) := (sets : set (set α)) (nonempty : sets.nonempty) (inter_sets {x y} : x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y) instance filter_basis.nonempty_sets (B : filter_basis α) : nonempty B.sets := B.nonempty.to_subtype /-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter_basis α) := ⟨λ U B, U ∈ B.sets⟩ -- For illustration purposes, the filter basis defining (at_top : filter ℕ) instance : inhabited (filter_basis ℕ) := ⟨{ sets := range Ici, nonempty := ⟨Ici 0, mem_range_self 0⟩, inter_sets := begin rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, refine ⟨Ici (max n m), mem_range_self _, _⟩, rintros p p_in, split ; rw mem_Ici at *, exact le_of_max_le_left p_in, exact le_of_max_le_right p_in, end }⟩ /-- `is_basis p s` means the image of `s` bounded by `p` is a filter basis. -/ protected structure filter.is_basis (p : ι → Prop) (s : ι → set α) : Prop := (nonempty : ∃ i, p i) (inter : ∀ {i j}, p i → p j → ∃ k, p k ∧ s k ⊆ s i ∩ s j) namespace filter namespace is_basis /-- Constructs a filter basis from an indexed family of sets satisfying `is_basis`. -/ protected def filter_basis {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter_basis α := { sets := s '' set_of p, nonempty := let ⟨i, hi⟩ := h.nonempty in ⟨s i, mem_image_of_mem s hi⟩, inter_sets := by { rintros _ _ ⟨i, hi, rfl⟩ ⟨j, hj, rfl⟩, rcases h.inter hi hj with ⟨k, hk, hk'⟩, exact ⟨_, mem_image_of_mem s hk, hk'⟩ } } variables {p : ι → Prop} {s : ι → set α} (h : is_basis p s) lemma mem_filter_basis_iff {U : set α} : U ∈ h.filter_basis ↔ ∃ i, p i ∧ s i = U := iff.rfl end is_basis end filter namespace filter_basis /-- The filter associated to a filter basis. -/ protected def filter (B : filter_basis α) : filter α := { sets := {s | ∃ t ∈ B, t ⊆ s}, univ_sets := let ⟨s, s_in⟩ := B.nonempty in ⟨s, s_in, s.subset_univ⟩, sets_of_superset := λ x y ⟨s, s_in, h⟩ hxy, ⟨s, s_in, set.subset.trans h hxy⟩, inter_sets := λ x y ⟨s, s_in, hs⟩ ⟨t, t_in, ht⟩, let ⟨u, u_in, u_sub⟩ := B.inter_sets s_in t_in in ⟨u, u_in, set.subset.trans u_sub $ set.inter_subset_inter hs ht⟩ } lemma mem_filter_iff (B : filter_basis α) {U : set α} : U ∈ B.filter ↔ ∃ s ∈ B, s ⊆ U := iff.rfl lemma mem_filter_of_mem (B : filter_basis α) {U : set α} : U ∈ B → U ∈ B.filter:= λ U_in, ⟨U, U_in, subset.refl _⟩ lemma eq_infi_principal (B : filter_basis α) : B.filter = ⨅ s : B.sets, 𝓟 s := begin have : directed (≥) (λ (s : B.sets), 𝓟 (s : set α)), { rintros ⟨U, U_in⟩ ⟨V, V_in⟩, rcases B.inter_sets U_in V_in with ⟨W, W_in, W_sub⟩, use [W, W_in], finish }, ext U, simp [mem_filter_iff, mem_infi_of_directed this] end protected lemma generate (B : filter_basis α) : generate B.sets = B.filter := begin apply le_antisymm, { intros U U_in, rcases B.mem_filter_iff.mp U_in with ⟨V, V_in, h⟩, exact generate_sets.superset (generate_sets.basic V_in) h }, { rw sets_iff_generate, apply mem_filter_of_mem } end end filter_basis namespace filter namespace is_basis variables {p : ι → Prop} {s : ι → set α} /-- Constructs a filter from an indexed family of sets satisfying `is_basis`. -/ protected def filter (h : is_basis p s) : filter α := h.filter_basis.filter protected lemma mem_filter_iff (h : is_basis p s) {U : set α} : U ∈ h.filter ↔ ∃ i, p i ∧ s i ⊆ U := begin erw [h.filter_basis.mem_filter_iff], simp only [mem_filter_basis_iff h, exists_prop], split, { rintros ⟨_, ⟨i, pi, rfl⟩, h⟩, tauto }, { tauto } end lemma filter_eq_generate (h : is_basis p s) : h.filter = generate {U | ∃ i, p i ∧ s i = U} := by erw h.filter_basis.generate ; refl end is_basis /-- We say that a filter `l` has a basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/ protected structure has_basis (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop := (mem_iff' : ∀ (t : set α), t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t) section same_type variables {l l' : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} {i : ι} {p' : ι' → Prop} {s' : ι' → set α} {i' : ι'} lemma has_basis_generate (s : set (set α)) : (generate s).has_basis (λ t, finite t ∧ t ⊆ s) (λ t, ⋂₀ t) := ⟨begin intro U, rw mem_generate_iff, apply exists_congr, tauto end⟩ /-- The smallest filter basis containing a given collection of sets. -/ def filter_basis.of_sets (s : set (set α)) : filter_basis α := { sets := sInter '' { t | finite t ∧ t ⊆ s}, nonempty := ⟨univ, ∅, ⟨⟨finite_empty, empty_subset s⟩, sInter_empty⟩⟩, inter_sets := begin rintros _ _ ⟨a, ⟨fina, suba⟩, rfl⟩ ⟨b, ⟨finb, subb⟩, rfl⟩, exact ⟨⋂₀ (a ∪ b), mem_image_of_mem _ ⟨fina.union finb, union_subset suba subb⟩, by rw sInter_union⟩, end } /-- Definition of `has_basis` unfolded with implicit set argument. -/ lemma has_basis.mem_iff (hl : l.has_basis p s) : t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := hl.mem_iff' t lemma has_basis.eq_of_same_basis (hl : l.has_basis p s) (hl' : l'.has_basis p s) : l = l' := begin ext t, rw [hl.mem_iff, hl'.mem_iff] end lemma has_basis_iff : l.has_basis p s ↔ ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := ⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩ lemma has_basis.ex_mem (h : l.has_basis p s) : ∃ i, p i := let ⟨i, pi, h⟩ := h.mem_iff.mp univ_mem in ⟨i, pi⟩ protected lemma has_basis.nonempty (h : l.has_basis p s) : nonempty ι := nonempty_of_exists h.ex_mem protected lemma is_basis.has_basis (h : is_basis p s) : has_basis h.filter p s := ⟨λ t, by simp only [h.mem_filter_iff, exists_prop]⟩ lemma has_basis.mem_of_superset (hl : l.has_basis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l := (hl.mem_iff).2 ⟨i, hi, ht⟩ lemma has_basis.mem_of_mem (hl : l.has_basis p s) (hi : p i) : s i ∈ l := hl.mem_of_superset hi $ subset.refl _ /-- Index of a basis set such that `s i ⊆ t` as an element of `subtype p`. -/ noncomputable def has_basis.index (h : l.has_basis p s) (t : set α) (ht : t ∈ l) : {i : ι // p i} := ⟨(h.mem_iff.1 ht).some, (h.mem_iff.1 ht).some_spec.fst⟩ lemma has_basis.property_index (h : l.has_basis p s) (ht : t ∈ l) : p (h.index t ht) := (h.index t ht).2 lemma has_basis.set_index_mem (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ∈ l := h.mem_of_mem $ h.property_index _ lemma has_basis.set_index_subset (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ⊆ t := (h.mem_iff.1 ht).some_spec.snd lemma has_basis.is_basis (h : l.has_basis p s) : is_basis p s := { nonempty := let ⟨i, hi, H⟩ := h.mem_iff.mp univ_mem in ⟨i, hi⟩, inter := λ i j hi hj, by simpa [h.mem_iff] using l.inter_sets (h.mem_of_mem hi) (h.mem_of_mem hj) } lemma has_basis.filter_eq (h : l.has_basis p s) : h.is_basis.filter = l := by { ext U, simp [h.mem_iff, is_basis.mem_filter_iff] } lemma has_basis.eq_generate (h : l.has_basis p s) : l = generate { U | ∃ i, p i ∧ s i = U } := by rw [← h.is_basis.filter_eq_generate, h.filter_eq] lemma generate_eq_generate_inter (s : set (set α)) : generate s = generate (sInter '' { t | finite t ∧ t ⊆ s}) := by erw [(filter_basis.of_sets s).generate, ← (has_basis_generate s).filter_eq] ; refl lemma of_sets_filter_eq_generate (s : set (set α)) : (filter_basis.of_sets s).filter = generate s := by rw [← (filter_basis.of_sets s).generate, generate_eq_generate_inter s] ; refl lemma has_basis.to_has_basis' (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → s' i' ∈ l) : l.has_basis p' s' := begin refine ⟨λ t, ⟨λ ht, _, λ ⟨i', hi', ht⟩, mem_of_superset (h' i' hi') ht⟩⟩, rcases hl.mem_iff.1 ht with ⟨i, hi, ht⟩, rcases h i hi with ⟨i', hi', hs's⟩, exact ⟨i', hi', subset.trans hs's ht⟩ end lemma has_basis.to_has_basis (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l.has_basis p' s' := hl.to_has_basis' h $ λ i' hi', let ⟨i, hi, hss'⟩ := h' i' hi' in hl.mem_iff.2 ⟨i, hi, hss'⟩ lemma has_basis.to_subset (hl : l.has_basis p s) {t : ι → set α} (h : ∀ i, p i → t i ⊆ s i) (ht : ∀ i, p i → t i ∈ l) : l.has_basis p t := hl.to_has_basis' (λ i hi, ⟨i, hi, h i hi⟩) ht lemma has_basis.eventually_iff (hl : l.has_basis p s) {q : α → Prop} : (∀ᶠ x in l, q x) ↔ ∃ i, p i ∧ ∀ ⦃x⦄, x ∈ s i → q x := by simpa using hl.mem_iff lemma has_basis.frequently_iff (hl : l.has_basis p s) {q : α → Prop} : (∃ᶠ x in l, q x) ↔ ∀ i, p i → ∃ x ∈ s i, q x := by simp [filter.frequently, hl.eventually_iff] lemma has_basis.exists_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P t → P s) : (∃ s ∈ l, P s) ↔ ∃ (i) (hi : p i), P (s i) := ⟨λ ⟨s, hs, hP⟩, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in ⟨i, hi, mono his hP⟩, λ ⟨i, hi, hP⟩, ⟨s i, hl.mem_of_mem hi, hP⟩⟩ lemma has_basis.forall_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P s → P t) : (∀ s ∈ l, P s) ↔ ∀ i, p i → P (s i) := ⟨λ H i hi, H (s i) $ hl.mem_of_mem hi, λ H s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in mono his (H i hi)⟩ lemma has_basis.ne_bot_iff (hl : l.has_basis p s) : ne_bot l ↔ (∀ {i}, p i → (s i).nonempty) := forall_mem_nonempty_iff_ne_bot.symm.trans $ hl.forall_iff $ λ _ _, nonempty.mono lemma has_basis.eq_bot_iff (hl : l.has_basis p s) : l = ⊥ ↔ ∃ i, p i ∧ s i = ∅ := not_iff_not.1 $ ne_bot_iff.symm.trans $ hl.ne_bot_iff.trans $ by simp only [not_exists, not_and, ← ne_empty_iff_nonempty] lemma basis_sets (l : filter α) : l.has_basis (λ s : set α, s ∈ l) id := ⟨λ t, exists_mem_subset_iff.symm⟩ lemma has_basis_self {l : filter α} {P : set α → Prop} : has_basis l (λ s, s ∈ l ∧ P s) id ↔ ∀ t ∈ l, ∃ r ∈ l, P r ∧ r ⊆ t := begin simp only [has_basis_iff, exists_prop, id, and_assoc], exact forall_congr (λ s, ⟨λ h, h.1, λ h, ⟨h, λ ⟨t, hl, hP, hts⟩, mem_of_superset hl hts⟩⟩) end /-- If `{s i | p i}` is a basis of a filter `l` and each `s i` includes `s j` such that `p j ∧ q j`, then `{s j | p j ∧ q j}` is a basis of `l`. -/ lemma has_basis.restrict (h : l.has_basis p s) {q : ι → Prop} (hq : ∀ i, p i → ∃ j, p j ∧ q j ∧ s j ⊆ s i) : l.has_basis (λ i, p i ∧ q i) s := begin refine ⟨λ t, ⟨λ ht, _, λ ⟨i, hpi, hti⟩, h.mem_iff.2 ⟨i, hpi.1, hti⟩⟩⟩, rcases h.mem_iff.1 ht with ⟨i, hpi, hti⟩, rcases hq i hpi with ⟨j, hpj, hqj, hji⟩, exact ⟨j, ⟨hpj, hqj⟩, subset.trans hji hti⟩ end /-- If `{s i | p i}` is a basis of a filter `l` and `V ∈ l`, then `{s i | p i ∧ s i ⊆ V}` is a basis of `l`. -/ lemma has_basis.restrict_subset (h : l.has_basis p s) {V : set α} (hV : V ∈ l) : l.has_basis (λ i, p i ∧ s i ⊆ V) s := h.restrict $ λ i hi, (h.mem_iff.1 (inter_mem hV (h.mem_of_mem hi))).imp $ λ j hj, ⟨hj.fst, subset_inter_iff.1 hj.snd⟩ lemma has_basis.has_basis_self_subset {p : set α → Prop} (h : l.has_basis (λ s, s ∈ l ∧ p s) id) {V : set α} (hV : V ∈ l) : l.has_basis (λ s, s ∈ l ∧ p s ∧ s ⊆ V) id := by simpa only [and_assoc] using h.restrict_subset hV theorem has_basis.ge_iff (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → s' i' ∈ l := ⟨λ h i' hi', h $ hl'.mem_of_mem hi', λ h s hs, let ⟨i', hi', hs⟩ := hl'.mem_iff.1 hs in mem_of_superset (h _ hi') hs⟩ theorem has_basis.le_iff (hl : l.has_basis p s) : l ≤ l' ↔ ∀ t ∈ l', ∃ i (hi : p i), s i ⊆ t := by simp only [le_def, hl.mem_iff] theorem has_basis.le_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → ∃ i (hi : p i), s i ⊆ s' i' := by simp only [hl'.ge_iff, hl.mem_iff] lemma has_basis.ext (hl : l.has_basis p s) (hl' : l'.has_basis p' s') (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l = l' := begin apply le_antisymm, { rw hl.le_basis_iff hl', simpa using h' }, { rw hl'.le_basis_iff hl, simpa using h }, end lemma has_basis.inf (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊓ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) := ⟨begin intro t, split, { simp only [mem_inf_iff, exists_prop, hl.mem_iff, hl'.mem_iff], rintros ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, rfl⟩, use [(i, i'), ⟨hi, hi'⟩, inter_subset_inter ht ht'] }, { rintros ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩, exact mem_inf_of_inter (hl.mem_of_mem hi) (hl'.mem_of_mem hi') H } end⟩ lemma has_basis_principal (t : set α) : (𝓟 t).has_basis (λ i : unit, true) (λ i, t) := ⟨λ U, by simp⟩ lemma has_basis.sup (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊔ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) := ⟨begin intros t, simp only [mem_sup, hl.mem_iff, hl'.mem_iff, prod.exists, union_subset_iff, exists_prop, and_assoc, exists_and_distrib_left], simp only [← and_assoc, exists_and_distrib_right, and_comm] end⟩ lemma has_basis.inf_principal (hl : l.has_basis p s) (s' : set α) : (l ⊓ 𝓟 s').has_basis p (λ i, s i ∩ s') := ⟨λ t, by simp only [mem_inf_principal, hl.mem_iff, subset_def, mem_set_of_eq, mem_inter_iff, and_imp]⟩ lemma has_basis.inf_basis_ne_bot_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃i'⦄ (hi' : p' i'), (s i ∩ s' i').nonempty := (hl.inf hl').ne_bot_iff.trans $ by simp [@forall_swap _ ι'] lemma has_basis.inf_ne_bot_iff (hl : l.has_basis p s) : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃s'⦄ (hs' : s' ∈ l'), (s i ∩ s').nonempty := hl.inf_basis_ne_bot_iff l'.basis_sets lemma has_basis.inf_principal_ne_bot_iff (hl : l.has_basis p s) {t : set α} : ne_bot (l ⊓ 𝓟 t) ↔ ∀ ⦃i⦄ (hi : p i), (s i ∩ t).nonempty := (hl.inf_principal t).ne_bot_iff lemma inf_ne_bot_iff : ne_bot (l ⊓ l') ↔ ∀ ⦃s : set α⦄ (hs : s ∈ l) ⦃s'⦄ (hs' : s' ∈ l'), (s ∩ s').nonempty := l.basis_sets.inf_ne_bot_iff lemma inf_principal_ne_bot_iff {s : set α} : ne_bot (l ⊓ 𝓟 s) ↔ ∀ U ∈ l, (U ∩ s).nonempty := l.basis_sets.inf_principal_ne_bot_iff lemma inf_eq_bot_iff {f g : filter α} : f ⊓ g = ⊥ ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ := not_iff_not.1 $ ne_bot_iff.symm.trans $ inf_ne_bot_iff.trans $ by simp [← ne_empty_iff_nonempty] protected lemma disjoint_iff {f g : filter α} : disjoint f g ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ := disjoint_iff.trans inf_eq_bot_iff lemma mem_iff_inf_principal_compl {f : filter α} {s : set α} : s ∈ f ↔ f ⊓ 𝓟 sᶜ = ⊥ := begin refine not_iff_not.1 ((inf_principal_ne_bot_iff.trans _).symm.trans ne_bot_iff), exact ⟨λ h hs, by simpa [empty_not_nonempty] using h s hs, λ hs t ht, inter_compl_nonempty_iff.2 $ λ hts, hs $ mem_of_superset ht hts⟩, end lemma not_mem_iff_inf_principal_compl {f : filter α} {s : set α} : s ∉ f ↔ ne_bot (f ⊓ 𝓟 sᶜ) := (not_congr mem_iff_inf_principal_compl).trans ne_bot_iff.symm lemma mem_iff_disjoint_principal_compl {f : filter α} {s : set α} : s ∈ f ↔ disjoint f (𝓟 sᶜ) := mem_iff_inf_principal_compl.trans disjoint_iff.symm lemma le_iff_forall_disjoint_principal_compl {f g : filter α} : f ≤ g ↔ ∀ V ∈ g, disjoint f (𝓟 Vᶜ) := forall_congr $ λ _, forall_congr $ λ _, mem_iff_disjoint_principal_compl lemma le_iff_forall_inf_principal_compl {f g : filter α} : f ≤ g ↔ ∀ V ∈ g, f ⊓ 𝓟 Vᶜ = ⊥ := forall_congr $ λ _, forall_congr $ λ _, mem_iff_inf_principal_compl lemma inf_ne_bot_iff_frequently_left {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in f, p x) → ∃ᶠ x in g, p x := by simpa only [inf_ne_bot_iff, frequently_iff, exists_prop, and_comm] lemma inf_ne_bot_iff_frequently_right {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in g, p x) → ∃ᶠ x in f, p x := by { rw inf_comm, exact inf_ne_bot_iff_frequently_left } lemma has_basis.eq_binfi (h : l.has_basis p s) : l = ⨅ i (_ : p i), 𝓟 (s i) := eq_binfi_of_mem_iff_exists_mem $ λ t, by simp only [h.mem_iff, mem_principal] lemma has_basis.eq_infi (h : l.has_basis (λ _, true) s) : l = ⨅ i, 𝓟 (s i) := by simpa only [infi_true] using h.eq_binfi lemma has_basis_infi_principal {s : ι → set α} (h : directed (≥) s) [nonempty ι] : (⨅ i, 𝓟 (s i)).has_basis (λ _, true) s := ⟨begin refine λ t, (mem_infi_of_directed (h.mono_comp _ _) t).trans $ by simp only [exists_prop, true_and, mem_principal], exact λ _ _, principal_mono.2 end⟩ /-- If `s : ι → set α` is an indexed family of sets, then finite intersections of `s i` form a basis of `⨅ i, 𝓟 (s i)`. -/ lemma has_basis_infi_principal_finite (s : ι → set α) : (⨅ i, 𝓟 (s i)).has_basis (λ t : set ι, finite t) (λ t, ⋂ i ∈ t, s i) := begin refine ⟨λ U, (mem_infi_finite _).trans _⟩, simp only [infi_principal_finset, mem_Union, mem_principal, exists_prop, exists_finite_iff_finset, finset.set_bInter_coe] end lemma has_basis_binfi_principal {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o (≥)) S) (ne : S.nonempty) : (⨅ i ∈ S, 𝓟 (s i)).has_basis (λ i, i ∈ S) s := ⟨begin refine λ t, (mem_binfi_of_directed _ ne).trans $ by simp only [mem_principal], rw [directed_on_iff_directed, ← directed_comp, (∘)] at h ⊢, apply h.mono_comp _ _, exact λ _ _, principal_mono.2 end⟩ lemma has_basis_binfi_principal' (h : ∀ i, p i → ∀ j, p j → ∃ k (h : p k), s k ⊆ s i ∧ s k ⊆ s j) (ne : ∃ i, p i) : (⨅ i (h : p i), 𝓟 (s i)).has_basis p s := filter.has_basis_binfi_principal h ne lemma has_basis.map (f : α → β) (hl : l.has_basis p s) : (l.map f).has_basis p (λ i, f '' (s i)) := ⟨λ t, by simp only [mem_map, image_subset_iff, hl.mem_iff, preimage]⟩ lemma has_basis.comap (f : β → α) (hl : l.has_basis p s) : (l.comap f).has_basis p (λ i, f ⁻¹' (s i)) := ⟨begin intro t, simp only [mem_comap, exists_prop, hl.mem_iff], split, { rintros ⟨t', ⟨i, hi, ht'⟩, H⟩, exact ⟨i, hi, subset.trans (preimage_mono ht') H⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, ⟨i, hi, subset.refl _⟩, H⟩ } end⟩ lemma comap_has_basis (f : α → β) (l : filter β) : has_basis (comap f l) (λ s : set β, s ∈ l) (λ s, f ⁻¹' s) := ⟨λ t, mem_comap⟩ lemma has_basis.prod_self (hl : l.has_basis p s) : (l ×ᶠ l).has_basis p (λ i, (s i).prod (s i)) := ⟨begin intro t, apply mem_prod_iff.trans, split, { rintros ⟨t₁, ht₁, t₂, ht₂, H⟩, rcases hl.mem_iff.1 (inter_mem ht₁ ht₂) with ⟨i, hi, ht⟩, exact ⟨i, hi, λ p ⟨hp₁, hp₂⟩, H ⟨(ht hp₁).1, (ht hp₂).2⟩⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, hl.mem_of_mem hi, s i, hl.mem_of_mem hi, H⟩ } end⟩ lemma mem_prod_self_iff {s} : s ∈ l ×ᶠ l ↔ ∃ t ∈ l, set.prod t t ⊆ s := l.basis_sets.prod_self.mem_iff lemma has_basis.sInter_sets (h : has_basis l p s) : ⋂₀ l.sets = ⋂ i ∈ set_of p, s i := begin ext x, suffices : (∀ t ∈ l, x ∈ t) ↔ ∀ i, p i → x ∈ s i, by simpa only [mem_Inter, mem_set_of_eq, mem_sInter], simp_rw h.mem_iff, split, { intros h i hi, exact h (s i) ⟨i, hi, subset.refl _⟩ }, { rintros h _ ⟨i, hi, sub⟩, exact sub (h i hi) }, end variables [preorder ι] (l p s) /-- `is_antimono_basis p s` means the image of `s` bounded by `p` is a filter basis such that `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/ structure is_antimono_basis extends is_basis p s : Prop := (decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i) (mono : monotone p) /-- We say that a filter `l` has a antimono basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/ structure has_antimono_basis [preorder ι] (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop := (decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i) (mono : monotone p) end same_type section two_types variables {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β} lemma has_basis.tendsto_left_iff (hla : la.has_basis pa sa) : tendsto f la lb ↔ ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t := by { simp only [tendsto, (hla.map f).le_iff, image_subset_iff], refl } lemma has_basis.tendsto_right_iff (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := by simpa only [tendsto, hlb.ge_iff, mem_map, filter.eventually] lemma has_basis.tendsto_iff (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := by simp [hlb.tendsto_right_iff, hla.eventually_iff] lemma tendsto.basis_left (H : tendsto f la lb) (hla : la.has_basis pa sa) : ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t := hla.tendsto_left_iff.1 H lemma tendsto.basis_right (H : tendsto f la lb) (hlb : lb.has_basis pb sb) : ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := hlb.tendsto_right_iff.1 H lemma tendsto.basis_both (H : tendsto f la lb) (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := (hla.tendsto_iff hlb).1 H lemma has_basis.prod (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la ×ᶠ lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := (hla.comap prod.fst).inf (hlb.comap prod.snd) lemma has_basis.prod' {la : filter α} {lb : filter β} {ι : Type*} {p : ι → Prop} {sa : ι → set α} {sb : ι → set β} (hla : la.has_basis p sa) (hlb : lb.has_basis p sb) (h_dir : ∀ {i j}, p i → p j → ∃ k, p k ∧ sa k ⊆ sa i ∧ sb k ⊆ sb j) : (la ×ᶠ lb).has_basis p (λ i, (sa i).prod (sb i)) := ⟨begin intros t, rw mem_prod_iff, split, { rintros ⟨u, u_in, v, v_in, huv⟩, rcases hla.mem_iff.mp u_in with ⟨i, hi, si⟩, rcases hlb.mem_iff.mp v_in with ⟨j, hj, sj⟩, rcases h_dir hi hj with ⟨k, hk, ki, kj⟩, use [k, hk], calc (sa k).prod (sb k) ⊆ (sa i).prod (sb j) : set.prod_mono ki kj ... ⊆ u.prod v : set.prod_mono si sj ... ⊆ t : huv, }, { rintro ⟨i, hi, h⟩, exact ⟨sa i, hla.mem_of_mem hi, sb i, hlb.mem_of_mem hi, h⟩ }, end⟩ end two_types /-- `is_countably_generated f` means `f = generate s` for some countable `s`. -/ def is_countably_generated (f : filter α) : Prop := ∃ s : set (set α), countable s ∧ f = generate s /-- `is_countable_basis p s` means the image of `s` bounded by `p` is a countable filter basis. -/ structure is_countable_basis (p : ι → Prop) (s : ι → set α) extends is_basis p s : Prop := (countable : countable $ set_of p) /-- We say that a filter `l` has a countable basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and the set defined by `p` is countable. -/ structure has_countable_basis (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop := (countable : countable $ set_of p) /-- A countable filter basis `B` on a type `α` is a nonempty countable collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure countable_filter_basis (α : Type*) extends filter_basis α := (countable : countable sets) -- For illustration purposes, the countable filter basis defining (at_top : filter ℕ) instance nat.inhabited_countable_filter_basis : inhabited (countable_filter_basis ℕ) := ⟨{ countable := countable_range (λ n, Ici n), ..(default $ filter_basis ℕ),}⟩ lemma antimono_seq_of_seq (s : ℕ → set α) : ∃ t : ℕ → set α, (∀ i j, i ≤ j → t j ⊆ t i) ∧ (⨅ i, 𝓟 $ s i) = ⨅ i, 𝓟 (t i) := begin use λ n, ⋂ m ≤ n, s m, split, { exact λ i j hij, bInter_mono' (Iic_subset_Iic.2 hij) (λ n hn, subset.refl _) }, apply le_antisymm; rw le_infi_iff; intro i, { rw le_principal_iff, refine (bInter_mem (finite_le_nat _)).2 (λ j hji, _), rw ← le_principal_iff, apply infi_le_of_le j _, apply le_refl _ }, { apply infi_le_of_le i _, rw principal_mono, intro a, simp, intro h, apply h, refl }, end lemma countable_binfi_eq_infi_seq [complete_lattice α] {B : set ι} (Bcbl : countable B) (Bne : B.nonempty) (f : ι → α) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin rw countable_iff_exists_surjective_to_subtype Bne at Bcbl, rcases Bcbl with ⟨g, gsurj⟩, rw infi_subtype', use (λ n, g n), apply le_antisymm; rw le_infi_iff, { intro i, apply infi_le_of_le (g i) _, apply le_refl _ }, { intros a, rcases gsurj a with ⟨i, rfl⟩, apply infi_le } end lemma countable_binfi_eq_infi_seq' [complete_lattice α] {B : set ι} (Bcbl : countable B) (f : ι → α) {i₀ : ι} (h : f i₀ = ⊤) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin cases B.eq_empty_or_nonempty with hB Bnonempty, { rw [hB, infi_emptyset], use λ n, i₀, simp [h] }, { exact countable_binfi_eq_infi_seq Bcbl Bnonempty f } end lemma countable_binfi_principal_eq_seq_infi {B : set (set α)} (Bcbl : countable B) : ∃ (x : ℕ → set α), (⨅ t ∈ B, 𝓟 t) = ⨅ i, 𝓟 (x i) := countable_binfi_eq_infi_seq' Bcbl 𝓟 principal_univ namespace is_countably_generated /-- A set generating a countably generated filter. -/ def generating_set {f : filter α} (h : is_countably_generated f) := classical.some h lemma countable_generating_set {f : filter α} (h : is_countably_generated f) : countable h.generating_set := (classical.some_spec h).1 lemma eq_generate {f : filter α} (h : is_countably_generated f) : f = generate h.generating_set := (classical.some_spec h).2 /-- A countable filter basis for a countably generated filter. -/ def countable_filter_basis {l : filter α} (h : is_countably_generated l) : countable_filter_basis α := { countable := (countable_set_of_finite_subset h.countable_generating_set).image _, ..filter_basis.of_sets (h.generating_set) } lemma filter_basis_filter {l : filter α} (h : is_countably_generated l) : h.countable_filter_basis.to_filter_basis.filter = l := begin conv_rhs { rw h.eq_generate }, apply of_sets_filter_eq_generate, end lemma has_countable_basis {l : filter α} (h : is_countably_generated l) : l.has_countable_basis (λ t, finite t ∧ t ⊆ h.generating_set) (λ t, ⋂₀ t) := ⟨by convert has_basis_generate _ ; exact h.eq_generate, countable_set_of_finite_subset h.countable_generating_set⟩ lemma exists_countable_infi_principal {f : filter α} (h : f.is_countably_generated) : ∃ s : set (set α), countable s ∧ f = ⨅ t ∈ s, 𝓟 t := begin let B := h.countable_filter_basis, use [B.sets, B.countable], rw ← h.filter_basis_filter, rw B.to_filter_basis.eq_infi_principal, rw infi_subtype'' end lemma exists_seq {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 (x i) := begin rcases cblb.exists_countable_infi_principal with ⟨B, Bcbl, rfl⟩, exact countable_binfi_principal_eq_seq_infi Bcbl, end /-- If `f` is countably generated and `f.has_basis p s`, then `f` admits a decreasing basis enumerated by natural numbers such that all sets have the form `s i`. More precisely, there is a sequence `i n` such that `p (i n)` for all `n` and `s (i n)` is a decreasing sequence of sets which forms a basis of `f`-/ lemma exists_antimono_subbasis {f : filter α} (cblb : f.is_countably_generated) {p : ι → Prop} {s : ι → set α} (hs : f.has_basis p s) : ∃ x : ℕ → ι, (∀ i, p (x i)) ∧ f.has_antimono_basis (λ _, true) (λ i, s (x i)) := begin rcases cblb.exists_seq with ⟨x', hx'⟩, have : ∀ i, x' i ∈ f := λ i, hx'.symm ▸ (infi_le (λ i, 𝓟 (x' i)) i) (mem_principal_self _), let x : ℕ → {i : ι // p i} := λ n, nat.rec_on n (hs.index _ $ this 0) (λ n xn, (hs.index _ $ inter_mem (this $ n + 1) (hs.mem_of_mem xn.coe_prop))), have x_mono : ∀ n : ℕ, s (x n.succ) ⊆ s (x n) := λ n, subset.trans (hs.set_index_subset _) (inter_subset_right _ _), replace x_mono : ∀ ⦃i j⦄, i ≤ j → s (x j) ≤ s (x i), { refine @monotone_nat_of_le_succ (order_dual $ set α) _ _ _, exact x_mono }, have x_subset : ∀ i, s (x i) ⊆ x' i, { rintro (_|i), exacts [hs.set_index_subset _, subset.trans (hs.set_index_subset _) (inter_subset_left _ _)] }, refine ⟨λ i, x i, λ i, (x i).2, _⟩, have : (⨅ i, 𝓟 (s (x i))).has_antimono_basis (λ _, true) (λ i, s (x i)) := ⟨has_basis_infi_principal (directed_of_sup x_mono), λ i j _ _ hij, x_mono hij, monotone_const⟩, convert this, exact le_antisymm (le_infi $ λ i, le_principal_iff.2 $ by cases i; apply hs.set_index_mem) (hx'.symm ▸ le_infi (λ i, le_principal_iff.2 $ this.to_has_basis.mem_iff.2 ⟨i, trivial, x_subset i⟩)) end /-- A countably generated filter admits a basis formed by a monotonically decreasing sequence of sets. -/ lemma exists_antimono_basis {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x := let ⟨x, hxf, hx⟩ := cblb.exists_antimono_subbasis f.basis_sets in ⟨x, hx⟩ end is_countably_generated lemma has_countable_basis.is_countably_generated {f : filter α} {p : ι → Prop} {s : ι → set α} (h : f.has_countable_basis p s) : f.is_countably_generated := ⟨{t | ∃ i, p i ∧ s i = t}, h.countable.image s, h.to_has_basis.eq_generate⟩ lemma is_countably_generated_seq (x : ℕ → set α) : is_countably_generated (⨅ i, 𝓟 $ x i) := begin rcases antimono_seq_of_seq x with ⟨y, am, h⟩, rw h, use [range y, countable_range _], rw (has_basis_infi_principal _).eq_generate, { simp [range] }, { exact directed_of_sup am }, { use 0 }, end lemma is_countably_generated_of_seq {f : filter α} (h : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 $ x i) : f.is_countably_generated := let ⟨x, h⟩ := h in by rw h ; apply is_countably_generated_seq lemma is_countably_generated_binfi_principal {B : set $ set α} (h : countable B) : is_countably_generated (⨅ (s ∈ B), 𝓟 s) := is_countably_generated_of_seq (countable_binfi_principal_eq_seq_infi h) lemma is_countably_generated_iff_exists_antimono_basis {f : filter α} : is_countably_generated f ↔ ∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x := begin split, { exact λ h, h.exists_antimono_basis }, { rintros ⟨x, h⟩, rw h.to_has_basis.eq_infi, exact is_countably_generated_seq x }, end lemma is_countably_generated_principal (s : set α) : is_countably_generated (𝓟 s) := begin rw show 𝓟 s = ⨅ i : ℕ, 𝓟 s, by simp, apply is_countably_generated_seq end namespace is_countably_generated lemma inf {f g : filter α} (hf : is_countably_generated f) (hg : is_countably_generated g) : is_countably_generated (f ⊓ g) := begin rw is_countably_generated_iff_exists_antimono_basis at hf hg, rcases hf with ⟨s, hs⟩, rcases hg with ⟨t, ht⟩, exact has_countable_basis.is_countably_generated ⟨hs.to_has_basis.inf ht.to_has_basis, set.countable_encodable _⟩ end lemma inf_principal {f : filter α} (h : is_countably_generated f) (s : set α) : is_countably_generated (f ⊓ 𝓟 s) := h.inf (filter.is_countably_generated_principal s) lemma exists_antimono_seq' {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ ∀ {s}, (s ∈ f ↔ ∃ i, x i ⊆ s) := let ⟨x, hx⟩ := is_countably_generated_iff_exists_antimono_basis.mp cblb in ⟨x, λ i j, hx.decreasing trivial trivial, λ s, by simp [hx.to_has_basis.mem_iff]⟩ protected lemma comap {l : filter β} (h : l.is_countably_generated) (f : α → β) : (comap f l).is_countably_generated := let ⟨x, hx_mono⟩ := h.exists_antimono_basis in is_countably_generated_of_seq ⟨_, (hx_mono.to_has_basis.comap _).eq_infi⟩ end is_countably_generated end filter
d8fdb71c0a11a91aab1a9b4d92ff6214798f78f7
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/analysis/normed_space/deriv.lean
80fc8b49f9e94b7a1b0aac299ace64097ad2bf29
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
14,819
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The Fréchet derivative. Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[k] F` a bounded k-linear map. Then `has_fderiv_at_within f f' x s` 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_at_within f f' x univ` The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. -/ import topology.basic topology.sequences topology.opens import analysis.normed_space.operator_norm import analysis.asymptotics import tactic.abel open filter asymptotics bounded_linear_map section variables {k : Type*} [normed_field k] variables {E : Type*} [normed_space k E] variables {F : Type*} [normed_space k F] variables {G : Type*} [normed_space k G] variables (c : k) variables (f : E → F) (f' : E →L[k] F) variables (x : E) (s: set E) (L : filter E) def has_fderiv_at_filter := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L def has_fderiv_at_within := has_fderiv_at_filter f f' x (nhds_within x s) def has_fderiv_at := has_fderiv_at_filter f f' x (nhds x) variables {f} {f₀ f₁ g: E → F} variables {f'} {f₀' f₁' g': E →L[k] F} variables {x} variables {s} {t : set E} variables {L} {L₁ L₂ : filter E} 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_at_within_iff_tendsto : has_fderiv_at_within f f' x s ↔ 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 (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₂ → has_fderiv_at_filter f f' x L₁ := is_o.mono hst theorem has_fderiv_at_within.mono (hst : s ⊆ t) : has_fderiv_at_within f f' x t → has_fderiv_at_within f f' x s := has_fderiv_at_filter.mono (nhds_within_mono _ hst) theorem has_fderiv_at_filter_of_has_fderiv_at (hL : L ≤ nhds x) (h : has_fderiv_at f f' x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at_within_of_has_fderiv_at : has_fderiv_at f f' x → has_fderiv_at_within f f' x s := has_fderiv_at_filter_of_has_fderiv_at lattice.inf_le_left 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_at_within_congr (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_within f₀ f₀' x s ↔ has_fderiv_at_within f₁ f₁' x s := has_fderiv_at_filter_congr h₀ h₁ theorem has_fderiv_at_within.congr (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_within f₀ f₀' x s → has_fderiv_at_within f₁ f₁' x s := (has_fderiv_at_within_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 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_at_within_id (x : E) (s : set E) : has_fderiv_at_within id (id : E →L[k] E) x s := 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 _ _ 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_at_within_const (c : F) (x : E) (s : set E) : has_fderiv_at_within (λ x, c) (0 : E →L[k] F) x s := 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 _ _ _ set_option class.instance_max_depth 43 theorem has_fderiv_at_filter_smul (h : has_fderiv_at_filter f f' x L) : 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_at_within_smul (h : has_fderiv_at_within f f' x s) : has_fderiv_at_within (λ x, c • f x) (c • f') x s := has_fderiv_at_filter_smul _ h theorem has_fderiv_at_smul (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, c • f x) (c • f') x := has_fderiv_at_filter_smul _ h 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 (λ x, f x + g x) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp theorem has_fderiv_at_within_add (hf : has_fderiv_at_within f f' x s) (hg : has_fderiv_at_within g g' x s) : has_fderiv_at_within (λ x, f x + g x) (f' + g') x s := has_fderiv_at_filter_add hf 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 := has_fderiv_at_filter_add hf hg 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 := (has_fderiv_at_filter_smul (-1 : k) h).congr (by simp) (by simp) theorem has_fderiv_at_within_neg (h : has_fderiv_at_within f f' x s) : has_fderiv_at_within (λ x, -f x) (-f') x s := has_fderiv_at_filter_neg h theorem has_fderiv_at_neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := has_fderiv_at_filter_neg h 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 := has_fderiv_at_filter_add hf (has_fderiv_at_filter_neg hg) theorem has_fderiv_at_within_sub (hf : has_fderiv_at_within f f' x s) (hg : has_fderiv_at_within g g' x s) : has_fderiv_at_within (λ x, f x - g x) (f' - g') x s := has_fderiv_at_filter_sub hf 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 := has_fderiv_at_filter_sub hf hg 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 _ _) 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_at_within.continuous_at_within (h : has_fderiv_at_within f f' x s) : continuous_at_within f x s := 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 theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[k] G} (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' (f x) (L.map f)) : 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} (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' (f x) (L.map f)) : 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_at_within.comp {g : F → G} {g' : F →L[k] G} (hf : has_fderiv_at_within f f' x s) (hg : has_fderiv_at_within g g' (f x) (f '' s)) : has_fderiv_at_within (g ∘ f) (g'.comp f') x s := hf.comp (has_fderiv_at_filter.mono hf.continuous_at_within.tendsto_nhds_within_image hg) /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[k] G} (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' (f x)) : has_fderiv_at (g ∘ f) (g'.comp f') x := hf.comp (hg.mono hf.continuous_at) end section variables (k : Type*) [nondiscrete_normed_field k] variables {E : Type*} [normed_space k E] variables {F : Type*} [normed_space k F] open topological_space set_option class.instance_max_depth 55 /-- The differential of a map at a point along a filter is unique, given that filter is coarser than the neighbourhood filter of the point.-/ lemma fderiv_at_filter_unique (f : E → F) (x₀ : E) {L : filter E} (h : nhds x₀ ≤ L) {A₁ A₂ : E →L[k] F} : has_fderiv_at_filter f A₁ x₀ L → has_fderiv_at_filter f A₂ x₀ L → A₁ = A₂ := assume (eq₁ : is_o (λ x, f x - f x₀ - A₁ (x - x₀)) (λ x, x - x₀) L) (eq₂ : is_o (λ x, f x - f x₀ - A₂ (x - x₀)) (λ x, x - x₀) L), -- To prove that A₁ = A₂, substract eq₁ and eq₂. After some calculation this implies -- that for ∀ v ∈ E, lim_{n→∞} A₂ v - A₁ v = 0. We first show that this implies the claim -- using the uniqueness of limits in normed spaces. suffices ∀ v : E, tendsto (λ n : ℕ, A₂ v - A₁ v) at_top (nhds 0), begin ext v, symmetry, rw [←sub_eq_zero_iff_eq], symmetry, exact tendsto_nhds_unique at_top_ne_bot (this v) tendsto_const_nhds end, assume v, -- substract the equations eq₁ and eq₂ showing that A₁ and A₂ are differential have is_o (λ x, A₂ (x - x₀) - A₁ (x - x₀)) (λ x, x - x₀) L, by simpa using eq₁.sub eq₂, -- pick ξ ≠ 0, ∥ξ∥ < 1 and plugin in the sequence ξ^n + x₀, replace filter by at_top let ⟨ξ, _, _⟩ := exists_norm_lt_one k in have is_o (λ n, A₂ (ξ^n • v) - A₁ (ξ^n • v)) (λ n, ξ^n • v) (comap ((λ n:ℕ, x₀ + ξ^n • v)) (nhds x₀)), by simpa [function.comp] using ((this.comp (λ (n : ℕ), ξ^n • v + x₀)).mono (comap_mono h)), -- refine the filter to at_top have at_top_is_finer : at_top ≤ comap (λ (n : ℕ), (ξ^n) • v + x₀) (nhds x₀), begin rw ←tendsto_iff_comap, have : continuous (λ c : k, c • v + x₀) := continuous_add (continuous_smul continuous_id continuous_const) continuous_const, simpa using ‹continuous (λ c : k, c • v + x₀)›.to_sequentially_continuous (λ n, ξ^n) (tendsto_pow_at_top_nhds_0_of_lt_1_normed_field ‹∥ξ∥ < 1›) end, -- and use monotonicity of little o have is_o (λ n : ℕ, A₂ (ξ^n • v) - A₁ (ξ^n • v)) (λ n, ξ^n • v) at_top, from is_o.mono at_top_is_finer (by simpa using this), -- the ξ^n factor cancels have is_o (λ (x : ℕ), A₂ v - A₁ v) (λ (x : ℕ), v) at_top, begin convert @is_o_smul _ _ _ _ _ _ _ (λ n : ℕ, (ξ^n)⁻¹) _ _ _ this using 1; simp [smul_smul, smul_add, inv_mul_cancel ((λ n, pow_ne_zero n ((norm_pos_iff ξ).mp ‹0 < ∥ξ∥›)) _)] end, show tendsto (λ (n : ℕ), A₂ v - A₁ v) at_top (nhds 0), from is_o_one_iff.mp (this.trans_is_O (is_O_const_one v _) : is_o _ (λ n, (1:k)) _) theorem fderiv_at_unique (f : E → F) (x₀ : E) {A₁ A₂ : E →L[k] F} : has_fderiv_at f A₁ x₀ → has_fderiv_at f A₂ x₀ → A₁ = A₂ := assume H₁ H₂, fderiv_at_filter_unique k f x₀ (le_refl (nhds x₀)) H₁ H₂ theorem fderiv_at_within_open_unique (f : E → F) (U : opens E) (x₀ : U) {A₁ A₂ : E →L[k] F} : has_fderiv_at_within f A₁ x₀ U → has_fderiv_at_within f A₂ x₀ U → A₁ = A₂ := assume H₁ H₂, fderiv_at_filter_unique k f x₀ (le_of_eq $ eq.symm (nhds_within_eq_of_open x₀.2 U.2)) H₁ H₂ 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_space ℝ E] variables {F : Type*} [normed_space ℝ F] variables {G : Type*} [normed_space ℝ G] set_option class.instance_max_depth 34 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
c825d299c46e0121a3fbc7f415342463a13e84d5
5ee26964f602030578ef0159d46145dd2e357ba5
/src/r_o_d_completion.lean
3de1a4cfded067bde186eabff61bfd99ba58ccfc
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
10,255
lean
-- rational open data completion stuff. -- In this file we show that r_o_d_completion r := A<T/s> -- satisfies the property that if v in D(T1,s1) ⊂ D(T2,s2) then -- the maps A<Ti/si> - > K_v-hat commute with the restriction map. -- We then, assuming D(T,s) are a basis for Spa(A), show that -- we can get maps O_X(U) -> K_v-hat for an arbitrary open with v ∈ U. -- we need this for the valuations on the stalks. import valuation.localization_Huber import for_mathlib.sheaves.stalk_of_rings -- for defining valuations on stalks --import valuation.field -- where KB just dumped valuation_on_completion variable {A : Huber_pair} open topological_space valuation Spv spa namespace spa.r_o_d_completion section scary_uniform_space_instance set_option class.instance_max_depth 100 noncomputable def uniform_space' (v : spa A) : uniform_space (valuation_field (out (v.val))) := topological_add_group.to_uniform_space _ local attribute [instance] uniform_space' instance (v : spa A) : uniform_add_group (valuation_field (out (v.val))) := topological_add_group_is_uniform noncomputable def to_complete_valuation_field {r : rational_open_data A} {v : spa A} (hv : v ∈ r.rational_open) : r_o_d_completion r → ring_completion (valuation_field (Spv.out v.1)) := ring_completion.map (Huber_pair.rational_open_data.to_valuation_field hv) example {r : rational_open_data A} {v : spa A} (hv : v ∈ r.rational_open) : is_ring_hom (Huber_pair.rational_open_data.to_valuation_field hv) := by apply_instance example {r : rational_open_data A} {v : spa A} (hv : v ∈ r.rational_open) : is_ring_hom (Huber_pair.rational_open_data.to_valuation_field hv) := by apply_instance instance {r : rational_open_data A} {v : spa A} (hv : v ∈ r.rational_open) : is_ring_hom (to_complete_valuation_field hv) := ring_completion.map_is_ring_hom (rational_open_data.localization r) (valuation_field (Spv.out v.1)) (Huber_pair.rational_open_data.to_valuation_field_cts hv) -- next we need to show that the completed maps to K_v-hat all commute with the -- restriction maps /-- the maps from rationals opens to completions commute with allowable restriction maps-/ theorem to_valuation_field_commutes {r1 r2 : spa.rational_open_data A} {v : spa A} (hv1 : v ∈ r1.rational_open) (hv2 : v ∈ r2.rational_open) (h : r1 ≤ r2) : (to_complete_valuation_field hv1) = (to_complete_valuation_field hv2) ∘ (r_o_d_completion.restriction h) := begin delta to_complete_valuation_field, delta r_o_d_completion.restriction, let uc1 : uniform_continuous (rational_open_data.localization_map h) := localization_map_is_uniform_continuous h, let uc2 : continuous (Huber_pair.rational_open_data.to_valuation_field hv2) := Huber_pair.rational_open_data.to_valuation_field_cts hv2, rw Huber_pair.rational_open_data.to_valuation_field_commutes hv1 hv2 h, -- is the noncompleted commute. convert ring_completion.map_comp uc1 _, apply uniform_continuous_of_continuous uc2, end end scary_uniform_space_instance end spa.r_o_d_completion -- Now we need to show that for any O_X(U) with v in U we have a map -- to K_v-hat. We do this under the additional assumption that D(T,s) is a basis. -- First let's write a noncomputable function which gets a basis element. -- def rational_basis (A : Huber_pair) : set (set (spa A)) := -- {U : set (spa A) | ∃ r : rational_open_data A, U = r.rational_open } lemma spa.exists_rational_open_subset {v : spa A} {U : opens (spa A)} (hv : v ∈ U) : ∃ r : rational_open_data_subsets U, v ∈ r.1.rational_open := begin suffices : U.1 ∈ nhds v, rw mem_nhds_of_is_topological_basis (rational_basis.is_basis A) at this, rcases this with ⟨_, ⟨r, rfl⟩, hv, hr⟩, use ⟨r, hr⟩, exact hv, apply mem_nhds_sets U.2 hv, end noncomputable def spa.rational_open_subset_nhd {v : spa A} {U : opens (spa A)} (hv : v ∈ U) : rational_open_data_subsets U := classical.some $ spa.exists_rational_open_subset hv def spa.mem_rational_open_subset_nhd {v : spa A} {U : opens (spa A)} (hv : v ∈ U) : v ∈ (spa.rational_open_subset_nhd hv).1.rational_open := classical.some_spec $ spa.exists_rational_open_subset hv namespace spa.presheaf section scary_uniform_space_instance set_option class.instance_max_depth 100 noncomputable def uniform_space' (v : spa A) : uniform_space (valuation_field (out (v.val))) := topological_add_group.to_uniform_space _ local attribute [instance] uniform_space' /-- The map from F(U) to K_v for v ∈ U -/ noncomputable def to_valuation_field_completion {v : spa A} {U : opens (spa A)} (hv : v ∈ U) (f : spa.presheaf_value U) : ring_completion (valuation_field (Spv.out v.1)) := spa.r_o_d_completion.to_complete_valuation_field (spa.mem_rational_open_subset_nhd hv) $ f.1 $ spa.rational_open_subset_nhd hv instance {v : spa A} {U : opens (spa A)} (hv : v ∈ U) : is_ring_hom (to_valuation_field_completion hv) := begin delta to_valuation_field_completion, let F := (λ (f : presheaf_value U), spa.r_o_d_completion.to_complete_valuation_field (spa.mem_rational_open_subset_nhd hv) (f.val (spa.rational_open_subset_nhd hv))), show is_ring_hom F, have H : F = ((spa.r_o_d_completion.to_complete_valuation_field (spa.mem_rational_open_subset_nhd hv)) ∘ (λ (f : presheaf_value U), (f.val (spa.rational_open_subset_nhd hv)))), refl, rw H, refine is_ring_hom.comp _ _, end end scary_uniform_space_instance -- I need now to prove that if V ⊆ U then to_valuation_field_completion commutes with res -- before we even start with this terrifying noncomputable spa.rational_open_subset_nhd -- let's check that spa.r_o_d_completion.to_complete_valuation_field commutes with ≤ lemma to_valuation_field_completion_well_defined_aux₁ {v : spa A} {U : opens (spa A)} (hv : v ∈ U) (f : spa.presheaf_value U) {r1 r2 : rational_open_data_subsets U} (h1 : v ∈ r1.1.rational_open) (h2 : v ∈ r2.1.rational_open) : spa.r_o_d_completion.to_complete_valuation_field h1 (f.1 r1) = spa.r_o_d_completion.to_complete_valuation_field (begin show v ∈ (rational_open_data.inter r1.1 r2.1).rational_open, rw rational_open_data.rational_open_data_inter, exact ⟨h1, h2⟩ end) (f.1 (rational_open_data_subsets_inter r1 r2)) := begin rw spa.r_o_d_completion.to_valuation_field_commutes h1 _ (rational_open_data.rational_open_data_le_inter_left r1.1 r2.1), swap, rw rational_open_data.rational_open_data_inter, exact ⟨h1, h2⟩, unfold function.comp, congr' 1, -- exact times out here; convert closes the goal really quickly convert f.2 r1 (rational_open_data_subsets_inter r1 r2) _, end -- now the other way lemma to_valuation_field_completion_well_defined_aux₂ {v : spa A} {U : opens (spa A)} (hv : v ∈ U) (f : spa.presheaf_value U) {r1 r2 : rational_open_data_subsets U} (h1 : v ∈ r1.1.rational_open) (h2 : v ∈ r2.1.rational_open) : spa.r_o_d_completion.to_complete_valuation_field h2 (f.1 r2) = spa.r_o_d_completion.to_complete_valuation_field (begin show v ∈ (rational_open_data.inter r1.1 r2.1).rational_open, rw rational_open_data.rational_open_data_inter, exact ⟨h1, h2⟩ end) (f.1 (rational_open_data_subsets_inter r1 r2)) := begin rw spa.r_o_d_completion.to_valuation_field_commutes h2 _ (rational_open_data.rational_open_data_le_inter_right r1.1 r2.1), swap, rw rational_open_data.rational_open_data_inter, exact ⟨h1, h2⟩, unfold function.comp, congr' 1, -- exact times out here; convert closes the goal really quickly convert f.2 r2 (rational_open_data_subsets_inter r1 r2) _, end -- now let's check it agrees on any rational_open_data_subsets lemma to_valuation_field_completion_well_defined_aux₃ {v : spa A} {U : opens (spa A)} (hv : v ∈ U) (f : spa.presheaf_value U) {r1 r2 : rational_open_data_subsets U} (h1 : v ∈ r1.1.rational_open) (h2 : v ∈ r2.1.rational_open) : spa.r_o_d_completion.to_complete_valuation_field h1 (f.1 r1) = spa.r_o_d_completion.to_complete_valuation_field h2 (f.1 r2) := begin rw to_valuation_field_completion_well_defined_aux₁ hv f h1 h2, rw to_valuation_field_completion_well_defined_aux₂ hv f h1 h2, end -- next I will prove that for every r : rational_open_data_subsets U with v ∈ r.1.rational_open, -- f gets sent to the same thing. lemma to_valuation_field_completion_well_defined {v : spa A} {U : opens (spa A)} (hv : v ∈ U) (f : spa.presheaf_value U) (r : rational_open_data_subsets U) (hr : v ∈ r.1.rational_open): to_valuation_field_completion hv f = spa.r_o_d_completion.to_complete_valuation_field hr (f.1 r) := to_valuation_field_completion_well_defined_aux₃ hv f _ hr -- now the main goal /-- If v ∈ U then the map from 𝒪_X(U) to `completion (valuation_field v)` commutes with restriction (so we can get a map from the stalk at v) -/ theorem to_valuation_field_completion_commutes {v : spa A} {U V : opens (spa A)} (hv : v ∈ U) (hUV : U ⊆ V) (f : spa.presheaf_value V) : to_valuation_field_completion (hUV hv) f = to_valuation_field_completion hv (spa.presheaf_map hUV f) := begin -- to_valuation_field_completion involves choosing a random basis element. let rU := spa.rational_open_subset_nhd hv, let rV := spa.rational_open_subset_nhd (hUV hv), -- we now need to intersect these two things. let rUV1 := rational_open_data.inter rU.1 rV.1, rw to_valuation_field_completion_well_defined hv (spa.presheaf_map hUV f) ⟨rUV1, begin rw rational_open_data.rational_open_data_inter, exact set.subset.trans (set.inter_subset_left _ _) rU.2 end⟩ ( begin rw rational_open_data.rational_open_data_inter, split, exact spa.mem_rational_open_subset_nhd hv, exact spa.mem_rational_open_subset_nhd _, end), rw to_valuation_field_completion_well_defined (hUV hv) f ⟨rUV1, begin rw rational_open_data.rational_open_data_inter, exact set.subset.trans (set.inter_subset_right _ _) rV.2 end⟩ ( begin rw rational_open_data.rational_open_data_inter, split, exact spa.mem_rational_open_subset_nhd hv, exact spa.mem_rational_open_subset_nhd _, end), refl, end end spa.presheaf
fd0b502433f0c992bae8262d7dba33c99c3649ae
7cef822f3b952965621309e88eadf618da0c8ae9
/src/order/boolean_algebra.lean
06e487b50dbc4dcc17f38e62c5a793a5d891454c
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
3,820
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 Type class hierarchy for Boolean algebras. -/ import order.bounded_lattice set_option old_structure_cmd true namespace lattice universes u variables {α : Type u} {w x y z : α} section prio set_option default_priority 100 -- see Note [default priority] /-- A boolean algebra is a bounded distributive lattice with a complementation operation `-` such that `x ⊓ - x = ⊥` and `x ⊔ - x = ⊤`. This is a generalization of (classical) logic of propositions, or the powerset lattice. -/ class boolean_algebra α extends bounded_distrib_lattice α, has_neg α, has_sub α := (inf_neg_eq_bot : ∀x:α, x ⊓ - x = ⊥) (sup_neg_eq_top : ∀x:α, x ⊔ - x = ⊤) (sub_eq : ∀x y:α, x - y = x ⊓ - y) end prio section boolean_algebra variables [boolean_algebra α] @[simp] theorem inf_neg_eq_bot : x ⊓ - x = ⊥ := boolean_algebra.inf_neg_eq_bot x @[simp] theorem neg_inf_eq_bot : - x ⊓ x = ⊥ := eq.trans inf_comm inf_neg_eq_bot @[simp] theorem sup_neg_eq_top : x ⊔ - x = ⊤ := boolean_algebra.sup_neg_eq_top x @[simp] theorem neg_sup_eq_top : - x ⊔ x = ⊤ := eq.trans sup_comm sup_neg_eq_top theorem sub_eq : x - y = x ⊓ - y := boolean_algebra.sub_eq x y theorem neg_unique (i : x ⊓ y = ⊥) (s : x ⊔ y = ⊤) : - x = y := calc -x = -x ⊓ (x ⊔ y) : by simp [s] ... = -x ⊓ x ⊔ -x ⊓ y : inf_sup_left ... = y ⊓ x ⊔ y ⊓ -x : by simp [i, inf_comm] ... = y ⊓ (x ⊔ -x) : inf_sup_left.symm ... = y : by simp @[simp] theorem neg_top : - ⊤ = (⊥:α) := neg_unique (by simp) (by simp) @[simp] theorem neg_bot : - ⊥ = (⊤:α) := neg_unique (by simp) (by simp) @[simp] theorem neg_neg : - (- x) = x := neg_unique (by simp) (by simp) theorem neg_eq_neg_of_eq (h : - x = - y) : x = y := have - - x = - - y, from congr_arg has_neg.neg h, by simp [neg_neg] at this; assumption @[simp] theorem neg_eq_neg_iff : - x = - y ↔ x = y := ⟨neg_eq_neg_of_eq, congr_arg has_neg.neg⟩ @[simp] theorem neg_inf : - (x ⊓ y) = -x ⊔ -y := neg_unique -- TODO: try rsimp if it supports custom lemmas (calc (x ⊓ y) ⊓ (- x ⊔ - y) = (y ⊓ (x ⊓ - x)) ⊔ (x ⊓ (y ⊓ - y)) : by rw [inf_sup_left]; ac_refl ... = ⊥ : by simp) (calc (x ⊓ y) ⊔ (- x ⊔ - y) = (- y ⊔ (x ⊔ - x)) ⊓ (- x ⊔ (y ⊔ - y)) : by rw [sup_inf_right]; ac_refl ... = ⊤ : by simp) @[simp] theorem neg_sup : - (x ⊔ y) = -x ⊓ -y := begin [smt] eblast_using [neg_neg, neg_inf] end theorem neg_le_neg (h : y ≤ x) : - x ≤ - y := le_of_inf_eq $ calc -x ⊓ -y = - (x ⊔ y) : neg_sup.symm ... = -x : congr_arg has_neg.neg $ sup_of_le_left h theorem neg_le_neg_iff_le : - y ≤ - x ↔ x ≤ y := ⟨assume h, by have h := neg_le_neg h; simp at h; assumption, neg_le_neg⟩ theorem le_neg_of_le_neg (h : y ≤ - x) : x ≤ - y := have - (- x) ≤ - y, from neg_le_neg h, by simp at this; assumption theorem neg_le_of_neg_le (h : - y ≤ x) : - x ≤ y := have - x ≤ - (- y), from neg_le_neg h, by simp at this; assumption theorem neg_le_iff_neg_le : y ≤ - x ↔ x ≤ - y := ⟨le_neg_of_le_neg, le_neg_of_le_neg⟩ theorem sup_sub_same : x ⊔ (y - x) = x ⊔ y := by simp [sub_eq, sup_inf_left] theorem sub_eq_left (h : x ⊓ y = ⊥) : x - y = x := calc x - y = (x ⊓ -y) ⊔ (x ⊓ y) : by simp [h, sub_eq] ... = (-y ⊓ x) ⊔ (y ⊓ x) : by simp [inf_comm] ... = (-y ⊔ y) ⊓ x : inf_sup_right.symm ... = x : by simp theorem sub_le_sub (h₁ : w ≤ y) (h₂ : z ≤ x) : w - x ≤ y - z := by rw [sub_eq, sub_eq]; from inf_le_inf h₁ (neg_le_neg h₂) end boolean_algebra end lattice
1b530666f49cf9b14f73cebe76dda3a265f182fa
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/finset/fold.lean
fb2d29741216e5ee0b44eea354885c2e0da15f45
[ "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
5,402
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.finset.basic import data.multiset.fold /-! # The fold operation for a commutative associative operation over a finset. -/ namespace finset open multiset variables {α β γ : Type*} /-! ### fold -/ section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation a * b := op a b include hc ha /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left] @[simp] theorem fold_singleton : ({a} : finset α).fold op b f = f a * b := rfl @[simp] theorem fold_map {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← map_add, union_val, inter_val, union_add_inter, map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := begin by_cases (a ∈ s), { rw [← insert_erase h], simp [← ha.assoc, hi.idempotent] }, { apply fold_insert h }, end lemma fold_op_rel_iff_and {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∧ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∧ ∀ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← and_assoc, and_comm (r c (f a)), and_assoc], apply and_congr iff.rfl, split, { rintro ⟨h₁, h₂⟩, intros b hb, rw finset.mem_insert at hb, rcases hb with rfl|hb; solve_by_elim }, { intro h, split, { exact h a (finset.mem_insert_self _ _), }, { intros b hb, apply h b, rw finset.mem_insert, right, exact hb } } end lemma fold_op_rel_iff_or {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∨ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∨ ∃ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← or_assoc, or_comm (r c (f a)), or_assoc], apply or_congr iff.rfl, split, { rintro (h₁|⟨x, hx, h₂⟩), { use a, simp [h₁] }, { refine ⟨x, by simp [hx], h₂⟩ } }, { rintro ⟨x, hx, h⟩, rw mem_insert at hx, cases hx, { left, rwa hx at h }, { right, exact ⟨x, hx, h⟩ } } end omit hc ha section order variables [decidable_linear_order β] (c : β) lemma le_fold_min : c ≤ s.fold min b f ↔ (c ≤ b ∧ ∀ x∈s, c ≤ f x) := fold_op_rel_iff_and $ λ x y z, le_min_iff lemma fold_min_le : s.fold min b f ≤ c ↔ (b ≤ c ∨ ∃ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ ≤ _ ↔ _, exact min_le_iff end lemma lt_fold_min : c < s.fold min b f ↔ (c < b ∧ ∀ x∈s, c < f x) := fold_op_rel_iff_and $ λ x y z, lt_min_iff lemma fold_min_lt : s.fold min b f < c ↔ (b < c ∨ ∃ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ < _ ↔ _, exact min_lt_iff end lemma fold_max_le : s.fold max b f ≤ c ↔ (b ≤ c ∧ ∀ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ ≤ _ ↔ _, exact max_le_iff end lemma le_fold_max : c ≤ s.fold max b f ↔ (c ≤ b ∨ ∃ x∈s, c ≤ f x) := fold_op_rel_iff_or $ λ x y z, le_max_iff lemma fold_max_lt : s.fold max b f < c ↔ (b < c ∧ ∀ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ < _ ↔ _, exact max_lt_iff end lemma lt_fold_max : c < s.fold max b f ↔ (c < b ∨ ∃ x∈s, c < f x) := fold_op_rel_iff_or $ λ x y z, lt_max_iff end order end fold end finset
d8df0dc18b639a7db8da9f13f1017fcc6bf2a683
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/InternalExceptionId.lean
49a78026ab9f511a91a3bc982d0edab93c45f659
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,258
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 -/ namespace Lean structure InternalExceptionId := (idx : Nat := 0) instance : Inhabited InternalExceptionId := ⟨{}⟩ instance : HasBeq InternalExceptionId := ⟨fun id₁ id₂ => id₁.idx == id₂.idx⟩ def mkInternalExceptionsRef : IO (IO.Ref (Array Name)) := IO.mkRef #[] @[init mkInternalExceptionsRef] constant internalExceptionsRef : IO.Ref (Array Name) := arbitrary _ def registerInternalExceptionId (name : Name) : IO InternalExceptionId := do exs ← internalExceptionsRef.get; when (exs.contains name) $ throw $ IO.userError ("invalid internal exception id, '" ++ toString name ++ "' has already been used"); let nextIdx := exs.size; internalExceptionsRef.modify fun a => a.push name; pure { idx := nextIdx } def InternalExceptionId.toString (id : InternalExceptionId) : String := "internal exception #" ++ toString id.idx def InternalExceptionId.getName (id : InternalExceptionId) : IO Name := do exs ← internalExceptionsRef.get; let i := id.idx; if h : i < exs.size then pure $ exs.get ⟨i, h⟩ else throw $ IO.userError "invalid internal exception id" end Lean
69a20826614bd6d15d65cc01af451b031ff081e7
680b0d1592ce164979dab866b232f6fa743f2cc8
/library/data/list/sort.lean
0584a8fe96470c2fe2623b8911ee98436bc5665f
[ "Apache-2.0" ]
permissive
syohex/lean
657428ab520f8277fc18cf04bea2ad200dbae782
081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc
refs/heads/master
1,611,274,838,635
1,452,668,188,000
1,452,668,188,000
49,562,028
0
0
null
1,452,675,604,000
1,452,675,602,000
null
UTF-8
Lean
false
false
7,579
lean
/- Copyright (c) 2015 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Naive sort for lists -/ import data.list.comb data.list.set data.list.perm data.list.sorted logic.connectives algebra.order namespace list open decidable nat variable {A : Type} variable (R : A → A → Prop) variable [decR : decidable_rel R] include decR definition min_core : list A → A → A | [] a := a | (b::l) a := if R b a then min_core l b else min_core l a definition min : Π (l : list A), l ≠ nil → A | [] h := absurd rfl h | (a::l) h := min_core R l a variable [decA : decidable_eq A] include decA variable {R} variables (to : total R) (tr : transitive R) (rf : reflexive R) lemma min_core_lemma : ∀ {b l} a, b ∈ l ∨ b = a → R (min_core R l a) b | b [] a h := or.elim h (suppose b ∈ [], absurd this !not_mem_nil) (suppose b = a, assert R a a, from rf a, begin subst b, unfold min_core, assumption end) | b (c::l) a h := or.elim h (suppose b ∈ c :: l, or.elim (eq_or_mem_of_mem_cons this) (suppose b = c, or.elim (em (R c a)) (suppose R c a, assert R (min_core R l b) b, from min_core_lemma _ (or.inr rfl), begin unfold min_core, rewrite [if_pos `R c a`], subst c, assumption end) (suppose ¬ R c a, assert R a c, from or_resolve_right (to c a) this, assert R (min_core R l a) a, from min_core_lemma _ (or.inr rfl), assert R (min_core R l a) c, from tr this `R a c`, begin unfold min_core, rewrite [if_neg `¬ R c a`], subst b, exact `R (min_core R l a) c` end)) (suppose b ∈ l, or.elim (em (R c a)) (suppose R c a, assert R (min_core R l c) b, from min_core_lemma _ (or.inl `b ∈ l`), begin unfold min_core, rewrite [if_pos `R c a`], assumption end) (suppose ¬ R c a, assert R (min_core R l a) b, from min_core_lemma _ (or.inl `b ∈ l`), begin unfold min_core, rewrite [if_neg `¬ R c a`], assumption end))) (suppose b = a, assert R (min_core R l a) b, from min_core_lemma _ (or.inr this), or.elim (em (R c a)) (suppose R c a, assert R (min_core R l c) c, from min_core_lemma _ (or.inr rfl), assert R (min_core R l c) a, from tr this `R c a`, begin unfold min_core, rewrite [if_pos `R c a`], subst b, exact `R (min_core R l c) a` end) (suppose ¬ R c a, begin unfold min_core, rewrite [if_neg `¬ R c a`], assumption end)) lemma min_core_le_of_mem {b : A} {l : list A} (a : A) : b ∈ l → R (min_core R l a) b := assume h : b ∈ l, min_core_lemma to tr rf a (or.inl h) lemma min_core_le {l : list A} (a : A) : R (min_core R l a) a := min_core_lemma to tr rf a (or.inr rfl) lemma min_lemma : ∀ {l} (h : l ≠ nil), all l (R (min R l h)) | [] h := absurd rfl h | (b::l) h := all_of_forall (take x, suppose x ∈ b::l, or.elim (eq_or_mem_of_mem_cons this) (suppose x = b, assert R (min_core R l b) b, from min_core_le to tr rf b, begin subst x, unfold min, assumption end) (suppose x ∈ l, assert R (min_core R l b) x, from min_core_le_of_mem to tr rf _ this, begin unfold min, assumption end)) variable (R) lemma min_core_mem : ∀ l a, min_core R l a ∈ l ∨ min_core R l a = a | [] a := or.inr rfl | (b::l) a := or.elim (em (R b a)) (suppose R b a, begin unfold min_core, rewrite [if_pos `R b a`], apply or.elim (min_core_mem l b), suppose min_core R l b ∈ l, or.inl (mem_cons_of_mem _ this), suppose min_core R l b = b, by rewrite this; exact or.inl !mem_cons end) (suppose ¬ R b a, begin unfold min_core, rewrite [if_neg `¬ R b a`], apply or.elim (min_core_mem l a), suppose min_core R l a ∈ l, or.inl (mem_cons_of_mem _ this), suppose min_core R l a = a, or.inr this end) lemma min_mem : ∀ (l : list A) (h : l ≠ nil), min R l h ∈ l | [] h := absurd rfl h | (a::l) h := begin unfold min, apply or.elim (min_core_mem R l a), suppose min_core R l a ∈ l, mem_cons_of_mem _ this, suppose min_core R l a = a, by rewrite this; apply mem_cons end omit decR private lemma ne_nil {l : list A} {n : nat} : length l = succ n → l ≠ nil := assume h₁ h₂, by rewrite h₂ at h₁; contradiction include decR lemma sort_aux_lemma {l n} (h : length l = succ n) : length (erase (min R l (ne_nil h)) l) = n := have min R l _ ∈ l, from min_mem R l (ne_nil h), assert length (erase (min R l _) l) = pred (length l), from length_erase_of_mem this, by rewrite h at this; exact this definition sort_aux : Π (n : nat) (l : list A), length l = n → list A | 0 l h := [] | (succ n) l h := let m := min R l (ne_nil h) in let l₁ := erase m l in m :: sort_aux n l₁ (sort_aux_lemma R h) definition sort (l : list A) : list A := sort_aux R (length l) l rfl open perm lemma sort_aux_perm : ∀ {n : nat} {l : list A} (h : length l = n), sort_aux R n l h ~ l | 0 l h := by rewrite [↑sort_aux, eq_nil_of_length_eq_zero h] | (succ n) l h := let m := min R l (ne_nil h) in assert leq : length (erase m l) = n, from sort_aux_lemma R h, calc m :: sort_aux R n (erase m l) leq ~ m :: erase m l : perm.skip m (sort_aux_perm leq) ... ~ l : perm_erase (min_mem _ _ _) lemma sort_perm (l : list A) : sort R l ~ l := sort_aux_perm R rfl lemma strongly_sorted_sort_aux : ∀ {n : nat} {l : list A} (h : length l = n), strongly_sorted R (sort_aux R n l h) | 0 l h := !strongly_sorted.base | (succ n) l h := let m := min R l (ne_nil h) in assert leq : length (erase m l) = n, from sort_aux_lemma R h, assert ss : strongly_sorted R (sort_aux R n (erase m l) leq), from strongly_sorted_sort_aux leq, assert all l (R m), from min_lemma to tr rf (ne_nil h), assert hall : all (sort_aux R n (erase m l) leq) (R m), from all_of_forall (take x, suppose x ∈ sort_aux R n (erase m l) leq, have x ∈ erase m l, from mem_perm (sort_aux_perm R leq) this, have x ∈ l, from mem_of_mem_erase this, show R m x, from of_mem_of_all this `all l (R m)`), strongly_sorted.step hall ss variable {R} lemma strongly_sorted_sort_core (to : total R) (tr : transitive R) (rf : reflexive R) (l : list A) : strongly_sorted R (sort R l) := @strongly_sorted_sort_aux _ _ _ _ to tr rf (length l) l rfl lemma sort_eq_of_perm_core {l₁ l₂ : list A} (to : total R) (tr : transitive R) (rf : reflexive R) (asy : anti_symmetric R) (h : l₁ ~ l₂) : sort R l₁ = sort R l₂ := have s₁ : sorted R (sort R l₁), from sorted_of_strongly_sorted (strongly_sorted_sort_core to tr rf l₁), have s₂ : sorted R (sort R l₂), from sorted_of_strongly_sorted (strongly_sorted_sort_core to tr rf l₂), have p : sort R l₁ ~ sort R l₂, from calc sort R l₁ ~ l₁ : sort_perm ... ~ l₂ : h ... ~ sort R l₂ : sort_perm, eq_of_sorted_of_perm tr asy p s₁ s₂ section omit decR lemma strongly_sorted_sort [decidable_linear_order A] (l : list A) : strongly_sorted le (sort le l) := strongly_sorted_sort_core le.total (@le.trans A _) le.refl l lemma sort_eq_of_perm {l₁ l₂ : list A} [decidable_linear_order A] (h : l₁ ~ l₂) : sort le l₁ = sort le l₂ := sort_eq_of_perm_core le.total (@le.trans A _) le.refl (@le.antisymm A _) h end end list
c57835732cf077901ace1d2b1f06b0fce53aeed9
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Meta/UnificationHint.lean
5c17aa6722996e1ab8723f180c2c9bdd3d0160d4
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
5,407
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.ScopedEnvExtension import Lean.Util.Recognizers import Lean.Meta.DiscrTree import Lean.Meta.LevelDefEq import Lean.Meta.SynthInstance namespace Lean.Meta structure UnificationHintEntry where keys : Array DiscrTree.Key val : Name deriving Inhabited structure UnificationHints where discrTree : DiscrTree Name := DiscrTree.empty deriving Inhabited instance : ToFormat UnificationHints where format h := fmt h.discrTree def UnificationHints.add (hints : UnificationHints) (e : UnificationHintEntry) : UnificationHints := { hints with discrTree := hints.discrTree.insertCore e.keys e.val } builtin_initialize unificationHintExtension : SimpleScopedEnvExtension UnificationHintEntry UnificationHints ← registerSimpleScopedEnvExtension { name := `unifHints addEntry := UnificationHints.add initial := {} } structure UnificationConstraint where lhs : Expr rhs : Expr structure UnificationHint where pattern : UnificationConstraint constraints : List UnificationConstraint private partial def decodeUnificationHint (e : Expr) : ExceptT MessageData Id UnificationHint := do decode e #[] where decodeConstraint (e : Expr) : ExceptT MessageData Id UnificationConstraint := match e.eq? with | some (_, lhs, rhs) => return UnificationConstraint.mk lhs rhs | none => throw m!"invalid unification hint constraint, unexpected term{indentExpr e}" decode (e : Expr) (cs : Array UnificationConstraint) : ExceptT MessageData Id UnificationHint := do match e with | Expr.forallE _ d b _ => do let c ← decodeConstraint d if b.hasLooseBVars then throw m!"invalid unification hint constraint, unexpected dependency{indentExpr e}" decode b (cs.push c) | _ => do let p ← decodeConstraint e return { pattern := p, constraints := cs.toList } private partial def validateHint (declName : Name) (hint : UnificationHint) : MetaM Unit := do hint.constraints.forM fun c => do unless (← isDefEq c.lhs c.rhs) do throwError "invalid unification hint, failed to unify constraint left-hand-side{indentExpr c.lhs}\nwith right-hand-side{indentExpr c.rhs}" unless (← isDefEq hint.pattern.lhs hint.pattern.rhs) do throwError "invalid unification hint, failed to unify pattern left-hand-side{indentExpr hint.pattern.lhs}\nwith right-hand-side{indentExpr hint.pattern.rhs}" def addUnificationHint (declName : Name) (kind : AttributeKind) : MetaM Unit := withNewMCtxDepth do let info ← getConstInfo declName match info.value? with | none => throwError "invalid unification hint, it must be a definition" | some val => let (_, _, body) ← lambdaMetaTelescope val match decodeUnificationHint body with | Except.error msg => throwError msg | Except.ok hint => let keys ← DiscrTree.mkPath hint.pattern.lhs validateHint declName hint unificationHintExtension.add { keys := keys, val := declName } kind trace[Meta.debug] "addUnificationHint: {unificationHintExtension.getState (← getEnv)}" builtin_initialize registerBuiltinAttribute { name := `unificationHint descr := "unification hint" add := fun declName stx kind => do Attribute.Builtin.ensureNoArgs stx discard <| addUnificationHint declName kind |>.run } def tryUnificationHints (t s : Expr) : MetaM Bool := do trace[Meta.isDefEq.hint] "{t} =?= {s}" unless (← read).config.unificationHints do return false if t.isMVar then return false let hints := unificationHintExtension.getState (← getEnv) let candidates ← hints.discrTree.getMatch t for candidate in candidates do if (← tryCandidate candidate) then return true return false where isDefEqPattern p e := withReducible <| Meta.isExprDefEqAux p e tryCandidate candidate : MetaM Bool := traceCtx `Meta.isDefEq.hint <| checkpointDefEq do trace[Meta.isDefEq.hint] "trying hint {candidate} at {t} =?= {s}" let cinfo ← getConstInfo candidate let us ← cinfo.levelParams.mapM fun _ => mkFreshLevelMVar let val := cinfo.instantiateValueLevelParams us let (xs, bis, body) ← lambdaMetaTelescope val let hint? ← withConfig (fun cfg => { cfg with unificationHints := false }) do match decodeUnificationHint body with | Except.error _ => return none | Except.ok hint => if (← isDefEqPattern hint.pattern.lhs t <&&> isDefEqPattern hint.pattern.rhs s) then return some hint else return none match hint? with | none => return false | some hint => trace[Meta.isDefEq.hint] "{candidate} succeeded, applying constraints" for c in hint.constraints do unless (← Meta.isExprDefEqAux c.lhs c.rhs) do return false for x in xs, bi in bis do if bi == BinderInfo.instImplicit then match (← trySynthInstance (← inferType x)) with | LOption.some val => unless (← isDefEq x val) do return false | _ => return false return true builtin_initialize registerTraceClass `Meta.isDefEq.hint end Lean.Meta
c03b6d8b7eed72e6f58dec947702e383bb21286a
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/hit/trunc.hlean
3bf63c008838c4799cc8623c601e5044643a5d54
[ "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
680
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: hit.trunc Authors: Floris van Doorn n-truncation of types. Ported from Coq HoTT -/ /- The hit n-truncation is primitive, declared in init.hit. -/ import types.sigma open is_trunc eq equiv is_equiv function prod sum sigma namespace trunc protected definition elim {n : trunc_index} {A : Type} {P : Type} [Pt : is_trunc n P] (H : A → P) : trunc n A → P := trunc.rec H protected definition elim_on {n : trunc_index} {A : Type} {P : Type} (aa : trunc n A) [Pt : is_trunc n P] (H : A → P) : P := elim H aa end trunc
0a5346a0a4525921c31fe260f1f37654fc44645e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/special_functions/exp.lean
24a73fee4cb2afbd51e507db935eecfe78a47964
[ "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
15,244
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne -/ import analysis.asymptotics.theta import analysis.complex.basic import analysis.specific_limits.normed /-! # Complex and real exponential > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove continuity of `complex.exp` and `real.exp`. We also prove a few facts about limits of `real.exp` at infinity. ## Tags exp -/ noncomputable theory open finset filter metric asymptotics set function open_locale classical topology namespace complex variables {z y x : ℝ} lemma exp_bound_sq (x z : ℂ) (hz : ‖z‖ ≤ 1) : ‖exp (x + z) - exp x - z • exp x‖ ≤ ‖exp x‖ * ‖z‖ ^ 2 := calc ‖exp (x + z) - exp x - z * exp x‖ = ‖exp x * (exp z - 1 - z)‖ : by { congr, rw [exp_add], ring } ... = ‖exp x‖ * ‖exp z - 1 - z‖ : norm_mul _ _ ... ≤ ‖exp x‖ * ‖z‖^2 : mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le hz) (norm_nonneg _) lemma locally_lipschitz_exp {r : ℝ} (hr_nonneg : 0 ≤ r) (hr_le : r ≤ 1) (x y : ℂ) (hyx : ‖y - x‖ < r) : ‖exp y - exp x‖ ≤ (1 + r) * ‖exp x‖ * ‖y - x‖ := begin have hy_eq : y = x + (y - x), by abel, have hyx_sq_le : ‖y - x‖ ^ 2 ≤ r * ‖y - x‖, { rw pow_two, exact mul_le_mul hyx.le le_rfl (norm_nonneg _) hr_nonneg, }, have h_sq : ∀ z, ‖z‖ ≤ 1 → ‖exp (x + z) - exp x‖ ≤ ‖z‖ * ‖exp x‖ + ‖exp x‖ * ‖z‖ ^ 2, { intros z hz, have : ‖exp (x + z) - exp x - z • exp x‖ ≤ ‖exp x‖ * ‖z‖ ^ 2, from exp_bound_sq x z hz, rw [← sub_le_iff_le_add', ← norm_smul z (_ : ℂ)], exact (norm_sub_norm_le _ _).trans this }, calc ‖exp y - exp x‖ = ‖exp (x + (y - x)) - exp x‖ : by nth_rewrite 0 hy_eq ... ≤ ‖y - x‖ * ‖exp x‖ + ‖exp x‖ * ‖y - x‖ ^ 2 : h_sq (y - x) (hyx.le.trans hr_le) ... ≤ ‖y - x‖ * ‖exp x‖ + ‖exp x‖ * (r * ‖y - x‖) : add_le_add_left (mul_le_mul le_rfl hyx_sq_le (sq_nonneg _) (norm_nonneg _)) _ ... = (1 + r) * ‖exp x‖ * ‖y - x‖ : by ring, end @[continuity] lemma continuous_exp : continuous exp := continuous_iff_continuous_at.mpr $ λ x, continuous_at_of_locally_lipschitz zero_lt_one (2 * ‖exp x‖) (locally_lipschitz_exp zero_le_one le_rfl x) lemma continuous_on_exp {s : set ℂ} : continuous_on exp s := continuous_exp.continuous_on end complex section complex_continuous_exp_comp variable {α : Type*} open complex lemma filter.tendsto.cexp {l : filter α} {f : α → ℂ} {z : ℂ} (hf : tendsto f l (𝓝 z)) : tendsto (λ x, exp (f x)) l (𝓝 (exp z)) := (continuous_exp.tendsto _).comp hf variables [topological_space α] {f : α → ℂ} {s : set α} {x : α} lemma continuous_within_at.cexp (h : continuous_within_at f s x) : continuous_within_at (λ y, exp (f y)) s x := h.cexp lemma continuous_at.cexp (h : continuous_at f x) : continuous_at (λ y, exp (f y)) x := h.cexp lemma continuous_on.cexp (h : continuous_on f s) : continuous_on (λ y, exp (f y)) s := λ x hx, (h x hx).cexp lemma continuous.cexp (h : continuous f) : continuous (λ y, exp (f y)) := continuous_iff_continuous_at.2 $ λ x, h.continuous_at.cexp end complex_continuous_exp_comp namespace real @[continuity] lemma continuous_exp : continuous exp := complex.continuous_re.comp complex.continuous_of_real.cexp lemma continuous_on_exp {s : set ℝ} : continuous_on exp s := continuous_exp.continuous_on end real section real_continuous_exp_comp variable {α : Type*} open real lemma filter.tendsto.exp {l : filter α} {f : α → ℝ} {z : ℝ} (hf : tendsto f l (𝓝 z)) : tendsto (λ x, exp (f x)) l (𝓝 (exp z)) := (continuous_exp.tendsto _).comp hf variables [topological_space α] {f : α → ℝ} {s : set α} {x : α} lemma continuous_within_at.exp (h : continuous_within_at f s x) : continuous_within_at (λ y, exp (f y)) s x := h.exp lemma continuous_at.exp (h : continuous_at f x) : continuous_at (λ y, exp (f y)) x := h.exp lemma continuous_on.exp (h : continuous_on f s) : continuous_on (λ y, exp (f y)) s := λ x hx, (h x hx).exp lemma continuous.exp (h : continuous f) : continuous (λ y, exp (f y)) := continuous_iff_continuous_at.2 $ λ x, h.continuous_at.exp end real_continuous_exp_comp namespace real variables {α : Type*} {x y z : ℝ} {l : filter α} lemma exp_half (x : ℝ) : exp (x / 2) = sqrt (exp x) := by rw [eq_comm, sqrt_eq_iff_sq_eq, sq, ← exp_add, add_halves]; exact (exp_pos _).le /-- The real exponential function tends to `+∞` at `+∞`. -/ lemma tendsto_exp_at_top : tendsto exp at_top at_top := begin have A : tendsto (λx:ℝ, x + 1) at_top at_top := tendsto_at_top_add_const_right at_top 1 tendsto_id, have B : ∀ᶠ x in at_top, x + 1 ≤ exp x := eventually_at_top.2 ⟨0, λx hx, add_one_le_exp x⟩, exact tendsto_at_top_mono' at_top B A end /-- The real exponential function tends to `0` at `-∞` or, equivalently, `exp(-x)` tends to `0` at `+∞` -/ lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp tendsto_exp_at_top).congr (λx, (exp_neg x).symm) /-- The real exponential function tends to `1` at `0`. -/ lemma tendsto_exp_nhds_0_nhds_1 : tendsto exp (𝓝 0) (𝓝 1) := by { convert continuous_exp.tendsto 0, simp } lemma tendsto_exp_at_bot : tendsto exp at_bot (𝓝 0) := (tendsto_exp_neg_at_top_nhds_0.comp tendsto_neg_at_bot_at_top).congr $ λ x, congr_arg exp $ neg_neg x lemma tendsto_exp_at_bot_nhds_within : tendsto exp at_bot (𝓝[>] 0) := tendsto_inf.2 ⟨tendsto_exp_at_bot, tendsto_principal.2 $ eventually_of_forall exp_pos⟩ @[simp] lemma is_bounded_under_ge_exp_comp (l : filter α) (f : α → ℝ) : is_bounded_under (≥) l (λ x, exp (f x)) := is_bounded_under_of ⟨0, λ x, (exp_pos _).le⟩ @[simp] lemma is_bounded_under_le_exp_comp {f : α → ℝ} : is_bounded_under (≤) l (λ x, exp (f x)) ↔ is_bounded_under (≤) l f := exp_monotone.is_bounded_under_le_comp tendsto_exp_at_top /-- The function `exp(x)/x^n` tends to `+∞` at `+∞`, for any natural number `n` -/ lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top := begin refine (at_top_basis_Ioi.tendsto_iff (at_top_basis' 1)).2 (λ C hC₁, _), have hC₀ : 0 < C, from zero_lt_one.trans_le hC₁, have : 0 < (exp 1 * C)⁻¹ := inv_pos.2 (mul_pos (exp_pos _) hC₀), obtain ⟨N, hN⟩ : ∃ N, ∀ k ≥ N, (↑k ^ n : ℝ) / exp 1 ^ k < (exp 1 * C)⁻¹ := eventually_at_top.1 ((tendsto_pow_const_div_const_pow_of_one_lt n (one_lt_exp_iff.2 zero_lt_one)).eventually (gt_mem_nhds this)), simp only [← exp_nat_mul, mul_one, div_lt_iff, exp_pos, ← div_eq_inv_mul] at hN, refine ⟨N, trivial, λ x hx, _⟩, rw set.mem_Ioi at hx, have hx₀ : 0 < x, from N.cast_nonneg.trans_lt hx, rw [set.mem_Ici, le_div_iff (pow_pos hx₀ _), ← le_div_iff' hC₀], calc x ^ n ≤ ⌈x⌉₊ ^ n : pow_le_pow_of_le_left hx₀.le (nat.le_ceil _) _ ... ≤ exp ⌈x⌉₊ / (exp 1 * C) : (hN _ (nat.lt_ceil.2 hx).le).le ... ≤ exp (x + 1) / (exp 1 * C) : div_le_div_of_le (mul_pos (exp_pos _) hC₀).le (exp_le_exp.2 $ (nat.ceil_lt_add_one hx₀.le).le) ... = exp x / C : by rw [add_comm, exp_add, mul_div_mul_left _ _ (exp_pos _).ne'] end /-- The function `x^n * exp(-x)` tends to `0` at `+∞`, for any natural number `n`. -/ lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_div_pow_at_top n)).congr $ λx, by rw [comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg] /-- The function `(b * exp x + c) / (x ^ n)` tends to `+∞` at `+∞`, for any natural number `n` and any real numbers `b` and `c` such that `b` is positive. -/ lemma tendsto_mul_exp_add_div_pow_at_top (b c : ℝ) (n : ℕ) (hb : 0 < b) : tendsto (λ x, (b * exp x + c) / x ^ n) at_top at_top := begin rcases eq_or_ne n 0 with rfl | hn, { simp only [pow_zero, div_one], exact (tendsto_exp_at_top.const_mul_at_top hb).at_top_add tendsto_const_nhds }, simp only [add_div, mul_div_assoc], exact ((tendsto_exp_div_pow_at_top n).const_mul_at_top hb).at_top_add (tendsto_const_nhds.div_at_top (tendsto_pow_at_top hn)) end /-- The function `(x ^ n) / (b * exp x + c)` tends to `0` at `+∞`, for any natural number `n` and any real numbers `b` and `c` such that `b` is nonzero. -/ lemma tendsto_div_pow_mul_exp_add_at_top (b c : ℝ) (n : ℕ) (hb : 0 ≠ b) : tendsto (λ x, x ^ n / (b * exp x + c)) at_top (𝓝 0) := begin have H : ∀ d e, 0 < d → tendsto (λ (x:ℝ), x^n / (d * (exp x) + e)) at_top (𝓝 0), { intros b' c' h, convert (tendsto_mul_exp_add_div_pow_at_top b' c' n h).inv_tendsto_at_top , ext x, simpa only [pi.inv_apply] using (inv_div _ _).symm }, cases lt_or_gt_of_ne hb, { exact H b c h }, { convert (H (-b) (-c) (neg_pos.mpr h)).neg, { ext x, field_simp, rw [← neg_add (b * exp x) c, neg_div_neg_eq] }, { exact neg_zero.symm } }, end /-- `real.exp` as an order isomorphism between `ℝ` and `(0, +∞)`. -/ def exp_order_iso : ℝ ≃o Ioi (0 : ℝ) := strict_mono.order_iso_of_surjective _ (exp_strict_mono.cod_restrict exp_pos) $ (continuous_exp.subtype_mk _).surjective (by simp only [tendsto_Ioi_at_top, subtype.coe_mk, tendsto_exp_at_top]) (by simp [tendsto_exp_at_bot_nhds_within]) @[simp] lemma coe_exp_order_iso_apply (x : ℝ) : (exp_order_iso x : ℝ) = exp x := rfl @[simp] lemma coe_comp_exp_order_iso : coe ∘ exp_order_iso = exp := rfl @[simp] lemma range_exp : range exp = Ioi 0 := by rw [← coe_comp_exp_order_iso, range_comp, exp_order_iso.range_eq, image_univ, subtype.range_coe] @[simp] lemma map_exp_at_top : map exp at_top = at_top := by rw [← coe_comp_exp_order_iso, ← filter.map_map, order_iso.map_at_top, map_coe_Ioi_at_top] @[simp] lemma comap_exp_at_top : comap exp at_top = at_top := by rw [← map_exp_at_top, comap_map exp_injective, map_exp_at_top] @[simp] lemma tendsto_exp_comp_at_top {f : α → ℝ} : tendsto (λ x, exp (f x)) l at_top ↔ tendsto f l at_top := by rw [← tendsto_comap_iff, comap_exp_at_top] lemma tendsto_comp_exp_at_top {f : ℝ → α} : tendsto (λ x, f (exp x)) at_top l ↔ tendsto f at_top l := by rw [← tendsto_map'_iff, map_exp_at_top] @[simp] lemma map_exp_at_bot : map exp at_bot = 𝓝[>] 0 := by rw [← coe_comp_exp_order_iso, ← filter.map_map, exp_order_iso.map_at_bot, ← map_coe_Ioi_at_bot] @[simp] lemma comap_exp_nhds_within_Ioi_zero : comap exp (𝓝[>] 0) = at_bot := by rw [← map_exp_at_bot, comap_map exp_injective] lemma tendsto_comp_exp_at_bot {f : ℝ → α} : tendsto (λ x, f (exp x)) at_bot l ↔ tendsto f (𝓝[>] 0) l := by rw [← map_exp_at_bot, tendsto_map'_iff] @[simp] lemma comap_exp_nhds_zero : comap exp (𝓝 0) = at_bot := (comap_nhds_within_range exp 0).symm.trans $ by simp @[simp] lemma tendsto_exp_comp_nhds_zero {f : α → ℝ} : tendsto (λ x, exp (f x)) l (𝓝 0) ↔ tendsto f l at_bot := by rw [← tendsto_comap_iff, comap_exp_nhds_zero] lemma is_o_pow_exp_at_top {n : ℕ} : (λ x, x^n) =o[at_top] real.exp := by simpa [is_o_iff_tendsto (λ x hx, ((exp_pos x).ne' hx).elim)] using tendsto_div_pow_mul_exp_add_at_top 1 0 n zero_ne_one @[simp] lemma is_O_exp_comp_exp_comp {f g : α → ℝ} : (λ x, exp (f x)) =O[l] (λ x, exp (g x)) ↔ is_bounded_under (≤) l (f - g) := iff.trans (is_O_iff_is_bounded_under_le_div $ eventually_of_forall $ λ x, exp_ne_zero _) $ by simp only [norm_eq_abs, abs_exp, ← exp_sub, is_bounded_under_le_exp_comp, pi.sub_def] @[simp] lemma is_Theta_exp_comp_exp_comp {f g : α → ℝ} : (λ x, exp (f x)) =Θ[l] (λ x, exp (g x)) ↔ is_bounded_under (≤) l (λ x, |f x - g x|) := by simp only [is_bounded_under_le_abs, ← is_bounded_under_le_neg, neg_sub, is_Theta, is_O_exp_comp_exp_comp, pi.sub_def] @[simp] lemma is_o_exp_comp_exp_comp {f g : α → ℝ} : (λ x, exp (f x)) =o[l] (λ x, exp (g x)) ↔ tendsto (λ x, g x - f x) l at_top := by simp only [is_o_iff_tendsto, exp_ne_zero, ← exp_sub, ← tendsto_neg_at_top_iff, false_implies_iff, implies_true_iff, tendsto_exp_comp_nhds_zero, neg_sub] @[simp] lemma is_o_one_exp_comp {f : α → ℝ} : (λ x, 1 : α → ℝ) =o[l] (λ x, exp (f x)) ↔ tendsto f l at_top := by simp only [← exp_zero, is_o_exp_comp_exp_comp, sub_zero] /-- `real.exp (f x)` is bounded away from zero along a filter if and only if this filter is bounded from below under `f`. -/ @[simp] lemma is_O_one_exp_comp {f : α → ℝ} : (λ x, 1 : α → ℝ) =O[l] (λ x, exp (f x)) ↔ is_bounded_under (≥) l f := by simp only [← exp_zero, is_O_exp_comp_exp_comp, pi.sub_def, zero_sub, is_bounded_under_le_neg] /-- `real.exp (f x)` is bounded away from zero along a filter if and only if this filter is bounded from below under `f`. -/ lemma is_O_exp_comp_one {f : α → ℝ} : (λ x, exp (f x)) =O[l] (λ x, 1 : α → ℝ) ↔ is_bounded_under (≤) l f := by simp only [is_O_one_iff, norm_eq_abs, abs_exp, is_bounded_under_le_exp_comp] /-- `real.exp (f x)` is bounded away from zero and infinity along a filter `l` if and only if `|f x|` is bounded from above along this filter. -/ @[simp] lemma is_Theta_exp_comp_one {f : α → ℝ} : (λ x, exp (f x)) =Θ[l] (λ x, 1 : α → ℝ) ↔ is_bounded_under (≤) l (λ x, |f x|) := by simp only [← exp_zero, is_Theta_exp_comp_exp_comp, sub_zero] end real namespace complex lemma comap_exp_comap_abs_at_top : comap exp (comap abs at_top) = comap re at_top := calc comap exp (comap abs at_top) = comap re (comap real.exp at_top) : by simp only [comap_comap, (∘), abs_exp] ... = comap re at_top : by rw [real.comap_exp_at_top] lemma comap_exp_nhds_zero : comap exp (𝓝 0) = comap re at_bot := calc comap exp (𝓝 0) = comap re (comap real.exp (𝓝 0)) : by simp only [comap_comap, ← comap_abs_nhds_zero, (∘), abs_exp] ... = comap re at_bot : by rw [real.comap_exp_nhds_zero] lemma comap_exp_nhds_within_zero : comap exp (𝓝[≠] 0) = comap re at_bot := have exp ⁻¹' {0}ᶜ = univ, from eq_univ_of_forall exp_ne_zero, by simp [nhds_within, comap_exp_nhds_zero, this] lemma tendsto_exp_nhds_zero_iff {α : Type*} {l : filter α} {f : α → ℂ} : tendsto (λ x, exp (f x)) l (𝓝 0) ↔ tendsto (λ x, re (f x)) l at_bot := by rw [← tendsto_comap_iff, comap_exp_nhds_zero, tendsto_comap_iff] /-- `complex.abs (complex.exp z) → ∞` as `complex.re z → ∞`. TODO: use `bornology.cobounded`. -/ lemma tendsto_exp_comap_re_at_top : tendsto exp (comap re at_top) (comap abs at_top) := comap_exp_comap_abs_at_top ▸ tendsto_comap /-- `complex.exp z → 0` as `complex.re z → -∞`.-/ lemma tendsto_exp_comap_re_at_bot : tendsto exp (comap re at_bot) (𝓝 0) := comap_exp_nhds_zero ▸ tendsto_comap lemma tendsto_exp_comap_re_at_bot_nhds_within : tendsto exp (comap re at_bot) (𝓝[≠] 0) := comap_exp_nhds_within_zero ▸ tendsto_comap end complex
5ddbf1e147b4d92442da61ec078353c50d52678b
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/group_power/basic.lean
0a03c45def955e7044aef88fdf25b58ab1b9712a
[ "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
17,613
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 data.nat.basic import tactic.monotonicity.basic import group_theory.group_action.defs /-! # 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`. Scalar multiplication by naturals and integers is handled by the `•` (`has_scalar.smul`) notation defined elsewhere. ## 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₂} instance monoid.has_pow [monoid M] : has_pow M ℕ := ⟨λ x n, npow n x⟩ instance add_monoid.has_scalar_nat [add_monoid M] : has_scalar ℕ M := ⟨nsmul⟩ attribute [to_additive add_monoid.has_scalar_nat] monoid.has_pow instance div_inv_monoid.has_pow [div_inv_monoid M] : has_pow M ℤ := ⟨λ x n, gpow n x⟩ instance sub_neg_monoid.has_scalar_int [sub_neg_monoid M] : has_scalar ℤ M := ⟨gsmul⟩ attribute [to_additive sub_neg_monoid.has_scalar_int] div_inv_monoid.has_pow @[simp, to_additive nsmul_eq_smul] lemma npow_eq_pow {M : Type*} [monoid M] (n : ℕ) (x : M) : npow n x = x^n := rfl @[simp, to_additive gsmul_eq_smul] lemma gpow_eq_pow {M : Type*} [div_inv_monoid M] (n : ℤ) (x : M) : gpow n x = x^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] attribute [to_additive add_monoid.nsmul_zero'] monoid.npow_zero' @[simp, to_additive] lemma pow_right {a x y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x^n) (y^n) := begin induction n with n ih, { simp [← npow_eq_pow, monoid.npow_zero'], }, { simp only [← npow_eq_pow, nat.succ_eq_add_one, npow_one, npow_add] at ⊢ ih, exact ih.mul_right h } end end semiconj_by namespace commute variables [monoid M] {a b : M} @[simp, to_additive] theorem pow_right (h : commute a b) (n : ℕ) : commute a (b ^ n) := h.pow_right n @[simp, to_additive] theorem pow_left (h : commute a b) (n : ℕ) : commute (a ^ n) b := (h.symm.pow_right n).symm @[simp, to_additive] theorem pow_pow (h : commute a b) (m n : ℕ) : commute (a ^ m) (b ^ n) := (h.pow_left m).pow_right n @[simp, to_additive] theorem self_pow (a : M) (n : ℕ) : commute a (a ^ n) := (commute.refl a).pow_right n @[simp, to_additive] theorem pow_self (a : M) (n : ℕ) : commute (a ^ n) a := (commute.refl a).pow_left n @[simp, to_additive] 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] -- the attributes are intentionally out of order. `zero_smul` proves `zero_nsmul`. @[to_additive zero_nsmul, simp] theorem pow_zero (a : M) : a^0 = 1 := monoid.npow_zero' _ @[to_additive succ_nsmul] theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := by rw [← npow_eq_pow, nat.add_comm, npow_add, npow_one, npow_eq_pow] /-- Note that most of the lemmas about powers of two refer to it as `sq`. -/ @[to_additive two_nsmul] theorem pow_two (a : M) : a^2 = a * a := by rw [← npow_eq_pow, show 2 = 1 + 1, by refl, npow_add, npow_one] alias pow_two ← sq @[to_additive nsmul_add_comm'] theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := commute.pow_self a n @[to_additive succ_nsmul'] theorem pow_succ' (a : M) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] @[to_additive add_nsmul] 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]] @[simp, to_additive one_nsmul] theorem pow_one (a : M) : a^1 = a := by rw [← npow_eq_pow, npow_one] @[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 -- the attributes are intentionally out of order. `smul_zero` proves `nsmul_zero`. @[to_additive nsmul_zero, simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 := by induction n with n ih; [exact pow_zero _, rw [pow_succ, ih, one_mul]] @[to_additive mul_nsmul'] theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := begin induction n with n ih, { rw [nat.mul_zero, pow_zero, pow_zero] }, { rw [nat.mul_succ, pow_add, pow_succ', ih] } end @[to_additive nsmul_left_comm] lemma pow_right_comm (a : M) (m n : ℕ) : (a^m)^n = (a^n)^m := by rw [←pow_mul, nat.mul_comm, pow_mul] @[to_additive mul_nsmul] theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [nat.mul_comm, pow_mul] @[to_additive nsmul_add_sub_nsmul] 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, tsub_add_cancel_of_le h] @[to_additive sub_nsmul_nsmul_add] theorem pow_sub_mul_pow (a : M) {m n : ℕ} (h : m ≤ n) : a ^ (n - m) * a ^ m = a ^ n := by rw [←pow_add, tsub_add_cancel_of_le h] @[to_additive bit0_nsmul] theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ @[to_additive bit1_nsmul] theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] @[to_additive nsmul_add_comm] theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m := commute.pow_pow_self a m n @[simp, to_additive add_monoid_hom.map_nsmul] theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := by rw [pow_zero, pow_zero, f.map_one] | (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow] @[to_additive] 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 only [pow_zero, one_mul]) $ λ 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 @[to_additive bit0_nsmul'] theorem pow_bit0' (a : M) (n : ℕ) : a ^ bit0 n = (a * a) ^ n := by rw [pow_bit0, (commute.refl a).mul_pow] @[to_additive bit1_nsmul'] theorem pow_bit1' (a : M) (n : ℕ) : a ^ bit1 n = (a * a) ^ n * a := by rw [bit1, pow_succ', pow_bit0'] @[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] @[to_additive nsmul_add] theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_pow n /-- The `n`th power map on a commutative monoid for a natural `n`, considered as a morphism of monoids. -/ @[to_additive nsmul_add_monoid_hom "Multiplication by a natural `n` on a commutative additive monoid, considered as a morphism of additive monoids.", simps] def pow_monoid_hom (n : ℕ) : M →* M := { to_fun := (^ n), map_one' := one_pow _, map_mul' := λ a b, mul_pow a b n } -- the below line causes the linter to complain :-/ -- attribute [simps] pow_monoid_hom nsmul_add_monoid_hom lemma dvd_pow {x y : M} (hxy : x ∣ y) : ∀ {n : ℕ} (hn : n ≠ 0), x ∣ y^n | 0 hn := (hn rfl).elim | (n + 1) hn := by { rw pow_succ, exact hxy.mul_right _ } alias dvd_pow ← has_dvd.dvd.pow lemma dvd_pow_self (a : M) {n : ℕ} (hn : n ≠ 0) : a ∣ a^n := dvd_rfl.pow hn end comm_monoid section div_inv_monoid variable [div_inv_monoid G] open int @[simp, norm_cast, to_additive] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := begin induction n with n ih, { change gpow 0 a = a ^ 0, rw [div_inv_monoid.gpow_zero', pow_zero] }, { change gpow (of_nat n) a = a ^ n at ih, change gpow (of_nat n.succ) a = a ^ n.succ, rw [div_inv_monoid.gpow_succ', pow_succ, ih] } end @[to_additive] theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := gpow_coe_nat _ _ @[simp, to_additive] theorem gpow_neg_succ_of_nat (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := by { rw ← gpow_coe_nat, exact div_inv_monoid.gpow_neg' n a } @[simp, to_additive zero_gsmul] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := by { convert pow_zero a using 1, exact gpow_coe_nat a 0 } @[simp, to_additive one_gsmul] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := by { convert pow_one a using 1, exact gpow_coe_nat a 1 } end div_inv_monoid section group variables [group G] [group H] [add_group A] [add_group B] open int section nat @[simp, to_additive neg_nsmul] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := begin induction n with n ih, { rw [pow_zero, pow_zero, one_inv] }, { rw [pow_succ', pow_succ, ih, mul_inv_rev] } end @[to_additive nsmul_sub] -- rename to sub_nsmul? theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from tsub_add_cancel_of_le h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 @[to_additive nsmul_neg_comm] 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 end nat @[simp, to_additive gsmul_zero] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1 | (n : ℕ) := by rw [gpow_coe_nat, one_pow] | -[1+ n] := by rw [gpow_neg_succ_of_nat, one_pow, one_inv] @[simp, to_additive neg_gsmul] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := div_inv_monoid.gpow_neg' _ _ | 0 := by { change a ^ (0 : ℤ) = (a ^ (0 : ℤ))⁻¹, simp } | -[1+ n] := by { rw [gpow_neg_succ_of_nat, inv_inv, ← gpow_coe_nat], refl } 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] @[to_additive neg_one_gsmul] theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := by { rw [← congr_arg has_inv.inv (pow_one x), gpow_neg, ← gpow_coe_nat], refl } @[to_additive gsmul_neg] theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := by rw [gpow_coe_nat, gpow_coe_nat, inv_pow] | -[1+ n] := by rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, inv_pow] @[to_additive add_commute.gsmul_add] theorem commute.mul_gpow {a b : G} (h : commute a b) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n | (n : ℕ) := by simp [gpow_coe_nat, 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] @[to_additive gsmul_add] theorem mul_gpow (a b : G) (n : ℤ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_gpow n @[to_additive gsmul_sub] theorem div_gpow (a b : G) (n : ℤ) : (a / b) ^ n = a ^ n / b ^ n := by rw [div_eq_mul_inv, div_eq_mul_inv, mul_gpow, inv_gpow] /-- The `n`th power map (`n` an integer) on a commutative group, considered as a group homomorphism. -/ @[to_additive "Multiplication by an integer `n` on a commutative additive group, considered as an additive group homomorphism.", simps] def gpow_group_hom (n : ℤ) : G →* G := { to_fun := (^ n), map_one' := one_gpow n, map_mul' := λ a b, mul_gpow a b n } end comm_group lemma zero_pow [monoid_with_zero R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0 | (n+1) _ := by rw [pow_succ, 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 lemma pow_eq_zero_of_le [monoid_with_zero M] {x : M} {n m : ℕ} (hn : n ≤ m) (hx : x^n = 0) : x^m = 0 := by rw [← tsub_add_cancel_of_le hn, pow_add, hx, mul_zero] 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 (pow_zero _) | (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, tsub_add_cancel_of_le h]⟩ theorem pow_dvd_pow_of_dvd [comm_monoid R] {a b : R} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n | 0 := by rw [pow_zero, pow_zero] | (n+1) := by { rw [pow_succ, pow_succ], exact mul_dvd_mul h (pow_dvd_pow_of_dvd n) } lemma sq_sub_sq {R : Type*} [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by rw [sq, sq, mul_self_sub_mul_self] alias sq_sub_sq ← pow_two_sub_pow_two lemma eq_or_eq_neg_of_sq_eq_sq [comm_ring R] [is_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, ← sq_sub_sq a b, sub_eq_zero] 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] }, { rw pow_succ at H, 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 lemma pow_ne_zero_iff [monoid_with_zero R] [no_zero_divisors R] {a : R} {n : ℕ} (hn : 0 < n) : a ^ n ≠ 0 ↔ a ≠ 0 := by rwa [not_iff_not, pow_eq_zero_iff] @[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 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 := (pow_dvd_pow c (min_le_left n m)).trans ha, replace hb := (pow_dvd_pow c (min_le_right n m)).trans hb, exact dvd_add ha hb end end semiring section comm_semiring variables [comm_semiring R] lemma add_sq (a b : R) : (a + b) ^ 2 = a ^ 2 + 2 * a * b + b ^ 2 := by simp only [sq, add_mul_self_eq] alias add_sq ← add_pow_two end comm_semiring @[simp] lemma neg_sq {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [sq] alias neg_sq ← neg_pow_two lemma sub_sq {R} [comm_ring R] (a b : R) : (a - b) ^ 2 = a ^ 2 - 2 * a * b + b ^ 2 := by rw [sub_eq_add_neg, add_sq, neg_sq, mul_neg_eq_neg_mul_symm, ← sub_eq_add_neg] alias sub_sq ← sub_pow_two 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) := rfl lemma of_mul_gpow [group G] (x : G) (n : ℤ) : additive.of_mul (x ^ n) = n • additive.of_mul x := rfl @[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 : ℕ) := by simp [gpow_coe_nat, h.pow_right n] | -[1+n] := by simp [(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
921bf53901f366b594d6bf932355528f5be2b8c9
3cb7d30bb276fa1e8fe9ca7b979f53cbfafb2dbb
/leanpkg/leanpkg/resolve.lean
9e88343532dc2c8bf7c167900d73e03074d99979
[ "Apache-2.0" ]
permissive
andrejtokarcik/lean
e4148f69d020385c4fc07662b77792681b26c4d9
ceacfa7445953cbc8860ddabc55407430a9ca5c3
refs/heads/master
1,584,800,445,031
1,529,598,225,000
1,529,598,469,000
138,652,902
0
0
Apache-2.0
1,529,962,767,000
1,529,962,767,000
null
UTF-8
Lean
false
false
3,843
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ import leanpkg.manifest system.io leanpkg.proc leanpkg.git namespace leanpkg def assignment := list (string × string) namespace assignment def empty : assignment := [] def find : assignment → string → option string | [] s := none | ((k, v) :: kvs) s := if k = s then some v else find kvs s def contains (a : assignment) (s : string) : bool := (a.find s).is_some def insert (a : assignment) (k v : string) : assignment := if a.contains k then a else (k, v) :: a def fold {α} (i : α) (f : α → string → string → α) : assignment → α := list.foldl (λ a ⟨k, v⟩, f a k v) i end assignment @[reducible] def solver := state_t assignment io instance {α : Type} : has_coe (io α) (solver α) := ⟨state_t.lift⟩ def not_yet_assigned (d : string) : solver bool := do assg ← get, return $ ¬ assg.contains d def resolved_path (d : string) : solver string := do assg ← get, some path ← return (assg.find d) | io.fail "", return path -- TODO(gabriel): directory existence testing def dir_exists (d : string) : io bool := do ch ← io.proc.spawn { cmd := "test", args := ["-d", d] }, ev ← io.proc.wait ch, return $ ev = 0 -- TODO(gabriel): windows? def resolve_dir (abs_or_rel : string) (base : string) : string := if abs_or_rel.front = '/' then abs_or_rel -- absolute else base ++ "/" ++ abs_or_rel def materialize (relpath : string) (dep : dependency) : solver punit := match dep.src with | (source.path dir) := do let depdir := resolve_dir dir relpath, io.put_str_ln $ dep.name ++ ": using local path " ++ depdir, modify $ λ assg, assg.insert dep.name depdir | (source.git url rev) := do let depdir := "_target/deps/" ++ dep.name, already_there ← dir_exists depdir, if already_there then do { io.put_str_ln $ dep.name ++ ": trying to update " ++ depdir ++ " to revision " ++ rev, hash ← git_parse_origin_revision depdir rev, rev_ex ← git_revision_exists depdir hash, when (¬rev_ex) $ exec_cmd {cmd := "git", args := ["fetch"], cwd := depdir} } else do { io.put_str_ln $ dep.name ++ ": cloning " ++ url ++ " to " ++ depdir, exec_cmd {cmd := "mkdir", args := ["-p", depdir]}, exec_cmd {cmd := "git", args := ["clone", url, depdir]} }, hash ← git_parse_origin_revision depdir rev, exec_cmd {cmd := "git", args := ["checkout", "--detach", hash], cwd := depdir}, modify $ λ assg, assg.insert dep.name depdir end def solve_deps_core : ∀ (rel_path : string) (d : manifest) (max_depth : ℕ), solver unit | _ _ 0 := io.fail "maximum dependency resolution depth reached" | relpath d (max_depth + 1) := do deps ← monad.filter (not_yet_assigned ∘ dependency.name) d.dependencies, deps.mmap' (materialize relpath), deps.mmap' $ λ dep, do p ← resolved_path dep.name, d' ← manifest.from_file $ p ++ "/" ++ "leanpkg.toml", when (d'.name ≠ dep.name) $ io.fail $ d.name ++ " (in " ++ relpath ++ ") depends on " ++ d'.name ++ ", but resolved dependency has name " ++ dep.name ++ " (in " ++ p ++ ")", solve_deps_core p d' max_depth def solve_deps (d : manifest) : io assignment := do (_, assg) ← (solve_deps_core "." d 1024).run $ assignment.empty.insert d.name ".", return assg def construct_path_core (depname : string) (dirname : string) : io (list string) := list.map (λ relpath, dirname ++ "/" ++ relpath) <$> manifest.effective_path <$> (manifest.from_file $ dirname ++ "/" ++ leanpkg_toml_fn) def construct_path (assg : assignment) : io (list string) := do let assg := assg.fold [] (λ xs depname dirname, (depname, dirname) :: xs), list.join <$> (assg.mmap $ λ ⟨depname, dirname⟩, construct_path_core depname dirname) end leanpkg
fa8c2d3b632416fe8f84e260c98971bbcea6c82e
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/semiquot.lean
eade815ccb6ae2a669950217a6228feba6fc4c2c
[ "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
6,935
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro A data type for semiquotients, which are classically equivalent to nonempty sets, but are useful for programming; the idea is that a semiquotient set `S` represents some (particular but unknown) element of `S`. This can be used to model nondeterministic functions, which return something in a range of values (represented by the predicate `S`) but are not completely determined. -/ import data.set.lattice data.quot /-- A member of `semiquot α` is classically a nonempty `set α`, and in the VM is represented by an element of `α`; the relation between these is that the VM element is required to be a member of the set `s`. The specific element of `s` that the VM computes is hidden by a quotient construction, allowing for the representation of nondeterministic functions. -/ structure {u} semiquot (α : Type*) := mk' :: (s : set α) (val : trunc ↥s) namespace semiquot variables {α : Type*} {β : Type*} instance : has_mem α (semiquot α) := ⟨λ a q, a ∈ q.s⟩ def mk {a : α} {s : set α} (h : a ∈ s) : semiquot α := ⟨s, trunc.mk ⟨a, h⟩⟩ theorem ext_s {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s := ⟨congr_arg _, λ h, by cases q₁; cases q₂; congr; exact h⟩ theorem ext {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ := ext_s.trans (set.ext_iff _ _) theorem exists_mem (q : semiquot α) : ∃ a, a ∈ q := let ⟨⟨a, h⟩, h₂⟩ := q.2.exists_rep in ⟨a, h⟩ theorem eq_mk_of_mem {q : semiquot α} {a : α} (h : a ∈ q) : q = @mk _ a q.1 h := ext_s.2 rfl theorem ne_empty (q : semiquot α) : q.s ≠ ∅ := let ⟨a, h⟩ := q.exists_mem in set.ne_empty_of_mem h protected def pure (a : α) : semiquot α := mk (set.mem_singleton a) @[simp] theorem mem_pure' {a b : α} : a ∈ semiquot.pure b ↔ a = b := set.mem_singleton_iff def blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) : semiquot α := ⟨s, trunc.lift (λ a : q.s, trunc.mk ⟨a.1, h a.2⟩) (λ _ _, trunc.eq _ _) q.2⟩ def blur (s : set α) (q : semiquot α) : semiquot α := blur' q (set.subset_union_right s q.s) theorem blur_eq_blur' (q : semiquot α) (s : set α) (h : q.s ⊆ s) : blur s q = blur' q h := by unfold blur; congr; exact set.union_eq_self_of_subset_right h @[simp] theorem mem_blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) {a : α} : a ∈ blur' q h ↔ a ∈ s := iff.rfl def of_trunc (q : trunc α) : semiquot α := ⟨set.univ, q.map (λ a, ⟨a, trivial⟩)⟩ def to_trunc (q : semiquot α) : trunc α := q.2.map subtype.val def lift_on (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) : β := trunc.lift_on q.2 (λ x, f x.1) (λ x y, h _ _ x.2 y.2) theorem lift_on_of_mem (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) (a : α) (aq : a ∈ q) : lift_on q f h = f a := by revert h; rw eq_mk_of_mem aq; intro; refl def map (f : α → β) (q : semiquot α) : semiquot β := ⟨f '' q.1, q.2.map (λ x, ⟨f x.1, set.mem_image_of_mem _ x.2⟩)⟩ @[simp] theorem mem_map (f : α → β) (q : semiquot α) (b : β) : b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b := set.mem_image _ _ _ def bind (q : semiquot α) (f : α → semiquot β) : semiquot β := ⟨⋃ a ∈ q.1, (f a).1, q.2.bind (λ a, (f a.1).2.map (λ b, ⟨b.1, set.mem_bUnion a.2 b.2⟩))⟩ @[simp] theorem mem_bind (q : semiquot α) (f : α → semiquot β) (b : β) : b ∈ bind q f ↔ ∃ a, a ∈ q ∧ b ∈ f a := set.mem_bUnion_iff instance : monad semiquot := { pure := @semiquot.pure, map := @semiquot.map, bind := @semiquot.bind } @[simp] theorem mem_pure {a b : α} : a ∈ (pure b : semiquot α) ↔ a = b := set.mem_singleton_iff theorem mem_pure_self (a : α) : a ∈ (pure a : semiquot α) := set.mem_singleton a @[simp] theorem pure_inj {a b : α} : (pure a : semiquot α) = pure b ↔ a = b := ext_s.trans set.singleton_eq_singleton_iff instance : is_lawful_monad semiquot := { pure_bind := λ α β x f, ext.2 $ by simp, bind_assoc := λ α β γ s f g, ext.2 $ by simp; exact λ c, ⟨λ ⟨b, ⟨a, as, bf⟩, cg⟩, ⟨a, as, b, bf, cg⟩, λ ⟨a, as, b, bf, cg⟩, ⟨b, ⟨a, as, bf⟩, cg⟩⟩, id_map := λ α q, ext.2 $ by simp, bind_pure_comp_eq_map := λ α β f s, ext.2 $ by simp [eq_comm] } instance : has_le (semiquot α) := ⟨λ s t, s.s ⊆ t.s⟩ instance : partial_order (semiquot α) := { le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t, le_refl := λ s, set.subset.refl _, le_trans := λ s t u, set.subset.trans, le_antisymm := λ s t h₁ h₂, ext_s.2 (set.subset.antisymm h₁ h₂) } instance : lattice.semilattice_sup (semiquot α) := { sup := λ s, blur s.s, le_sup_left := λ s t, set.subset_union_left _ _, le_sup_right := λ s t, set.subset_union_right _ _, sup_le := λ s t u, set.union_subset, ..semiquot.partial_order } @[simp] theorem pure_le {a : α} {s : semiquot α} : pure a ≤ s ↔ a ∈ s := set.singleton_subset_iff def is_pure (q : semiquot α) := ∀ a b ∈ q, a = b def get (q) (h : @is_pure α q) : α := lift_on q id h theorem get_mem {q : semiquot α} (p) : get q p ∈ q := let ⟨a, h⟩ := exists_mem q in by unfold get; rw lift_on_of_mem q _ _ a h; exact h theorem eq_pure {q : semiquot α} (p) : q = pure (get q p) := ext.2 $ λ a, by simp; exact ⟨λ h, p _ _ h (get_mem _), λ e, e.symm ▸ get_mem _⟩ @[simp] theorem pure_is_pure (a : α) : is_pure (pure a) | b c ab ac := by simp at *; cc theorem is_pure_iff {s : semiquot α} : is_pure s ↔ ∃ a, s = pure a := ⟨λ h, ⟨_, eq_pure h⟩, λ ⟨a, e⟩, e.symm ▸ pure_is_pure _⟩ theorem is_pure.mono {s t : semiquot α} (st : s ≤ t) (h : is_pure t) : is_pure s | a b as bs := h _ _ (st as) (st bs) theorem is_pure.min {s t : semiquot α} (h : is_pure t) : s ≤ t ↔ s = t := ⟨λ st, le_antisymm st $ by rw [eq_pure h, eq_pure (h.mono st)]; simp; exact h _ _ (get_mem _) (st $ get_mem _), le_of_eq⟩ theorem is_pure_of_subsingleton [subsingleton α] (q : semiquot α) : is_pure q | a b aq bq := subsingleton.elim _ _ def univ [inhabited α] : semiquot α := mk $ set.mem_univ (default _) @[simp] theorem mem_univ [inhabited α] : ∀ a, a ∈ @univ α _ := @set.mem_univ α @[congr] theorem univ_unique (I J : inhabited α) : @univ _ I = @univ _ J := ext.2 $ by simp @[simp] theorem is_pure_univ [inhabited α] : @is_pure α univ ↔ subsingleton α := ⟨λ h, ⟨λ a b, h a b trivial trivial⟩, λ ⟨h⟩ a b _ _, h a b⟩ instance [inhabited α] : lattice.order_top (semiquot α) := { top := univ, le_top := λ s, set.subset_univ _, ..semiquot.partial_order } instance [inhabited α] : lattice.semilattice_sup_top (semiquot α) := { ..semiquot.lattice.order_top, ..semiquot.lattice.semilattice_sup } end semiquot
b2880926dfbf3e361a65275f433074eade22ab5d
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/type_library/nat.lean
98dd41e06d4e2ea2c52ba4ff6d9e457173d82f53
[]
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
91
lean
namespace hidden inductive nat : Type | zero : nat | succ (n' : nat) : nat end hidden
f2703ac4b90f698f462d09001d33949905ba1fb4
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/normed_space/riesz_lemma.lean
ac4c101c7b26d05b90685677699163703f45ed77
[ "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,374
lean
/- Copyright (c) 2019 Jean Lo. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jean Lo, Yury Kudryashov -/ import analysis.normed_space.basic import topology.metric_space.hausdorff_distance /-! # Applications of the Hausdorff distance in normed spaces Riesz's lemma, stated for a normed space over a normed field: for any closed proper subspace `F` of `E`, there is a nonzero `x` such that `∥x - F∥` is at least `r * ∥x∥` for any `r < 1`. This is `riesz_lemma`. In a nontrivially normed field (with an element `c` of norm `> 1`) and any `R > ∥c∥`, one can guarantee `∥x∥ ≤ R` and `∥x - y∥ ≥ 1` for any `y` in `F`. This is `riesz_lemma_of_norm_lt`. A further lemma, `metric.closed_ball_inf_dist_compl_subset_closure`, finds a *closed* ball within the closure of a set `s` of optimal distance from a point in `x` to the frontier of `s`. -/ open set metric open_locale topological_space variables {𝕜 : Type*} [normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] variables {F : Type*} [seminormed_add_comm_group F] [normed_space ℝ F] /-- Riesz's lemma, which usually states that it is possible to find a vector with norm 1 whose distance to a closed proper subspace is arbitrarily close to 1. The statement here is in terms of multiples of norms, since in general the existence of an element of norm exactly 1 is not guaranteed. For a variant giving an element with norm in `[1, R]`, see `riesz_lemma_of_norm_lt`. -/ lemma riesz_lemma {F : subspace 𝕜 E} (hFc : is_closed (F : set E)) (hF : ∃ x : E, x ∉ F) {r : ℝ} (hr : r < 1) : ∃ x₀ : E, x₀ ∉ F ∧ ∀ y ∈ F, r * ∥x₀∥ ≤ ∥x₀ - y∥ := begin classical, obtain ⟨x, hx⟩ : ∃ x : E, x ∉ F := hF, let d := metric.inf_dist x F, have hFn : (F : set E).nonempty, from ⟨_, F.zero_mem⟩, have hdp : 0 < d, from lt_of_le_of_ne metric.inf_dist_nonneg (λ heq, hx ((hFc.mem_iff_inf_dist_zero hFn).2 heq.symm)), let r' := max r 2⁻¹, have hr' : r' < 1, by { simp [r', hr], norm_num }, have hlt : 0 < r' := lt_of_lt_of_le (by norm_num) (le_max_right r 2⁻¹), have hdlt : d < d / r', from (lt_div_iff hlt).mpr ((mul_lt_iff_lt_one_right hdp).2 hr'), obtain ⟨y₀, hy₀F, hxy₀⟩ : ∃ y ∈ F, dist x y < d / r' := (metric.inf_dist_lt_iff hFn).mp hdlt, have x_ne_y₀ : x - y₀ ∉ F, { by_contradiction h, have : (x - y₀) + y₀ ∈ F, from F.add_mem h hy₀F, simp only [neg_add_cancel_right, sub_eq_add_neg] at this, exact hx this }, refine ⟨x - y₀, x_ne_y₀, λy hy, le_of_lt _⟩, have hy₀y : y₀ + y ∈ F, from F.add_mem hy₀F hy, calc r * ∥x - y₀∥ ≤ r' * ∥x - y₀∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) ... < d : by { rw ←dist_eq_norm, exact (lt_div_iff' hlt).1 hxy₀ } ... ≤ dist x (y₀ + y) : metric.inf_dist_le_dist_of_mem hy₀y ... = ∥x - y₀ - y∥ : by { rw [sub_sub, dist_eq_norm] } end /-- A version of Riesz lemma: given a strict closed subspace `F`, one may find an element of norm `≤ R` which is at distance at least `1` of every element of `F`. Here, `R` is any given constant strictly larger than the norm of an element of norm `> 1`. For a version without an `R`, see `riesz_lemma`. Since we are considering a general nontrivially normed field, there may be a gap in possible norms (for instance no element of norm in `(1,2)`). Hence, we can not allow `R` arbitrarily close to `1`, and require `R > ∥c∥` for some `c : 𝕜` with norm `> 1`. -/ lemma riesz_lemma_of_norm_lt {c : 𝕜} (hc : 1 < ∥c∥) {R : ℝ} (hR : ∥c∥ < R) {F : subspace 𝕜 E} (hFc : is_closed (F : set E)) (hF : ∃ x : E, x ∉ F) : ∃ x₀ : E, ∥x₀∥ ≤ R ∧ ∀ y ∈ F, 1 ≤ ∥x₀ - y∥ := begin have Rpos : 0 < R := (norm_nonneg _).trans_lt hR, have : ∥c∥ / R < 1, by { rw div_lt_iff Rpos, simpa using hR }, rcases riesz_lemma hFc hF this with ⟨x, xF, hx⟩, have x0 : x ≠ 0 := λ H, by simpa [H] using xF, obtain ⟨d, d0, dxlt, ledx, -⟩ : ∃ (d : 𝕜), d ≠ 0 ∧ ∥d • x∥ < R ∧ R / ∥c∥ ≤ ∥d • x∥ ∧ ∥d∥⁻¹ ≤ R⁻¹ * ∥c∥ * ∥x∥ := rescale_to_shell hc Rpos x0, refine ⟨d • x, dxlt.le, λ y hy, _⟩, set y' := d⁻¹ • y with hy', have y'F : y' ∈ F, by simp [hy', submodule.smul_mem _ _ hy], have yy' : y = d • y', by simp [hy', smul_smul, mul_inv_cancel d0], calc 1 = (∥c∥/R) * (R/∥c∥) : by field_simp [Rpos.ne', (zero_lt_one.trans hc).ne'] ... ≤ (∥c∥/R) * (∥d • x∥) : mul_le_mul_of_nonneg_left ledx (div_nonneg (norm_nonneg _) Rpos.le) ... = ∥d∥ * (∥c∥/R * ∥x∥) : by { simp [norm_smul], ring } ... ≤ ∥d∥ * ∥x - y'∥ : mul_le_mul_of_nonneg_left (hx y' (by simp [hy', submodule.smul_mem _ _ hy])) (norm_nonneg _) ... = ∥d • x - y∥ : by simp [yy', ← smul_sub, norm_smul], end lemma metric.closed_ball_inf_dist_compl_subset_closure {x : F} {s : set F} (hx : x ∈ s) : closed_ball x (inf_dist x sᶜ) ⊆ closure s := begin cases eq_or_ne (inf_dist x sᶜ) 0 with h₀ h₀, { rw [h₀, closed_ball_zero'], exact closure_mono (singleton_subset_iff.2 hx) }, { rw ← closure_ball x h₀, exact closure_mono ball_inf_dist_compl_subset } end
93b8f831432ba588f1bfde8281d53d0cb607c883
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/list/count.lean
5660878757f146a920ad63f7538c11eb5b12dce8
[ "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
10,131
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import data.list.big_operators.basic /-! # Counting in lists > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves basic properties of `list.countp` and `list.count`, which count the number of elements of a list satisfying a predicate and equal to a given element respectively. Their definitions can be found in [`data.list.defs`](./defs). -/ open nat variables {α β : Type*} {l l₁ l₂ : list α} namespace list section countp variables (p q : α → Prop) [decidable_pred p] [decidable_pred q] @[simp] lemma countp_nil : countp p [] = 0 := rfl @[simp] lemma countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] lemma countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa lemma countp_cons (a : α) (l) : countp p (a :: l) = countp p l + ite (p a) 1 0 := by { by_cases h : p a; simp [h] } lemma length_eq_countp_add_countp (l) : length l = countp p l + countp (λ a, ¬p a) l := by induction l with x h ih; [refl, by_cases p x]; [simp only [countp_cons_of_pos _ _ h, countp_cons_of_neg (λ a, ¬p a) _ (decidable.not_not.2 h), ih, length], simp only [countp_cons_of_pos (λ a, ¬p a) _ h, countp_cons_of_neg _ _ h, ih, length]]; ac_refl lemma countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ _ h, ih, filter_cons_of_neg _ h]]; refl lemma countp_le_length : countp p l ≤ l.length := by simpa only [countp_eq_length_filter] using length_filter_le _ _ @[simp] lemma countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] lemma countp_join : ∀ l : list (list α), countp p l.join = (l.map (countp p)).sum | [] := rfl | (a :: l) := by rw [join, countp_append, map_cons, sum_cons, countp_join] lemma countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] @[simp] theorem countp_eq_zero {l} : countp p l = 0 ↔ ∀ a ∈ l, ¬ p a := by { rw [← not_iff_not, ← ne.def, ← pos_iff_ne_zero, countp_pos], simp } @[simp] lemma countp_eq_length {l} : countp p l = l.length ↔ ∀ a ∈ l, p a := by rw [countp_eq_length_filter, filter_length_eq_length] lemma length_filter_lt_length_iff_exists (l) : length (filter p l) < length l ↔ ∃ x ∈ l, ¬p x := by rw [length_eq_countp_add_countp p l, ← countp_pos, countp_eq_length_filter, lt_add_iff_pos_right] lemma sublist.countp_le (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (s.filter p) @[simp] lemma countp_filter (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] @[simp] lemma countp_true : l.countp (λ _, true) = l.length := by simp @[simp] lemma countp_false : l.countp (λ _, false) = 0 := by simp @[simp] lemma countp_map (p : β → Prop) [decidable_pred p] (f : α → β) : ∀ l, countp p (map f l) = countp (p ∘ f) l | [] := rfl | (a::l) := by rw [map_cons, countp_cons, countp_cons, countp_map] variables {p q} lemma countp_mono_left (h : ∀ x ∈ l, p x → q x) : countp p l ≤ countp q l := begin induction l with a l ihl, { refl }, rw [forall_mem_cons] at h, cases h with ha hl, rw [countp_cons, countp_cons], refine add_le_add (ihl hl) _, split_ifs; try { simp only [le_rfl, zero_le] }, exact absurd (ha ‹_›) ‹_› end lemma countp_congr (h : ∀ x ∈ l, p x ↔ q x) : countp p l = countp q l := le_antisymm (countp_mono_left $ λ x hx, (h x hx).1) (countp_mono_left $ λ x hx, (h x hx).2) end countp /-! ### count -/ section count variables [decidable_eq α] @[simp] lemma count_nil (a : α) : count a [] = 0 := rfl lemma count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl lemma count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] lemma count_cons_self (a : α) (l : list α) : count a (a::l) = count a l + 1 := if_pos rfl @[simp, priority 990] lemma count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h lemma count_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } lemma count_le_length (a : α) (l : list α) : count a l ≤ l.length := countp_le_length _ lemma sublist.count_le (h : l₁ <+ l₂) (a : α) : count a l₁ ≤ count a l₂ := h.countp_le _ lemma count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := (sublist_cons _ _).count_le _ lemma count_singleton (a : α) : count a [a] = 1 := if_pos rfl lemma count_singleton' (a b : α) : count a [b] = ite (a = b) 1 0 := rfl @[simp] lemma count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append _ lemma count_join (l : list (list α)) (a : α) : l.join.count a = (l.map (count a)).sum := countp_join _ _ lemma count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by simp [-add_comm] @[simp] lemma count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp] lemma one_le_count_iff_mem {a : α} {l : list α} : 1 ≤ count a l ↔ a ∈ l := count_pos @[simp, priority 980] lemma count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := decidable.by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') lemma not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', (count_pos.2 h').ne' h @[simp] lemma count_eq_zero {a : α} {l} : count a l = 0 ↔ a ∉ l := ⟨not_mem_of_count_eq_zero, count_eq_zero_of_not_mem⟩ @[simp] lemma count_eq_length {a : α} {l} : count a l = l.length ↔ ∀ b ∈ l, a = b := countp_eq_length _ @[simp] lemma count_replicate_self (a : α) (n : ℕ) : count a (replicate n a) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_replicate]; exact λ b m, (eq_of_mem_replicate m).symm lemma count_replicate (a b : α) (n : ℕ) : count a (replicate n b) = if a = b then n else 0 := begin split_ifs with h, exacts [h ▸ count_replicate_self _ _, count_eq_zero_of_not_mem $ mt eq_of_mem_replicate h] end theorem filter_eq (l : list α) (a : α) : l.filter (eq a) = replicate (count a l) a := by simp [eq_replicate, count, countp_eq_length_filter, @eq_comm _ _ a] theorem filter_eq' (l : list α) (a : α) : l.filter (λ x, x = a) = replicate (count a l) a := by simp only [filter_eq, @eq_comm _ _ a] lemma le_count_iff_replicate_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ replicate n a <+ l := ⟨λ h, ((replicate_sublist_replicate a).2 h).trans $ filter_eq l a ▸ filter_sublist _, λ h, by simpa only [count_replicate_self] using h.count_le a⟩ lemma replicate_count_eq_of_count_eq_length {a : α} {l : list α} (h : count a l = length l) : replicate (count a l) a = l := (le_count_iff_replicate_sublist.mp le_rfl).eq_of_length $ (length_replicate (count a l) a).trans h @[simp] lemma count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter, show (λ b, a = b ∧ p b) = eq a, by { ext b, constructor; cc }] lemma count_bind {α β} [decidable_eq β] (l : list α) (f : α → list β) (x : β) : count x (l.bind f) = sum (map (count x ∘ f) l) := by rw [list.bind, count_join, map_map] @[simp] lemma count_map_of_injective {α β} [decidable_eq α] [decidable_eq β] (l : list α) (f : α → β) (hf : function.injective f) (x : α) : count (f x) (map f l) = count x l := by simp only [count, countp_map, (∘), hf.eq_iff] lemma count_le_count_map [decidable_eq β] (l : list α) (f : α → β) (x : α) : count x l ≤ count (f x) (map f l) := begin rw [count, count, countp_map], exact countp_mono_left (λ y hyl, congr_arg f), end lemma count_erase (a b : α) : ∀ l : list α, count a (l.erase b) = count a l - ite (a = b) 1 0 | [] := by simp | (c :: l) := begin rw [erase_cons], by_cases hc : c = b, { rw [if_pos hc, hc, count_cons', nat.add_sub_cancel] }, { rw [if_neg hc, count_cons', count_cons', count_erase], by_cases ha : a = b, { rw [← ha, eq_comm] at hc, rw [if_pos ha, if_neg hc, add_zero, add_zero] }, { rw [if_neg ha, tsub_zero, tsub_zero] } } end @[simp] lemma count_erase_self (a : α) (l : list α) : count a (list.erase l a) = count a l - 1 := by rw [count_erase, if_pos rfl] @[simp] lemma count_erase_of_ne {a b : α} (ab : a ≠ b) (l : list α) : count a (l.erase b) = count a l := by rw [count_erase, if_neg ab, tsub_zero] @[to_additive] lemma prod_map_eq_pow_single [monoid β] {l : list α} (a : α) (f : α → β) (hf : ∀ a' ≠ a, a' ∈ l → f a' = 1) : (l.map f).prod = (f a) ^ (l.count a) := begin induction l with a' as h generalizing a, { rw [map_nil, prod_nil, count_nil, pow_zero] }, { specialize h a (λ a' ha' hfa', hf a' ha' (mem_cons_of_mem _ hfa')), rw [list.map_cons, list.prod_cons, count_cons, h], split_ifs with ha', { rw [ha', pow_succ] }, { rw [hf a' (ne.symm ha') (list.mem_cons_self a' as), one_mul] } } end @[to_additive] lemma prod_eq_pow_single [monoid α] {l : list α} (a : α) (h : ∀ a' ≠ a, a' ∈ l → a' = 1) : l.prod = a ^ (l.count a) := trans (by rw [map_id'']) (prod_map_eq_pow_single a id h) end count end list
25c9820cc21605045e9f1b8d820a70e8731dd6fa
a9fe717b93ccfa4b2e64faeb24f96dfefb390240
/eqelim.lean
ae8da261f5d9ecba7fdab6eb0d732152a8ed2926
[]
no_license
skbaek/omega
ab1f4a6daadfc8c855f14c39d9459ab841527141
715e384ed14e8eb177a326700066e7c98269e078
refs/heads/master
1,588,000,876,352
1,552,645,917,000
1,552,645,917,000
174,442,914
1
0
null
null
null
null
UTF-8
Lean
false
false
3,429
lean
import .ee .int variables {α β : Type} open tactic meta structure ee_state := (eqs : list term) (les : list term) (ees : list ee) @[reducible] meta def eqelim := state_t ee_state tactic meta def abort {α : Type} : eqelim α := ⟨λ x, failed⟩ private meta def mk_eqelim_state (eqs les : list term) : tactic ee_state := return (ee_state.mk eqs les [])-- ⟨eqs,les,[]⟩ meta def get_eqs : eqelim (list term) := ee_state.eqs <$> get meta def get_les : eqelim (list term) := ee_state.les <$> get meta def get_ees : eqelim (list ee) := ee_state.ees <$> get meta def set_eqs (eqs : list term) : eqelim unit := modify $ λ s, {eqs := eqs, ..s} meta def set_les (les : list term) : eqelim unit := modify $ λ s, {les := les, ..s} meta def set_ees (es : list ee) : eqelim unit := modify $ λ s, {ees := es, ..s} meta def add_ee (e : ee) : eqelim unit := do es ← get_ees, set_ees (es ++ [e]) meta def head_eq : eqelim term := do eqs ← get_eqs, match eqs with | [] := abort | (eq::eqs') := set_eqs eqs' >> pure eq end meta def run {α : Type} (eqs les : list term) (r : eqelim α) : tactic α := prod.fst <$> (mk_eqelim_state eqs les >>= r.run) meta def ee_commit (t1 : eqelim α) (t2 : eqelim β) (t3 : α → eqelim β) : eqelim β := do x ← ((t1 >>= return ∘ some) <|> return none), match x with | none := t2 | (some a) := t3 a end notation t1 `!>>=` t2 `;` t3 := ee_commit t1 t2 t3 private meta def of_tactic {α : Type} : tactic α → eqelim α := state_t.lift meta def get_gcd (t : term) : eqelim int := pure ↑(ints.gcd t.snd) meta def factor (i : int) (t : term) : eqelim term := if i ∣ t.fst then add_ee (ee.factor i) >> pure (t.div i) else abort /- If list has a nonzero element, return that element with its index. Otherwise, return none. -/ meta def find_min_coeff_core : list int → eqelim (int × nat) | [] := abort | (i::is) := (do (j,n) ← find_min_coeff_core is, if i ≠ 0 ∧ i.nat_abs ≤ j.nat_abs then pure (i,0) else pure (j,n+1)) <|> (if i = (0 : int) then abort else pure (i,0)) -- Returns (s,m,i), where -- s = term equivalent to t -- m = index of nonzero coefficient with smallest absolute value -- i = nonzero coefficient with smallest absolute value (positive) meta def find_min_coeff (t : term) : eqelim (int × nat × term) := do (i,n) ← find_min_coeff_core t.snd, if 0 < i then pure (i,n,t) else add_ee (ee.neg) >> pure (-i,n,t.neg) meta def elim_eq : eqelim unit := do t ← head_eq, i ← get_gcd t, factor i t !>>= (set_eqs [] >> add_ee (ee.nondiv i)) ; λ s, find_min_coeff s !>>= add_ee ee.drop ; λ x, let i : int := x.fst in let n : nat := x.snd.fst in let u : term := x.snd.snd in if i = 1 then do eqs ← get_eqs, les ← get_les, set_eqs (eqs.map (cancel n u)), set_les (les.map (cancel n u)), add_ee (ee.cancel n) else let v : term := coeffs_reduce n u.fst u.snd in let r : term := rhs n u.fst u.snd in do eqs ← get_eqs, les ← get_les, set_eqs (v::eqs.map (subst n r)), set_les (les.map (subst n r)), add_ee (ee.reduce n), elim_eq meta def elim_eqs : eqelim (list ee) := elim_eq !>>= get_ees ; λ _, elim_eqs meta def find_ees : clause → tactic (list ee) | (eqs,les) := run eqs les elim_eqs
d0eb8c9de93b9e61b3d0dee765f450dbd78637f6
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/discrete_category.lean
b31d74023d41fb448b41101c5e082f5a62663379
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
3,125
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Floris van Doorn -/ import data.ulift import data.fintype.basic import category_theory.opposites namespace category_theory universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation def discrete (α : Type u₁) := α instance discrete_category (α : Type u₁) : small_category (discrete α) := { hom := λ X Y, ulift (plift (X = Y)), id := λ X, ulift.up (plift.up rfl), comp := λ X Y Z g f, by { rcases f with ⟨⟨rfl⟩⟩, exact g } } namespace discrete variables {α : Type u₁} instance [inhabited α] : inhabited (discrete α) := by unfold discrete; apply_instance instance [fintype α] : fintype (discrete α) := by { dsimp [discrete], apply_instance } instance fintype_fun [decidable_eq α] (X Y : discrete α) : fintype (X ⟶ Y) := by { apply ulift.fintype } @[simp] lemma id_def (X : discrete α) : ulift.up (plift.up (eq.refl X)) = 𝟙 X := rfl end discrete variables {C : Type u₂} [category.{v₂} C] namespace functor def of_function {I : Type u₁} (F : I → C) : (discrete I) ⥤ C := { obj := F, map := λ X Y f, begin cases f, cases f, cases f, exact 𝟙 (F X) end } @[simp] lemma of_function_obj {I : Type u₁} (F : I → C) (i : I) : (of_function F).obj i = F i := rfl lemma of_function_map {I : Type u₁} (F : I → C) {i : discrete I} (f : i ⟶ i) : (of_function F).map f = 𝟙 (F i) := by { cases f, cases f, cases f, refl } end functor namespace nat_trans def of_homs {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ⟶ G.obj i) : F ⟶ G := { app := f } @[simp] lemma of_homs_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ⟶ G.obj i) (i) : (of_homs f).app i = f i := rfl def of_function {I : Type u₁} {F G : I → C} (f : Π i : I, F i ⟶ G i) : (functor.of_function F) ⟶ (functor.of_function G) := of_homs f @[simp] lemma of_function_app {I : Type u₁} {F G : I → C} (f : Π i : I, F i ⟶ G i) (i : I) : (of_function f).app i = f i := rfl end nat_trans namespace nat_iso def of_isos {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) : F ≅ G := of_components f (by tidy) end nat_iso namespace discrete variables {J : Type v₁} def lift {α : Type u₁} {β : Type u₂} (f : α → β) : (discrete α) ⥤ (discrete β) := functor.of_function f open opposite protected def opposite (α : Type u₁) : (discrete α)ᵒᵖ ≌ discrete α := let F : discrete α ⥤ (discrete α)ᵒᵖ := functor.of_function (λ x, op x) in begin refine equivalence.mk (functor.left_op F) F _ (nat_iso.of_isos $ λ X, by simp [F]), refine nat_iso.of_components (λ X, by simp [F]) _, tidy end @[simp] lemma functor_map_id (F : discrete J ⥤ C) {j : discrete J} (f : j ⟶ j) : F.map f = 𝟙 (F.obj j) := begin have h : f = 𝟙 j, { cases f, cases f, ext, }, rw h, simp, end end discrete end category_theory
a8044bdf3cec96ab5b4199351f2db2dda0db3eef
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/box_integral/partition/basic.lean
1dbd30f876aa90e2608337d59abdeb0a2cf0c0e6
[ "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
29,243
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.box.basic /-! # Partitions of rectangular boxes in `ℝⁿ` In this file we define (pre)partitions of rectangular boxes in `ℝⁿ`. A partition of a box `I` in `ℝⁿ` (see `box_integral.prepartition` and `box_integral.prepartition.is_partition`) is a finite set of pairwise disjoint boxes such that their union is exactly `I`. We use `boxes : finset (box ι)` to store the set of boxes. Many lemmas about box integrals deal with pairwise disjoint collections of subboxes, so we define a structure `box_integral.prepartition (I : box_integral.box ι)` that stores a collection of boxes such that * each box `J ∈ boxes` is a subbox of `I`; * the boxes are pairwise disjoint as sets in `ℝⁿ`. Then we define a predicate `box_integral.prepartition.is_partition`; `π.is_partition` means that the boxes of `π` actually cover the whole `I`. We also define some operations on prepartitions: * `box_integral.partition.bUnion`: split each box of a partition into smaller boxes; * `box_integral.partition.restrict`: restrict a partition to a smaller box. We also define a `semilattice_inf` structure on `box_integral.partition I` for all `I : box_integral.box ι`. ## Tags rectangular box, partition -/ open set finset function open_locale classical nnreal big_operators noncomputable theory namespace box_integral variables {ι : Type*} /-- A prepartition of `I : box_integral.box ι` is a finite set of pairwise disjoint subboxes of `I`. -/ structure prepartition (I : box ι) := (boxes : finset (box ι)) (le_of_mem' : ∀ J ∈ boxes, J ≤ I) (pairwise_disjoint : set.pairwise ↑boxes (disjoint on (coe : box ι → set (ι → ℝ)))) namespace prepartition variables {I J J₁ J₂ : box ι} (π : prepartition I) {π₁ π₂ : prepartition I} {x : ι → ℝ} instance : has_mem (box ι) (prepartition I) := ⟨λ J π, J ∈ π.boxes⟩ @[simp] lemma mem_boxes : J ∈ π.boxes ↔ J ∈ π := iff.rfl @[simp] lemma mem_mk {s h₁ h₂} : J ∈ (mk s h₁ h₂ : prepartition I) ↔ J ∈ s := iff.rfl lemma disjoint_coe_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (h : J₁ ≠ J₂) : disjoint (J₁ : set (ι → ℝ)) J₂ := π.pairwise_disjoint h₁ h₂ h lemma eq_of_mem_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hx₁ : x ∈ J₁) (hx₂ : x ∈ J₂) : J₁ = J₂ := by_contra $ λ H, (π.disjoint_coe_of_mem h₁ h₂ H).le_bot ⟨hx₁, hx₂⟩ lemma eq_of_le_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle₁ : J ≤ J₁) (hle₂ : J ≤ J₂) : J₁ = J₂ := π.eq_of_mem_of_mem h₁ h₂ (hle₁ J.upper_mem) (hle₂ J.upper_mem) lemma eq_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle : J₁ ≤ J₂) : J₁ = J₂ := π.eq_of_le_of_le h₁ h₂ le_rfl hle lemma le_of_mem (hJ : J ∈ π) : J ≤ I := π.le_of_mem' J hJ lemma lower_le_lower (hJ : J ∈ π) : I.lower ≤ J.lower := box.antitone_lower (π.le_of_mem hJ) lemma upper_le_upper (hJ : J ∈ π) : J.upper ≤ I.upper := box.monotone_upper (π.le_of_mem hJ) lemma injective_boxes : function.injective (boxes : prepartition I → finset (box ι)) := by { rintro ⟨s₁, h₁, h₁'⟩ ⟨s₂, h₂, h₂'⟩ (rfl : s₁ = s₂), refl } @[ext] lemma ext (h : ∀ J, J ∈ π₁ ↔ J ∈ π₂) : π₁ = π₂ := injective_boxes $ finset.ext h /-- The singleton prepartition `{J}`, `J ≤ I`. -/ @[simps] def single (I J : box ι) (h : J ≤ I) : prepartition I := ⟨{J}, by simpa, by simp⟩ @[simp] lemma mem_single {J'} (h : J ≤ I) : J' ∈ single I J h ↔ J' = J := mem_singleton /-- We say that `π ≤ π'` if each box of `π` is a subbox of some box of `π'`. -/ instance : has_le (prepartition I) := ⟨λ π π', ∀ ⦃I⦄, I ∈ π → ∃ I' ∈ π', I ≤ I'⟩ instance : partial_order (prepartition I) := { le := (≤), le_refl := λ π I hI, ⟨I, hI, le_rfl⟩, le_trans := λ π₁ π₂ π₃ h₁₂ h₂₃ I₁ hI₁, let ⟨I₂, hI₂, hI₁₂⟩ := h₁₂ hI₁, ⟨I₃, hI₃, hI₂₃⟩ := h₂₃ hI₂ in ⟨I₃, hI₃, hI₁₂.trans hI₂₃⟩, le_antisymm := begin suffices : ∀ {π₁ π₂ : prepartition I}, π₁ ≤ π₂ → π₂ ≤ π₁ → π₁.boxes ⊆ π₂.boxes, from λ π₁ π₂ h₁ h₂, injective_boxes (subset.antisymm (this h₁ h₂) (this h₂ h₁)), intros π₁ π₂ h₁ h₂ J hJ, rcases h₁ hJ with ⟨J', hJ', hle⟩, rcases h₂ hJ' with ⟨J'', hJ'', hle'⟩, obtain rfl : J = J'', from π₁.eq_of_le hJ hJ'' (hle.trans hle'), obtain rfl : J' = J, from le_antisymm ‹_› ‹_›, assumption end } instance : order_top (prepartition I) := { top := single I I le_rfl, le_top := λ π J hJ, ⟨I, by simp, π.le_of_mem hJ⟩ } instance : order_bot (prepartition I) := { bot := ⟨∅, λ J hJ, false.elim hJ, λ J hJ, false.elim hJ⟩, bot_le := λ π J hJ, false.elim hJ } instance : inhabited (prepartition I) := ⟨⊤⟩ lemma le_def : π₁ ≤ π₂ ↔ ∀ J ∈ π₁, ∃ J' ∈ π₂, J ≤ J' := iff.rfl @[simp] lemma mem_top : J ∈ (⊤ : prepartition I) ↔ J = I := mem_singleton @[simp] lemma top_boxes : (⊤ : prepartition I).boxes = {I} := rfl @[simp] lemma not_mem_bot : J ∉ (⊥ : prepartition I) := id @[simp] lemma bot_boxes : (⊥ : prepartition I).boxes = ∅ := rfl /-- An auxiliary lemma used to prove that the same point can't belong to more than `2 ^ fintype.card ι` closed boxes of a prepartition. -/ lemma inj_on_set_of_mem_Icc_set_of_lower_eq (x : ι → ℝ) : inj_on (λ J : box ι, {i | J.lower i = x i}) {J | J ∈ π ∧ x ∈ J.Icc} := begin rintros J₁ ⟨h₁, hx₁⟩ J₂ ⟨h₂, hx₂⟩ (H : {i | J₁.lower i = x i} = {i | J₂.lower i = x i}), suffices : ∀ i, (Ioc (J₁.lower i) (J₁.upper i) ∩ Ioc (J₂.lower i) (J₂.upper i)).nonempty, { choose y hy₁ hy₂, exact π.eq_of_mem_of_mem h₁ h₂ hy₁ hy₂ }, intro i, simp only [set.ext_iff, mem_set_of_eq] at H, cases (hx₁.1 i).eq_or_lt with hi₁ hi₁, { have hi₂ : J₂.lower i = x i, from (H _).1 hi₁, have H₁ : x i < J₁.upper i, by simpa only [hi₁] using J₁.lower_lt_upper i, have H₂ : x i < J₂.upper i, by simpa only [hi₂] using J₂.lower_lt_upper i, rw [Ioc_inter_Ioc, hi₁, hi₂, sup_idem, set.nonempty_Ioc], exact lt_min H₁ H₂ }, { have hi₂ : J₂.lower i < x i, from (hx₂.1 i).lt_of_ne (mt (H _).2 hi₁.ne), exact ⟨x i, ⟨hi₁, hx₁.2 i⟩, ⟨hi₂, hx₂.2 i⟩⟩ } end /-- The set of boxes of a prepartition that contain `x` in their closures has cardinality at most `2 ^ fintype.card ι`. -/ lemma card_filter_mem_Icc_le [fintype ι] (x : ι → ℝ) : (π.boxes.filter (λ J : box ι, x ∈ J.Icc)).card ≤ 2 ^ fintype.card ι := begin rw [← fintype.card_set], refine finset.card_le_card_of_inj_on (λ J : box ι, {i | J.lower i = x i}) (λ _ _, finset.mem_univ _) _, simpa only [finset.mem_filter] using π.inj_on_set_of_mem_Icc_set_of_lower_eq x end /-- Given a prepartition `π : box_integral.prepartition I`, `π.Union` is the part of `I` covered by the boxes of `π`. -/ protected def Union : set (ι → ℝ) := ⋃ J ∈ π, ↑J lemma Union_def : π.Union = ⋃ J ∈ π, ↑J := rfl lemma Union_def' : π.Union = ⋃ J ∈ π.boxes, ↑J := rfl @[simp] lemma mem_Union : x ∈ π.Union ↔ ∃ J ∈ π, x ∈ J := set.mem_Union₂ @[simp] lemma Union_single (h : J ≤ I) : (single I J h).Union = J := by simp [Union_def] @[simp] lemma Union_top : (⊤ : prepartition I).Union = I := by simp [prepartition.Union] @[simp] lemma Union_eq_empty : π₁.Union = ∅ ↔ π₁ = ⊥ := by simp [← injective_boxes.eq_iff, finset.ext_iff, prepartition.Union, imp_false] @[simp] lemma Union_bot : (⊥ : prepartition I).Union = ∅ := Union_eq_empty.2 rfl lemma subset_Union (h : J ∈ π) : ↑J ⊆ π.Union := subset_bUnion_of_mem h lemma Union_subset : π.Union ⊆ I := Union₂_subset π.le_of_mem' @[mono] lemma Union_mono (h : π₁ ≤ π₂) : π₁.Union ⊆ π₂.Union := λ x hx, let ⟨J₁, hJ₁, hx⟩ := π₁.mem_Union.1 hx, ⟨J₂, hJ₂, hle⟩ := h hJ₁ in π₂.mem_Union.2 ⟨J₂, hJ₂, hle hx⟩ lemma disjoint_boxes_of_disjoint_Union (h : disjoint π₁.Union π₂.Union) : disjoint π₁.boxes π₂.boxes := finset.disjoint_left.2 $ λ J h₁ h₂, disjoint.le_bot (h.mono (π₁.subset_Union h₁) (π₂.subset_Union h₂)) ⟨J.upper_mem, J.upper_mem⟩ lemma le_iff_nonempty_imp_le_and_Union_subset : π₁ ≤ π₂ ↔ (∀ (J ∈ π₁) (J' ∈ π₂), (J ∩ J' : set (ι → ℝ)).nonempty → J ≤ J') ∧ π₁.Union ⊆ π₂.Union := begin fsplit, { refine λ H, ⟨λ J hJ J' hJ' Hne, _, Union_mono H⟩, rcases H hJ with ⟨J'', hJ'', Hle⟩, rcases Hne with ⟨x, hx, hx'⟩, rwa π₂.eq_of_mem_of_mem hJ' hJ'' hx' (Hle hx) }, { rintro ⟨H, HU⟩ J hJ, simp only [set.subset_def, mem_Union] at HU, rcases HU J.upper ⟨J, hJ, J.upper_mem⟩ with ⟨J₂, hJ₂, hx⟩, exact ⟨J₂, hJ₂, H _ hJ _ hJ₂ ⟨_, J.upper_mem, hx⟩⟩ } end lemma eq_of_boxes_subset_Union_superset (h₁ : π₁.boxes ⊆ π₂.boxes) (h₂ : π₂.Union ⊆ π₁.Union) : π₁ = π₂ := le_antisymm (λ J hJ, ⟨J, h₁ hJ, le_rfl⟩) $ le_iff_nonempty_imp_le_and_Union_subset.2 ⟨λ J₁ hJ₁ J₂ hJ₂ Hne, (π₂.eq_of_mem_of_mem hJ₁ (h₁ hJ₂) Hne.some_spec.1 Hne.some_spec.2).le, h₂⟩ /-- Given a prepartition `π` of a box `I` and a collection of prepartitions `πi J` of all boxes `J ∈ π`, returns the prepartition of `I` into the union of the boxes of all `πi J`. Though we only use the values of `πi` on the boxes of `π`, we require `πi` to be a globally defined function. -/ @[simps] def bUnion (πi : Π J : box ι, prepartition J) : prepartition I := { boxes := π.boxes.bUnion $ λ J, (πi J).boxes, le_of_mem' := λ J hJ, begin simp only [finset.mem_bUnion, exists_prop, mem_boxes] at hJ, rcases hJ with ⟨J', hJ', hJ⟩, exact ((πi J').le_of_mem hJ).trans (π.le_of_mem hJ') end, pairwise_disjoint := begin simp only [set.pairwise, finset.mem_coe, finset.mem_bUnion], rintro J₁' ⟨J₁, hJ₁, hJ₁'⟩ J₂' ⟨J₂, hJ₂, hJ₂'⟩ Hne, rw [function.on_fun, set.disjoint_left], rintros x hx₁ hx₂, apply Hne, obtain rfl : J₁ = J₂, from π.eq_of_mem_of_mem hJ₁ hJ₂ ((πi J₁).le_of_mem hJ₁' hx₁) ((πi J₂).le_of_mem hJ₂' hx₂), exact (πi J₁).eq_of_mem_of_mem hJ₁' hJ₂' hx₁ hx₂ end } variables {πi πi₁ πi₂ : Π J : box ι, prepartition J} @[simp] lemma mem_bUnion : J ∈ π.bUnion πi ↔ ∃ J' ∈ π, J ∈ πi J' := by simp [bUnion] lemma bUnion_le (πi : Π J, prepartition J) : π.bUnion πi ≤ π := λ J hJ, let ⟨J', hJ', hJ⟩ := π.mem_bUnion.1 hJ in ⟨J', hJ', (πi J').le_of_mem hJ⟩ @[simp] lemma bUnion_top : π.bUnion (λ _, ⊤) = π := by { ext, simp } @[congr] lemma bUnion_congr (h : π₁ = π₂) (hi : ∀ J ∈ π₁, πi₁ J = πi₂ J) : π₁.bUnion πi₁ = π₂.bUnion πi₂ := by { subst π₂, ext J, simp [hi] { contextual := tt } } lemma bUnion_congr_of_le (h : π₁ = π₂) (hi : ∀ J ≤ I, πi₁ J = πi₂ J) : π₁.bUnion πi₁ = π₂.bUnion πi₂ := bUnion_congr h $ λ J hJ, hi J (π₁.le_of_mem hJ) @[simp] lemma Union_bUnion (πi : Π J : box ι, prepartition J) : (π.bUnion πi).Union = ⋃ J ∈ π, (πi J).Union := by simp [prepartition.Union] @[simp] lemma sum_bUnion_boxes {M : Type*} [add_comm_monoid M] (π : prepartition I) (πi : Π J, prepartition J) (f : box ι → M) : ∑ J in π.boxes.bUnion (λ J, (πi J).boxes), f J = ∑ J in π.boxes, ∑ J' in (πi J).boxes, f J' := begin refine finset.sum_bUnion (λ J₁ h₁ J₂ h₂ hne, finset.disjoint_left.2 $ λ J' h₁' h₂', _), exact hne (π.eq_of_le_of_le h₁ h₂ ((πi J₁).le_of_mem h₁') ((πi J₂).le_of_mem h₂')) end /-- Given a box `J ∈ π.bUnion πi`, returns the box `J' ∈ π` such that `J ∈ πi J'`. For `J ∉ π.bUnion πi`, returns `I`. -/ def bUnion_index (πi : Π J, prepartition J) (J : box ι) : box ι := if hJ : J ∈ π.bUnion πi then (π.mem_bUnion.1 hJ).some else I lemma bUnion_index_mem (hJ : J ∈ π.bUnion πi) : π.bUnion_index πi J ∈ π := by { rw [bUnion_index, dif_pos hJ], exact (π.mem_bUnion.1 hJ).some_spec.fst } lemma bUnion_index_le (πi : Π J, prepartition J) (J : box ι) : π.bUnion_index πi J ≤ I := begin by_cases hJ : J ∈ π.bUnion πi, { exact π.le_of_mem (π.bUnion_index_mem hJ) }, { rw [bUnion_index, dif_neg hJ], exact le_rfl } end lemma mem_bUnion_index (hJ : J ∈ π.bUnion πi) : J ∈ πi (π.bUnion_index πi J) := by convert (π.mem_bUnion.1 hJ).some_spec.snd; exact dif_pos hJ lemma le_bUnion_index (hJ : J ∈ π.bUnion πi) : J ≤ π.bUnion_index πi J := le_of_mem _ (π.mem_bUnion_index hJ) /-- Uniqueness property of `box_integral.partition.bUnion_index`. -/ lemma bUnion_index_of_mem (hJ : J ∈ π) {J'} (hJ' : J' ∈ πi J) : π.bUnion_index πi J' = J := have J' ∈ π.bUnion πi, from π.mem_bUnion.2 ⟨J, hJ, hJ'⟩, π.eq_of_le_of_le (π.bUnion_index_mem this) hJ (π.le_bUnion_index this) (le_of_mem _ hJ') lemma bUnion_assoc (πi : Π J, prepartition J) (πi' : box ι → Π J : box ι, prepartition J) : π.bUnion (λ J, (πi J).bUnion (πi' J)) = (π.bUnion πi).bUnion (λ J, πi' (π.bUnion_index πi J) J) := begin ext J, simp only [mem_bUnion, exists_prop], fsplit, { rintro ⟨J₁, hJ₁, J₂, hJ₂, hJ⟩, refine ⟨J₂, ⟨J₁, hJ₁, hJ₂⟩, _⟩, rwa π.bUnion_index_of_mem hJ₁ hJ₂ }, { rintro ⟨J₁, ⟨J₂, hJ₂, hJ₁⟩, hJ⟩, refine ⟨J₂, hJ₂, J₁, hJ₁, _⟩, rwa π.bUnion_index_of_mem hJ₂ hJ₁ at hJ } end /-- Create a `box_integral.prepartition` from a collection of possibly empty boxes by filtering out the empty one if it exists. -/ def of_with_bot (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) : prepartition I := { boxes := boxes.erase_none, le_of_mem' := λ J hJ, begin rw mem_erase_none at hJ, simpa only [with_bot.some_eq_coe, with_bot.coe_le_coe] using le_of_mem _ hJ end, pairwise_disjoint := λ J₁ h₁ J₂ h₂ hne, begin simp only [mem_coe, mem_erase_none] at h₁ h₂, exact box.disjoint_coe.1 (pairwise_disjoint h₁ h₂ (mt option.some_inj.1 hne)) end } @[simp] lemma mem_of_with_bot {boxes : finset (with_bot (box ι))} {h₁ h₂} : J ∈ (of_with_bot boxes h₁ h₂ : prepartition I) ↔ (J : with_bot (box ι)) ∈ boxes := mem_erase_none @[simp] lemma Union_of_with_bot (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) : (of_with_bot boxes le_of_mem pairwise_disjoint).Union = ⋃ J ∈ boxes, ↑J := begin suffices : (⋃ (J : box ι) (hJ : ↑J ∈ boxes), ↑J) = ⋃ J ∈ boxes, ↑J, by simpa [of_with_bot, prepartition.Union], simp only [← box.bUnion_coe_eq_coe, @Union_comm _ _ (box ι), @Union_comm _ _ (@eq _ _ _), Union_Union_eq_right] end lemma of_with_bot_le {boxes : finset (with_bot (box ι))} {le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ boxes, J ≠ ⊥ → ∃ J' ∈ π, J ≤ ↑J') : of_with_bot boxes le_of_mem pairwise_disjoint ≤ π := have ∀ (J : box ι), ↑J ∈ boxes → ∃ J' ∈ π, J ≤ J', from λ J hJ, by simpa only [with_bot.coe_le_coe] using H J hJ with_bot.coe_ne_bot, by simpa [of_with_bot, le_def] lemma le_of_with_bot {boxes : finset (with_bot (box ι))} {le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ π, ∃ J' ∈ boxes, ↑J ≤ J') : π ≤ of_with_bot boxes le_of_mem pairwise_disjoint := begin intros J hJ, rcases H J hJ with ⟨J', J'mem, hle⟩, lift J' to box ι using ne_bot_of_le_ne_bot with_bot.coe_ne_bot hle, exact ⟨J', mem_of_with_bot.2 J'mem, with_bot.coe_le_coe.1 hle⟩ end lemma of_with_bot_mono {boxes₁ : finset (with_bot (box ι))} {le_of_mem₁ : ∀ J ∈ boxes₁, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint₁ : set.pairwise (boxes₁ : set (with_bot (box ι))) disjoint} {boxes₂ : finset (with_bot (box ι))} {le_of_mem₂ : ∀ J ∈ boxes₂, (J : with_bot (box ι)) ≤ I} {pairwise_disjoint₂ : set.pairwise (boxes₂ : set (with_bot (box ι))) disjoint} (H : ∀ J ∈ boxes₁, J ≠ ⊥ → ∃ J' ∈ boxes₂, J ≤ J') : of_with_bot boxes₁ le_of_mem₁ pairwise_disjoint₁ ≤ of_with_bot boxes₂ le_of_mem₂ pairwise_disjoint₂ := le_of_with_bot _ $ λ J hJ, H J (mem_of_with_bot.1 hJ) with_bot.coe_ne_bot lemma sum_of_with_bot {M : Type*} [add_comm_monoid M] (boxes : finset (with_bot (box ι))) (le_of_mem : ∀ J ∈ boxes, (J : with_bot (box ι)) ≤ I) (pairwise_disjoint : set.pairwise (boxes : set (with_bot (box ι))) disjoint) (f : box ι → M) : ∑ J in (of_with_bot boxes le_of_mem pairwise_disjoint).boxes, f J = ∑ J in boxes, option.elim 0 f J := finset.sum_erase_none _ _ /-- Restrict a prepartition to a box. -/ def restrict (π : prepartition I) (J : box ι) : prepartition J := of_with_bot (π.boxes.image (λ J', J ⊓ J')) (λ J' hJ', by { rcases finset.mem_image.1 hJ' with ⟨J', -, rfl⟩, exact inf_le_left }) begin simp only [set.pairwise, on_fun, finset.mem_coe, finset.mem_image], rintro _ ⟨J₁, h₁, rfl⟩ _ ⟨J₂, h₂, rfl⟩ Hne, have : J₁ ≠ J₂, by { rintro rfl, exact Hne rfl }, exact ((box.disjoint_coe.2 $ π.disjoint_coe_of_mem h₁ h₂ this).inf_left' _).inf_right' _ end @[simp] lemma mem_restrict : J₁ ∈ π.restrict J ↔ ∃ (J' ∈ π), (J₁ : with_bot (box ι)) = J ⊓ J' := by simp [restrict, eq_comm] lemma mem_restrict' : J₁ ∈ π.restrict J ↔ ∃ (J' ∈ π), (J₁ : set (ι → ℝ)) = J ∩ J' := by simp only [mem_restrict, ← box.with_bot_coe_inj, box.coe_inf, box.coe_coe] @[mono] lemma restrict_mono {π₁ π₂ : prepartition I} (Hle : π₁ ≤ π₂) : π₁.restrict J ≤ π₂.restrict J := begin refine of_with_bot_mono (λ J₁ hJ₁ hne, _), rw finset.mem_image at hJ₁, rcases hJ₁ with ⟨J₁, hJ₁, rfl⟩, rcases Hle hJ₁ with ⟨J₂, hJ₂, hle⟩, exact ⟨_, finset.mem_image_of_mem _ hJ₂, inf_le_inf_left _ $ with_bot.coe_le_coe.2 hle⟩ end lemma monotone_restrict : monotone (λ π : prepartition I, restrict π J) := λ π₁ π₂, restrict_mono /-- Restricting to a larger box does not change the set of boxes. We cannot claim equality of prepartitions because they have different types. -/ lemma restrict_boxes_of_le (π : prepartition I) (h : I ≤ J) : (π.restrict J).boxes = π.boxes := begin simp only [restrict, of_with_bot, erase_none_eq_bUnion], refine finset.image_bUnion.trans _, refine (finset.bUnion_congr rfl _).trans finset.bUnion_singleton_eq_self, intros J' hJ', rw [inf_of_le_right, ← with_bot.some_eq_coe, option.to_finset_some], exact with_bot.coe_le_coe.2 ((π.le_of_mem hJ').trans h) end @[simp] lemma restrict_self : π.restrict I = π := injective_boxes $ restrict_boxes_of_le π le_rfl @[simp] lemma Union_restrict : (π.restrict J).Union = J ∩ π.Union := by simp [restrict, ← inter_Union, ← Union_def] @[simp] lemma restrict_bUnion (πi : Π J, prepartition J) (hJ : J ∈ π) : (π.bUnion πi).restrict J = πi J := begin refine (eq_of_boxes_subset_Union_superset (λ J₁ h₁, _) _).symm, { refine (mem_restrict _).2 ⟨J₁, π.mem_bUnion.2 ⟨J, hJ, h₁⟩, (inf_of_le_right _).symm⟩, exact with_bot.coe_le_coe.2 (le_of_mem _ h₁) }, { simp only [Union_restrict, Union_bUnion, set.subset_def, set.mem_inter_iff, set.mem_Union], rintro x ⟨hxJ, J₁, h₁, hx⟩, obtain rfl : J = J₁, from π.eq_of_mem_of_mem hJ h₁ hxJ (Union_subset _ hx), exact hx } end lemma bUnion_le_iff {πi : Π J, prepartition J} {π' : prepartition I} : π.bUnion πi ≤ π' ↔ ∀ J ∈ π, πi J ≤ π'.restrict J := begin fsplit; intros H J hJ, { rw ← π.restrict_bUnion πi hJ, exact restrict_mono H }, { rw mem_bUnion at hJ, rcases hJ with ⟨J₁, h₁, hJ⟩, rcases H J₁ h₁ hJ with ⟨J₂, h₂, Hle⟩, rcases π'.mem_restrict.mp h₂ with ⟨J₃, h₃, H⟩, exact ⟨J₃, h₃, Hle.trans $ with_bot.coe_le_coe.1 $ H.trans_le inf_le_right⟩ } end lemma le_bUnion_iff {πi : Π J, prepartition J} {π' : prepartition I} : π' ≤ π.bUnion πi ↔ π' ≤ π ∧ ∀ J ∈ π, π'.restrict J ≤ πi J := begin refine ⟨λ H, ⟨H.trans (π.bUnion_le πi), λ J hJ, _⟩, _⟩, { rw ← π.restrict_bUnion πi hJ, exact restrict_mono H }, { rintro ⟨H, Hi⟩ J' hJ', rcases H hJ' with ⟨J, hJ, hle⟩, have : J' ∈ π'.restrict J, from π'.mem_restrict.2 ⟨J', hJ', (inf_of_le_right $ with_bot.coe_le_coe.2 hle).symm⟩, rcases Hi J hJ this with ⟨Ji, hJi, hlei⟩, exact ⟨Ji, π.mem_bUnion.2 ⟨J, hJ, hJi⟩, hlei⟩ } end instance : has_inf (prepartition I) := ⟨λ π₁ π₂, π₁.bUnion (λ J, π₂.restrict J)⟩ lemma inf_def (π₁ π₂ : prepartition I) : π₁ ⊓ π₂ = π₁.bUnion (λ J, π₂.restrict J) := rfl @[simp] lemma mem_inf {π₁ π₂ : prepartition I} : J ∈ π₁ ⊓ π₂ ↔ ∃ (J₁ ∈ π₁) (J₂ ∈ π₂), (J : with_bot (box ι)) = J₁ ⊓ J₂ := by simp only [inf_def, mem_bUnion, mem_restrict] @[simp] lemma Union_inf (π₁ π₂ : prepartition I) : (π₁ ⊓ π₂).Union = π₁.Union ∩ π₂.Union := by simp only [inf_def, Union_bUnion, Union_restrict, ← Union_inter, ← Union_def] instance : semilattice_inf (prepartition I) := { inf_le_left := λ π₁ π₂, π₁.bUnion_le _, inf_le_right := λ π₁ π₂, (bUnion_le_iff _).2 (λ J hJ, le_rfl), le_inf := λ π π₁ π₂ h₁ h₂, π₁.le_bUnion_iff.2 ⟨h₁, λ J hJ, restrict_mono h₂⟩, .. prepartition.has_inf, .. prepartition.partial_order } /-- The prepartition with boxes `{J ∈ π | p J}`. -/ @[simps] def filter (π : prepartition I) (p : box ι → Prop) : prepartition I := { boxes := π.boxes.filter p, le_of_mem' := λ J hJ, π.le_of_mem (mem_filter.1 hJ).1, pairwise_disjoint := λ J₁ h₁ J₂ h₂, π.disjoint_coe_of_mem (mem_filter.1 h₁).1 (mem_filter.1 h₂).1 } @[simp] lemma mem_filter {p : box ι → Prop} : J ∈ π.filter p ↔ J ∈ π ∧ p J := finset.mem_filter lemma filter_le (π : prepartition I) (p : box ι → Prop) : π.filter p ≤ π := λ J hJ, let ⟨hπ, hp⟩ := π.mem_filter.1 hJ in ⟨J, hπ, le_rfl⟩ lemma filter_of_true {p : box ι → Prop} (hp : ∀ J ∈ π, p J) : π.filter p = π := by { ext J, simpa using hp J } @[simp] lemma filter_true : π.filter (λ _, true) = π := π.filter_of_true (λ _ _, trivial) @[simp] lemma Union_filter_not (π : prepartition I) (p : box ι → Prop) : (π.filter (λ J, ¬p J)).Union = π.Union \ (π.filter p).Union := begin simp only [prepartition.Union], convert (@set.bUnion_diff_bUnion_eq _ (box ι) π.boxes (π.filter p).boxes coe _).symm, { ext J x, simp { contextual := tt } }, { convert π.pairwise_disjoint, simp } end lemma sum_fiberwise {α M} [add_comm_monoid M] (π : prepartition I) (f : box ι → α) (g : box ι → M) : ∑ y in π.boxes.image f, ∑ J in (π.filter (λ J, f J = y)).boxes, g J = ∑ J in π.boxes, g J := by convert sum_fiberwise_of_maps_to (λ _, finset.mem_image_of_mem f) g /-- Union of two disjoint prepartitions. -/ @[simps] def disj_union (π₁ π₂ : prepartition I) (h : disjoint π₁.Union π₂.Union) : prepartition I := { boxes := π₁.boxes ∪ π₂.boxes, le_of_mem' := λ J hJ, (finset.mem_union.1 hJ).elim π₁.le_of_mem π₂.le_of_mem, pairwise_disjoint := suffices ∀ (J₁ ∈ π₁) (J₂ ∈ π₂), J₁ ≠ J₂ → disjoint (J₁ : set (ι → ℝ)) J₂, by simpa [pairwise_union_of_symmetric (symmetric_disjoint.comap _), pairwise_disjoint], λ J₁ h₁ J₂ h₂ _, h.mono (π₁.subset_Union h₁) (π₂.subset_Union h₂) } @[simp] lemma mem_disj_union (H : disjoint π₁.Union π₂.Union) : J ∈ π₁.disj_union π₂ H ↔ J ∈ π₁ ∨ J ∈ π₂ := finset.mem_union @[simp] lemma Union_disj_union (h : disjoint π₁.Union π₂.Union) : (π₁.disj_union π₂ h).Union = π₁.Union ∪ π₂.Union := by simp [disj_union, prepartition.Union, Union_or, Union_union_distrib] @[simp] lemma sum_disj_union_boxes {M : Type*} [add_comm_monoid M] (h : disjoint π₁.Union π₂.Union) (f : box ι → M) : ∑ J in π₁.boxes ∪ π₂.boxes, f J = ∑ J in π₁.boxes, f J + ∑ J in π₂.boxes, f J := sum_union $ disjoint_boxes_of_disjoint_Union h section distortion variable [fintype ι] /-- The distortion of a prepartition is the maximum of the distortions of the boxes of this prepartition. -/ def distortion : ℝ≥0 := π.boxes.sup box.distortion lemma distortion_le_of_mem (h : J ∈ π) : J.distortion ≤ π.distortion := le_sup h lemma distortion_le_iff {c : ℝ≥0} : π.distortion ≤ c ↔ ∀ J ∈ π, box.distortion J ≤ c := finset.sup_le_iff lemma distortion_bUnion (π : prepartition I) (πi : Π J, prepartition J) : (π.bUnion πi).distortion = π.boxes.sup (λ J, (πi J).distortion) := sup_bUnion _ _ @[simp] lemma distortion_disj_union (h : disjoint π₁.Union π₂.Union) : (π₁.disj_union π₂ h).distortion = max π₁.distortion π₂.distortion := sup_union lemma distortion_of_const {c} (h₁ : π.boxes.nonempty) (h₂ : ∀ J ∈ π, box.distortion J = c) : π.distortion = c := (sup_congr rfl h₂).trans (sup_const h₁ _) @[simp] lemma distortion_top (I : box ι) : distortion (⊤ : prepartition I) = I.distortion := sup_singleton @[simp] lemma distortion_bot (I : box ι) : distortion (⊥ : prepartition I) = 0 := sup_empty end distortion /-- A prepartition `π` of `I` is a partition if the boxes of `π` cover the whole `I`. -/ def is_partition (π : prepartition I) := ∀ x ∈ I, ∃ J ∈ π, x ∈ J lemma is_partition_iff_Union_eq {π : prepartition I} : π.is_partition ↔ π.Union = I := by simp_rw [is_partition, set.subset.antisymm_iff, π.Union_subset, true_and, set.subset_def, mem_Union, box.mem_coe] @[simp] lemma is_partition_single_iff (h : J ≤ I) : is_partition (single I J h) ↔ J = I := by simp [is_partition_iff_Union_eq] lemma is_partition_top (I : box ι) : is_partition (⊤ : prepartition I) := λ x hx, ⟨I, mem_top.2 rfl, hx⟩ namespace is_partition variables {π} lemma Union_eq (h : π.is_partition) : π.Union = I := is_partition_iff_Union_eq.1 h lemma Union_subset (h : π.is_partition) (π₁ : prepartition I) : π₁.Union ⊆ π.Union := h.Union_eq.symm ▸ π₁.Union_subset protected lemma exists_unique (h : π.is_partition) (hx : x ∈ I) : ∃! J ∈ π, x ∈ J := begin rcases h x hx with ⟨J, h, hx⟩, exact exists_unique.intro2 J h hx (λ J' h' hx', π.eq_of_mem_of_mem h' h hx' hx), end lemma nonempty_boxes (h : π.is_partition) : π.boxes.nonempty := let ⟨J, hJ, _⟩ := h _ I.upper_mem in ⟨J, hJ⟩ lemma eq_of_boxes_subset (h₁ : π₁.is_partition) (h₂ : π₁.boxes ⊆ π₂.boxes) : π₁ = π₂ := eq_of_boxes_subset_Union_superset h₂ $ h₁.Union_subset _ lemma le_iff (h : π₂.is_partition) : π₁ ≤ π₂ ↔ ∀ (J ∈ π₁) (J' ∈ π₂), (J ∩ J' : set (ι → ℝ)).nonempty → J ≤ J' := le_iff_nonempty_imp_le_and_Union_subset.trans $ and_iff_left $ h.Union_subset _ protected lemma bUnion (h : is_partition π) (hi : ∀ J ∈ π, is_partition (πi J)) : is_partition (π.bUnion πi) := λ x hx, let ⟨J, hJ, hxi⟩ := h x hx, ⟨Ji, hJi, hx⟩ := hi J hJ x hxi in ⟨Ji, π.mem_bUnion.2 ⟨J, hJ, hJi⟩, hx⟩ protected lemma restrict (h : is_partition π) (hJ : J ≤ I) : is_partition (π.restrict J) := is_partition_iff_Union_eq.2 $ by simp [h.Union_eq, hJ] protected lemma inf (h₁ : is_partition π₁) (h₂ : is_partition π₂) : is_partition (π₁ ⊓ π₂) := is_partition_iff_Union_eq.2 $ by simp [h₁.Union_eq, h₂.Union_eq] end is_partition lemma Union_bUnion_partition (h : ∀ J ∈ π, (πi J).is_partition) : (π.bUnion πi).Union = π.Union := (Union_bUnion _ _).trans $ Union_congr_of_surjective id surjective_id $ λ J, Union_congr_of_surjective id surjective_id $ λ hJ, (h J hJ).Union_eq lemma is_partition_disj_union_of_eq_diff (h : π₂.Union = I \ π₁.Union) : is_partition (π₁.disj_union π₂ (h.symm ▸ disjoint_diff)) := is_partition_iff_Union_eq.2 $ (Union_disj_union _).trans $ by simp [h, π₁.Union_subset] end prepartition end box_integral
bf02f39c69eece55e427e74766c1fa1810a2f576
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Meta/Tactic/ElimInfo.lean
bb4dcc2c7ed3c2359d69e27e0024b174fa1f9d3e
[ "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
3,820
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.Basic import Lean.Meta.Check namespace Lean.Meta structure ElimAltInfo where name : Name numFields : Nat deriving Repr structure ElimInfo where name : Name motivePos : Nat targetsPos : Array Nat := #[] altsInfo : Array ElimAltInfo := #[] deriving Repr def getElimInfo (declName : Name) : MetaM ElimInfo := do let declInfo ← getConstInfo declName forallTelescopeReducing declInfo.type fun xs type => do let motive := type.getAppFn let targets := type.getAppArgs unless motive.isFVar && targets.all (·.isFVar) && targets.size > 0 do throwError "unexpected eliminator resulting type{indentExpr type}" let motiveType ← inferType motive forallTelescopeReducing motiveType fun motiveArgs motiveResultType => do unless motiveArgs.size == targets.size do throwError "unexpected number of arguments at motive type{indentExpr motiveType}" unless motiveResultType.isSort do throwError "motive result type must be a sort{indentExpr motiveType}" let some motivePos ← pure (xs.indexOf? motive) | throwError "unexpected eliminator type{indentExpr declInfo.type}" let targetsPos ← targets.mapM fun target => do match xs.indexOf? target with | none => throwError "unexpected eliminator type{indentExpr declInfo.type}" | some targetPos => pure targetPos.val let mut altsInfo := #[] for i in [:xs.size] do let x := xs[i] if x != motive && !targets.contains x then let xDecl ← getLocalDecl x.fvarId! if xDecl.binderInfo.isExplicit then let numFields ← forallTelescopeReducing xDecl.type fun args _ => pure args.size altsInfo := altsInfo.push { name := xDecl.userName, numFields := numFields : ElimAltInfo } pure { name := declName, motivePos := motivePos, targetsPos := targetsPos, altsInfo := altsInfo } /-- Eliminators/recursors may have implicit targets. For builtin recursors, all indices are implicit targets. Given an eliminator and the sequence of explicit targets, this methods returns a new sequence containing implicit and explicit targets. -/ partial def addImplicitTargets (elimInfo : ElimInfo) (targets : Array Expr) : MetaM (Array Expr) := withNewMCtxDepth do let f ← mkConstWithFreshMVarLevels elimInfo.name let targets ← collect (← inferType f) 0 0 #[] let targets ← targets.mapM instantiateMVars for target in targets do if (← hasAssignableMVar target) then throwError "failed to infer implicit target, it contains unresolved metavariables{indentExpr target}" return targets where collect (type : Expr) (argIdx targetIdx : Nat) (targets' : Array Expr) : MetaM (Array Expr) := do match (← whnfD type) with | Expr.forallE _ d b c => if elimInfo.targetsPos.contains argIdx then if c.binderInfo.isExplicit then unless targetIdx < targets.size do throwError "insufficient number of targets for '{elimInfo.name}'" let target := targets[targetIdx] let targetType ← inferType target unless (← isDefEq d targetType) do throwError "target{indentExpr target}\n{← mkHasTypeButIsExpectedMsg targetType d}" collect (b.instantiate1 target) (argIdx+1) (targetIdx+1) (targets'.push target) else let implicitTarget ← mkFreshExprMVar d collect (b.instantiate1 implicitTarget) (argIdx+1) targetIdx (targets'.push implicitTarget) else collect (b.instantiate1 (← mkFreshExprMVar d)) (argIdx+1) targetIdx targets' | _ => return targets' end Lean.Meta
022faca9c4099f1fc58749ed0088edac0b720f0b
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/ring_theory/principal_ideal_domain.lean
a4554f8ebb45baa9d1edfc20e1b13d28f62b6573
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
7,437
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes, Morenikeji Neri -/ import ring_theory.noetherian import ring_theory.unique_factorization_domain universes u v variables {R : Type u} {M : Type v} open set function open submodule open_locale classical /-- An `R`-submodule of `M` is principal if it is generated by one element. -/ class submodule.is_principal [ring R] [add_comm_group M] [module R M] (S : submodule R M) : Prop := (principal [] : ∃ a, S = span R {a}) section prio set_option default_priority 100 -- see Note [default priority] class principal_ideal_domain (R : Type u) extends integral_domain R := (principal : ∀ (S : ideal R), S.is_principal) end prio -- see Note [lower instance priority] attribute [instance, priority 500] principal_ideal_domain.principal namespace submodule.is_principal variables [comm_ring R] [add_comm_group M] [module R M] /-- `generator I`, if `I` is a principal submodule, is the `x ∈ M` such that `span R {x} = I` -/ noncomputable def generator (S : submodule R M) [S.is_principal] : M := classical.some (principal S) lemma span_singleton_generator (S : submodule R M) [S.is_principal] : span R {generator S} = S := eq.symm (classical.some_spec (principal S)) @[simp] lemma generator_mem (S : submodule R M) [S.is_principal] : generator S ∈ S := by { conv_rhs { rw ← span_singleton_generator S }, exact subset_span (mem_singleton _) } lemma mem_iff_eq_smul_generator (S : submodule R M) [S.is_principal] {x : M} : x ∈ S ↔ ∃ s : R, x = s • generator S := by simp_rw [@eq_comm _ x, ← mem_span_singleton, span_singleton_generator] lemma mem_iff_generator_dvd (S : ideal R) [S.is_principal] {x : R} : x ∈ S ↔ generator S ∣ x := (mem_iff_eq_smul_generator S).trans (exists_congr (λ a, by simp only [mul_comm, smul_eq_mul])) lemma eq_bot_iff_generator_eq_zero (S : submodule R M) [S.is_principal] : S = ⊥ ↔ generator S = 0 := by rw [← @span_singleton_eq_bot R M, span_singleton_generator] end submodule.is_principal namespace is_prime open submodule.is_principal ideal lemma to_maximal_ideal [principal_ideal_domain R] {S : ideal R} [hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S := is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin assume T x hST hxS hxT, haveI := principal_ideal_domain.principal S, haveI := principal_ideal_domain.principal T, cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz, cases hpi.2 (show generator T * z ∈ S, from hz ▸ generator_mem S), { have hTS : T ≤ S, rwa [← span_singleton_generator T, submodule.span_le, singleton_subset_iff], exact (hxS $ hTS hxT).elim }, cases (mem_iff_generator_dvd _).1 h with y hy, have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS, rw [← mul_one (generator S), hy, mul_left_comm, domain.mul_right_inj this] at hz, exact hz.symm ▸ ideal.mul_mem_right _ (generator_mem T) end⟩ end is_prime section open euclidean_domain variable [euclidean_domain R] lemma mod_mem_iff {S : ideal R} {x y : R} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := ⟨λ hxy, div_add_mod x y ▸ ideal.add_mem S (ideal.mul_mem_right S hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ ideal.sub_mem S hx (ideal.mul_mem_right S hy)⟩ @[priority 100] -- see Note [lower instance priority] instance euclidean_domain.to_principal_ideal_domain : principal_ideal_domain R := { principal := λ S, by exactI ⟨if h : {x : R | x ∈ S ∧ x ≠ 0}.nonempty then have wf : well_founded (euclidean_domain.r : R → R → Prop) := euclidean_domain.r_well_founded, have hmin : well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ∈ S ∧ well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ≠ 0, from well_founded.min_mem wf {x : R | x ∈ S ∧ x ≠ 0} h, ⟨well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h, submodule.ext $ λ x, ⟨λ hx, div_add_mod x (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ▸ (ideal.mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $ have (x % (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ∉ {x : R | x ∈ S ∧ x ≠ 0}), from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2), have x % well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h = 0, by finish [(mod_mem_iff hmin.1).2 hx], by simp *), λ hx, let ⟨y, hy⟩ := ideal.mem_span_singleton.1 hx in hy.symm ▸ ideal.mul_mem_right _ hmin.1⟩⟩ else ⟨0, submodule.ext $ λ a, by rw [← @submodule.bot_coe R R _ _ ring.to_module, span_eq, submodule.mem_bot]; exact ⟨λ haS, by_contradiction $ λ ha0, h ⟨a, ⟨haS, ha0⟩⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩⟩ } end namespace principal_ideal_domain variables [principal_ideal_domain R] @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring : is_noetherian_ring R := ⟨assume s : ideal R, begin rcases (principal s).principal with ⟨a, rfl⟩, rw [← finset.coe_singleton], exact ⟨{a}, submodule.ext' rfl⟩ end⟩ section open_locale classical lemma factors_decreasing (b₁ b₂ : R) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) : submodule.span R ({b₁ * b₂} : set R) < submodule.span R {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h, h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] end lemma is_maximal_of_irreducible {p : R} (hp : irreducible p) : ideal.is_maximal (span R ({p} : set R)) := ⟨mt ideal.span_singleton_eq_top.1 hp.1, λ I hI, begin rcases principal I with ⟨a, rfl⟩, erw ideal.span_singleton_eq_top, unfreezeI, rcases ideal.span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩, refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)), erw [ideal.span_singleton_le_span_singleton, mul_dvd_of_is_unit_right hb] end⟩ lemma irreducible_iff_prime {p : R} : irreducible p ↔ prime p := ⟨λ hp, (ideal.span_singleton_prime hp.ne_zero).1 $ (is_maximal_of_irreducible hp).is_prime, irreducible_of_prime⟩ lemma associates_irreducible_iff_prime : ∀{p : associates R}, irreducible p ↔ p.prime := associates.forall_associated.2 $ assume a, by rw [associates.irreducible_mk_iff, associates.prime_mk, irreducible_iff_prime] section open_locale classical noncomputable def factors (a : R) : multiset R := if h : a = 0 then ∅ else classical.some (is_noetherian_ring.exists_factors a h) lemma factors_spec (a : R) (h : a ≠ 0) : (∀b∈factors a, irreducible b) ∧ associated a (factors a).prod := begin unfold factors, rw [dif_neg h], exact classical.some_spec (is_noetherian_ring.exists_factors a h) end /-- The unique factorization domain structure given by the principal ideal domain. This is not added as type class instance, since the `factors` might be computed in a different way. E.g. factors could return normalized values. -/ noncomputable def to_unique_factorization_domain : unique_factorization_domain R := { factors := factors, factors_prod := assume a ha, associated.symm (factors_spec a ha).2, prime_factors := assume a ha, by simpa [irreducible_iff_prime] using (factors_spec a ha).1 } end end principal_ideal_domain
dde50996c024354008bfd57bf8d48e8fa060bf7b
bb31430994044506fa42fd667e2d556327e18dfe
/src/linear_algebra/isomorphisms.lean
b77b3abdc038bf395a233a9b39bc458aaaecdb71
[ "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
6,401
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, Kevin Buzzard, Yury Kudryashov -/ import linear_algebra.quotient /-! # Isomorphism theorems for modules. * The Noether's first, second, and third isomorphism theorems for modules are proved as `linear_map.quot_ker_equiv_range`, `linear_map.quotient_inf_equiv_sup_quotient` and `submodule.quotient_quotient_equiv_quotient`. -/ universes u v variables {R M M₂ M₃ : Type*} variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-! The first and second isomorphism theorems for modules. -/ namespace linear_map open submodule section isomorphism_laws /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : (M ⧸ f.ker) ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_rfl) $ ker_eq_bot.mp $ submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans (linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _) /-- The first isomorphism theorem for surjective linear maps. -/ noncomputable def quot_ker_equiv_of_surjective (f : M →ₗ[R] M₂) (hf : function.surjective f) : (M ⧸ f.ker) ≃ₗ[R] M₂ := f.quot_ker_equiv_range.trans (linear_equiv.of_top f.range (linear_map.range_eq_top.2 hf)) @[simp] lemma quot_ker_equiv_range_apply_mk (x : M) : (f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x := rfl @[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) : f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x := f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x) /-- Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')` to `x + p'`, where `p` and `p'` are submodules of an ambient module. -/ def quotient_inf_to_sup_quotient (p p' : submodule R M) : p ⧸ (comap p.subtype (p ⊓ p')) →ₗ[R] _ ⧸ (comap (p ⊔ p').subtype p') := by exact (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf_right _ le_sup_left) end /-- Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism. -/ noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) : (p ⧸ (comap p.subtype (p ⊓ p'))) ≃ₗ[R] _ ⧸ (comap (p ⊔ p').subtype p') := by exact linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') ⟨begin rw [← ker_eq_bot, quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end, begin rw [← range_eq_top, quotient_inf_to_sup_quotient, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end⟩ @[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) : ⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl @[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) : quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) = submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) := rfl lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M) (x : p ⊔ p') (hx : (x:M) ∈ p) : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = submodule.quotient.mk ⟨x, hx⟩ := (linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply] @[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M} {x : p ⊔ p'} : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' := (linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply] lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'} (hx : (x:M) ∈ p') : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 := quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx end isomorphism_laws end linear_map /-! The third isomorphism theorem for modules. -/ namespace submodule variables (S T : submodule R M) (h : S ≤ T) /-- The map from the third isomorphism theorem for modules: `(M / S) / (T / S) → M / T`. -/ def quotient_quotient_equiv_quotient_aux (h : S ≤ T) : (M ⧸ S) ⧸ (T.map S.mkq) →ₗ[R] M ⧸ T := by exact liftq _ (mapq S T linear_map.id h) (by { rintro _ ⟨x, hx, rfl⟩, rw [linear_map.mem_ker, mkq_apply, mapq_apply], exact (quotient.mk_eq_zero _).mpr hx }) @[simp] lemma quotient_quotient_equiv_quotient_aux_mk (x : M ⧸ S) : quotient_quotient_equiv_quotient_aux S T h (quotient.mk x) = mapq S T linear_map.id h x := liftq_apply _ _ _ @[simp] lemma quotient_quotient_equiv_quotient_aux_mk_mk (x : M) : quotient_quotient_equiv_quotient_aux S T h (quotient.mk (quotient.mk x)) = quotient.mk x := by rw [quotient_quotient_equiv_quotient_aux_mk, mapq_apply, linear_map.id_apply] /-- **Noether's third isomorphism theorem** for modules: `(M / S) / (T / S) ≃ M / T`. -/ def quotient_quotient_equiv_quotient : ((M ⧸ S) ⧸ (T.map S.mkq)) ≃ₗ[R] M ⧸ T := { to_fun := quotient_quotient_equiv_quotient_aux S T h, inv_fun := mapq _ _ (mkq S) (le_comap_map _ _), left_inv := λ x, quotient.induction_on' x $ λ x, quotient.induction_on' x $ λ x, by simp, right_inv := λ x, quotient.induction_on' x $ λ x, by simp, .. quotient_quotient_equiv_quotient_aux S T h } /-- Corollary of the third isomorphism theorem: `[S : T] [M : S] = [M : T]` -/ lemma card_quotient_mul_card_quotient (S T : submodule R M) (hST : T ≤ S) [decidable_pred (λ x, x ∈ S.map T.mkq)] [fintype (M ⧸ S)] [fintype (M ⧸ T)] : fintype.card (S.map T.mkq) * fintype.card (M ⧸ S) = fintype.card (M ⧸ T) := by rw [submodule.card_eq_card_quotient_mul_card (map T.mkq S), fintype.card_eq.mpr ⟨(quotient_quotient_equiv_quotient T S hST).to_equiv⟩] end submodule
c65a8f694fa3bd6fa8c4ee0d1d4123d90b845204
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/topology/metric_space/polish.lean
d30db5f66922496d15001a66f6a87090269fea23
[ "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
22,571
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.normed_space.basic import topology.metric_space.pi_nat import topology.metric_space.isometry import topology.metric_space.gluing /-! # Polish spaces A topological space is Polish if its topology is second-countable and there exists a compatible complete metric. This is the class of spaces that is well-behaved with respect to measure theory. In this file, we establish the basic properties of Polish spaces. ## Main definitions and results * `polish_space α` is a mixin typeclass on a topological space, requiring that the topology is second-countable and compatible with a complete metric. To endow the space with such a metric, use in a proof `letI := upgrade_polish_space α`. We register an instance from complete second-countable metric spaces to Polish spaces, not the other way around. * We register that countable products and sums of Polish spaces are Polish. * `is_closed.polish_space`: a closed subset of a Polish space is Polish. * `is_open.polish_space`: an open subset of a Polish space is Polish. * `exists_nat_nat_continuous_surjective`: any nonempty Polish space is the continuous image of the fundamental Polish space `ℕ → ℕ`. A fundamental property of Polish spaces is that one can put finer topologies, still Polish, with additional properties: * `exists_polish_space_forall_le`: on a topological space, consider countably many topologies `t n`, all Polish and finer than the original topology. Then there exists another Polish topology which is finer than all the `t n`. * `is_clopenable s` is a property of a subset `s` of a topological space, requiring that there exists a finer topology, which is Polish, for which `s` becomes open and closed. We show that this property is satisfied for open sets, closed sets, for complements, and for countable unions. Once Borel-measurable sets are defined in later files, it will follow that any Borel-measurable set is clopenable. Once the Lusin-Souslin theorem is proved using analytic sets, we will even show that a set is clopenable if and only if it is Borel-measurable, see `is_clopenable_iff_measurable_set`. -/ noncomputable theory open_locale classical topological_space filter open topological_space set metric filter function variables {α : Type*} {β : Type*} /-! ### Basic properties of Polish spaces -/ /-- A Polish space is a topological space with second countable topology, that can be endowed with a metric for which it is complete. We register an instance from complete second countable metric space to polish space, and not the other way around as this is the most common use case. To endow a Polish space with a complete metric space structure, do `letI := upgrade_polish_space α`. -/ class polish_space (α : Type*) [h : topological_space α] : Prop := (second_countable [] : second_countable_topology α) (complete : ∃ m : metric_space α, m.to_uniform_space.to_topological_space = h ∧ @complete_space α m.to_uniform_space) /-- A convenience class, for a Polish space endowed with a complete metric. No instance of this class should be registered: It should be used as `letI := upgrade_polish_space α` to endow a Polish space with a complete metric. -/ class upgraded_polish_space (α : Type*) extends metric_space α, second_countable_topology α, complete_space α @[priority 100] instance polish_space_of_complete_second_countable [m : metric_space α] [h : second_countable_topology α] [h' : complete_space α] : polish_space α := { second_countable := h, complete := ⟨m, rfl, h'⟩ } /-- Construct on a Polish space a metric (compatible with the topology) which is complete. -/ def polish_space_metric (α : Type*) [ht : topological_space α] [h : polish_space α] : metric_space α := h.complete.some.replace_topology h.complete.some_spec.1.symm lemma complete_polish_space_metric (α : Type*) [ht : topological_space α] [h : polish_space α] : @complete_space α (polish_space_metric α).to_uniform_space := begin convert h.complete.some_spec.2, exact metric_space.replace_topology_eq _ _ end /-- This definition endows a Polish space with a complete metric. Use it as: `letI := upgrade_polish_space α`. -/ def upgrade_polish_space (α : Type*) [ht : topological_space α] [h : polish_space α] : upgraded_polish_space α := begin letI := polish_space_metric α, exact { .. complete_polish_space_metric α, .. polish_space.second_countable α } end namespace polish_space @[priority 100] instance t2_space (α : Type*) [topological_space α] [polish_space α] : t2_space α := by { letI := upgrade_polish_space α, apply_instance } /-- A countable product of Polish spaces is Polish. -/ instance pi_countable {ι : Type*} [encodable ι] {E : ι → Type*} [∀ i, topological_space (E i)] [∀ i, polish_space (E i)] : polish_space (Π i, E i) := begin letI := λ i, upgrade_polish_space (E i), letI : metric_space (Π i, E i) := pi_countable.metric_space, apply_instance, end /-- Without this instance, `polish_space (ℕ → ℕ)` is not found by typeclass inference. -/ instance nat_fun [topological_space α] [polish_space α] : polish_space (ℕ → α) := by apply_instance /-- A countable disjoint union of Polish spaces is Polish. -/ instance sigma {ι : Type*} [encodable ι] {E : ι → Type*} [∀ n, topological_space (E n)] [∀ n, polish_space (E n)] : polish_space (Σ n, E n) := begin letI := λ n, upgrade_polish_space (E n), letI : metric_space (Σ n, E n) := sigma.metric_space, haveI : complete_space (Σ n, E n) := sigma.complete_space, apply_instance end /-- The disjoint union of two Polish spaces is Polish. -/ instance sum [topological_space α] [polish_space α] [topological_space β] [polish_space β] : polish_space (α ⊕ β) := begin letI := upgrade_polish_space α, letI := upgrade_polish_space β, letI : metric_space (α ⊕ β) := metric_space_sum, apply_instance end /-- Any nonempty Polish space is the continuous image of the fundamental space `ℕ → ℕ`. -/ lemma exists_nat_nat_continuous_surjective (α : Type*) [topological_space α] [polish_space α] [nonempty α] : ∃ (f : (ℕ → ℕ) → α), continuous f ∧ surjective f := begin letI := upgrade_polish_space α, exact exists_nat_nat_continuous_surjective_of_complete_space α end /-- Given a closed embedding into a Polish space, the source space is also Polish. -/ lemma _root_.closed_embedding.polish_space [topological_space α] [topological_space β] [polish_space β] {f : α → β} (hf : closed_embedding f) : polish_space α := begin letI := upgrade_polish_space β, letI : metric_space α := hf.to_embedding.comap_metric_space f, haveI : second_countable_topology α := hf.to_embedding.second_countable_topology, haveI : complete_space α, { rw complete_space_iff_is_complete_range hf.to_embedding.to_isometry.uniform_inducing, apply is_closed.is_complete, exact hf.closed_range }, apply_instance end /-- Pulling back a Polish topology under an equiv gives again a Polish topology. -/ lemma _root_.equiv.polish_space_induced [t : topological_space β] [polish_space β] (f : α ≃ β) : @polish_space α (t.induced f) := begin letI : topological_space α := t.induced f, exact (f.to_homeomorph_of_inducing ⟨rfl⟩).closed_embedding.polish_space, end /-- A closed subset of a Polish space is also Polish. -/ lemma _root_.is_closed.polish_space {α : Type*} [topological_space α] [polish_space α] {s : set α} (hs : is_closed s) : polish_space s := (is_closed.closed_embedding_subtype_coe hs).polish_space /-- A sequence of type synonyms of a given type `α`, useful in the proof of `exists_polish_space_forall_le` to endow each copy with a different topology. -/ @[nolint unused_arguments has_nonempty_instance] def aux_copy (α : Type*) {ι : Type*} (i : ι) : Type* := α /-- Given a Polish space, and countably many finer Polish topologies, there exists another Polish topology which is finer than all of them. -/ lemma exists_polish_space_forall_le {ι : Type*} [encodable ι] [t : topological_space α] [p : polish_space α] (m : ι → topological_space α) (hm : ∀ n, m n ≤ t) (h'm : ∀ n, @polish_space α (m n)) : ∃ (t' : topological_space α), (∀ n, t' ≤ m n) ∧ (t' ≤ t) ∧ @polish_space α t' := begin rcases is_empty_or_nonempty ι with hι|hι, { exact ⟨t, λ i, (is_empty.elim hι i : _), le_rfl, p⟩ }, unfreezingI { inhabit ι }, /- Consider the product of infinitely many copies of `α`, each endowed with the topology `m n`. This is a Polish space, as a product of Polish spaces. Pulling back this topology under the diagonal embedding of `α`, one gets a Polish topology which is finer than all the `m n`. -/ letI : ∀ (n : ι), topological_space (aux_copy α n) := λ n, m n, haveI : ∀ (n : ι), polish_space (aux_copy α n) := λ n, h'm n, letI T : topological_space (Π (n : ι), aux_copy α n) := by apply_instance, let f : α → Π (n : ι), aux_copy α n := λ x n, x, -- show that the induced topology is finer than all the `m n`. have T_le_m : ∀ n, T.induced f ≤ m n, { assume n s hs, refine ⟨set.pi ({n} : set ι) (λ i, s), _, _⟩, { apply is_open_set_pi (finite_singleton _), assume a ha, rw mem_singleton_iff.1 ha, exact hs }, { ext x, simp only [singleton_pi, mem_preimage] } }, refine ⟨T.induced f, λ n, T_le_m n, (T_le_m default).trans (hm default), _⟩, -- show that the new topology is Polish, as the pullback of a Polish topology under a closed -- embedding. have A : range f = ⋂ n, {x | x n = x default}, { ext x, split, { rintros ⟨y, rfl⟩, exact mem_Inter.2 (λ n, by simp only [mem_set_of_eq]) }, { assume hx, refine ⟨x default, _⟩, ext1 n, symmetry, exact (mem_Inter.1 hx n : _) } }, have f_closed : is_closed (range f), { rw A, apply is_closed_Inter (λ n, _), have C : ∀ (i : ι), continuous (λ (x : Π n, aux_copy α n), (id (x i) : α)), { assume i, apply continuous.comp _ (continuous_apply i), apply continuous_def.2 (λ s hs, _), exact hm i s hs }, apply is_closed_eq (C n) (C default) }, have K : @_root_.embedding _ _ (T.induced f) T f, { apply function.injective.embedding_induced, assume x y hxy, have : f x default = f y default, by rw hxy, exact this }, have L : @closed_embedding _ _ (T.induced f) T f, { split, { exact K }, { exact f_closed } }, exact @closed_embedding.polish_space _ _ (T.induced f) T (by apply_instance) _ L end /-! ### An open subset of a Polish space is Polish To prove this fact, one needs to construct another metric, giving rise to the same topology, for which the open subset is complete. This is not obvious, as for instance `(0,1) ⊆ ℝ` is not complete for the usual metric of `ℝ`: one should build a new metric that blows up close to the boundary. -/ section complete_copy variables [metric_space α] {s : set α} /-- A type synonym for a subset `s` of a metric space, on which we will construct another metric for which it will be complete. -/ @[nolint has_nonempty_instance] def complete_copy {α : Type*} (s : set α) : Type* := s /-- A distance on a subset `s` of a metric space, designed to make it complete if `s` is open. It is given by `dist' x y = dist x y + |1 / dist x sᶜ - 1 / dist y sᶜ|`, where the second term blows up close to the boundary to ensure that Cauchy sequences for `dist'` remain well inside `s`. -/ def has_dist_complete_copy (s : set α) : has_dist (complete_copy s) := ⟨λ x y, dist x.1 y.1 + abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist y.1 sᶜ)⟩ local attribute [instance] has_dist_complete_copy lemma dist_complete_copy_eq (x y : complete_copy s) : dist x y = dist x.1 y.1 + abs (1/inf_dist x.1 sᶜ - 1 / inf_dist y.1 sᶜ) := rfl lemma dist_le_dist_complete_copy (x y : complete_copy s) : dist x.1 y.1 ≤ dist x y := (le_add_iff_nonneg_right _).2 (abs_nonneg _) /-- A metric space structure on a subset `s` of a metric space, designed to make it complete if `s` is open. It is given by `dist' x y = dist x y + |1 / dist x sᶜ - 1 / dist y sᶜ|`, where the second term blows up close to the boundary to ensure that Cauchy sequences for `dist'` remain well inside `s`. -/ def complete_copy_metric_space (s : set α) : metric_space (complete_copy s) := { dist_self := λ x, by simp [dist_complete_copy_eq], dist_comm := λ x y, by simp [dist_complete_copy_eq, dist_comm, abs_sub_comm], dist_triangle := λ x y z, calc dist x z = dist x.1 z.1 + abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist z.1 sᶜ) : rfl ... ≤ (dist x.1 y.1 + dist y.1 z.1) + (abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist y.1 sᶜ) + abs (1 / inf_dist y.1 sᶜ - 1 / inf_dist z.1 sᶜ)) : begin rw [← real.dist_eq, ← real.dist_eq, ← real.dist_eq], exact add_le_add (dist_triangle _ _ _) (dist_triangle _ _ _) end ... = dist x y + dist y z : by { rw [dist_complete_copy_eq, dist_complete_copy_eq], abel }, eq_of_dist_eq_zero := begin assume x y hxy, apply subtype.coe_injective, refine dist_le_zero.1 _, rw ← hxy, exact dist_le_dist_complete_copy x y end } local attribute [instance] complete_copy_metric_space /-- The identity between the type synonym `complete_copy s` (with its modified metric) and the original subtype `s` is a homeomorphism. -/ def complete_copy_id_homeo (hs : is_open s) (h's : sᶜ.nonempty) : complete_copy s ≃ₜ s := { to_fun := id, inv_fun := id, left_inv := λ x, rfl, right_inv := λ x, rfl, continuous_to_fun := begin have : lipschitz_with 1 (λ (x : complete_copy s), (id x : s)), { apply lipschitz_with.mk_one, exact dist_le_dist_complete_copy }, exact this.continuous, end, continuous_inv_fun := begin apply continuous_iff_continuous_at.2 (λ x, _), suffices H : tendsto (λ (b : s), dist b.1 x.1 + |1 / inf_dist b.1 sᶜ - 1 / inf_dist x.1 sᶜ|) (𝓝 x) (𝓝 (dist x.1 x.1 + abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist x.1 sᶜ))), { rw [continuous_at, tendsto_iff_dist_tendsto_zero], simpa only [sub_self, abs_zero, add_zero, dist_self] using H }, have I : 0 < inf_dist x.val sᶜ, { rw ← hs.is_closed_compl.not_mem_iff_inf_dist_pos h's, simp }, apply tendsto.add, { apply continuous.tendsto, exact continuous_subtype_coe.dist continuous_const }, { refine (tendsto.sub_const _ _).abs, refine tendsto.div tendsto_const_nhds _ I.ne', exact ((continuous_inf_dist_pt _).comp continuous_subtype_coe).tendsto _ } end } lemma complete_space_complete_copy [complete_space α] (hs : is_open s) (h's : sᶜ.nonempty) : complete_space (complete_copy s) := begin refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) (by simp) _, assume u hu, have A : cauchy_seq (λ n, (u n).1), { apply cauchy_seq_of_le_tendsto_0 (λ (n : ℕ), (1/2)^n) (λ n m N hNn hNm, _) _, { exact (dist_le_dist_complete_copy (u n) (u m)).trans (hu N n m hNn hNm).le }, { exact tendsto_pow_at_top_nhds_0_of_lt_1 (by norm_num) (by norm_num) } }, obtain ⟨x, xlim⟩ : ∃ x, tendsto (λ n, (u n).1) at_top (𝓝 x), { haveI : nonempty α := ⟨(u 0).1⟩, exact ⟨_, A.tendsto_lim⟩ }, suffices xs : x ∈ s, { refine ⟨⟨x, xs⟩, _⟩, have L : tendsto (λ n, (id ⟨(u n).1, (u n).2⟩ : s)) at_top (𝓝 (⟨x, xs⟩)), { apply embedding_subtype_coe.tendsto_nhds_iff.2, exact xlim }, convert ((complete_copy_id_homeo hs h's).symm.continuous.tendsto _).comp L, ext1 n, simp [complete_copy_id_homeo] }, obtain ⟨C, hC⟩ : ∃ C, ∀ n, 1 / inf_dist (u n).1 sᶜ < C, { refine ⟨(1/2)^0 + dist (1 / inf_dist (u 0).1 sᶜ) 0, λ n, _⟩, calc 1 / inf_dist (u n).val sᶜ ≤ dist (1 / inf_dist (u n).val sᶜ) 0 : by { rw real.dist_0_eq_abs, exact le_abs_self _ } ... ≤ dist (1 / inf_dist (u n).1 sᶜ) (1 / inf_dist (u 0).1 sᶜ) + dist (1 / inf_dist (u 0).1 sᶜ) 0 : dist_triangle _ _ _ ... ≤ (dist (u n).1 (u 0).1 + dist (1 / inf_dist (u n).1 sᶜ) (1 / inf_dist (u 0).1 sᶜ)) + dist (1 / inf_dist (u 0).1 sᶜ) 0 : add_le_add (le_add_of_nonneg_left dist_nonneg) le_rfl ... = dist (u n) (u 0) + dist (1 / inf_dist (u 0).1 sᶜ) 0 : rfl ... < (1/2)^0 + dist (1 / inf_dist (u 0).1 sᶜ) 0 : add_lt_add_right (hu 0 n 0 (zero_le _) le_rfl) _ }, have Cpos : 0 < C, { apply lt_of_le_of_lt _ (hC 0), simp [inf_dist_nonneg] }, have I : ∀ n, 1/C ≤ inf_dist (u n).1 sᶜ, { assume n, have : 0 < inf_dist (u n).val sᶜ, { apply (hs.is_closed_compl.not_mem_iff_inf_dist_pos h's).1, simp }, rw div_le_iff' Cpos, exact (div_le_iff this).1 (hC n).le }, have I' : 1/C ≤ inf_dist x sᶜ, { have : tendsto (λ n, inf_dist (u n).1 sᶜ) at_top (𝓝 (inf_dist x sᶜ)) := ((continuous_inf_dist_pt sᶜ).tendsto x).comp xlim, exact ge_of_tendsto' this I }, suffices : x ∉ sᶜ, by simpa, apply (hs.is_closed_compl.not_mem_iff_inf_dist_pos h's).2 (lt_of_lt_of_le _ I'), simp [Cpos], end /-- An open subset of a Polish space is also Polish. -/ lemma _root_.is_open.polish_space {α : Type*} [topological_space α] [polish_space α] {s : set α} (hs : is_open s) : polish_space s := begin rcases eq_empty_or_nonempty sᶜ with h's|h's, { simp at h's, apply is_closed.polish_space, rw h's, exact is_closed_univ }, { letI := upgrade_polish_space α, haveI : complete_space (complete_copy s) := complete_space_complete_copy hs h's, haveI : second_countable_topology (complete_copy s) := (complete_copy_id_homeo hs h's).embedding.second_countable_topology, exact (complete_copy_id_homeo hs h's).symm.closed_embedding.polish_space } end end complete_copy /-! ### Clopenable sets in Polish spaces -/ /-- A set in a topological space is clopenable if there exists a finer Polish topology for which this set is open and closed. It turns out that this notion is equivalent to being Borel-measurable, but this is nontrivial (see `is_clopenable_iff_measurable_set`). -/ def is_clopenable [t : topological_space α] (s : set α) : Prop := ∃ (t' : topological_space α), t' ≤ t ∧ @polish_space α t' ∧ @is_closed α t' s ∧ @is_open α t' s /-- Given a closed set `s` in a Polish space, one can construct a finer Polish topology for which `s` is both open and closed. -/ lemma _root_.is_closed.is_clopenable [topological_space α] [polish_space α] {s : set α} (hs : is_closed s) : is_clopenable s := begin /- Both sets `s` and `sᶜ` admit a Polish topology. So does their disjoint union `s ⊕ sᶜ`. Pulling back this topology by the canonical bijection with `α` gives the desired Polish topology in which `s` is both open and closed. -/ haveI : polish_space s := hs.polish_space, let t : set α := sᶜ, haveI : polish_space t := hs.is_open_compl.polish_space, let f : α ≃ (s ⊕ t) := (equiv.set.sum_compl s).symm, letI T : topological_space (s ⊕ t) := by apply_instance, let t' : topological_space α := T.induced f, let g := @equiv.to_homeomorph_of_inducing _ _ t' T f { induced := rfl }, have A : g ⁻¹' (range (sum.inl : s → s ⊕ t)) = s, { ext x, by_cases h : x ∈ s, { simp only [equiv.set.sum_compl_symm_apply_of_mem, h, mem_preimage, equiv.to_fun_as_coe, mem_range_self, equiv.to_homeomorph_of_inducing_apply]}, { simp only [equiv.set.sum_compl_symm_apply_of_not_mem, h, not_false_iff, mem_preimage, equiv.to_homeomorph_of_inducing_apply, equiv.to_fun_as_coe, mem_range, exists_false]} }, refine ⟨t', _, f.polish_space_induced, _, _⟩, { assume u hu, change ∃ (s' : set (↥s ⊕ ↥t)), T.is_open s' ∧ f ⁻¹' s' = u, refine ⟨f.symm ⁻¹' u, _, by simp only [equiv.symm_symm, equiv.symm_preimage_preimage]⟩, refine is_open_sum_iff.2 ⟨_, _⟩, { have : is_open ((coe : s → α) ⁻¹' u) := is_open.preimage continuous_subtype_coe hu, have : sum.inl ⁻¹' (⇑(f.symm) ⁻¹' u) = (coe : s → α) ⁻¹' u, by { ext x, simp only [equiv.symm_symm, mem_preimage, equiv.set.sum_compl_apply_inl] }, rwa this }, { have : is_open ((coe : t → α) ⁻¹' u) := is_open.preimage continuous_subtype_coe hu, have : sum.inr ⁻¹' (⇑(f.symm) ⁻¹' u) = (coe : t → α) ⁻¹' u, by { ext x, simp only [equiv.symm_symm, mem_preimage, equiv.set.sum_compl_apply_inr] }, rwa this } }, { have : @is_closed α t' (g ⁻¹' (range (sum.inl : s → s ⊕ t))), { apply is_closed.preimage, { exact @homeomorph.continuous _ _ t' _ g }, { exact is_closed_range_inl } }, convert this, exact A.symm }, { have : @is_open α t' (g ⁻¹' (range (sum.inl : s → s ⊕ t))), { apply is_open.preimage, { exact @homeomorph.continuous _ _ t' _ g }, { exact is_open_range_inl } }, convert this, exact A.symm }, end lemma is_clopenable.compl [topological_space α] {s : set α} (hs : is_clopenable s) : is_clopenable sᶜ := begin rcases hs with ⟨t, t_le, t_polish, h, h'⟩, exact ⟨t, t_le, t_polish, @is_open.is_closed_compl α t s h', @is_closed.is_open_compl α t s h⟩, end lemma _root_.is_open.is_clopenable [topological_space α] [polish_space α] {s : set α} (hs : is_open s) : is_clopenable s := by simpa using hs.is_closed_compl.is_clopenable.compl lemma is_clopenable.Union [t : topological_space α] [polish_space α] {s : ℕ → set α} (hs : ∀ n, is_clopenable (s n)) : is_clopenable (⋃ n, s n) := begin choose m mt m_polish m_closed m_open using hs, obtain ⟨t', t'm, -, t'_polish⟩ : ∃ (t' : topological_space α), (∀ (n : ℕ), t' ≤ m n) ∧ (t' ≤ t) ∧ @polish_space α t' := exists_polish_space_forall_le m mt m_polish, have A : @is_open α t' (⋃ n, s n), { apply is_open_Union, assume n, apply t'm n, exact m_open n }, obtain ⟨t'', t''_le, t''_polish, h1, h2⟩ : ∃ (t'' : topological_space α), t'' ≤ t' ∧ @polish_space α t'' ∧ @is_closed α t'' (⋃ n, s n) ∧ @is_open α t'' (⋃ n, s n) := @is_open.is_clopenable α t' t'_polish _ A, exact ⟨t'', t''_le.trans ((t'm 0).trans (mt 0)), t''_polish, h1, h2⟩, end end polish_space
65eea59da7e339f685343384c9c4165161cfabd6
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/show_term.lean
5bed2854c91545ee0c3b46668d060aa8f9ced606
[ "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
1,213
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.core import tactic.tauto open tactic namespace tactic.interactive /-- `show_term { tac }` runs the tactic `tac`, and then prints the term that was constructed. This is useful for understanding what tactics are doing, and how metavariables are handled. As an example, if the goal is `ℕ × ℕ`, `show_term { split, exact 0 }` will print `(0, ?m_1)`, and afterwards there will be one remaining goal (of type `ℕ`). This indicates that `split, exact 0` partially filled in the original metavariable, but created a new metavariable for the resulting sub-goal. As another example, in ``` example {P Q R : Prop} (h₁ : Q → P) (h₂ : R) (h₃ : R → Q) : P ∧ R := by show_term { tauto } ``` the term mode proof `⟨h₁ (h₃ h₂), eq.mpr rfl h₂⟩` produced by `tauto` will be printed. -/ meta def show_term (t : itactic) : itactic := do g :: _ ← get_goals, t, trace g add_tactic_doc { name := "show_term", category := doc_category.tactic, decl_names := [``show_term], tags := ["debugging"] } end tactic.interactive
013389e7ebf4c714571fa43b253662f6b0483490
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Init/Core.lean
9b2117be7012bcf023ca745fe7c92d0e2d6e7b78
[ "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
65,557
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude import Init.Prelude import Init.SizeOf set_option linter.missingDocs true -- keep it documented universe u v w /-- `inline (f x)` is an indication to the compiler to inline the definition of `f` at the application site itself (by comparison to the `@[inline]` attribute, which applies to all applications of the function). -/ def inline {α : Sort u} (a : α) : α := a /-- `flip f a b` is `f b a`. It is useful for "point-free" programming, since it can sometimes be used to avoid introducing variables. For example, `(·<·)` is the less-than relation, and `flip (·<·)` is the greater-than relation. -/ @[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := fun b a => f a b @[simp] theorem Function.const_apply {y : β} {x : α} : const α y x = y := rfl @[simp] theorem Function.comp_apply {f : β → δ} {g : α → β} {x : α} : comp f g x = f (g x) := rfl attribute [simp] namedPattern /-- Thunks are "lazy" values that are evaluated when first accessed using `Thunk.get/map/bind`. The value is then stored and not recomputed for all further accesses. -/ -- NOTE: the runtime has special support for the `Thunk` type to implement this behavior structure Thunk (α : Type u) : Type u where /-- Constructs a new thunk from a function `Unit → α` that will be called when the thunk is forced. -/ mk :: /-- Extract the getter function out of a thunk. Use `Thunk.get` instead. -/ private fn : Unit → α attribute [extern "lean_mk_thunk"] Thunk.mk /-- Store a value in a thunk. Note that the value has already been computed, so there is no laziness. -/ @[extern "lean_thunk_pure"] protected def Thunk.pure (a : α) : Thunk α := ⟨fun _ => a⟩ /-- Forces a thunk to extract the value. This will cache the result, so a second call to the same function will return the value in O(1) instead of calling the stored getter function. -/ -- NOTE: we use `Thunk.get` instead of `Thunk.fn` as the accessor primitive as the latter has an additional `Unit` argument @[extern "lean_thunk_get_own"] protected def Thunk.get (x : @& Thunk α) : α := x.fn () /-- Map a function over a thunk. -/ @[inline] protected def Thunk.map (f : α → β) (x : Thunk α) : Thunk β := ⟨fun _ => f x.get⟩ /-- Constructs a thunk that applies `f` to the result of `x` when forced. -/ @[inline] protected def Thunk.bind (x : Thunk α) (f : α → Thunk β) : Thunk β := ⟨fun _ => (f x.get).get⟩ @[simp] theorem Thunk.sizeOf_eq [SizeOf α] (a : Thunk α) : sizeOf a = 1 + sizeOf a.get := by cases a; rfl /-- A variation on `Eq.ndrec` with the equality argument first. -/ abbrev Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} {b : α} (h : a = b) (m : motive a) : motive b := Eq.ndrec m h /-- If and only if, or logical bi-implication. `a ↔ b` means that `a` implies `b` and vice versa. By `propext`, this implies that `a` and `b` are equal and hence any expression involving `a` is equivalent to the corresponding expression with `b` instead. -/ structure Iff (a b : Prop) : Prop where /-- If `a → b` and `b → a` then `a` and `b` are equivalent. -/ intro :: /-- Modus ponens for if and only if. If `a ↔ b` and `a`, then `b`. -/ mp : a → b /-- Modus ponens for if and only if, reversed. If `a ↔ b` and `b`, then `a`. -/ mpr : b → a @[inheritDoc] infix:20 " <-> " => Iff @[inheritDoc] infix:20 " ↔ " => Iff /-- `Sum α β`, or `α ⊕ β`, is the disjoint union of types `α` and `β`. An element of `α ⊕ β` is either of the form `.inl a` where `a : α`, or `.inr b` where `b : β`. -/ inductive Sum (α : Type u) (β : Type v) where /-- Left injection into the sum type `α ⊕ β`. If `a : α` then `.inl a : α ⊕ β`. -/ | inl (val : α) : Sum α β /-- Right injection into the sum type `α ⊕ β`. If `b : β` then `.inr b : α ⊕ β`. -/ | inr (val : β) : Sum α β @[inheritDoc] infixr:30 " ⊕ " => Sum /-- `PSum α β`, or `α ⊕' β`, is the disjoint union of types `α` and `β`. It differs from `α ⊕ β` in that it allows `α` and `β` to have arbitrary sorts `Sort u` and `Sort v`, instead of restricting to `Type u` and `Type v`. This means that it can be used in situations where one side is a proposition, like `True ⊕' Nat`. The reason this is not the default is that this type lives in the universe `Sort (max 1 u v)`, which can cause problems for universe level unification, because the equation `max 1 u v = ?u + 1` has no solution in level arithmetic. `PSum` is usually only used in automation that constructs sums of arbitrary types. -/ inductive PSum (α : Sort u) (β : Sort v) where /-- Left injection into the sum type `α ⊕' β`. If `a : α` then `.inl a : α ⊕' β`. -/ | inl (val : α) : PSum α β /-- Right injection into the sum type `α ⊕' β`. If `b : β` then `.inr b : α ⊕' β`. -/ | inr (val : β) : PSum α β @[inheritDoc] infixr:30 " ⊕' " => PSum /-- `Sigma β`, also denoted `Σ a : α, β a` or `(a : α) × β a`, is the type of dependent pairs whose first component is `a : α` and whose second component is `b : β a` (so the type of the second component can depend on the value of the first component). It is sometimes known as the dependent sum type, since it is the type level version of an indexed summation. -/ structure Sigma {α : Type u} (β : α → Type v) where /-- Constructor for a dependent pair. If `a : α` and `b : β a` then `⟨a, b⟩ : Sigma β`. (This will usually require a type ascription to determine `β` since it is not determined from `a` and `b` alone.) -/ mk :: /-- The first component of a dependent pair. If `p : @Sigma α β` then `p.1 : α`. -/ fst : α /-- The second component of a dependent pair. If `p : Sigma β` then `p.2 : β p.1`. -/ snd : β fst attribute [unbox] Sigma /-- `PSigma β`, also denoted `Σ' a : α, β a` or `(a : α) ×' β a`, is the type of dependent pairs whose first component is `a : α` and whose second component is `b : β a` (so the type of the second component can depend on the value of the first component). It differs from `Σ a : α, β a` in that it allows `α` and `β` to have arbitrary sorts `Sort u` and `Sort v`, instead of restricting to `Type u` and `Type v`. This means that it can be used in situations where one side is a proposition, like `(p : Nat) ×' p = p`. The reason this is not the default is that this type lives in the universe `Sort (max 1 u v)`, which can cause problems for universe level unification, because the equation `max 1 u v = ?u + 1` has no solution in level arithmetic. `PSigma` is usually only used in automation that constructs pairs of arbitrary types. -/ structure PSigma {α : Sort u} (β : α → Sort v) where /-- Constructor for a dependent pair. If `a : α` and `b : β a` then `⟨a, b⟩ : PSigma β`. (This will usually require a type ascription to determine `β` since it is not determined from `a` and `b` alone.) -/ mk :: /-- The first component of a dependent pair. If `p : @Sigma α β` then `p.1 : α`. -/ fst : α /-- The second component of a dependent pair. If `p : Sigma β` then `p.2 : β p.1`. -/ snd : β fst /-- Existential quantification. If `p : α → Prop` is a predicate, then `∃ x : α, p x` asserts that there is some `x` of type `α` such that `p x` holds. To create an existential proof, use the `exists` tactic, or the anonymous constructor notation `⟨x, h⟩`. To unpack an existential, use `cases h` where `h` is a proof of `∃ x : α, p x`, or `let ⟨x, hx⟩ := h` where `. Because Lean has proof irrelevance, any two proofs of an existential are definitionally equal. One consequence of this is that it is impossible to recover the witness of an existential from the mere fact of its existence. For example, the following does not compile: ``` example (h : ∃ x : Nat, x = x) : Nat := let ⟨x, _⟩ := h -- fail, because the goal is `Nat : Type` x ``` The error message `recursor 'Exists.casesOn' can only eliminate into Prop` means that this only works when the current goal is another proposition: ``` example (h : ∃ x : Nat, x = x) : True := let ⟨x, _⟩ := h -- ok, because the goal is `True : Prop` trivial ``` -/ inductive Exists {α : Sort u} (p : α → Prop) : Prop where /-- Existential introduction. If `a : α` and `h : p a`, then `⟨a, h⟩` is a proof that `∃ x : α, p x`. -/ | intro (w : α) (h : p w) : Exists p /-- Auxiliary type used to compile `for x in xs` notation. This is the return value of the body of a `ForIn` call, representing the body of a for loop. It can be: * `.yield (a : α)`, meaning that we should continue the loop and `a` is the new state. `.yield` is produced by `continue` and reaching the bottom of the loop body. * `.done (a : α)`, meaning that we should early-exit the loop with state `a`. `.done` is produced by calls to `break` or `return` in the loop, -/ inductive ForInStep (α : Type u) where /-- `.done a` means that we should early-exit the loop. `.done` is produced by calls to `break` or `return` in the loop. -/ | done : α → ForInStep α /-- `.yield a` means that we should continue the loop. `.yield` is produced by `continue` and reaching the bottom of the loop body. -/ | yield : α → ForInStep α deriving Inhabited /-- `ForIn m ρ α` is the typeclass which supports `for x in xs` notation. Here `xs : ρ` is the type of the collection to iterate over, `x : α` is the element type which is made available inside the loop, and `m` is the monad for the encompassing `do` block. -/ class ForIn (m : Type u₁ → Type u₂) (ρ : Type u) (α : outParam (Type v)) where /-- `forIn x b f : m β` runs a for-loop in the monad `m` with additional state `β`. This traverses over the "contents" of `x`, and passes the elements `a : α` to `f : α → β → m (ForInStep β)`. `b : β` is the initial state, and the return value of `f` is the new state as well as a directive `.done` or `.yield` which indicates whether to abort early or continue iteration. The expression ``` let mut b := ... for x in xs do b ← foo x b ``` in a `do` block is syntactic sugar for: ``` let b := ... let b ← forIn xs b (fun x b => do let b ← foo x b return .yield b) ``` (Here `b` corresponds to the variables mutated in the loop.) -/ forIn {β} [Monad m] (x : ρ) (b : β) (f : α → β → m (ForInStep β)) : m β export ForIn (forIn) /-- `ForIn' m ρ α d` is a variation on the `ForIn m ρ α` typeclass which supports the `for h : x in xs` notation. It is the same as `for x in xs` except that `h : x ∈ xs` is provided as an additional argument to the body of the for-loop. -/ class ForIn' (m : Type u₁ → Type u₂) (ρ : Type u) (α : outParam (Type v)) (d : outParam $ Membership α ρ) where /-- `forIn' x b f : m β` runs a for-loop in the monad `m` with additional state `β`. This traverses over the "contents" of `x`, and passes the elements `a : α` along with a proof that `a ∈ x` to `f : (a : α) → a ∈ x → β → m (ForInStep β)`. `b : β` is the initial state, and the return value of `f` is the new state as well as a directive `.done` or `.yield` which indicates whether to abort early or continue iteration. -/ forIn' {β} [Monad m] (x : ρ) (b : β) (f : (a : α) → a ∈ x → β → m (ForInStep β)) : m β export ForIn' (forIn') /-- Auxiliary type used to compile `do` notation. It is used when compiling a do block nested inside a combinator like `tryCatch`. It encodes the possible ways the block can exit: * `pure (a : α) s` means that the block exited normally with return value `a`. * `return (b : β) s` means that the block exited via a `return b` early-exit command. * `break s` means that `break` was called, meaning that we should exit from the containing loop. * `continue s` means that `continue` was called, meaning that we should continue to the next iteration of the containing loop. All cases return a value `s : σ` which bundles all the mutable variables of the do-block. -/ inductive DoResultPRBC (α β σ : Type u) where /-- `pure (a : α) s` means that the block exited normally with return value `a` -/ | pure : α → σ → DoResultPRBC α β σ /-- `return (b : β) s` means that the block exited via a `return b` early-exit command -/ | return : β → σ → DoResultPRBC α β σ /-- `break s` means that `break` was called, meaning that we should exit from the containing loop -/ | break : σ → DoResultPRBC α β σ /-- `continue s` means that `continue` was called, meaning that we should continue to the next iteration of the containing loop -/ | continue : σ → DoResultPRBC α β σ /-- Auxiliary type used to compile `do` notation. It is the same as `DoResultPRBC α β σ` except that `break` and `continue` are not available because we are not in a loop context. -/ inductive DoResultPR (α β σ : Type u) where /-- `pure (a : α) s` means that the block exited normally with return value `a` -/ | pure : α → σ → DoResultPR α β σ /-- `return (b : β) s` means that the block exited via a `return b` early-exit command -/ | return : β → σ → DoResultPR α β σ /-- Auxiliary type used to compile `do` notation. It is an optimization of `DoResultPRBC PEmpty PEmpty σ` to remove the impossible cases, used when neither `pure` nor `return` are possible exit paths. -/ inductive DoResultBC (σ : Type u) where /-- `break s` means that `break` was called, meaning that we should exit from the containing loop -/ | break : σ → DoResultBC σ /-- `continue s` means that `continue` was called, meaning that we should continue to the next iteration of the containing loop -/ | continue : σ → DoResultBC σ /-- Auxiliary type used to compile `do` notation. It is an optimization of either `DoResultPRBC α PEmpty σ` or `DoResultPRBC PEmpty α σ` to remove the impossible case, used when either `pure` or `return` is never used. -/ inductive DoResultSBC (α σ : Type u) where /-- This encodes either `pure (a : α)` or `return (a : α)`: * `pure (a : α) s` means that the block exited normally with return value `a` * `return (b : β) s` means that the block exited via a `return b` early-exit command The one that is actually encoded depends on the context of use. -/ | pureReturn : α → σ → DoResultSBC α σ /-- `break s` means that `break` was called, meaning that we should exit from the containing loop -/ | break : σ → DoResultSBC α σ /-- `continue s` means that `continue` was called, meaning that we should continue to the next iteration of the containing loop -/ | continue : σ → DoResultSBC α σ /-- `HasEquiv α` is the typeclass which supports the notation `x ≈ y` where `x y : α`.-/ class HasEquiv (α : Sort u) where /-- `x ≈ y` says that `x` and `y` are equivalent. Because this is a typeclass, the notion of equivalence is type-dependent. -/ Equiv : α → α → Sort v @[inheritDoc] infix:50 " ≈ " => HasEquiv.Equiv /-- `EmptyCollection α` is the typeclass which supports the notation `∅`, also written as `{}`. -/ class EmptyCollection (α : Type u) where /-- `∅` or `{}` is the empty set or empty collection. It is supported by the `EmptyCollection` typeclass. -/ emptyCollection : α @[inheritDoc] notation "{" "}" => EmptyCollection.emptyCollection @[inheritDoc] notation "∅" => EmptyCollection.emptyCollection /-- `Task α` is a primitive for asynchronous computation. It represents a computation that will resolve to a value of type `α`, possibly being computed on another thread. This is similar to `Future` in Scala, `Promise` in Javascript, and `JoinHandle` in Rust. The tasks have an overridden representation in the runtime. -/ structure Task (α : Type u) : Type u where /-- `Task.pure (a : α)` constructs a task that is already resolved with value `a`. -/ pure :: /-- If `task : Task α` then `task.get : α` blocks the current thread until the value is available, and then returns the result of the task. -/ get : α deriving Inhabited attribute [extern "lean_task_pure"] Task.pure attribute [extern "lean_task_get_own"] Task.get instance : [Nonempty α] → Nonempty (Task α) | ⟨x⟩ => ⟨.pure x⟩ namespace Task /-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/ abbrev Priority := Nat /-- The default priority for spawned tasks, also the lowest priority: `0`. -/ def Priority.default : Priority := 0 /-- The highest regular priority for spawned tasks: `8`. Spawning a task with a priority higher than `Task.Priority.max` is not an error but will spawn a dedicated worker for the task, see `Task.Priority.dedicated`. Regular priority tasks are placed in a thread pool and worked on according to the priority order. -/ -- see `LEAN_MAX_PRIO` def Priority.max : Priority := 8 /-- Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread. This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more non-dedicated workers than the number of cores to reduce context switches. -/ def Priority.dedicated : Priority := 9 set_option linter.unusedVariables.funArgs false in /-- `spawn fn : Task α` constructs and immediately launches a new task for evaluating the function `fn () : α` asynchronously. `prio`, if provided, is the priority of the task. -/ @[noinline, extern "lean_task_spawn"] protected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α := ⟨fn ()⟩ set_option linter.unusedVariables.funArgs false in /-- `map f x` maps function `f` over the task `x`: that is, it constructs (and immediately launches) a new task which will wait for the value of `x` to be available and then calls `f` on the result. `prio`, if provided, is the priority of the task. -/ @[noinline, extern "lean_task_map"] protected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β := ⟨f x.get⟩ set_option linter.unusedVariables.funArgs false in /-- `bind x f` does a monad "bind" operation on the task `x` with function `f`: that is, it constructs (and immediately launches) a new task which will wait for the value of `x` to be available and then calls `f` on the result, resulting in a new task which is then run for a result. `prio`, if provided, is the priority of the task. -/ @[noinline, extern "lean_task_bind"] protected def bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) (prio := Priority.default) : Task β := ⟨(f x.get).get⟩ end Task /-- `NonScalar` is a type that is not a scalar value in our runtime. It is used as a stand-in for an arbitrary boxed value to avoid excessive monomorphization, and it is only created using `unsafeCast`. It is somewhat analogous to C `void*` in usage, but the type itself is not special. -/ structure NonScalar where /-- You should not use this function -/ mk :: /-- You should not use this function -/ val : Nat /-- `PNonScalar` is a type that is not a scalar value in our runtime. It is used as a stand-in for an arbitrary boxed value to avoid excessive monomorphization, and it is only created using `unsafeCast`. It is somewhat analogous to C `void*` in usage, but the type itself is not special. This is the universe-polymorphic version of `PNonScalar`; it is preferred to use `NonScalar` instead where applicable. -/ inductive PNonScalar : Type u where /-- You should not use this function -/ | mk (v : Nat) : PNonScalar @[simp] theorem Nat.add_zero (n : Nat) : n + 0 = n := rfl theorem optParam_eq (α : Sort u) (default : α) : optParam α default = α := rfl /-! # Boolean operators -/ /-- `strictOr` is the same as `or`, but it does not use short-circuit evaluation semantics: both sides are evaluated, even if the first value is `true`. -/ @[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ /-- `strictAnd` is the same as `and`, but it does not use short-circuit evaluation semantics: both sides are evaluated, even if the first value is `false`. -/ @[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ /-- `x != y` is boolean not-equal. It is the negation of `x == y` which is supplied by the `BEq` typeclass. Unlike `x ≠ y` (which is notation for `Ne x y`), this is `Bool` valued instead of `Prop` valued. It is mainly intended for programming applications. -/ @[inline] def bne {α : Type u} [BEq α] (a b : α) : Bool := !(a == b) @[inheritDoc] infix:50 " != " => bne /-- `LawfulBEq α` is a typeclass which asserts that the `BEq α` implementation (which supplies the `a == b` notation) coincides with logical equality `a = b`. In other words, `a == b` implies `a = b`, and `a == a` is true. -/ class LawfulBEq (α : Type u) [BEq α] : Prop where /-- If `a == b` evaluates to `true`, then `a` and `b` are equal in the logic. -/ eq_of_beq : {a b : α} → a == b → a = b /-- `==` is reflexive, that is, `(a == a) = true`. -/ protected rfl : {a : α} → a == a export LawfulBEq (eq_of_beq) instance : LawfulBEq Bool where eq_of_beq {a b} h := by cases a <;> cases b <;> first | rfl | contradiction rfl {a} := by cases a <;> decide instance [DecidableEq α] : LawfulBEq α where eq_of_beq := of_decide_eq_true rfl := of_decide_eq_self_eq_true _ instance : LawfulBEq Char := inferInstance instance : LawfulBEq String := inferInstance /-! # Logical connectives and equality -/ @[inheritDoc True.intro] def trivial : True := ⟨⟩ theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := fun ha => h₂ (h₁ ha) theorem not_false : ¬False := id theorem not_not_intro {p : Prop} (h : p) : ¬ ¬ p := fun hn : ¬ p => hn h -- proof irrelevance is built in theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl theorem id.def {α : Sort u} (a : α) : id a = a := rfl /-- If `h : α = β` is a proof of type equality, then `h.mp : α → β` is the induced "cast" operation, mapping elements of `α` to elements of `β`. You can prove theorems about the resulting element by induction on `h`, since `rfl.mp` is definitionally the identity function. -/ @[macroInline] def Eq.mp {α β : Sort u} (h : α = β) (a : α) : β := h ▸ a /-- If `h : α = β` is a proof of type equality, then `h.mpr : β → α` is the induced "cast" operation in the reverse direction, mapping elements of `β` to elements of `α`. You can prove theorems about the resulting element by induction on `h`, since `rfl.mpr` is definitionally the identity function. -/ @[macroInline] def Eq.mpr {α β : Sort u} (h : α = β) (b : β) : α := h ▸ b theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b := h₁ ▸ h₂ theorem cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl /-- `a ≠ b`, or `Ne a b` is defined as `¬ (a = b)` or `a = b → False`, and asserts that `a` and `b` are not equal. -/ @[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b) @[inheritDoc] infix:50 " ≠ " => Ne section Ne variable {α : Sort u} variable {a b : α} {p : Prop} theorem Ne.intro (h : a = b → False) : a ≠ b := h theorem Ne.elim (h : a ≠ b) : a = b → False := h theorem Ne.irrefl (h : a ≠ a) : False := h rfl theorem Ne.symm (h : a ≠ b) : b ≠ a := fun h₁ => h (h₁.symm) theorem false_of_ne : a ≠ a → False := Ne.irrefl theorem ne_false_of_self : p → p ≠ False := fun (hp : p) (h : p = False) => h ▸ hp theorem ne_true_of_not : ¬p → p ≠ True := fun (hnp : ¬p) (h : p = True) => have : ¬True := h ▸ hnp this trivial theorem true_ne_false : ¬True = False := ne_false_of_self trivial end Ne theorem Bool.of_not_eq_true : {b : Bool} → ¬ (b = true) → b = false | true, h => absurd rfl h | false, _ => rfl theorem Bool.of_not_eq_false : {b : Bool} → ¬ (b = false) → b = true | true, _ => rfl | false, h => absurd rfl h theorem ne_of_beq_false [BEq α] [LawfulBEq α] {a b : α} (h : (a == b) = false) : a ≠ b := by intro h'; subst h'; have : true = false := Eq.trans LawfulBEq.rfl.symm h; contradiction theorem beq_false_of_ne [BEq α] [LawfulBEq α] {a b : α} (h : a ≠ b) : (a == b) = false := have : ¬ (a == b) = true := by intro h'; rw [eq_of_beq h'] at h; contradiction Bool.of_not_eq_true this section variable {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} (m : motive a) {β : Sort u2} {b : β} (h : HEq a b) : motive b := h.rec m theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} {β : Sort u2} {b : β} (h : HEq a b) (m : motive a) : motive b := h.rec m theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : HEq a b) (h₂ : p a) : p b := eq_of_heq h₁ ▸ h₂ theorem HEq.subst {p : (T : Sort u) → T → Prop} (h₁ : HEq a b) (h₂ : p α a) : p β b := HEq.ndrecOn h₁ h₂ theorem HEq.symm (h : HEq a b) : HEq b a := h.rec (HEq.refl a) theorem heq_of_eq (h : a = a') : HEq a a' := Eq.subst h (HEq.refl a) theorem HEq.trans (h₁ : HEq a b) (h₂ : HEq b c) : HEq a c := HEq.subst h₂ h₁ theorem heq_of_heq_of_eq (h₁ : HEq a b) (h₂ : b = b') : HEq a b' := HEq.trans h₁ (heq_of_eq h₂) theorem heq_of_eq_of_heq (h₁ : a = a') (h₂ : HEq a' b) : HEq a b := HEq.trans (heq_of_eq h₁) h₂ theorem type_eq_of_heq (h : HEq a b) : α = β := h.rec (Eq.refl α) end theorem eqRec_heq {α : Sort u} {φ : α → Sort v} {a a' : α} : (h : a = a') → (p : φ a) → HEq (Eq.recOn (motive := fun x _ => φ x) h p) p | rfl, p => HEq.refl p theorem heq_of_eqRec_eq {α β : Sort u} {a : α} {b : β} (h₁ : α = β) (h₂ : Eq.rec (motive := fun α _ => α) a h₁ = b) : HEq a b := by subst h₁ apply heq_of_eq exact h₂ theorem cast_heq {α β : Sort u} : (h : α = β) → (a : α) → HEq (cast h a) a | rfl, a => HEq.refl a variable {a b c d : Prop} theorem iff_iff_implies_and_implies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right) theorem Iff.refl (a : Prop) : a ↔ a := Iff.intro (fun h => h) (fun h => h) protected theorem Iff.rfl {a : Prop} : a ↔ a := Iff.refl a theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := Iff.intro (fun ha => Iff.mp h₂ (Iff.mp h₁ ha)) (fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc)) theorem Iff.symm (h : a ↔ b) : b ↔ a := Iff.intro (Iff.mpr h) (Iff.mp h) theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) := Iff.intro Iff.symm Iff.symm theorem And.comm : a ∧ b ↔ b ∧ a := by constructor <;> intro ⟨h₁, h₂⟩ <;> exact ⟨h₂, h₁⟩ /-! # Exists -/ theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b := match h₁ with | intro a h => h₂ a h /-! # Decidable -/ theorem decide_true_eq_true (h : Decidable True) : @decide True h = true := match h with | isTrue _ => rfl | isFalse h => False.elim <| h ⟨⟩ theorem decide_false_eq_false (h : Decidable False) : @decide False h = false := match h with | isFalse _ => rfl | isTrue h => False.elim h /-- Similar to `decide`, but uses an explicit instance -/ @[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool := decide p (h := d) theorem toBoolUsing_eq_true {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true := decide_eq_true (inst := d) h theorem ofBoolUsing_eq_true {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p := of_decide_eq_true (inst := d) h theorem ofBoolUsing_eq_false {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p := of_decide_eq_false (inst := d) h instance : Decidable True := isTrue trivial instance : Decidable False := isFalse not_false namespace Decidable variable {p q : Prop} /-- Synonym for `dite` (dependent if-then-else). We can construct an element `q` (of any sort, not just a proposition) by cases on whether `p` is true or false, provided `p` is decidable. -/ @[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q := match dec with | isTrue h => h1 h | isFalse h => h2 h theorem em (p : Prop) [Decidable p] : p ∨ ¬p := byCases Or.inl Or.inr set_option linter.unusedVariables.funArgs false in theorem byContradiction [dec : Decidable p] (h : ¬p → False) : p := byCases id (fun np => False.elim (h np)) theorem of_not_not [Decidable p] : ¬ ¬ p → p := fun hnn => byContradiction (fun hn => absurd hn hnn) theorem not_and_iff_or_not (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := Iff.intro (fun h => match d₁, d₂ with | isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h | _, isFalse h₂ => Or.inr h₂ | isFalse h₁, _ => Or.inl h₁) (fun (h) ⟨hp, hq⟩ => match h with | Or.inl h => h hp | Or.inr h => h hq) end Decidable section variable {p q : Prop} /-- Transfer a decidability proof across an equivalence of propositions. -/ @[inline] def decidable_of_decidable_of_iff [Decidable p] (h : p ↔ q) : Decidable q := if hp : p then isTrue (Iff.mp h hp) else isFalse fun hq => absurd (Iff.mpr h hq) hp /-- Transfer a decidability proof across an equality of propositions. -/ @[inline] def decidable_of_decidable_of_eq [Decidable p] (h : p = q) : Decidable q := decidable_of_decidable_of_iff (p := p) (h ▸ Iff.rfl) end @[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p → q) := if hp : p then if hq : q then isTrue (fun _ => hq) else isFalse (fun h => absurd (h hp) hq) else isTrue (fun h => absurd h hp) instance {p q} [Decidable p] [Decidable q] : Decidable (p ↔ q) := if hp : p then if hq : q then isTrue ⟨fun _ => hq, fun _ => hp⟩ else isFalse fun h => hq (h.1 hp) else if hq : q then isFalse fun h => hp (h.2 hq) else isTrue ⟨fun h => absurd h hp, fun h => absurd h hq⟩ /-! # if-then-else expression theorems -/ theorem if_pos {c : Prop} {h : Decidable c} (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | isTrue _ => rfl | isFalse hnc => absurd hc hnc theorem if_neg {c : Prop} {h : Decidable c} (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | isTrue hc => absurd hc hnc | isFalse _ => rfl theorem dif_pos {c : Prop} {h : Decidable c} (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc := match h with | isTrue _ => rfl | isFalse hnc => absurd hc hnc theorem dif_neg {c : Prop} {h : Decidable c} (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc := match h with | isTrue hc => absurd hc hnc | isFalse _ => rfl -- Remark: dite and ite are "defally equal" when we ignore the proofs. theorem dif_eq_if (c : Prop) {h : Decidable c} {α : Sort u} (t : α) (e : α) : dite c (fun _ => t) (fun _ => e) = ite c t e := match h with | isTrue _ => rfl | isFalse _ => rfl instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) := match dC with | isTrue _ => dT | isFalse _ => dE instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) := match dC with | isTrue hc => dT hc | isFalse hc => dE hc /-- Auxiliary definition for generating compact `noConfusion` for enumeration types -/ abbrev noConfusionTypeEnum {α : Sort u} {β : Sort v} [inst : DecidableEq β] (f : α → β) (P : Sort w) (x y : α) : Sort w := (inst (f x) (f y)).casesOn (fun _ => P) (fun _ => P → P) /-- Auxiliary definition for generating compact `noConfusion` for enumeration types -/ abbrev noConfusionEnum {α : Sort u} {β : Sort v} [inst : DecidableEq β] (f : α → β) {P : Sort w} {x y : α} (h : x = y) : noConfusionTypeEnum f P x y := Decidable.casesOn (motive := fun (inst : Decidable (f x = f y)) => Decidable.casesOn (motive := fun _ => Sort w) inst (fun _ => P) (fun _ => P → P)) (inst (f x) (f y)) (fun h' => False.elim (h' (congrArg f h))) (fun _ => fun x => x) /-! # Inhabited -/ instance : Inhabited Prop where default := True deriving instance Inhabited for NonScalar, PNonScalar, True, ForInStep theorem nonempty_of_exists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α | ⟨w, _⟩ => ⟨w⟩ /-! # Subsingleton -/ /-- A "subsingleton" is a type with at most one element. In other words, it is either empty, or has a unique element. All propositions are subsingletons because of proof irrelevance, but some other types are subsingletons as well and they inherit many of the same properties as propositions. `Subsingleton α` is a typeclass, so it is usually used as an implicit argument and inferred by typeclass inference. -/ class Subsingleton (α : Sort u) : Prop where /-- Construct a proof that `α` is a subsingleton by showing that any two elements are equal. -/ intro :: /-- Any two elements of a subsingleton are equal. -/ allEq : (a b : α) → a = b protected theorem Subsingleton.elim {α : Sort u} [h : Subsingleton α] : (a b : α) → a = b := h.allEq protected theorem Subsingleton.helim {α β : Sort u} [h₁ : Subsingleton α] (h₂ : α = β) (a : α) (b : β) : HEq a b := by subst h₂ apply heq_of_eq apply Subsingleton.elim instance (p : Prop) : Subsingleton p := ⟨fun a b => proofIrrel a b⟩ instance (p : Prop) : Subsingleton (Decidable p) := Subsingleton.intro fun | isTrue t₁ => fun | isTrue _ => rfl | isFalse f₂ => absurd t₁ f₂ | isFalse f₁ => fun | isTrue t₂ => absurd t₂ f₁ | isFalse _ => rfl theorem recSubsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : ∀ (h : p), Subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)] : Subsingleton (h.casesOn h₂ h₁) := match h with | isTrue h => h₃ h | isFalse h => h₄ h /-- An equivalence relation `~ : α → α → Prop` is a relation that is: * reflexive: `x ~ x` * symmetric: `x ~ y` implies `y ~ x` * transitive: `x ~ y` and `y ~ z` implies `x ~ z` Equality is an equivalence relation, and equivalence relations share many of the properties of equality. In particular, `Quot α r` is most well behaved when `r` is an equivalence relation, and in this case we use `Quotient` instead. -/ structure Equivalence {α : Sort u} (r : α → α → Prop) : Prop where /-- An equivalence relation is reflexive: `x ~ x` -/ refl : ∀ x, r x x /-- An equivalence relation is symmetric: `x ~ y` implies `y ~ x` -/ symm : ∀ {x y}, r x y → r y x /-- An equivalence relation is transitive: `x ~ y` and `y ~ z` implies `x ~ z` -/ trans : ∀ {x y z}, r x y → r y z → r x z /-- The empty relation is the relation on `α` which is always `False`. -/ def emptyRelation {α : Sort u} (_ _ : α) : Prop := False /-- `Subrelation q r` means that `q ⊆ r` or `∀ x y, q x y → r x y`. It is the analogue of the subset relation on relations. -/ def Subrelation {α : Sort u} (q r : α → α → Prop) := ∀ {x y}, q x y → r x y /-- The inverse image of `r : β → β → Prop` by a function `α → β` is the relation `s : α → α → Prop` defined by `s a b = r (f a) (f b)`. -/ def InvImage {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop := fun a₁ a₂ => r (f a₁) (f a₂) /-- The transitive closure `r⁺` of a relation `r` is the smallest relation which is transitive and contains `r`. `r⁺ a z` if and only if there exists a sequence `a r b r ... r z` of length at least 1 connecting `a` to `z`. -/ inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop where /-- If `r a b` then `r⁺ a b`. This is the base case of the transitive closure. -/ | base : ∀ a b, r a b → TC r a b /-- The transitive closure is transitive. -/ | trans : ∀ a b c, TC r a b → TC r b c → TC r a c /-! # Subtype -/ namespace Subtype theorem existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x) | ⟨a, h⟩ => ⟨a, h⟩ variable {α : Type u} {p : α → Prop} protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2 | ⟨_, _⟩, ⟨_, _⟩, rfl => rfl theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := by cases a exact rfl instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} where default := ⟨a, h⟩ instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} := fun ⟨a, h₁⟩ ⟨b, h₂⟩ => if h : a = b then isTrue (by subst h; exact rfl) else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h)) end Subtype /-! # Sum -/ section variable {α : Type u} {β : Type v} instance Sum.inhabitedLeft [Inhabited α] : Inhabited (Sum α β) where default := Sum.inl default instance Sum.inhabitedRight [Inhabited β] : Inhabited (Sum α β) where default := Sum.inr default instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) := fun a b => match a, b with | Sum.inl a, Sum.inl b => if h : a = b then isTrue (h ▸ rfl) else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h | Sum.inr a, Sum.inr b => if h : a = b then isTrue (h ▸ rfl) else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h | Sum.inr _, Sum.inl _ => isFalse fun h => Sum.noConfusion h | Sum.inl _, Sum.inr _ => isFalse fun h => Sum.noConfusion h end /-! # Product -/ instance [Inhabited α] [Inhabited β] : Inhabited (α × β) where default := (default, default) instance [Inhabited α] [Inhabited β] : Inhabited (MProd α β) where default := ⟨default, default⟩ instance [Inhabited α] [Inhabited β] : Inhabited (PProd α β) where default := ⟨default, default⟩ instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) := fun (a, b) (a', b') => match decEq a a' with | isTrue e₁ => match decEq b b' with | isTrue e₂ => isTrue (e₁ ▸ e₂ ▸ rfl) | isFalse n₂ => isFalse fun h => Prod.noConfusion h fun _ e₂' => absurd e₂' n₂ | isFalse n₁ => isFalse fun h => Prod.noConfusion h fun e₁' _ => absurd e₁' n₁ instance [BEq α] [BEq β] : BEq (α × β) where beq := fun (a₁, b₁) (a₂, b₂) => a₁ == a₂ && b₁ == b₂ /-- Lexicographical order for products -/ def Prod.lexLt [LT α] [LT β] (s : α × β) (t : α × β) : Prop := s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2) instance Prod.lexLtDec [LT α] [LT β] [DecidableEq α] [DecidableEq β] [(a b : α) → Decidable (a < b)] [(a b : β) → Decidable (a < b)] : (s t : α × β) → Decidable (Prod.lexLt s t) := fun _ _ => inferInstanceAs (Decidable (_ ∨ _)) theorem Prod.lexLt_def [LT α] [LT β] (s t : α × β) : (Prod.lexLt s t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) := rfl theorem Prod.ext (p : α × β) : (p.1, p.2) = p := by cases p; rfl /-- `Prod.map f g : α₁ × β₁ → α₂ × β₂` maps across a pair by applying `f` to the first component and `g` to the second. -/ def Prod.map {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂ | (a, b) => (f a, g b) /-! # Dependent products -/ theorem ex_of_PSigma {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x) | ⟨x, hx⟩ => ⟨x, hx⟩ protected theorem PSigma.eta {α : Sort u} {β : α → Sort v} {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} (h₁ : a₁ = a₂) (h₂ : Eq.ndrec b₁ h₁ = b₂) : PSigma.mk a₁ b₁ = PSigma.mk a₂ b₂ := by subst h₁ subst h₂ exact rfl /-! # Universe polymorphic unit -/ theorem PUnit.subsingleton (a b : PUnit) : a = b := by cases a; cases b; exact rfl theorem PUnit.eq_punit (a : PUnit) : a = ⟨⟩ := PUnit.subsingleton a ⟨⟩ instance : Subsingleton PUnit := Subsingleton.intro PUnit.subsingleton instance : Inhabited PUnit where default := ⟨⟩ instance : DecidableEq PUnit := fun a b => isTrue (PUnit.subsingleton a b) /-! # Setoid -/ /-- A setoid is a type with a distinguished equivalence relation, denoted `≈`. This is mainly used as input to the `Quotient` type constructor. -/ class Setoid (α : Sort u) where /-- `x ≈ y` is the distinguished equivalence relation of a setoid. -/ r : α → α → Prop /-- The relation `x ≈ y` is an equivalence relation. -/ iseqv : Equivalence r instance {α : Sort u} [Setoid α] : HasEquiv α := ⟨Setoid.r⟩ namespace Setoid variable {α : Sort u} [Setoid α] theorem refl (a : α) : a ≈ a := iseqv.refl a theorem symm {a b : α} (hab : a ≈ b) : b ≈ a := iseqv.symm hab theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := iseqv.trans hab hbc end Setoid /-! # Propositional extensionality -/ /-- The axiom of **propositional extensionality**. It asserts that if propositions `a` and `b` are logically equivalent (i.e. we can prove `a` from `b` and vice versa), then `a` and `b` are *equal*, meaning that we can replace `a` with `b` in all contexts. For simple expressions like `a ∧ c ∨ d → e` we can prove that because all the logical connectives respect logical equivalence, we can replace `a` with `b` in this expression without using `propext`. However, for higher order expressions like `P a` where `P : Prop → Prop` is unknown, or indeed for `a = b` itself, we cannot replace `a` with `b` without an axiom which says exactly this. This is a relatively uncontroversial axiom, which is intuitionistically valid. It does however block computation when using `#reduce` to reduce proofs directly (which is not recommended), meaning that canonicity, the property that all closed terms of type `Nat` normalize to numerals, fails to hold when this (or any) axiom is used: ``` set_option pp.proofs true def foo : Nat := by have : (True → True) ↔ True := ⟨λ _ => trivial, λ _ _ => trivial⟩ have := propext this ▸ (2 : Nat) exact this #reduce foo -- propext { mp := fun x x => True.intro, mpr := fun x => True.intro } ▸ 2 #eval foo -- 2 ``` `#eval` can evaluate it to a numeral because the compiler erases casts and does not evaluate proofs, so `propext`, whose return type is a proposition, can never block it. -/ axiom propext {a b : Prop} : (a ↔ b) → a = b theorem Eq.propIntro {a b : Prop} (h₁ : a → b) (h₂ : b → a) : a = b := propext <| Iff.intro h₁ h₂ -- Eq for Prop is now decidable if the equivalent Iff is decidable instance {p q : Prop} [d : Decidable (p ↔ q)] : Decidable (p = q) := match d with | isTrue h => isTrue (propext h) | isFalse h => isFalse fun heq => h (heq ▸ Iff.rfl) gen_injective_theorems% Prod gen_injective_theorems% PProd gen_injective_theorems% MProd gen_injective_theorems% Subtype gen_injective_theorems% Fin gen_injective_theorems% Array gen_injective_theorems% Sum gen_injective_theorems% PSum gen_injective_theorems% Nat gen_injective_theorems% Option gen_injective_theorems% List gen_injective_theorems% Except gen_injective_theorems% EStateM.Result gen_injective_theorems% Lean.Name gen_injective_theorems% Lean.Syntax @[simp] theorem beq_iff_eq [BEq α] [LawfulBEq α] (a b : α) : a == b ↔ a = b := ⟨eq_of_beq, by intro h; subst h; exact LawfulBEq.rfl⟩ /-! # Quotients -/ /-- Iff can now be used to do substitutions in a calculation -/ theorem Iff.subst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b := Eq.subst (propext h₁) h₂ namespace Quot /-- The **quotient axiom**, or at least the nontrivial part of the quotient axiomatization. Quotient types are introduced by the `init_quot` command in `Init.Prelude` which introduces the axioms: ``` opaque Quot {α : Sort u} (r : α → α → Prop) : Sort u opaque Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r opaque Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → f a = f b) → Quot r → β opaque Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q ``` All of these axioms are true if we assume `Quot α r = α` and `Quot.mk` and `Quot.lift` are identity functions, so they do not add much. However this axiom cannot be explained in that way (it is false for that interpretation), so the real power of quotient types come from this axiom. It says that the quotient by `r` maps elements which are related by `r` to equal values in the quotient. Together with `Quot.lift` which says that functions which respect `r` can be lifted to functions on the quotient, we can deduce that `Quot α r` exactly consists of the equivalence classes with respect to `r`. It is important to note that `r` need not be an equivalence relation in this axiom. When `r` is not an equivalence relation, we are actually taking a quotient with respect to the equivalence relation generated by `r`. -/ axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : (a b : α) → r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a := rfl protected theorem indBeta {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (p : (a : α) → motive (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a := rfl /-- `Quot.liftOn q f h` is the same as `Quot.lift f h q`. It just reorders the argument `q : Quot r` to be first. -/ protected abbrev liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : (a b : α) → r a b → f a = f b) : β := lift f c q @[elabAsElim] protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (q : Quot r) (h : (a : α) → motive (Quot.mk r a)) : motive q := ind h q theorem exists_rep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) := q.inductionOn (fun a => ⟨a, rfl⟩) section variable {α : Sort u} variable {r : α → α → Prop} variable {motive : Quot r → Sort v} /-- Auxiliary definition for `Quot.rec`. -/ @[reducible, macroInline] protected def indep (f : (a : α) → motive (Quot.mk r a)) (a : α) : PSigma motive := ⟨Quot.mk r a, f a⟩ protected theorem indepCoherent (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : (a b : α) → r a b → Quot.indep f a = Quot.indep f b := fun a b e => PSigma.eta (sound e) (h a b e) protected theorem liftIndepPr1 (f : (a : α) → motive (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := by induction q using Quot.ind exact rfl /-- Dependent recursion principle for `Quot`. This constructor can be tricky to use, so you should consider the simpler versions if they apply: * `Quot.lift`, for nondependent functions * `Quot.ind`, for theorems / proofs of propositions about quotients * `Quot.recOnSubsingleton`, when the target type is a `Subsingleton` * `Quot.hrecOn`, which uses `HEq (f a) (f b)` instead of a `sound p ▸ f a = f b` assummption -/ protected abbrev rec (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : motive q := Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2) @[inheritDoc Quot.rec] protected abbrev recOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : motive q := q.rec f h /-- Dependent induction principle for a quotient, when the target type is a `Subsingleton`. In this case the quotient's side condition is trivial so any function can be lifted. -/ protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quot.mk r a))] (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) : motive q := by induction q using Quot.rec apply f apply Subsingleton.elim /-- Heterogeneous dependent recursion principle for a quotient. This may be easier to work with since it uses `HEq` instead of an `Eq.ndrec` in the hypothesis. -/ protected abbrev hrecOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (c : (a b : α) → (p : r a b) → HEq (f a) (f b)) : motive q := Quot.recOn q f fun a b p => eq_of_heq <| have p₁ : HEq (Eq.ndrec (f a) (sound p)) (f a) := eqRec_heq (sound p) (f a) HEq.trans p₁ (c a b p) end end Quot set_option linter.unusedVariables.funArgs false in /-- `Quotient α s` is the same as `Quot α r`, but it is specialized to a setoid `s` (that is, an equivalence relation) instead of an arbitrary relation. Prefer `Quotient` over `Quot` if your relation is actually an equivalence relation. -/ def Quotient {α : Sort u} (s : Setoid α) := @Quot α Setoid.r namespace Quotient /-- The canonical quotient map into a `Quotient`. -/ @[inline] protected def mk {α : Sort u} (s : Setoid α) (a : α) : Quotient s := Quot.mk Setoid.r a /-- The canonical quotient map into a `Quotient`. (This synthesizes the setoid by typeclass inference.) -/ protected def mk' {α : Sort u} [s : Setoid α] (a : α) : Quotient s := Quotient.mk s a /-- The analogue of `Quot.sound`: If `a` and `b` are related by the equivalence relation, then they have equal equivalence classes. -/ def sound {α : Sort u} {s : Setoid α} {a b : α} : a ≈ b → Quotient.mk s a = Quotient.mk s b := Quot.sound /-- The analogue of `Quot.lift`: if `f : α → β` respects the equivalence relation `≈`, then it lifts to a function on `Quotient s` such that `lift f h (mk a) = f a`. -/ protected abbrev lift {α : Sort u} {β : Sort v} {s : Setoid α} (f : α → β) : ((a b : α) → a ≈ b → f a = f b) → Quotient s → β := Quot.lift f protected theorem ind {α : Sort u} {s : Setoid α} {motive : Quotient s → Prop} : ((a : α) → motive (Quotient.mk s a)) → (q : Quot Setoid.r) → motive q := Quot.ind /-- The analogue of `Quot.liftOn`: if `f : α → β` respects the equivalence relation `≈`, then it lifts to a function on `Quotient s` such that `lift (mk a) f h = f a`. -/ protected abbrev liftOn {α : Sort u} {β : Sort v} {s : Setoid α} (q : Quotient s) (f : α → β) (c : (a b : α) → a ≈ b → f a = f b) : β := Quot.liftOn q f c @[elabAsElim] protected theorem inductionOn {α : Sort u} {s : Setoid α} {motive : Quotient s → Prop} (q : Quotient s) (h : (a : α) → motive (Quotient.mk s a)) : motive q := Quot.inductionOn q h theorem exists_rep {α : Sort u} {s : Setoid α} (q : Quotient s) : Exists (fun (a : α) => Quotient.mk s a = q) := Quot.exists_rep q section variable {α : Sort u} variable {s : Setoid α} variable {motive : Quotient s → Sort v} /-- The analogue of `Quot.rec` for `Quotient`. See `Quot.rec`. -/ @[inline, elabAsElim] protected def rec (f : (a : α) → motive (Quotient.mk s a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) (q : Quotient s) : motive q := Quot.rec f h q /-- The analogue of `Quot.recOn` for `Quotient`. See `Quot.recOn`. -/ @[elabAsElim] protected abbrev recOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk s a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) : motive q := Quot.recOn q f h /-- The analogue of `Quot.recOnSubsingleton` for `Quotient`. See `Quot.recOnSubsingleton`. -/ @[elabAsElim] protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quotient.mk s a))] (q : Quotient s) (f : (a : α) → motive (Quotient.mk s a)) : motive q := Quot.recOnSubsingleton (h := h) q f /-- The analogue of `Quot.hrecOn` for `Quotient`. See `Quot.hrecOn`. -/ @[elabAsElim] protected abbrev hrecOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk s a)) (c : (a b : α) → (p : a ≈ b) → HEq (f a) (f b)) : motive q := Quot.hrecOn q f c end section universe uA uB uC variable {α : Sort uA} {β : Sort uB} {φ : Sort uC} variable {s₁ : Setoid α} {s₂ : Setoid β} /-- Lift a binary function to a quotient on both arguments. -/ protected abbrev lift₂ (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ := by apply Quotient.lift (fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂) _ q₁ intros induction q₂ using Quotient.ind apply c; assumption; apply Setoid.refl /-- Lift a binary function to a quotient on both arguments. -/ protected abbrev liftOn₂ (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) : φ := Quotient.lift₂ f c q₁ q₂ @[elabAsElim] protected theorem ind₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (h : (a : α) → (b : β) → motive (Quotient.mk s₁ a) (Quotient.mk s₂ b)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h @[elabAsElim] protected theorem inductionOn₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : (a : α) → (b : β) → motive (Quotient.mk s₁ a) (Quotient.mk s₂ b)) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h @[elabAsElim] protected theorem inductionOn₃ {s₃ : Setoid φ} {motive : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : (a : α) → (b : β) → (c : φ) → motive (Quotient.mk s₁ a) (Quotient.mk s₂ b) (Quotient.mk s₃ c)) : motive q₁ q₂ q₃ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind induction q₃ using Quotient.ind apply h end section Exact variable {α : Sort u} private def rel {s : Setoid α} (q₁ q₂ : Quotient s) : Prop := Quotient.liftOn₂ q₁ q₂ (fun a₁ a₂ => a₁ ≈ a₂) (fun _ _ _ _ a₁b₁ a₂b₂ => propext (Iff.intro (fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂)) (fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂))))) private theorem rel.refl {s : Setoid α} (q : Quotient s) : rel q q := q.inductionOn Setoid.refl private theorem rel_of_eq {s : Setoid α} {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ := fun h => Eq.ndrecOn h (rel.refl q₁) theorem exact {s : Setoid α} {a b : α} : Quotient.mk s a = Quotient.mk s b → a ≈ b := fun h => rel_of_eq h end Exact section universe uA uB uC variable {α : Sort uA} {β : Sort uB} variable {s₁ : Setoid α} {s₂ : Setoid β} /-- Lift a binary function to a quotient on both arguments. -/ @[elabAsElim] protected abbrev recOnSubsingleton₂ {motive : Quotient s₁ → Quotient s₂ → Sort uC} [s : (a : α) → (b : β) → Subsingleton (motive (Quotient.mk s₁ a) (Quotient.mk s₂ b))] (q₁ : Quotient s₁) (q₂ : Quotient s₂) (g : (a : α) → (b : β) → motive (Quotient.mk s₁ a) (Quotient.mk s₂ b)) : motive q₁ q₂ := by induction q₁ using Quot.recOnSubsingleton induction q₂ using Quot.recOnSubsingleton apply g intro a; apply s induction q₂ using Quot.recOnSubsingleton intro a; apply s infer_instance end end Quotient section variable {α : Type u} variable (r : α → α → Prop) instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) := fun (q₁ q₂ : Quotient s) => Quotient.recOnSubsingleton₂ q₁ q₂ fun a₁ a₂ => match d a₁ a₂ with | isTrue h₁ => isTrue (Quotient.sound h₁) | isFalse h₂ => isFalse fun h => absurd (Quotient.exact h) h₂ /-! # Function extensionality -/ /-- **Function extensionality** is the statement that if two functions take equal values every point, then the functions themselves are equal: `(∀ x, f x = g x) → f = g`. It is called "extensionality" because it talks about how to prove two objects are equal based on the properties of the object (compare with set extensionality, which is `(∀ x, x ∈ s ↔ x ∈ t) → s = t`). This is often an axiom in dependent type theory systems, because it cannot be proved from the core logic alone. However in lean's type theory this follows from the existence of quotient types (note the `Quot.sound` in the proof, as well as the `show` line which makes use of the definitional equality `Quot.lift f h (Quot.mk x) = f x`). -/ theorem funext {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : ∀ x, f x = g x) : f = g := by let eqv (f g : (x : α) → β x) := ∀ x, f x = g x let extfunApp (f : Quot eqv) (x : α) : β x := Quot.liftOn f (fun (f : ∀ (x : α), β x) => f x) (fun _ _ h => h x) show extfunApp (Quot.mk eqv f) = extfunApp (Quot.mk eqv g) exact congrArg extfunApp (Quot.sound h) instance {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) where allEq f g := funext fun a => Subsingleton.elim (f a) (g a) /-! # Squash -/ /-- `Squash α` is the quotient of `α` by the always true relation. It is empty if `α` is empty, otherwise it is a singleton. (Thus it is unconditionally a `Subsingleton`.) It is the "universal `Subsingleton`" mapped from `α`. It is similar to `Nonempty α`, which has the same properties, but unlike `Nonempty` this is a `Type u`, that is, it is "data", and the compiler represents an element of `Squash α` the same as `α` itself (as compared to `Nonempty α`, whose elements are represented by a dummy value). `Squash.lift` will extract a value in any subsingleton `β` from a function on `α`, while `Nonempty.rec` can only do the same when `β` is a proposition. -/ def Squash (α : Type u) := Quot (fun (_ _ : α) => True) /-- The canonical quotient map into `Squash α`. -/ def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x theorem Squash.ind {α : Type u} {motive : Squash α → Prop} (h : ∀ (a : α), motive (Squash.mk a)) : ∀ (q : Squash α), motive q := Quot.ind h /-- If `β` is a subsingleton, then a function `α → β` lifts to `Squash α → β`. -/ @[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β := Quot.lift f (fun _ _ _ => Subsingleton.elim _ _) s instance : Subsingleton (Squash α) where allEq a b := by induction a using Squash.ind induction b using Squash.ind apply Quot.sound trivial /-! # Relations -/ /-- `Antisymm (·≤·)` says that `(·≤·)` is antisymmetric, that is, `a ≤ b → b ≤ a → a = b`. -/ class Antisymm {α : Sort u} (r : α → α → Prop) where /-- An antisymmetric relation `(·≤·)` satisfies `a ≤ b → b ≤ a → a = b`. -/ antisymm {a b : α} : r a b → r b a → a = b namespace Lean /-! # Kernel reduction hints -/ /-- When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`. The kernel will not use the interpreter if `c` is not a constant. This feature is useful for performing proofs by reflection. Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with `Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled. Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base. This is extra 30k lines of code. More importantly, you will probably not be able to check your development using external type checkers (e.g., Trepplein) that do not implement this feature. Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter. So, you are mainly losing the capability of type checking your development using external checkers. Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations. If an extern function is executed, then the trusted code base will also include the implementation of the associated foreign function. -/ opaque reduceBool (b : Bool) : Bool := b /-- Similar to `Lean.reduceBool` for closed `Nat` terms. Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`. The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression. We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/ opaque reduceNat (n : Nat) : Nat := n /-- The axiom `ofReduceBool` is used to perform proofs by reflection. See `reduceBool`. This axiom is usually not used directly, because it has some syntactic restrictions. Instead, the `native_decide` tactic can be used to prove any proposition whose decidability instance can be evaluated to `true` using the lean compiler / interpreter. Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base. This is extra 30k lines of code. More importantly, you will probably not be able to check your development using external type checkers (e.g., Trepplein) that do not implement this feature. Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter. So, you are mainly losing the capability of type checking your development using external checkers. -/ axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b /-- The axiom `ofReduceNat` is used to perform proofs by reflection. See `reduceBool`. Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base. This is extra 30k lines of code. More importantly, you will probably not be able to check your development using external type checkers (e.g., Trepplein) that do not implement this feature. Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter. So, you are mainly losing the capability of type checking your development using external checkers. -/ axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b /-- `IsAssociative op` says that `op` is an associative operation, i.e. `(a ∘ b) ∘ c = a ∘ (b ∘ c)`. It is used by the `ac_rfl` tactic. -/ class IsAssociative {α : Sort u} (op : α → α → α) where /-- An associative operation satisfies `(a ∘ b) ∘ c = a ∘ (b ∘ c)`. -/ assoc : (a b c : α) → op (op a b) c = op a (op b c) /-- `IsCommutative op` says that `op` is a commutative operation, i.e. `a ∘ b = b ∘ a`. It is used by the `ac_rfl` tactic. -/ class IsCommutative {α : Sort u} (op : α → α → α) where /-- A commutative operation satisfies `a ∘ b = b ∘ a`. -/ comm : (a b : α) → op a b = op b a /-- `IsIdempotent op` says that `op` is an idempotent operation, i.e. `a ∘ a = a`. It is used by the `ac_rfl` tactic (which also simplifies up to idempotence when available). -/ class IsIdempotent {α : Sort u} (op : α → α → α) where /-- An idempotent operation satisfies `a ∘ a = a`. -/ idempotent : (x : α) → op x x = x /-- `IsNeutral op e` says that `e` is a neutral operation for `op`, i.e. `a ∘ e = a = e ∘ a`. It is used by the `ac_rfl` tactic (which also simplifies neutral elements when available). -/ class IsNeutral {α : Sort u} (op : α → α → α) (neutral : α) where /-- A neutral element can be cancelled on the left: `e ∘ a = a`. -/ left_neutral : (a : α) → op neutral a = a /-- A neutral element can be cancelled on the right: `a ∘ e = a`. -/ right_neutral : (a : α) → op a neutral = a end Lean
e34bd29dc59895edd51213c4c4d4f3c746a05342
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Lean/Meta/Tactic/Simp/Types.lean
df8105609cfc47578ef3d033b421320b9f491714
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,077
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.Simp.SimpLemmas namespace Lean.Meta namespace Simp structure Result where expr : Expr proof? : Option Expr := none -- If none, proof is assumed to be `refl` deriving Inhabited abbrev Cache := ExprMap Result structure Context where config : Config parent? : Option Expr := none simpLemmas : SimpLemmas structure State (σ : Type) where user : σ -- user state cache : Cache := {} numSteps : Nat := 0 abbrev SimpM (σ : Type) := ReaderT Context $ StateRefT (State σ) $ MetaM inductive Step where | visit : Result → Step | done : Result → Step def Step.result : Step → Result | Step.visit r => r | Step.done r => r structure Methods (σ : Type) where pre : Expr → SimpM σ Step := fun e => return Step.visit { expr := e } post : Expr → SimpM σ Step := fun e => return Step.done { expr := e } discharge? : Expr → SimpM σ (Option Expr) := fun e => return none /- Internal monad -/ abbrev M (σ : Type) := ReaderT (Methods σ) $ SimpM σ def pre (e : Expr) : M σ Step := do (← read).pre e def post (e : Expr) : M σ Step := do (← read).post e def discharge? (e : Expr) : M σ (Option Expr) := do (← read).discharge? e def getConfig : M σ Config := return (← readThe Context).config @[inline] def withParent (parent : Expr) (f : M σ α) : M σ α := withTheReader Context (fun ctx => { ctx with parent? := parent }) f def getSimpLemmas : M σ SimpLemmas := return (← readThe Context).simpLemmas @[inline] def withSimpLemmas (s : SimpLemmas) (x : M σ α) : M σ α := do let cacheSaved := (← get).cache modify fun s => { s with cache := {} } try withTheReader Context (fun ctx => { ctx with simpLemmas := s }) x finally modify fun s => { s with cache := cacheSaved } end Simp export Simp (SimpM) end Lean.Meta
d5fff81d210c192b77854b67ade00ed00f407300
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/monotonicity/test_cases.lean
16d174d8b2e0d39cb77dfcacfc8422d2586792f6
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,396
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.nat.basic import data.list.basic import tactic.monotonicity.interactive open list tactic tactic.interactive meta class elaborable (α : Type) (β : out_param Type) := (elaborate : α → tactic β) export elaborable (elaborate) meta instance : elaborable pexpr expr := ⟨ to_expr ⟩ meta instance elaborable_list {α α'} [elaborable α α'] : elaborable (list α) (list α') := ⟨ mmap elaborate ⟩ meta def mono_function.elaborate : mono_function ff → tactic mono_function | (mono_function.non_assoc x y z) := mono_function.non_assoc <$> elaborate x <*> elaborate y <*> elaborate z | (mono_function.assoc x y z) := mono_function.assoc <$> elaborate x <*> traverse elaborate y <*> traverse elaborate z | (mono_function.assoc_comm x y) := mono_function.assoc_comm <$> elaborate x <*> elaborate y meta instance elaborable_mono_function : elaborable (mono_function ff) mono_function := ⟨ mono_function.elaborate ⟩ meta instance prod_elaborable {α α' β β' : Type} [elaborable α α'] [elaborable β β'] : elaborable (α × β) (α' × β') := ⟨ λ i, prod.rec_on i (λ x y, prod.mk <$> elaborate x <*> elaborate y) ⟩ meta def parse_mono_function' (l r : pexpr) := do l' ← to_expr l, r' ← to_expr r, parse_ac_mono_function { mono_cfg . } l' r' run_cmd do xs ← mmap to_expr [``(1),``(2),``(3)], ys ← mmap to_expr [``(1),``(2),``(4)], x ← match_prefix { unify := ff } xs ys, p ← elaborate ([``(1),``(2)] , [``(3)], [``(4)]), guard $ x = p run_cmd do xs ← mmap to_expr [``(1),``(2),``(3),``(6),``(7)], ys ← mmap to_expr [``(1),``(2),``(4),``(5),``(6),``(7)], x ← match_assoc { unify := ff } xs ys, p ← elaborate ([``(1), ``(2)], [``(3)], ([``(4), ``(5)], [``(6), ``(7)])), guard (x = p) run_cmd do x ← to_expr ``(7 + 3 : ℕ) >>= check_ac, x ← pp x.2.2.1, let y := "(some (is_left_id.left_id, (is_right_id.right_id, 0)))", guard (x.to_string = y) <|> fail ("guard: " ++ x.to_string) meta def test_pp {α} [has_to_tactic_format α] (tag : format) (expected : string) (prog : tactic α) : tactic unit := do r ← prog, pp_r ← pp r, guard (pp_r.to_string = expected) <|> fail format!"test_pp: {tag}" run_cmd do test_pp "test1" "(3 + 6, (4 + 5, ([], has_add.add _ 2 + 1)))" (parse_mono_function' ``(1 + 3 + 2 + 6) ``(4 + 2 + 1 + 5)), test_pp "test2" "([1] ++ [3] ++ [2] ++ [6], ([4] ++ [2] ++ [1] ++ [5], ([], append none _ none)))" (parse_mono_function' ``([1] ++ [3] ++ [2] ++ [6]) ``([4] ++ [2] ++ ([1] ++ [5]))), test_pp "test3" "([3] ++ [2], ([5] ++ [4], ([], append (some [1]) _ (some [2]))))" (parse_mono_function' ``([1] ++ [3] ++ [2] ++ [2]) ``([1] ++ [5] ++ ([4] ++ [2]))) def my_id {α : Type*} : α → α := id @[mono] lemma test_monotone {α : Type*} [preorder α] : monotone (my_id : α → α) := λ x y h, h example : my_id 0 ≤ my_id 1 := begin mono, simp, end @[mono] lemma test_strict_mono {α : Type*} [preorder α] : strict_mono (my_id : α → α) := λ x y h, h example : my_id 0 < my_id 1 := begin mono, simp, end
262fe093a518a62ffeefd13d8f5a90e6811fa1b6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/constructions/over/products.lean
cfd8ca68c6ec87515e40ab757f32516d49e36617
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,255
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.shapes.pullbacks import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.finite_products /-! # Products in the over category Shows that products in the over category can be derived from wide pullbacks in the base category. The main result is `over_product_of_wide_pullback`, which says that if `C` has `J`-indexed wide pullbacks, then `over B` has `J`-indexed products. -/ universes w v u -- morphism levels before object levels. See note [category_theory universes]. open category_theory category_theory.limits variables {J : Type w} variables {C : Type u} [category.{v} C] variable {X : C} namespace category_theory.over namespace construct_products /-- (Implementation) Given a product diagram in `C/B`, construct the corresponding wide pullback diagram in `C`. -/ @[reducible] def wide_pullback_diagram_of_diagram_over (B : C) {J : Type w} (F : discrete J ⥤ over B) : wide_pullback_shape J ⥤ C := wide_pullback_shape.wide_cospan B (λ j, (F.obj ⟨j⟩).left) (λ j, (F.obj ⟨j⟩).hom) /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_inverse_obj (B : C) {J : Type w} (F : discrete J ⥤ over B) (c : cone F) : cone (wide_pullback_diagram_of_diagram_over B F) := { X := c.X.left, π := { app := λ X, option.cases_on X c.X.hom (λ (j : J), (c.π.app ⟨j⟩).left), -- `tidy` can do this using `case_bash`, but let's try to be a good `-T50000` citizen: naturality' := λ X Y f, begin dsimp, cases X; cases Y; cases f, { rw [category.id_comp, category.comp_id], }, { rw [over.w, category.id_comp], }, { rw [category.id_comp, category.comp_id], }, end } } /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_inverse (B : C) {J : Type w} (F : discrete J ⥤ over B) : cone F ⥤ cone (wide_pullback_diagram_of_diagram_over B F) := { obj := cones_equiv_inverse_obj B F, map := λ c₁ c₂ f, { hom := f.hom.left, w' := λ j, begin cases j, { simp }, { dsimp, rw ← f.w ⟨j⟩, refl } end } } local attribute [tidy] tactic.discrete_cases /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_functor (B : C) {J : Type w} (F : discrete J ⥤ over B) : cone (wide_pullback_diagram_of_diagram_over B F) ⥤ cone F := { obj := λ c, { X := over.mk (c.π.app none), π := { app := λ ⟨j⟩, over.hom_mk (c.π.app (some j)) (by apply c.w (wide_pullback_shape.hom.term j)) } }, map := λ c₁ c₂ f, { hom := over.hom_mk f.hom } } local attribute [tidy] tactic.case_bash /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simp] def cones_equiv_unit_iso (B : C) (F : discrete J ⥤ over B) : 𝟭 (cone (wide_pullback_diagram_of_diagram_over B F)) ≅ cones_equiv_functor B F ⋙ cones_equiv_inverse B F := nat_iso.of_components (λ _, cones.ext {hom := 𝟙 _, inv := 𝟙 _} (by tidy)) (by tidy) /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simp] def cones_equiv_counit_iso (B : C) (F : discrete J ⥤ over B) : cones_equiv_inverse B F ⋙ cones_equiv_functor B F ≅ 𝟭 (cone F) := nat_iso.of_components (λ _, cones.ext {hom := over.hom_mk (𝟙 _), inv := over.hom_mk (𝟙 _)} (by tidy)) (by tidy) -- TODO: Can we add `. obviously` to the second arguments of `nat_iso.of_components` and -- `cones.ext`? /-- (Impl) Establish an equivalence between the category of cones for `F` and for the "grown" `F`. -/ @[simps] def cones_equiv (B : C) (F : discrete J ⥤ over B) : cone (wide_pullback_diagram_of_diagram_over B F) ≌ cone F := { functor := cones_equiv_functor B F, inverse := cones_equiv_inverse B F, unit_iso := cones_equiv_unit_iso B F, counit_iso := cones_equiv_counit_iso B F, } /-- Use the above equivalence to prove we have a limit. -/ lemma has_over_limit_discrete_of_wide_pullback_limit {B : C} (F : discrete J ⥤ over B) [has_limit (wide_pullback_diagram_of_diagram_over B F)] : has_limit F := has_limit.mk { cone := _, is_limit := is_limit.of_right_adjoint (cones_equiv B F).functor (limit.is_limit (wide_pullback_diagram_of_diagram_over B F)) } /-- Given a wide pullback in `C`, construct a product in `C/B`. -/ lemma over_product_of_wide_pullback [has_limits_of_shape (wide_pullback_shape J) C] {B : C} : has_limits_of_shape (discrete J) (over B) := { has_limit := λ F, has_over_limit_discrete_of_wide_pullback_limit F } /-- Given a pullback in `C`, construct a binary product in `C/B`. -/ lemma over_binary_product_of_pullback [has_pullbacks C] {B : C} : has_binary_products (over B) := over_product_of_wide_pullback /-- Given all wide pullbacks in `C`, construct products in `C/B`. -/ lemma over_products_of_wide_pullbacks [has_wide_pullbacks.{w} C] {B : C} : has_products.{w} (over B) := λ J, over_product_of_wide_pullback /-- Given all finite wide pullbacks in `C`, construct finite products in `C/B`. -/ lemma over_finite_products_of_finite_wide_pullbacks [has_finite_wide_pullbacks C] {B : C} : has_finite_products (over B) := ⟨λ n, over_product_of_wide_pullback⟩ end construct_products local attribute [tidy] tactic.discrete_cases /-- Construct terminal object in the over category. This isn't an instance as it's not typically the way we want to define terminal objects. (For instance, this gives a terminal object which is different from the generic one given by `over_product_of_wide_pullback` above.) -/ lemma over_has_terminal (B : C) : has_terminal (over B) := { has_limit := λ F, has_limit.mk { cone := { X := over.mk (𝟙 _), π := { app := λ p, p.as.elim } }, is_limit := { lift := λ s, over.hom_mk _, fac' := λ _ j, j.as.elim, uniq' := λ s m _, begin ext, rw over.hom_mk_left, have := m.w, dsimp at this, rwa [category.comp_id, category.comp_id] at this end } } } end category_theory.over
6303331ceb5fb4d541f8669b203e3abe28ce38f0
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/perm/cycle_type.lean
3c6b01e64c0ade94838125d63816038d1aa0b91f
[ "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
26,326
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import algebra.gcd_monoid.multiset import combinatorics.partition import group_theory.perm.cycles import ring_theory.int.basic import tactic.linarith /-! # Cycle Types In this file we define the cycle type of a permutation. ## Main definitions - `σ.cycle_type` where `σ` is a permutation of a `fintype` - `σ.partition` where `σ` is a permutation of a `fintype` ## Main results - `sum_cycle_type` : The sum of `σ.cycle_type` equals `σ.support.card` - `lcm_cycle_type` : The lcm of `σ.cycle_type` equals `order_of σ` - `is_conj_iff_cycle_type_eq` : Two permutations are conjugate if and only if they have the same cycle type. * `exists_prime_order_of_dvd_card`: For every prime `p` dividing the order of a finite group `G` there exists an element of order `p` in `G`. This is known as Cauchy`s theorem. -/ namespace equiv.perm open equiv list multiset variables {α : Type*} [fintype α] section cycle_type variables [decidable_eq α] /-- The cycle type of a permutation -/ def cycle_type (σ : perm α) : multiset ℕ := σ.cycle_factors_finset.1.map (finset.card ∘ support) lemma cycle_type_def (σ : perm α) : σ.cycle_type = σ.cycle_factors_finset.1.map (finset.card ∘ support) := rfl lemma cycle_type_eq' {σ : perm α} (s : finset (perm α)) (h1 : ∀ f : perm α, f ∈ s → f.is_cycle) (h2 : ∀ (a ∈ s) (b ∈ s), a ≠ b → disjoint a b) (h0 : s.noncomm_prod id (λ a ha b hb, (em (a = b)).by_cases (λ h, h ▸ commute.refl a) (set.pairwise.mono' (λ _ _, disjoint.commute) h2 a ha b hb)) = σ) : σ.cycle_type = s.1.map (finset.card ∘ support) := begin rw cycle_type_def, congr, rw cycle_factors_finset_eq_finset, exact ⟨h1, h2, h0⟩ end lemma cycle_type_eq {σ : perm α} (l : list (perm α)) (h0 : l.prod = σ) (h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle) (h2 : l.pairwise disjoint) : σ.cycle_type = l.map (finset.card ∘ support) := begin have hl : l.nodup := nodup_of_pairwise_disjoint_cycles h1 h2, rw cycle_type_eq' l.to_finset, { simp [list.erase_dup_eq_self.mpr hl] }, { simpa using h1 }, { simpa [hl] using h0 }, { simpa [list.erase_dup_eq_self.mpr hl] using list.forall_of_pairwise disjoint.symmetric h2 } end lemma cycle_type_one : (1 : perm α).cycle_type = 0 := cycle_type_eq [] rfl (λ _, false.elim) pairwise.nil lemma cycle_type_eq_zero {σ : perm α} : σ.cycle_type = 0 ↔ σ = 1 := by simp [cycle_type_def, cycle_factors_finset_eq_empty_iff] lemma card_cycle_type_eq_zero {σ : perm α} : σ.cycle_type.card = 0 ↔ σ = 1 := by rw [card_eq_zero, cycle_type_eq_zero] lemma two_le_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 2 ≤ n := begin simp only [cycle_type_def, ←finset.mem_def, function.comp_app, multiset.mem_map, mem_cycle_factors_finset_iff] at h, obtain ⟨_, ⟨hc, -⟩, rfl⟩ := h, exact hc.two_le_card_support end lemma one_lt_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 1 < n := two_le_of_mem_cycle_type h lemma is_cycle.cycle_type {σ : perm α} (hσ : is_cycle σ) : σ.cycle_type = [σ.support.card] := cycle_type_eq [σ] (mul_one σ) (λ τ hτ, (congr_arg is_cycle (list.mem_singleton.mp hτ)).mpr hσ) (pairwise_singleton disjoint σ) lemma card_cycle_type_eq_one {σ : perm α} : σ.cycle_type.card = 1 ↔ σ.is_cycle := begin rw card_eq_one, simp_rw [cycle_type_def, multiset.map_eq_singleton, ←finset.singleton_val, finset.val_inj, cycle_factors_finset_eq_singleton_iff], split, { rintro ⟨_, _, ⟨h, -⟩, -⟩, exact h }, { intro h, use [σ.support.card, σ], simp [h] } end lemma disjoint.cycle_type {σ τ : perm α} (h : disjoint σ τ) : (σ * τ).cycle_type = σ.cycle_type + τ.cycle_type := begin rw [cycle_type_def, cycle_type_def, cycle_type_def, h.cycle_factors_finset_mul_eq_union, ←map_add, finset.union_val, multiset.add_eq_union_iff_disjoint.mpr _], rw [←finset.disjoint_val], exact h.disjoint_cycle_factors_finset end lemma cycle_type_inv (σ : perm α) : σ⁻¹.cycle_type = σ.cycle_type := cycle_induction_on (λ τ : perm α, τ⁻¹.cycle_type = τ.cycle_type) σ rfl (λ σ hσ, by rw [hσ.cycle_type, hσ.inv.cycle_type, support_inv]) (λ σ τ hστ hc hσ hτ, by rw [mul_inv_rev, hστ.cycle_type, ←hσ, ←hτ, add_comm, disjoint.cycle_type (λ x, or.imp (λ h : τ x = x, inv_eq_iff_eq.mpr h.symm) (λ h : σ x = x, inv_eq_iff_eq.mpr h.symm) (hστ x).symm)]) lemma cycle_type_conj {σ τ : perm α} : (τ * σ * τ⁻¹).cycle_type = σ.cycle_type := begin revert τ, apply cycle_induction_on _ σ, { intro, simp }, { intros σ hσ τ, rw [hσ.cycle_type, hσ.is_cycle_conj.cycle_type, card_support_conj] }, { intros σ τ hd hc hσ hτ π, rw [← conj_mul, hd.cycle_type, disjoint.cycle_type, hσ, hτ], intro a, apply (hd (π⁻¹ a)).imp _ _; { intro h, rw [perm.mul_apply, perm.mul_apply, h, apply_inv_self] } } end lemma sum_cycle_type (σ : perm α) : σ.cycle_type.sum = σ.support.card := cycle_induction_on (λ τ : perm α, τ.cycle_type.sum = τ.support.card) σ (by rw [cycle_type_one, sum_zero, support_one, finset.card_empty]) (λ σ hσ, by rw [hσ.cycle_type, coe_sum, list.sum_singleton]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, sum_add, hσ, hτ, hστ.card_support_mul]) lemma sign_of_cycle_type (σ : perm α) : sign σ = (σ.cycle_type.map (λ n, -(-1 : units ℤ) ^ n)).prod := cycle_induction_on (λ τ : perm α, sign τ = (τ.cycle_type.map (λ n, -(-1 : units ℤ) ^ n)).prod) σ (by rw [sign_one, cycle_type_one, map_zero, prod_zero]) (λ σ hσ, by rw [hσ.sign, hσ.cycle_type, coe_map, coe_prod, list.map_singleton, list.prod_singleton]) (λ σ τ hστ hc hσ hτ, by rw [sign_mul, hσ, hτ, hστ.cycle_type, map_add, prod_add]) lemma lcm_cycle_type (σ : perm α) : σ.cycle_type.lcm = order_of σ := cycle_induction_on (λ τ : perm α, τ.cycle_type.lcm = order_of τ) σ (by rw [cycle_type_one, lcm_zero, order_of_one]) (λ σ hσ, by rw [hσ.cycle_type, ←singleton_coe, ←singleton_eq_cons, lcm_singleton, order_of_is_cycle hσ, normalize_eq]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, lcm_add, lcm_eq_nat_lcm, hστ.order_of, hσ, hτ]) lemma dvd_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : n ∣ order_of σ := begin rw ← lcm_cycle_type, exact dvd_lcm h, end lemma order_of_cycle_of_dvd_order_of (f : perm α) (x : α) : order_of (cycle_of f x) ∣ order_of f := begin by_cases hx : f x = x, { rw ←cycle_of_eq_one_iff at hx, simp [hx] }, { refine dvd_of_mem_cycle_type _, rw [cycle_type, multiset.mem_map], refine ⟨f.cycle_of x, _, _⟩, { rwa [←finset.mem_def, cycle_of_mem_cycle_factors_finset_iff, mem_support] }, { simp [order_of_is_cycle (is_cycle_cycle_of _ hx)] } } end lemma two_dvd_card_support {σ : perm α} (hσ : σ ^ 2 = 1) : 2 ∣ σ.support.card := (congr_arg (has_dvd.dvd 2) σ.sum_cycle_type).mp (multiset.dvd_sum (λ n hn, by rw le_antisymm (nat.le_of_dvd zero_lt_two $ (dvd_of_mem_cycle_type hn).trans $ order_of_dvd_of_pow_eq_one hσ) (two_le_of_mem_cycle_type hn))) lemma cycle_type_prime_order {σ : perm α} (hσ : (order_of σ).prime) : ∃ n : ℕ, σ.cycle_type = repeat (order_of σ) (n + 1) := begin rw eq_repeat_of_mem (λ n hn, or_iff_not_imp_left.mp (hσ.2 n (dvd_of_mem_cycle_type hn)) (ne_of_gt (one_lt_of_mem_cycle_type hn))), use σ.cycle_type.card - 1, rw tsub_add_cancel_of_le, rw [nat.succ_le_iff, pos_iff_ne_zero, ne, card_cycle_type_eq_zero], rintro rfl, rw order_of_one at hσ, exact hσ.ne_one rfl, end lemma is_cycle_of_prime_order {σ : perm α} (h1 : (order_of σ).prime) (h2 : σ.support.card < 2 * (order_of σ)) : σ.is_cycle := begin obtain ⟨n, hn⟩ := cycle_type_prime_order h1, rw [←σ.sum_cycle_type, hn, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_lt_mul_right (order_of_pos σ), nat.succ_lt_succ_iff, nat.lt_succ_iff, nat.le_zero_iff] at h2, rw [←card_cycle_type_eq_one, hn, card_repeat, h2], end lemma cycle_type_le_of_mem_cycle_factors_finset {f g : perm α} (hf : f ∈ g.cycle_factors_finset) : f.cycle_type ≤ g.cycle_type := begin rw mem_cycle_factors_finset_iff at hf, rw [cycle_type_def, cycle_type_def, hf.left.cycle_factors_finset_eq_singleton], refine map_le_map _, simpa [←finset.mem_def, mem_cycle_factors_finset_iff] using hf end lemma cycle_type_mul_mem_cycle_factors_finset_eq_sub {f g : perm α} (hf : f ∈ g.cycle_factors_finset) : (g * f⁻¹).cycle_type = g.cycle_type - f.cycle_type := begin suffices : (g * f⁻¹).cycle_type + f.cycle_type = g.cycle_type - f.cycle_type + f.cycle_type, { rw tsub_add_cancel_of_le (cycle_type_le_of_mem_cycle_factors_finset hf) at this, simp [←this] }, simp [←(disjoint_mul_inv_of_mem_cycle_factors_finset hf).cycle_type, tsub_add_cancel_of_le (cycle_type_le_of_mem_cycle_factors_finset hf)] end theorem is_conj_of_cycle_type_eq {σ τ : perm α} (h : cycle_type σ = cycle_type τ) : is_conj σ τ := begin revert τ, apply cycle_induction_on _ σ, { intros τ h, rw [cycle_type_one, eq_comm, cycle_type_eq_zero] at h, rw h }, { intros σ hσ τ hστ, have hτ := card_cycle_type_eq_one.2 hσ, rw [hστ, card_cycle_type_eq_one] at hτ, apply hσ.is_conj hτ, rw [hσ.cycle_type, hτ.cycle_type, coe_eq_coe, singleton_perm] at hστ, simp only [and_true, eq_self_iff_true] at hστ, exact hστ }, { intros σ τ hστ hσ h1 h2 π hπ, rw [hστ.cycle_type] at hπ, { have h : σ.support.card ∈ map (finset.card ∘ perm.support) π.cycle_factors_finset.val, { simp [←cycle_type_def, ←hπ, hσ.cycle_type] }, obtain ⟨σ', hσ'l, hσ'⟩ := multiset.mem_map.mp h, have key : is_conj (σ' * (π * σ'⁻¹)) π, { rw is_conj_iff, use σ'⁻¹, simp [mul_assoc] }, refine is_conj.trans _ key, have hs : σ.cycle_type = σ'.cycle_type, { rw [←finset.mem_def, mem_cycle_factors_finset_iff] at hσ'l, rw [hσ.cycle_type, ←hσ', hσ'l.left.cycle_type] }, refine hστ.is_conj_mul (h1 hs) (h2 _) _, { rw [cycle_type_mul_mem_cycle_factors_finset_eq_sub, ←hπ, add_comm, hs, add_tsub_cancel_right], rwa finset.mem_def }, { exact (disjoint_mul_inv_of_mem_cycle_factors_finset hσ'l).symm } } } end theorem is_conj_iff_cycle_type_eq {σ τ : perm α} : is_conj σ τ ↔ σ.cycle_type = τ.cycle_type := ⟨λ h, begin obtain ⟨π, rfl⟩ := is_conj_iff.1 h, rw cycle_type_conj, end, is_conj_of_cycle_type_eq⟩ @[simp] lemma cycle_type_extend_domain {β : Type*} [fintype β] [decidable_eq β] {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) {g : perm α} : cycle_type (g.extend_domain f) = cycle_type g := begin apply cycle_induction_on _ g, { rw [extend_domain_one, cycle_type_one, cycle_type_one] }, { intros σ hσ, rw [(hσ.extend_domain f).cycle_type, hσ.cycle_type, card_support_extend_domain] }, { intros σ τ hd hc hσ hτ, rw [hd.cycle_type, ← extend_domain_mul, (hd.extend_domain f).cycle_type, hσ, hτ] } end lemma mem_cycle_type_iff {n : ℕ} {σ : perm α} : n ∈ cycle_type σ ↔ ∃ c τ : perm α, σ = c * τ ∧ disjoint c τ ∧ is_cycle c ∧ c.support.card = n := begin split, { intro h, obtain ⟨l, rfl, hlc, hld⟩ := trunc_cycle_factors σ, rw cycle_type_eq _ rfl hlc hld at h, obtain ⟨c, cl, rfl⟩ := list.exists_of_mem_map h, rw (list.perm_cons_erase cl).pairwise_iff (λ _ _ hd, _) at hld, swap, { exact hd.symm }, refine ⟨c, (l.erase c).prod, _, _, hlc _ cl, rfl⟩, { rw [← list.prod_cons, (list.perm_cons_erase cl).symm.prod_eq' (hld.imp (λ _ _, disjoint.commute))] }, { exact disjoint_prod_right _ (λ g, list.rel_of_pairwise_cons hld) } }, { rintros ⟨c, t, rfl, hd, hc, rfl⟩, simp [hd.cycle_type, hc.cycle_type] } end lemma le_card_support_of_mem_cycle_type {n : ℕ} {σ : perm α} (h : n ∈ cycle_type σ) : n ≤ σ.support.card := (le_sum_of_mem h).trans (le_of_eq σ.sum_cycle_type) lemma cycle_type_of_card_le_mem_cycle_type_add_two {n : ℕ} {g : perm α} (hn2 : fintype.card α < n + 2) (hng : n ∈ g.cycle_type) : g.cycle_type = {n} := begin obtain ⟨c, g', rfl, hd, hc, rfl⟩ := mem_cycle_type_iff.1 hng, by_cases g'1 : g' = 1, { rw [hd.cycle_type, hc.cycle_type, multiset.singleton_eq_cons, multiset.singleton_coe, g'1, cycle_type_one, add_zero] }, contrapose! hn2, apply le_trans _ (c * g').support.card_le_univ, rw [hd.card_support_mul], exact add_le_add_left (two_le_card_support_of_ne_one g'1) _, end end cycle_type lemma card_compl_support_modeq [decidable_eq α] {p n : ℕ} [hp : fact p.prime] {σ : perm α} (hσ : σ ^ p ^ n = 1) : σ.supportᶜ.card ≡ fintype.card α [MOD p] := begin rw [nat.modeq_iff_dvd' σ.supportᶜ.card_le_univ, ←finset.card_compl, compl_compl], refine (congr_arg _ σ.sum_cycle_type).mp (multiset.dvd_sum (λ k hk, _)), obtain ⟨m, -, hm⟩ := (nat.dvd_prime_pow hp.out).mp (order_of_dvd_of_pow_eq_one hσ), obtain ⟨l, -, rfl⟩ := (nat.dvd_prime_pow hp.out).mp ((congr_arg _ hm).mp (dvd_of_mem_cycle_type hk)), exact dvd_pow_self _ (λ h, (one_lt_of_mem_cycle_type hk).ne $ by rw [h, pow_zero]), end lemma exists_fixed_point_of_prime {p n : ℕ} [hp : fact p.prime] (hα : ¬ p ∣ fintype.card α) {σ : perm α} (hσ : σ ^ p ^ n = 1) : ∃ a : α, σ a = a := begin classical, contrapose! hα, simp_rw ← mem_support at hα, exact nat.modeq_zero_iff_dvd.mp ((congr_arg _ (finset.card_eq_zero.mpr (compl_eq_bot.mpr (finset.eq_univ_iff_forall.mpr hα)))).mp (card_compl_support_modeq hσ).symm), end lemma exists_fixed_point_of_prime' {p n : ℕ} [hp : fact p.prime] (hα : p ∣ fintype.card α) {σ : perm α} (hσ : σ ^ p ^ n = 1) {a : α} (ha : σ a = a) : ∃ b : α, σ b = b ∧ b ≠ a := begin classical, have h : ∀ b : α, b ∈ σ.supportᶜ ↔ σ b = b := λ b, by rw [finset.mem_compl, mem_support, not_not], obtain ⟨b, hb1, hb2⟩ := finset.exists_ne_of_one_lt_card (lt_of_lt_of_le hp.out.one_lt (nat.le_of_dvd (finset.card_pos.mpr ⟨a, (h a).mpr ha⟩) (nat.modeq_zero_iff_dvd.mp ((card_compl_support_modeq hσ).trans (nat.modeq_zero_iff_dvd.mpr hα))))) a, exact ⟨b, (h b).mp hb1, hb2⟩, end lemma is_cycle_of_prime_order' {σ : perm α} (h1 : (order_of σ).prime) (h2 : fintype.card α < 2 * (order_of σ)) : σ.is_cycle := begin classical, exact is_cycle_of_prime_order h1 (lt_of_le_of_lt σ.support.card_le_univ h2), end lemma is_cycle_of_prime_order'' {σ : perm α} (h1 : (fintype.card α).prime) (h2 : order_of σ = fintype.card α) : σ.is_cycle := is_cycle_of_prime_order' ((congr_arg nat.prime h2).mpr h1) begin classical, rw [←one_mul (fintype.card α), ←h2, mul_lt_mul_right (order_of_pos σ)], exact one_lt_two, end section cauchy variables (G : Type*) [group G] (n : ℕ) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one : set (vector G n) := {v | v.to_list.prod = 1} namespace vectors_prod_eq_one lemma mem_iff {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma zero_eq : vectors_prod_eq_one G 0 = {vector.nil} := set.eq_singleton_iff_unique_mem.mpr ⟨eq.refl (1 : G), λ v hv, v.eq_nil⟩ lemma one_eq : vectors_prod_eq_one G 1 = {vector.nil.cons 1} := begin simp_rw [set.eq_singleton_iff_unique_mem, mem_iff, vector.to_list_singleton, list.prod_singleton, vector.head_cons], exact ⟨rfl, λ v hv, v.cons_head_tail.symm.trans (congr_arg2 vector.cons hv v.tail.eq_nil)⟩, end instance zero_unique : unique (vectors_prod_eq_one G 0) := by { rw zero_eq, exact set.unique_singleton vector.nil } instance one_unique : unique (vectors_prod_eq_one G 1) := by { rw one_eq, exact set.unique_singleton (vector.nil.cons 1) } /-- Given a vector `v` of length `n`, make a vector of length `n + 1` whose product is `1`, by appending the inverse of the product of `v`. -/ @[simps] def vector_equiv : vector G n ≃ vectors_prod_eq_one G (n + 1) := { to_fun := λ v, ⟨v.to_list.prod⁻¹ ::ᵥ v, by rw [mem_iff, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩, inv_fun := λ v, v.1.tail, left_inv := λ v, v.tail_cons v.to_list.prod⁻¹, right_inv := λ v, subtype.ext ((congr_arg2 vector.cons (eq_inv_of_mul_eq_one (by { rw [←list.prod_cons, ←vector.to_list_cons, v.1.cons_head_tail], exact v.2 })).symm rfl).trans v.1.cons_head_tail) } /-- Given a vector `v` of length `n` whose product is 1, make a vector of length `n - 1`, by deleting the last entry of `v`. -/ def equiv_vector : vectors_prod_eq_one G n ≃ vector G (n - 1) := ((vector_equiv G (n - 1)).trans (if hn : n = 0 then (show vectors_prod_eq_one G (n - 1 + 1) ≃ vectors_prod_eq_one G n, by { rw hn, exact equiv_of_unique_of_unique }) else by rw tsub_add_cancel_of_le (nat.pos_of_ne_zero hn).nat_succ_le)).symm instance [fintype G] : fintype (vectors_prod_eq_one G n) := fintype.of_equiv (vector G (n - 1)) (equiv_vector G n).symm lemma card [fintype G] : fintype.card (vectors_prod_eq_one G n) = fintype.card G ^ (n - 1) := (fintype.card_congr (equiv_vector G n)).trans (card_vector (n - 1)) variables {G n} {g : G} (v : vectors_prod_eq_one G n) (j k : ℕ) /-- Rotate a vector whose product is 1. -/ def rotate : vectors_prod_eq_one G n := ⟨⟨_, (v.1.1.length_rotate k).trans v.1.2⟩, list.prod_rotate_eq_one_of_prod_eq_one v.2 k⟩ lemma rotate_zero : rotate v 0 = v := subtype.ext (subtype.ext v.1.1.rotate_zero) lemma rotate_rotate : rotate (rotate v j) k = rotate v (j + k) := subtype.ext (subtype.ext (v.1.1.rotate_rotate j k)) lemma rotate_length : rotate v n = v := subtype.ext (subtype.ext ((congr_arg _ v.1.2.symm).trans v.1.1.rotate_length)) end vectors_prod_eq_one lemma exists_prime_order_of_dvd_card {G : Type*} [group G] [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ fintype.card G) : ∃ x : G, order_of x = p := begin have hp' : p - 1 ≠ 0 := mt tsub_eq_zero_iff_le.mp (not_le_of_lt hp.out.one_lt), have Scard := calc p ∣ fintype.card G ^ (p - 1) : hdvd.trans (dvd_pow (dvd_refl _) hp') ... = fintype.card (vectors_prod_eq_one G p) : (vectors_prod_eq_one.card G p).symm, let f : ℕ → vectors_prod_eq_one G p → vectors_prod_eq_one G p := λ k v, vectors_prod_eq_one.rotate v k, have hf1 : ∀ v, f 0 v = v := vectors_prod_eq_one.rotate_zero, have hf2 : ∀ j k v, f k (f j v) = f (j + k) v := λ j k v, vectors_prod_eq_one.rotate_rotate v j k, have hf3 : ∀ v, f p v = v := vectors_prod_eq_one.rotate_length, let σ := equiv.mk (f 1) (f (p - 1)) (λ s, by rw [hf2, add_tsub_cancel_of_le hp.out.one_lt.le, hf3]) (λ s, by rw [hf2, tsub_add_cancel_of_le hp.out.one_lt.le, hf3]), have hσ : ∀ k v, (σ ^ k) v = f k v := λ k v, nat.rec (hf1 v).symm (λ k hk, eq.trans (by exact congr_arg σ hk) (hf2 k 1 v)) k, replace hσ : σ ^ (p ^ 1) = 1 := perm.ext (λ v, by rw [pow_one, hσ, hf3, one_apply]), let v₀ : vectors_prod_eq_one G p := ⟨vector.repeat 1 p, (list.prod_repeat 1 p).trans (one_pow p)⟩, have hv₀ : σ v₀ = v₀ := subtype.ext (subtype.ext (list.rotate_repeat (1 : G) p 1)), obtain ⟨v, hv1, hv2⟩ := exists_fixed_point_of_prime' Scard hσ hv₀, refine exists_imp_exists (λ g hg, order_of_eq_prime _ (λ hg', hv2 _)) (list.rotate_one_eq_self_iff_eq_repeat.mp (subtype.ext_iff.mp (subtype.ext_iff.mp hv1))), { rw [←list.prod_repeat, ←v.1.2, ←hg, (show v.val.val.prod = 1, from v.2)] }, { rw [subtype.ext_iff_val, subtype.ext_iff_val, hg, hg', v.1.2], refl }, end end cauchy lemma subgroup_eq_top_of_swap_mem [decidable_eq α] {H : subgroup (perm α)} [d : decidable_pred (∈ H)] {τ : perm α} (h0 : (fintype.card α).prime) (h1 : fintype.card α ∣ fintype.card H) (h2 : τ ∈ H) (h3 : is_swap τ) : H = ⊤ := begin haveI : fact (fintype.card α).prime := ⟨h0⟩, obtain ⟨σ, hσ⟩ := exists_prime_order_of_dvd_card (fintype.card α) h1, have hσ1 : order_of (σ : perm α) = fintype.card α := (order_of_subgroup σ).trans hσ, have hσ2 : is_cycle ↑σ := is_cycle_of_prime_order'' h0 hσ1, have hσ3 : (σ : perm α).support = ⊤ := finset.eq_univ_of_card (σ : perm α).support ((order_of_is_cycle hσ2).symm.trans hσ1), have hσ4 : subgroup.closure {↑σ, τ} = ⊤ := closure_prime_cycle_swap h0 hσ2 hσ3 h3, rw [eq_top_iff, ←hσ4, subgroup.closure_le, set.insert_subset, set.singleton_subset_iff], exact ⟨subtype.mem σ, h2⟩, end section partition variables [decidable_eq α] /-- The partition corresponding to a permutation -/ def partition (σ : perm α) : (fintype.card α).partition := { parts := σ.cycle_type + repeat 1 (fintype.card α - σ.support.card), parts_pos := λ n hn, begin cases mem_add.mp hn with hn hn, { exact zero_lt_one.trans (one_lt_of_mem_cycle_type hn) }, { exact lt_of_lt_of_le zero_lt_one (ge_of_eq (multiset.eq_of_mem_repeat hn)) }, end, parts_sum := by rw [sum_add, sum_cycle_type, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_one, add_tsub_cancel_of_le σ.support.card_le_univ] } lemma parts_partition {σ : perm α} : σ.partition.parts = σ.cycle_type + repeat 1 (fintype.card α - σ.support.card) := rfl lemma filter_parts_partition_eq_cycle_type {σ : perm α} : (partition σ).parts.filter (λ n, 2 ≤ n) = σ.cycle_type := begin rw [parts_partition, filter_add, multiset.filter_eq_self.2 (λ _, two_le_of_mem_cycle_type), multiset.filter_eq_nil.2 (λ a h, _), add_zero], rw multiset.eq_of_mem_repeat h, dec_trivial end lemma partition_eq_of_is_conj {σ τ : perm α} : is_conj σ τ ↔ σ.partition = τ.partition := begin rw [is_conj_iff_cycle_type_eq], refine ⟨λ h, _, λ h, _⟩, { rw [nat.partition.ext_iff, parts_partition, parts_partition, ← sum_cycle_type, ← sum_cycle_type, h] }, { rw [← filter_parts_partition_eq_cycle_type, ← filter_parts_partition_eq_cycle_type, h] } end end partition /-! ### 3-cycles -/ /-- A three-cycle is a cycle of length 3. -/ def is_three_cycle [decidable_eq α] (σ : perm α) : Prop := σ.cycle_type = {3} namespace is_three_cycle variables [decidable_eq α] {σ : perm α} lemma cycle_type (h : is_three_cycle σ) : σ.cycle_type = {3} := h lemma card_support (h : is_three_cycle σ) : σ.support.card = 3 := by rw [←sum_cycle_type, h.cycle_type, multiset.sum_singleton] lemma _root_.card_support_eq_three_iff : σ.support.card = 3 ↔ σ.is_three_cycle := begin refine ⟨λ h, _, is_three_cycle.card_support⟩, by_cases h0 : σ.cycle_type = 0, { rw [←sum_cycle_type, h0, sum_zero] at h, exact (ne_of_lt zero_lt_three h).elim }, obtain ⟨n, hn⟩ := exists_mem_of_ne_zero h0, by_cases h1 : σ.cycle_type.erase n = 0, { rw [←sum_cycle_type, ←cons_erase hn, h1, ←singleton_eq_cons, multiset.sum_singleton] at h, rw [is_three_cycle, ←cons_erase hn, h1, h, singleton_eq_cons] }, obtain ⟨m, hm⟩ := exists_mem_of_ne_zero h1, rw [←sum_cycle_type, ←cons_erase hn, ←cons_erase hm, multiset.sum_cons, multiset.sum_cons] at h, linarith [two_le_of_mem_cycle_type hn, two_le_of_mem_cycle_type (mem_of_mem_erase hm)], end lemma is_cycle (h : is_three_cycle σ) : is_cycle σ := by rw [←card_cycle_type_eq_one, h.cycle_type, card_singleton] lemma sign (h : is_three_cycle σ) : sign σ = 1 := begin rw [sign_of_cycle_type, h.cycle_type], refl, end lemma inv {f : perm α} (h : is_three_cycle f) : is_three_cycle (f⁻¹) := by rwa [is_three_cycle, cycle_type_inv] @[simp] lemma inv_iff {f : perm α} : is_three_cycle (f⁻¹) ↔ is_three_cycle f := ⟨by { rw ← inv_inv f, apply inv }, inv⟩ lemma order_of {g : perm α} (ht : is_three_cycle g) : order_of g = 3 := by rw [←lcm_cycle_type, ht.cycle_type, multiset.lcm_singleton, normalize_eq] lemma is_three_cycle_sq {g : perm α} (ht : is_three_cycle g) : is_three_cycle (g * g) := begin rw [←pow_two, ←card_support_eq_three_iff, support_pow_coprime, ht.card_support], rw [ht.order_of, nat.coprime_iff_gcd_eq_one], norm_num, end end is_three_cycle section variable [decidable_eq α] lemma is_three_cycle_swap_mul_swap_same {a b c : α} (ab : a ≠ b) (ac : a ≠ c) (bc : b ≠ c) : is_three_cycle (swap a b * swap a c) := begin suffices h : support (swap a b * swap a c) = {a, b, c}, { rw [←card_support_eq_three_iff, h], simp [ab, ac, bc] }, apply le_antisymm ((support_mul_le _ _).trans (λ x, _)) (λ x hx, _), { simp [ab, ac, bc] }, { simp only [finset.mem_insert, finset.mem_singleton] at hx, rw mem_support, simp only [perm.coe_mul, function.comp_app, ne.def], obtain rfl | rfl | rfl := hx, { rw [swap_apply_left, swap_apply_of_ne_of_ne ac.symm bc.symm], exact ac.symm }, { rw [swap_apply_of_ne_of_ne ab.symm bc, swap_apply_right], exact ab }, { rw [swap_apply_right, swap_apply_left], exact bc } } end open subgroup lemma swap_mul_swap_same_mem_closure_three_cycles {a b c : α} (ab : a ≠ b) (ac : a ≠ c) : (swap a b * swap a c) ∈ closure {σ : perm α | is_three_cycle σ } := begin by_cases bc : b = c, { subst bc, simp [one_mem] }, exact subset_closure (is_three_cycle_swap_mul_swap_same ab ac bc) end lemma is_swap.mul_mem_closure_three_cycles {σ τ : perm α} (hσ : is_swap σ) (hτ : is_swap τ) : σ * τ ∈ closure {σ : perm α | is_three_cycle σ } := begin obtain ⟨a, b, ab, rfl⟩ := hσ, obtain ⟨c, d, cd, rfl⟩ := hτ, by_cases ac : a = c, { subst ac, exact swap_mul_swap_same_mem_closure_three_cycles ab cd }, have h' : swap a b * swap c d = swap a b * swap a c * (swap c a * swap c d), { simp [swap_comm c a, mul_assoc] }, rw h', exact mul_mem _ (swap_mul_swap_same_mem_closure_three_cycles ab ac) (swap_mul_swap_same_mem_closure_three_cycles (ne.symm ac) cd), end end end equiv.perm
ae6cd803fe3b0cb62f82764509a39f3d0e4d5fd3
626e312b5c1cb2d88fca108f5933076012633192
/src/ring_theory/dedekind_domain.lean
4a07319214a2a6a5f564f31ec32e70004cbf015d
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,981
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.discrete_valuation_ring import ring_theory.fractional_ideal import ring_theory.ideal.over import ring_theory.integrally_closed import ring_theory.trace /-! # Dedekind domains This file defines the notion of a Dedekind domain (or Dedekind ring), giving three equivalent definitions (TODO: and shows that they are equivalent). ## Main definitions - `is_dedekind_domain` defines a Dedekind domain as a commutative ring that is Noetherian, integrally closed in its field of fractions and has Krull dimension at most one. `is_dedekind_domain_iff` shows that this does not depend on the choice of field of fractions. - `is_dedekind_domain_dvr` alternatively defines a Dedekind domain as an integral domain that is Noetherian, and the localization at every nonzero prime ideal is a DVR. - `is_dedekind_domain_inv` alternatively defines a Dedekind domain as an integral domain where every nonzero fractional ideal is invertible. - `is_dedekind_domain_inv_iff` shows that this does note depend on the choice of field of fractions. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. Often, definitions assume that Dedekind domains are not fields. We found it more practical to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J. Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [integral_domain A] [field K] open_locale non_zero_divisors /-- A ring `R` has Krull dimension at most one if all nonzero prime ideals are maximal. -/ def ring.dimension_le_one : Prop := ∀ p ≠ (⊥ : ideal R), p.is_prime → p.is_maximal open ideal ring namespace ring lemma dimension_le_one.principal_ideal_ring [is_principal_ideal_ring A] : dimension_le_one A := λ p nonzero prime, by { haveI := prime, exact is_prime.to_maximal_ideal nonzero } lemma dimension_le_one.is_integral_closure (B : Type*) [integral_domain B] [nontrivial R] [algebra R A] [algebra R B] [algebra B A] [is_scalar_tower R B A] [is_integral_closure B R A] (h : dimension_le_one R) : dimension_le_one B := λ p ne_bot prime, by exactI is_integral_closure.is_maximal_of_is_maximal_comap A p (h _ (is_integral_closure.comap_ne_bot A ne_bot) infer_instance) lemma dimension_le_one.integral_closure [nontrivial R] [algebra R A] (h : dimension_le_one R) : dimension_le_one (integral_closure R A) := h.is_integral_closure R A (integral_closure R A) end ring /-- A Dedekind domain is an integral domain that is Noetherian, integrally closed, and has Krull dimension at most one. This is definition 3.2 of [Neukirch1992]. The integral closure condition is independent of the choice of field of fractions: use `is_dedekind_domain_iff` to prove `is_dedekind_domain` for a given `fraction_map`. This is the default implementation, but there are equivalent definitions, `is_dedekind_domain_dvr` and `is_dedekind_domain_inv`. TODO: Prove that these are actually equivalent definitions. -/ class is_dedekind_domain : Prop := (is_noetherian_ring : is_noetherian_ring A) (dimension_le_one : dimension_le_one A) (is_integrally_closed : is_integrally_closed A) -- See library note [lower instance priority] attribute [instance, priority 100] is_dedekind_domain.is_noetherian_ring is_dedekind_domain.is_integrally_closed /-- An integral domain is a Dedekind domain iff and only if it is Noetherian, has dimension ≤ 1, and is integrally closed in a given fraction field. In particular, this definition does not depend on the choice of this fraction field. -/ lemma is_dedekind_domain_iff (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] : is_dedekind_domain A ↔ is_noetherian_ring A ∧ dimension_le_one A ∧ (∀ {x : K}, is_integral A x → ∃ y, algebra_map A K y = x) := ⟨λ ⟨hr, hd, hi⟩, ⟨hr, hd, λ x, (is_integrally_closed_iff K).mp hi⟩, λ ⟨hr, hd, hi⟩, ⟨hr, hd, (is_integrally_closed_iff K).mpr @hi⟩⟩ /-- A Dedekind domain is an integral domain that is Noetherian, and the localization at every nonzero prime is a discrete valuation ring. This is equivalent to `is_dedekind_domain`. TODO: prove the equivalence. -/ structure is_dedekind_domain_dvr : Prop := (is_noetherian_ring : is_noetherian_ring A) (is_dvr_at_nonzero_prime : ∀ P ≠ (⊥ : ideal A), P.is_prime → discrete_valuation_ring (localization.at_prime P)) section inverse variables {R₁ : Type*} [integral_domain R₁] [algebra R₁ K] [is_fraction_ring R₁ K] variables {I J : fractional_ideal R₁⁰ K} noncomputable instance : has_inv (fractional_ideal R₁⁰ K) := ⟨λ I, 1 / I⟩ lemma inv_eq : I⁻¹ = 1 / I := rfl lemma inv_zero' : (0 : fractional_ideal R₁⁰ K)⁻¹ = 0 := fractional_ideal.div_zero lemma inv_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : J⁻¹ = ⟨(1 : fractional_ideal R₁⁰ K) / J, fractional_ideal.fractional_div_of_nonzero h⟩ := fractional_ideal.div_nonzero _ lemma coe_inv_of_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : (↑J⁻¹ : submodule R₁ K) = is_localization.coe_submodule K ⊤ / J := by { rwa inv_nonzero _, refl, assumption } variables {K} lemma mem_inv_iff (hI : I ≠ 0) {x : K} : x ∈ I⁻¹ ↔ ∀ y ∈ I, x * y ∈ (1 : fractional_ideal R₁⁰ K) := fractional_ideal.mem_div_iff_of_nonzero hI lemma inv_anti_mono (hI : I ≠ 0) (hJ : J ≠ 0) (hIJ : I ≤ J) : J⁻¹ ≤ I⁻¹ := λ x, by { simp only [mem_inv_iff hI, mem_inv_iff hJ], exact λ h y hy, h y (hIJ hy) } lemma le_self_mul_inv {I : fractional_ideal R₁⁰ K} (hI : I ≤ (1 : fractional_ideal R₁⁰ K)) : I ≤ I * I⁻¹ := fractional_ideal.le_self_mul_one_div hI variables (K) lemma coe_ideal_le_self_mul_inv (I : ideal R₁) : (I : fractional_ideal R₁⁰ K) ≤ I * I⁻¹ := le_self_mul_inv fractional_ideal.coe_ideal_le_one /-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/ theorem right_inverse_eq (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : J = I⁻¹ := begin have hI : I ≠ 0 := fractional_ideal.ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, apply le_antisymm, { apply fractional_ideal.mul_le.mpr _, intros x hx y hy, rw mul_comm, exact (fractional_ideal.mem_div_iff_of_nonzero hI).mp hy x hx }, rw ← h, apply fractional_ideal.mul_left_mono I, apply (fractional_ideal.le_div_iff_of_nonzero hI).mpr _, intros y hy x hx, rw mul_comm, exact fractional_ideal.mul_mem_mul hx hy end theorem mul_inv_cancel_iff {I : fractional_ideal R₁⁰ K} : I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa ← right_inverse_eq K I J hJ⟩ lemma mul_inv_cancel_iff_is_unit {I : fractional_ideal R₁⁰ K} : I * I⁻¹ = 1 ↔ is_unit I := (mul_inv_cancel_iff K).trans is_unit_iff_exists_inv.symm variables {K' : Type*} [field K'] [algebra R₁ K'] [is_fraction_ring R₁ K'] @[simp] lemma map_inv (I : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (I⁻¹).map (h : K →ₐ[R₁] K') = (I.map h)⁻¹ := by rw [inv_eq, fractional_ideal.map_div, fractional_ideal.map_one, inv_eq] open submodule submodule.is_principal @[simp] lemma span_singleton_inv (x : K) : (fractional_ideal.span_singleton R₁⁰ x)⁻¹ = fractional_ideal.span_singleton _ (x⁻¹) := fractional_ideal.one_div_span_singleton x lemma mul_generator_self_inv (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : I * fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹ = 1 := begin -- Rewrite only the `I` that appears alone. conv_lhs { congr, rw fractional_ideal.eq_span_singleton_of_principal I }, rw [fractional_ideal.span_singleton_mul_span_singleton, mul_inv_cancel, fractional_ideal.span_singleton_one], intro generator_I_eq_zero, apply h, rw [fractional_ideal.eq_span_singleton_of_principal I, generator_I_eq_zero, fractional_ideal.span_singleton_zero] end lemma invertible_of_principal (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : I * I⁻¹ = 1 := (fractional_ideal.mul_div_self_cancel_iff).mpr ⟨fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹, mul_generator_self_inv _ I h⟩ lemma invertible_iff_generator_nonzero (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] : I * I⁻¹ = 1 ↔ generator (I : submodule R₁ K) ≠ 0 := begin split, { intros hI hg, apply fractional_ideal.ne_zero_of_mul_eq_one _ _ hI, rw [fractional_ideal.eq_span_singleton_of_principal I, hg, fractional_ideal.span_singleton_zero] }, { intro hg, apply invertible_of_principal, rw [fractional_ideal.eq_span_singleton_of_principal I], intro hI, have := fractional_ideal.mem_span_singleton_self _ (generator (I : submodule R₁ K)), rw [hI, fractional_ideal.mem_zero_iff] at this, contradiction } end lemma is_principal_inv (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : submodule.is_principal (I⁻¹).1 := begin rw [fractional_ideal.val_eq_coe, fractional_ideal.is_principal_iff], use (generator (I : submodule R₁ K))⁻¹, have hI : I * fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹) = 1, apply mul_generator_self_inv _ I h, exact (right_inverse_eq _ I (fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹)) hI).symm end @[simp] lemma fractional_ideal.one_inv : (1⁻¹ : fractional_ideal R₁⁰ K) = 1 := fractional_ideal.div_one /-- A Dedekind domain is an integral domain such that every fractional ideal has an inverse. This is equivalent to `is_dedekind_domain`. In particular we provide a `fractional_ideal.comm_group_with_zero` instance, assuming `is_dedekind_domain A`, which implies `is_dedekind_domain_inv`. For **integral** ideals, `is_dedekind_domain`(`_inv`) implies only `ideal.comm_cancel_monoid_with_zero`. -/ def is_dedekind_domain_inv : Prop := ∀ I ≠ (⊥ : fractional_ideal A⁰ (fraction_ring A)), I * I⁻¹ = 1 open fractional_ideal variables {R A K} lemma is_dedekind_domain_inv_iff [algebra A K] [is_fraction_ring A K] : is_dedekind_domain_inv A ↔ (∀ I ≠ (⊥ : fractional_ideal A⁰ K), I * I⁻¹ = 1) := begin set h : fraction_ring A ≃ₐ[A] K := fraction_ring.alg_equiv A K, split; rintros hi I hI, { have := hi (fractional_ideal.map h.symm.to_alg_hom I) (fractional_ideal.map_ne_zero h.symm.to_alg_hom hI), convert congr_arg (fractional_ideal.map h.to_alg_hom) this; simp only [alg_equiv.to_alg_hom_eq_coe, map_symm_map, map_one, fractional_ideal.map_mul, fractional_ideal.map_div, inv_eq] }, { have := hi (fractional_ideal.map h.to_alg_hom I) (fractional_ideal.map_ne_zero h.to_alg_hom hI), convert congr_arg (fractional_ideal.map h.symm.to_alg_hom) this; simp only [alg_equiv.to_alg_hom_eq_coe, map_map_symm, map_one, fractional_ideal.map_mul, fractional_ideal.map_div, inv_eq] }, end lemma fractional_ideal.adjoin_integral_eq_one_of_is_unit [algebra A K] [is_fraction_ring A K] (x : K) (hx : is_integral A x) (hI : is_unit (adjoin_integral A⁰ x hx)) : adjoin_integral A⁰ x hx = 1 := begin set I := adjoin_integral A⁰ x hx, have mul_self : I * I = I, { apply fractional_ideal.coe_to_submodule_injective, simp }, convert congr_arg (* I⁻¹) mul_self; simp only [(mul_inv_cancel_iff_is_unit K).mpr hI, mul_assoc, mul_one], end namespace is_dedekind_domain_inv variables [algebra A K] [is_fraction_ring A K] (h : is_dedekind_domain_inv A) include h lemma mul_inv_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I * I⁻¹ = 1 := is_dedekind_domain_inv_iff.mp h I hI lemma inv_mul_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I⁻¹ * I = 1 := (mul_comm _ _).trans (h.mul_inv_eq_one hI) protected lemma is_unit {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : is_unit I := is_unit_of_mul_eq_one _ _ (h.mul_inv_eq_one hI) lemma is_noetherian_ring : is_noetherian_ring A := begin refine is_noetherian_ring_iff.mpr ⟨λ (I : ideal A), _⟩, by_cases hI : I = ⊥, { rw hI, apply submodule.fg_bot }, have hI : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI, exact I.fg_of_is_unit (is_fraction_ring.injective A (fraction_ring A)) (h.is_unit hI) end lemma integrally_closed : is_integrally_closed A := begin -- It suffices to show that for integral `x`, -- `A[x]` (which is a fractional ideal) is in fact equal to `A`. refine ⟨λ x hx, _⟩, rw [← set.mem_range, ← algebra.mem_bot, ← subalgebra.mem_to_submodule, algebra.to_submodule_bot, ← coe_span_singleton A⁰ (1 : fraction_ring A), fractional_ideal.span_singleton_one, ← fractional_ideal.adjoin_integral_eq_one_of_is_unit x hx (h.is_unit _)], { exact mem_adjoin_integral_self A⁰ x hx }, { exact λ h, one_ne_zero (eq_zero_iff.mp h 1 (subalgebra.one_mem _)) }, end lemma dimension_le_one : dimension_le_one A := begin -- We're going to show that `P` is maximal because any (maximal) ideal `M` -- that is strictly larger would be `⊤`. rintros P P_ne hP, refine ideal.is_maximal_def.mpr ⟨hP.ne_top, λ M hM, _⟩, -- We may assume `P` and `M` (as fractional ideals) are nonzero. have P'_ne : (P : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr P_ne, have M'_ne : (M : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr (lt_of_le_of_lt bot_le hM).ne', -- In particular, we'll show `M⁻¹ * P ≤ P` suffices : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ P, { rw [eq_top_iff, ← coe_ideal_le_coe_ideal (fraction_ring A), fractional_ideal.coe_ideal_top], calc (1 : fractional_ideal A⁰ (fraction_ring A)) = _ * _ * _ : _ ... ≤ _ * _ : mul_right_mono (P⁻¹ * M : fractional_ideal A⁰ (fraction_ring A)) this ... = M : _, { rw [mul_assoc, ← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul, h.inv_mul_eq_one M'_ne] }, { rw [← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul] }, { apply_instance } }, -- Suppose we have `x ∈ M⁻¹ * P`, then in fact `x = algebra_map _ _ y` for some `y`. intros x hx, have le_one : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ 1, { rw [← h.inv_mul_eq_one M'_ne], exact fractional_ideal.mul_left_mono _ ((coe_ideal_le_coe_ideal (fraction_ring A)).mpr hM.le) }, obtain ⟨y, hy, rfl⟩ := (mem_coe_ideal _).mp (le_one hx), -- Since `M` is strictly greater than `P`, let `z ∈ M \ P`. obtain ⟨z, hzM, hzp⟩ := set_like.exists_of_lt hM, -- We have `z * y ∈ M * (M⁻¹ * P) = P`. have zy_mem := fractional_ideal.mul_mem_mul (mem_coe_ideal_of_mem A⁰ hzM) hx, rw [← ring_hom.map_mul, ← mul_assoc, h.mul_inv_eq_one M'_ne, one_mul] at zy_mem, obtain ⟨zy, hzy, zy_eq⟩ := (mem_coe_ideal A⁰).mp zy_mem, rw is_fraction_ring.injective A (fraction_ring A) zy_eq at hzy, -- But `P` is a prime ideal, so `z ∉ P` implies `y ∈ P`, as desired. exact mem_coe_ideal_of_mem A⁰ (or.resolve_left (hP.mem_or_mem hzy) hzp) end /-- Showing one side of the equivalence between the definitions `is_dedekind_domain_inv` and `is_dedekind_domain` of Dedekind domains. -/ theorem is_dedekind_domain : is_dedekind_domain A := ⟨h.is_noetherian_ring, h.dimension_le_one, h.integrally_closed⟩ end is_dedekind_domain_inv variables [algebra A K] [is_fraction_ring A K] /-- Specialization of `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` to Dedekind domains: Let `I : ideal A` be a nonzero ideal, where `A` is a Dedekind domain that is not a field. Then `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` states we can find a product of prime ideals that is contained within `I`. This lemma extends that result by making the product minimal: let `M` be a maximal ideal that contains `I`, then the product including `M` is contained within `I` and the product excluding `M` is not contained within `I`. -/ lemma exists_multiset_prod_cons_le_and_prod_not_le [is_dedekind_domain A] (hNF : ¬ is_field A) {I M : ideal A} (hI0 : I ≠ ⊥) (hIM : I ≤ M) [hM : M.is_maximal] : ∃ (Z : multiset (prime_spectrum A)), (M ::ₘ (Z.map prime_spectrum.as_ideal)).prod ≤ I ∧ ¬ (multiset.prod (Z.map prime_spectrum.as_ideal) ≤ I) := begin -- Let `Z` be a minimal set of prime ideals such that their product is contained in `J`. obtain ⟨Z₀, hZ₀⟩ := exists_prime_spectrum_prod_le_and_ne_bot_of_domain hNF hI0, obtain ⟨Z, ⟨hZI, hprodZ⟩, h_eraseZ⟩ := multiset.well_founded_lt.has_min (λ Z, (Z.map prime_spectrum.as_ideal).prod ≤ I ∧ (Z.map prime_spectrum.as_ideal).prod ≠ ⊥) ⟨Z₀, hZ₀⟩, have hZM : multiset.prod (Z.map prime_spectrum.as_ideal) ≤ M := le_trans hZI hIM, have hZ0 : Z ≠ 0, { rintro rfl, simpa [hM.ne_top] using hZM }, obtain ⟨_, hPZ', hPM⟩ := (hM.is_prime.multiset_prod_le (mt multiset.map_eq_zero.mp hZ0)).mp hZM, -- Then in fact there is a `P ∈ Z` with `P ≤ M`. obtain ⟨P, hPZ, rfl⟩ := multiset.mem_map.mp hPZ', letI := classical.dec_eq (ideal A), have := multiset.map_erase prime_spectrum.as_ideal subtype.coe_injective P Z, obtain ⟨hP0, hZP0⟩ : P.as_ideal ≠ ⊥ ∧ ((Z.erase P).map prime_spectrum.as_ideal).prod ≠ ⊥, { rwa [ne.def, ← multiset.cons_erase hPZ', multiset.prod_cons, ideal.mul_eq_bot, not_or_distrib, ← this] at hprodZ }, -- By maximality of `P` and `M`, we have that `P ≤ M` implies `P = M`. have hPM' := (is_dedekind_domain.dimension_le_one _ hP0 P.is_prime).eq_of_le hM.ne_top hPM, tactic.unfreeze_local_instances, subst hPM', -- By minimality of `Z`, erasing `P` from `Z` is exactly what we need. refine ⟨Z.erase P, _, _⟩, { convert hZI, rw [this, multiset.cons_erase hPZ'] }, { refine λ h, h_eraseZ (Z.erase P) ⟨h, _⟩ (multiset.erase_lt.mpr hPZ), exact hZP0 } end namespace fractional_ideal lemma exists_not_mem_one_of_ne_bot [is_dedekind_domain A] (hNF : ¬ is_field A) {I : ideal A} (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) : ∃ x : K, x ∈ (I⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K) := begin -- WLOG, let `I` be maximal. suffices : ∀ {M : ideal A} (hM : M.is_maximal), ∃ x : K, x ∈ (M⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K), { obtain ⟨M, hM, hIM⟩ : ∃ (M : ideal A), is_maximal M ∧ I ≤ M := ideal.exists_le_maximal I hI1, resetI, have hM0 := (M.bot_lt_of_maximal hNF).ne', obtain ⟨x, hxM, hx1⟩ := this hM, refine ⟨x, inv_anti_mono _ _ ((coe_ideal_le_coe_ideal _).mpr hIM) hxM, hx1⟩; apply fractional_ideal.coe_ideal_ne_zero; assumption }, -- Let `a` be a nonzero element of `M` and `J` the ideal generated by `a`. intros M hM, resetI, obtain ⟨⟨a, haM⟩, ha0⟩ := submodule.nonzero_mem_of_bot_lt (M.bot_lt_of_maximal hNF), replace ha0 : a ≠ 0 := subtype.coe_injective.ne ha0, let J : ideal A := ideal.span {a}, have hJ0 : J ≠ ⊥ := mt ideal.span_singleton_eq_bot.mp ha0, have hJM : J ≤ M := ideal.span_le.mpr (set.singleton_subset_iff.mpr haM), have hM0 : ⊥ < M := M.bot_lt_of_maximal hNF, -- Then we can find a product of prime (hence maximal) ideals contained in `J`, -- such that removing element `M` from the product is not contained in `J`. obtain ⟨Z, hle, hnle⟩ := exists_multiset_prod_cons_le_and_prod_not_le hNF hJ0 hJM, -- Choose an element `b` of the product that is not in `J`. obtain ⟨b, hbZ, hbJ⟩ := set_like.not_le_iff_exists.mp hnle, have hnz_fa : algebra_map A K a ≠ 0 := mt ((ring_hom.injective_iff _).mp (is_fraction_ring.injective A K) a) ha0, have hb0 : algebra_map A K b ≠ 0 := mt ((ring_hom.injective_iff _).mp (is_fraction_ring.injective A K) b) (λ h, hbJ $ h.symm ▸ J.zero_mem), -- Then `b a⁻¹ : K` is in `M⁻¹` but not in `1`. refine ⟨algebra_map A K b * (algebra_map A K a)⁻¹, (mem_inv_iff _).mpr _, _⟩, { exact (fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl _)).mpr hM0.ne' }, { rintro y₀ hy₀, obtain ⟨y, h_Iy, rfl⟩ := (fractional_ideal.mem_coe_ideal _).mp hy₀, rw [mul_comm, ← mul_assoc, ← ring_hom.map_mul], have h_yb : y * b ∈ J, { apply hle, rw multiset.prod_cons, exact submodule.smul_mem_smul h_Iy hbZ }, rw ideal.mem_span_singleton' at h_yb, rcases h_yb with ⟨c, hc⟩, rw [← hc, ring_hom.map_mul, mul_assoc, mul_inv_cancel hnz_fa, mul_one], apply fractional_ideal.coe_mem_one }, { refine mt (fractional_ideal.mem_one_iff _).mp _, rintros ⟨x', h₂_abs⟩, rw [← div_eq_mul_inv, eq_div_iff_mul_eq hnz_fa, ← ring_hom.map_mul] at h₂_abs, have := ideal.mem_span_singleton'.mpr ⟨x', is_fraction_ring.injective A K h₂_abs⟩, contradiction }, end lemma one_mem_inv_coe_ideal {I : ideal A} (hI : I ≠ ⊥) : (1 : K) ∈ (I : fractional_ideal A⁰ K)⁻¹ := begin rw mem_inv_iff (fractional_ideal.coe_ideal_ne_zero hI), intros y hy, rw one_mul, exact coe_ideal_le_one hy, assumption end lemma mul_inv_cancel_of_le_one [h : is_dedekind_domain A] {I : ideal A} (hI0 : I ≠ ⊥) (hI : ((I * I⁻¹)⁻¹ : fractional_ideal A⁰ K) ≤ 1) : (I * I⁻¹ : fractional_ideal A⁰ K) = 1 := begin -- Handle a few trivial cases. by_cases hI1 : I = ⊤, { rw [hI1, coe_ideal_top, one_mul, fractional_ideal.one_inv] }, by_cases hNF : is_field A, { letI := hNF.to_field A, rcases hI1 (I.eq_bot_or_top.resolve_left hI0) }, -- We'll show a contradiction with `exists_not_mem_one_of_ne_bot`: -- `J⁻¹ = (I * I⁻¹)⁻¹` cannot have an element `x ∉ 1`, so it must equal `1`. by_contradiction h_abs, obtain ⟨J, hJ⟩ : ∃ (J : ideal A), (J : fractional_ideal A⁰ K) = I * I⁻¹ := le_one_iff_exists_coe_ideal.mp mul_one_div_le_one, by_cases hJ0 : J = ⊥, { subst hJ0, apply hI0, rw [eq_bot_iff, ← coe_ideal_le_coe_ideal K, hJ], exact coe_ideal_le_self_mul_inv K I, apply_instance }, have hJ1 : J ≠ ⊤, { rintro rfl, rw [← hJ, coe_ideal_top] at h_abs, exact h_abs rfl }, obtain ⟨x, hx, hx1⟩ : ∃ (x : K), x ∈ (J : fractional_ideal A⁰ K)⁻¹ ∧ x ∉ (1 : fractional_ideal A⁰ K) := exists_not_mem_one_of_ne_bot hNF hJ0 hJ1, rw hJ at hx, exact hx1 (hI hx) end /-- Nonzero integral ideals in a Dedekind domain are invertible. We will use this to show that nonzero fractional ideals are invertible, and finally conclude that fractional ideals in a Dedekind domain form a group with zero. -/ lemma coe_ideal_mul_inv [h : is_dedekind_domain A] (I : ideal A) (hI0 : I ≠ ⊥) : (I * I⁻¹ : fractional_ideal A⁰ K) = 1 := begin -- We'll show `1 ≤ J⁻¹ = (I * I⁻¹)⁻¹ ≤ 1`. apply mul_inv_cancel_of_le_one hI0, by_cases hJ0 : (I * I⁻¹ : fractional_ideal A⁰ K) = 0, { rw [hJ0, inv_zero'], exact fractional_ideal.zero_le _ }, intros x hx, -- In particular, we'll show all `x ∈ J⁻¹` are integral. suffices : x ∈ integral_closure A K, { rwa [is_integrally_closed.integral_closure_eq_bot, algebra.mem_bot, set.mem_range, ← fractional_ideal.mem_one_iff] at this; assumption }, -- For that, we'll find a subalgebra that is f.g. as a module and contains `x`. -- `A` is a noetherian ring, so we just need to find a subalgebra between `{x}` and `I⁻¹`. rw mem_integral_closure_iff_mem_fg, have x_mul_mem : ∀ b ∈ (I⁻¹ : fractional_ideal A⁰ K), x * b ∈ (I⁻¹ : fractional_ideal A⁰ K), { intros b hb, rw mem_inv_iff at ⊢ hx, swap, { exact fractional_ideal.coe_ideal_ne_zero hI0 }, swap, { exact hJ0 }, simp only [mul_assoc, mul_comm b] at ⊢ hx, intros y hy, exact hx _ (fractional_ideal.mul_mem_mul hy hb) }, -- It turns out the subalgebra consisting of all `p(x)` for `p : polynomial A` works. refine ⟨alg_hom.range (polynomial.aeval x : polynomial A →ₐ[A] K), is_noetherian_submodule.mp (fractional_ideal.is_noetherian I⁻¹) _ (λ y hy, _), ⟨polynomial.X, polynomial.aeval_X x⟩⟩, obtain ⟨p, rfl⟩ := (alg_hom.mem_range _).mp hy, rw polynomial.aeval_eq_sum_range, refine submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ _), clear hi, induction i with i ih, { rw pow_zero, exact one_mem_inv_coe_ideal hI0 }, { show x ^ i.succ ∈ (I⁻¹ : fractional_ideal A⁰ K), rw pow_succ, exact x_mul_mem _ ih }, end /-- Nonzero fractional ideals in a Dedekind domain are units. This is also available as `_root_.mul_inv_cancel`, using the `comm_group_with_zero` instance defined below. -/ protected theorem mul_inv_cancel [is_dedekind_domain A] {I : fractional_ideal A⁰ K} (hne : I ≠ 0) : I * I⁻¹ = 1 := begin obtain ⟨a, J, ha, hJ⟩ : ∃ (a : A) (aI : ideal A), a ≠ 0 ∧ I = span_singleton A⁰ (algebra_map _ _ a)⁻¹ * aI := exists_eq_span_singleton_mul I, suffices h₂ : I * (span_singleton A⁰ (algebra_map _ _ a) * J⁻¹) = 1, { rw mul_inv_cancel_iff, exact ⟨span_singleton A⁰ (algebra_map _ _ a) * J⁻¹, h₂⟩ }, subst hJ, rw [mul_assoc, mul_left_comm (J : fractional_ideal A⁰ K), coe_ideal_mul_inv, mul_one, fractional_ideal.span_singleton_mul_span_singleton, inv_mul_cancel, fractional_ideal.span_singleton_one], { exact mt ((algebra_map A K).injective_iff.mp (is_fraction_ring.injective A K) _) ha }, { exact fractional_ideal.coe_ideal_ne_zero_iff.mp (right_ne_zero_of_mul hne) } end end fractional_ideal /-- `is_dedekind_domain` and `is_dedekind_domain_inv` are equivalent ways to express that an integral domain is a Dedekind domain. -/ theorem is_dedekind_domain_iff_is_dedekind_domain_inv : is_dedekind_domain A ↔ is_dedekind_domain_inv A := ⟨λ h I hI, by exactI fractional_ideal.mul_inv_cancel hI, λ h, h.is_dedekind_domain⟩ end inverse section is_dedekind_domain variables {R A} [is_dedekind_domain A] [algebra A K] [is_fraction_ring A K] open fractional_ideal noncomputable instance fractional_ideal.comm_group_with_zero : comm_group_with_zero (fractional_ideal A⁰ K) := { inv := λ I, I⁻¹, inv_zero := inv_zero' _, exists_pair_ne := ⟨0, 1, (coe_to_fractional_ideal_injective (le_refl _)).ne (by simpa using @zero_ne_one (ideal A) _ _)⟩, mul_inv_cancel := λ I, fractional_ideal.mul_inv_cancel, .. fractional_ideal.comm_semiring } noncomputable instance ideal.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero (ideal A) := function.injective.comm_cancel_monoid_with_zero (coe_ideal_hom A⁰ (fraction_ring A)) coe_ideal_injective (ring_hom.map_zero _) (ring_hom.map_one _) (ring_hom.map_mul _) /-- For ideals in a Dedekind domain, to divide is to contain. -/ lemma ideal.dvd_iff_le {I J : ideal A} : (I ∣ J) ↔ J ≤ I := ⟨ideal.le_of_dvd, λ h, begin by_cases hI : I = ⊥, { have hJ : J = ⊥, { rwa [hI, ← eq_bot_iff] at h }, rw [hI, hJ] }, have hI' : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI, have : (I : fractional_ideal A⁰ (fraction_ring A))⁻¹ * J ≤ 1 := le_trans (fractional_ideal.mul_left_mono (↑I)⁻¹ ((coe_ideal_le_coe_ideal _).mpr h)) (le_of_eq (inv_mul_cancel hI')), obtain ⟨H, hH⟩ := fractional_ideal.le_one_iff_exists_coe_ideal.mp this, use H, refine coe_to_fractional_ideal_injective (le_refl (non_zero_divisors A)) (show (J : fractional_ideal A⁰ (fraction_ring A)) = _, from _), rw [fractional_ideal.coe_ideal_mul, hH, ← mul_assoc, mul_inv_cancel hI', one_mul] end⟩ lemma ideal.dvd_not_unit_iff_lt {I J : ideal A} : dvd_not_unit I J ↔ J < I := ⟨λ ⟨hI, H, hunit, hmul⟩, lt_of_le_of_ne (ideal.dvd_iff_le.mp ⟨H, hmul⟩) (mt (λ h, have H = 1, from mul_left_cancel' hI (by rw [← hmul, h, mul_one]), show is_unit H, from this.symm ▸ is_unit_one) hunit), λ h, dvd_not_unit_of_dvd_of_not_dvd (ideal.dvd_iff_le.mpr (le_of_lt h)) (mt ideal.dvd_iff_le.mp (not_le_of_lt h))⟩ instance : wf_dvd_monoid (ideal A) := { well_founded_dvd_not_unit := have well_founded ((>) : ideal A → ideal A → Prop) := is_noetherian_iff_well_founded.mp (is_noetherian_ring_iff.mp is_dedekind_domain.is_noetherian_ring), by { convert this, ext, rw ideal.dvd_not_unit_iff_lt } } instance ideal.unique_factorization_monoid : unique_factorization_monoid (ideal A) := { irreducible_iff_prime := λ P, ⟨λ hirr, ⟨hirr.ne_zero, hirr.not_unit, λ I J, begin have : P.is_maximal, { use mt ideal.is_unit_iff.mpr hirr.not_unit, intros J hJ, obtain ⟨J_ne, H, hunit, P_eq⟩ := ideal.dvd_not_unit_iff_lt.mpr hJ, exact ideal.is_unit_iff.mp ((hirr.is_unit_or_is_unit P_eq).resolve_right hunit) }, simp only [ideal.dvd_iff_le, has_le.le, preorder.le, partial_order.le], contrapose!, rintros ⟨⟨x, x_mem, x_not_mem⟩, ⟨y, y_mem, y_not_mem⟩⟩, exact ⟨x * y, ideal.mul_mem_mul x_mem y_mem, mt this.is_prime.mem_or_mem (not_or x_not_mem y_not_mem)⟩, end⟩, prime.irreducible⟩, .. ideal.wf_dvd_monoid } noncomputable instance ideal.normalization_monoid : normalization_monoid (ideal A) := normalization_monoid_of_unique_units @[simp] lemma ideal.dvd_span_singleton {I : ideal A} {x : A} : I ∣ ideal.span {x} ↔ x ∈ I := ideal.dvd_iff_le.trans (ideal.span_le.trans set.singleton_subset_iff) lemma ideal.is_prime_of_prime {P : ideal A} (h : prime P) : is_prime P := begin refine ⟨_, λ x y hxy, _⟩, { unfreezingI { rintro rfl }, rw ← ideal.one_eq_top at h, exact h.not_unit is_unit_one }, { simp only [← ideal.dvd_span_singleton, ← ideal.span_singleton_mul_span_singleton] at ⊢ hxy, exact h.dvd_or_dvd hxy } end theorem ideal.prime_of_is_prime {P : ideal A} (hP : P ≠ ⊥) (h : is_prime P) : prime P := begin refine ⟨hP, mt ideal.is_unit_iff.mp h.ne_top, λ I J hIJ, _⟩, simpa only [ideal.dvd_iff_le] using (h.mul_le.mp (ideal.le_of_dvd hIJ)), end /-- In a Dedekind domain, the (nonzero) prime elements of the monoid with zero `ideal A` are exactly the prime ideals. -/ theorem ideal.prime_iff_is_prime {P : ideal A} (hP : P ≠ ⊥) : prime P ↔ is_prime P := ⟨ideal.is_prime_of_prime, ideal.prime_of_is_prime hP⟩ end is_dedekind_domain section is_integral_closure /-! ### `is_integral_closure` section We show that an integral closure of a Dedekind domain in a finite separable field extension is again a Dedekind domain. This implies the ring of integers of a number field is a Dedekind domain. -/ open algebra open_locale big_operators variables {A K} [algebra A K] [is_fraction_ring A K] variables {L : Type*} [field L] (C : Type*) [integral_domain C] variables [algebra K L] [finite_dimensional K L] [algebra A L] [is_scalar_tower A K L] variables [algebra C L] [is_integral_closure C A L] [algebra A C] [is_scalar_tower A C L] lemma is_integral_closure.range_le_span_dual_basis [is_separable K L] {ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L) (hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] : ((algebra.linear_map C L).restrict_scalars A).range ≤ submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) := begin let db := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b, rintros _ ⟨x, rfl⟩, simp only [linear_map.coe_restrict_scalars_eq_coe, algebra.linear_map_apply], have hx : is_integral A (algebra_map C L x) := (is_integral_closure.is_integral A L x).algebra_map, suffices : ∃ (c : ι → A), algebra_map C L x = ∑ i, c i • db i, { obtain ⟨c, x_eq⟩ := this, rw x_eq, refine submodule.sum_mem _ (λ i _, submodule.smul_mem _ _ (submodule.subset_span _)), rw set.mem_range, exact ⟨i, rfl⟩ }, suffices : ∃ (c : ι → K), ((∀ i, is_integral A (c i)) ∧ algebra_map C L x = ∑ i, c i • db i), { obtain ⟨c, hc, hx⟩ := this, have hc' : ∀ i, is_localization.is_integer A (c i) := λ i, is_integrally_closed.is_integral_iff.mp (hc i), use λ i, classical.some (hc' i), refine hx.trans (finset.sum_congr rfl (λ i _, _)), conv_lhs { rw [← classical.some_spec (hc' i)] }, rw [← is_scalar_tower.algebra_map_smul K (classical.some (hc' i)) (db i)] }, refine ⟨λ i, db.repr (algebra_map C L x) i, (λ i, _), (db.sum_repr _).symm⟩, rw bilin_form.dual_basis_repr_apply, exact is_integral_trace (is_integral_mul hx (hb_int i)) end lemma integral_closure_le_span_dual_basis [is_separable K L] {ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L) (hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] : (integral_closure A L).to_submodule ≤ submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) := begin refine le_trans _ (is_integral_closure.range_le_span_dual_basis (integral_closure A L) b hb_int), intros x hx, exact ⟨⟨x, hx⟩, rfl⟩ end variables (A) (K) include K /-- Send a set of `x`'es in a finite extension `L` of the fraction field of `R` to `(y : R) • x ∈ integral_closure R L`. -/ lemma exists_integral_multiples (s : finset L) : ∃ (y ≠ (0 : A)), ∀ x ∈ s, is_integral A (y • x) := begin haveI := classical.dec_eq L, refine s.induction _ _, { use [1, one_ne_zero], rintros x ⟨⟩ }, { rintros x s hx ⟨y, hy, hs⟩, obtain ⟨x', y', hy', hx'⟩ := exists_integral_multiple ((is_fraction_ring.is_algebraic_iff A K).mpr (algebra.is_algebraic_of_finite x)) ((algebra_map A L).injective_iff.mp _), refine ⟨y * y', mul_ne_zero hy hy', λ x'' hx'', _⟩, rcases finset.mem_insert.mp hx'' with (rfl | hx''), { rw [mul_smul, algebra.smul_def, algebra.smul_def, mul_comm _ x'', hx'], exact is_integral_mul is_integral_algebra_map x'.2 }, { rw [mul_comm, mul_smul, algebra.smul_def], exact is_integral_mul is_integral_algebra_map (hs _ hx'') }, { rw is_scalar_tower.algebra_map_eq A K L, apply (algebra_map K L).injective.comp, exact is_fraction_ring.injective _ _ } } end variables (L) /-- If `L` is a finite extension of `K = Frac(A)`, then `L` has a basis over `A` consisting of integral elements. -/ lemma finite_dimensional.exists_is_basis_integral : ∃ (s : finset L) (b : basis s K L), (∀ x, is_integral A (b x)) := begin letI := classical.dec_eq L, let s' := is_noetherian.finset_basis_index K L, let bs' := is_noetherian.finset_basis K L, obtain ⟨y, hy, his'⟩ := exists_integral_multiples A K (finset.univ.image bs'), have hy' : algebra_map A L y ≠ 0, { refine mt ((algebra_map A L).injective_iff.mp _ _) hy, rw is_scalar_tower.algebra_map_eq A K L, exact (algebra_map K L).injective.comp (is_fraction_ring.injective A K) }, refine ⟨s', bs'.map { to_fun := λ x, algebra_map A L y * x, inv_fun := λ x, (algebra_map A L y)⁻¹ * x, left_inv := _, right_inv := _, .. algebra.lmul _ _ (algebra_map A L y) }, _⟩, { intros x, simp only [inv_mul_cancel_left' hy'] }, { intros x, simp only [mul_inv_cancel_left' hy'] }, { rintros ⟨x', hx'⟩, simp only [algebra.smul_def, finset.mem_image, exists_prop, finset.mem_univ, true_and] at his', simp only [basis.map_apply, linear_equiv.coe_mk], exact his' _ ⟨_, rfl⟩ } end variables (A K L) [is_separable K L] include L /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure `C` of `A` in `L` is Noetherian. -/ lemma is_integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian_ring C := begin haveI := classical.dec_eq L, obtain ⟨s, b, hb_int⟩ := finite_dimensional.exists_is_basis_integral A K L, rw is_noetherian_ring_iff, let b' := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b, letI := is_noetherian_span_of_finite A (set.finite_range b'), let f : C →ₗ[A] submodule.span A (set.range b') := (submodule.of_le (is_integral_closure.range_le_span_dual_basis C b hb_int)).comp ((algebra.linear_map C L).restrict_scalars A).range_restrict, refine is_noetherian_of_tower A (is_noetherian_of_injective f _), rw [linear_map.ker_comp, submodule.ker_of_le, submodule.comap_bot, linear_map.ker_cod_restrict], exact linear_map.ker_eq_bot_of_injective (is_integral_closure.algebra_map_injective C A L) end variables {A K} /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure of `A` in `L` is Noetherian. -/ lemma integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian_ring (integral_closure A L) := is_integral_closure.is_noetherian_ring A K L (integral_closure A L) variables (A K) /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain, the integral closure `C` of `A` in `L` is a Dedekind domain. Can't be an instance since `A`, `K` or `L` can't be inferred. See also the instance `integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A` and `C := integral_closure A L`. -/ lemma is_integral_closure.is_dedekind_domain [h : is_dedekind_domain A] : is_dedekind_domain C := begin haveI : is_fraction_ring C L := is_integral_closure.is_fraction_ring_of_finite_extension A K L C, exact ⟨is_integral_closure.is_noetherian_ring A K L C, h.dimension_le_one.is_integral_closure _ L _, (is_integrally_closed_iff L).mpr (λ x hx, ⟨is_integral_closure.mk' C x (is_integral_trans (is_integral_closure.is_integral_algebra A L) _ hx), is_integral_closure.algebra_map_mk' _ _ _⟩)⟩ end /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain, the integral closure of `A` in `L` is a Dedekind domain. Can't be an instance since `K` can't be inferred. See also the instance `integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A`. -/ lemma integral_closure.is_dedekind_domain [h : is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) := is_integral_closure.is_dedekind_domain A K L (integral_closure A L) omit K variables [algebra (fraction_ring A) L] [is_scalar_tower A (fraction_ring A) L] variables [finite_dimensional (fraction_ring A) L] [is_separable (fraction_ring A) L] /- If `L` is a finite separable extension of `Frac(A)`, where `A` is a Dedekind domain, the integral closure of `A` in `L` is a Dedekind domain. See also the lemma `integral_closure.is_dedekind_domain` where you can choose the field of fractions yourself. -/ instance integral_closure.is_dedekind_domain_fraction_ring [is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) := integral_closure.is_dedekind_domain A (fraction_ring A) L end is_integral_closure
e1dbdda5a362db9b110ee30d7c96c7e6d87f1197
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/set_theory/lists_auto.lean
901ef53b81e72fc3cbcefb304761bfac07a78457
[]
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
8,332
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro A computable model of hereditarily finite sets with atoms (ZFA without infinity). This is useful for calculations in naive set theory. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.basic import Mathlib.data.sigma.default import Mathlib.PostPort universes u l u_1 u_2 u_3 namespace Mathlib inductive lists' (α : Type u) : Bool → Type u where | atom : α → lists' α false | nil : lists' α tt | cons' : {b : Bool} → lists' α b → lists' α tt → lists' α tt def lists (α : Type u_1) := sigma fun (b : Bool) => lists' α b namespace lists' protected instance inhabited {α : Type u_1} [Inhabited α] (b : Bool) : Inhabited (lists' α b) := sorry def cons {α : Type u_1} : lists α → lists' α tt → lists' α tt := sorry @[simp] def to_list {α : Type u_1} {b : Bool} : lists' α b → List (lists α) := sorry @[simp] theorem to_list_cons {α : Type u_1} (a : lists α) (l : lists' α tt) : to_list (cons a l) = a :: to_list l := sorry @[simp] def of_list {α : Type u_1} : List (lists α) → lists' α tt := sorry @[simp] theorem to_of_list {α : Type u_1} (l : List (lists α)) : to_list (of_list l) = l := sorry @[simp] theorem of_to_list {α : Type u_1} (l : lists' α tt) : of_list (to_list l) = l := sorry end lists' def lists'.subset {α : Type u_1} : lists' α tt → lists' α tt → Prop := fun (ᾰ ᾰ_1 : lists' α tt) => lists.equiv._mut_ ((fun (idx : psigma fun (ᾰ : lists' α tt) => psigma fun (ᾰ : lists' α tt) => Unit) => psum.inr idx) ((fun (ᾰ ᾰ_2 : lists' α tt) => psigma.mk ᾰ (psigma.mk ᾰ_2 Unit.unit)) ᾰ ᾰ_1)) namespace lists' protected instance has_subset {α : Type u_1} : has_subset (lists' α tt) := has_subset.mk subset protected instance has_mem {α : Type u_1} {b : Bool} : has_mem (lists α) (lists' α b) := has_mem.mk fun (a : lists α) (l : lists' α b) => ∃ (a' : lists α), ∃ (H : a' ∈ to_list l), lists.equiv a a' theorem mem_def {α : Type u_1} {b : Bool} {a : lists α} {l : lists' α b} : a ∈ l ↔ ∃ (a' : lists α), ∃ (H : a' ∈ to_list l), lists.equiv a a' := iff.rfl @[simp] theorem mem_cons {α : Type u_1} {a : lists α} {y : lists α} {l : lists' α tt} : a ∈ cons y l ↔ lists.equiv a y ∨ a ∈ l := sorry theorem cons_subset {α : Type u_1} {a : lists α} {l₁ : lists' α tt} {l₂ : lists' α tt} : cons a l₁ ⊆ l₂ ↔ a ∈ l₂ ∧ l₁ ⊆ l₂ := sorry theorem of_list_subset {α : Type u_1} {l₁ : List (lists α)} {l₂ : List (lists α)} (h : l₁ ⊆ l₂) : of_list l₁ ⊆ of_list l₂ := sorry theorem subset.refl {α : Type u_1} {l : lists' α tt} : l ⊆ l := eq.mpr (id (Eq._oldrec (Eq.refl (l ⊆ l)) (Eq.symm (of_to_list l)))) (of_list_subset (list.subset.refl (to_list l))) theorem subset_nil {α : Type u_1} {l : lists' α tt} : l ⊆ nil → l = nil := sorry theorem mem_of_subset' {α : Type u_1} {a : lists α} {l₁ : lists' α tt} {l₂ : lists' α tt} (s : l₁ ⊆ l₂) (h : a ∈ to_list l₁) : a ∈ l₂ := sorry theorem subset_def {α : Type u_1} {l₁ : lists' α tt} {l₂ : lists' α tt} : l₁ ⊆ l₂ ↔ ∀ (a : lists α), a ∈ to_list l₁ → a ∈ l₂ := sorry end lists' namespace lists def atom {α : Type u_1} (a : α) : lists α := sigma.mk false (lists'.atom a) def of' {α : Type u_1} (l : lists' α tt) : lists α := sigma.mk tt l @[simp] def to_list {α : Type u_1} : lists α → List (lists α) := sorry def is_list {α : Type u_1} (l : lists α) := ↥(sigma.fst l) def of_list {α : Type u_1} (l : List (lists α)) : lists α := of' (lists'.of_list l) theorem is_list_to_list {α : Type u_1} (l : List (lists α)) : is_list (of_list l) := Eq.refl (sigma.fst (of_list l)) theorem to_of_list {α : Type u_1} (l : List (lists α)) : to_list (of_list l) = l := sorry theorem of_to_list {α : Type u_1} {l : lists α} : is_list l → of_list (to_list l) = l := sorry protected instance inhabited {α : Type u_1} : Inhabited (lists α) := { default := of' lists'.nil } protected instance decidable_eq {α : Type u_1} [DecidableEq α] : DecidableEq (lists α) := eq.mpr sorry fun (a b : sigma fun (b : Bool) => lists' α b) => sigma.decidable_eq a b protected instance has_sizeof {α : Type u_1} [SizeOf α] : SizeOf (lists α) := eq.mpr sorry (sigma.has_sizeof Bool fun (b : Bool) => lists' α b) def induction_mut {α : Type u_1} (C : lists α → Sort u_2) (D : lists' α tt → Sort u_3) (C0 : (a : α) → C (atom a)) (C1 : (l : lists' α tt) → D l → C (of' l)) (D0 : D lists'.nil) (D1 : (a : lists α) → (l : lists' α tt) → C a → D l → D (lists'.cons a l)) : PProd ((l : lists α) → C l) ((l : lists' α tt) → D l) := { fst := fun (_x : lists α) => sorry, snd := fun (l : lists' α tt) => pprod.snd ((fun (b : Bool) (l : lists' α b) => lists'.rec (fun (a : α) => { fst := C0 a, snd := PUnit.unit }) { fst := C1 lists'.nil D0, snd := D0 } (fun {b : Bool} (a : lists' α b) (l : lists' α tt) (IH₁ : PProd (C (sigma.mk b a)) sorry) (IH₂ : PProd (C (sigma.mk tt l)) sorry) => { fst := C1 (lists'.cons' a l) (D1 (sigma.mk b a) l (pprod.fst IH₁) (pprod.snd IH₂)), snd := D1 (sigma.mk b a) l (pprod.fst IH₁) (pprod.snd IH₂) }) l) tt l) } def mem {α : Type u_1} (a : lists α) : lists α → Prop := sorry protected instance has_mem {α : Type u_1} : has_mem (lists α) (lists α) := has_mem.mk mem theorem is_list_of_mem {α : Type u_1} {a : lists α} {l : lists α} : a ∈ l → is_list l := sorry theorem equiv.antisymm_iff {α : Type u_1} {l₁ : lists' α tt} {l₂ : lists' α tt} : equiv (of' l₁) (of' l₂) ↔ l₁ ⊆ l₂ ∧ l₂ ⊆ l₁ := sorry theorem equiv_atom {α : Type u_1} {a : α} {l : lists α} : equiv (atom a) l ↔ atom a = l := sorry theorem equiv.symm {α : Type u_1} {l₁ : lists α} {l₂ : lists α} (h : equiv l₁ l₂) : equiv l₂ l₁ := sorry theorem equiv.trans {α : Type u_1} {l₁ : lists α} {l₂ : lists α} {l₃ : lists α} : equiv l₁ l₂ → equiv l₂ l₃ → equiv l₁ l₃ := sorry protected instance setoid {α : Type u_1} : setoid (lists α) := setoid.mk equiv sorry @[simp] def equiv.decidable_meas {α : Type u_1} : psum (psigma fun (l₁ : lists α) => lists α) (psum (psigma fun (l₁ : lists' α tt) => lists' α tt) (psigma fun (a : lists α) => lists' α tt)) → ℕ := sorry theorem sizeof_pos {α : Type u_1} {b : Bool} (l : lists' α b) : 0 < sizeof l := sorry theorem lt_sizeof_cons' {α : Type u_1} {b : Bool} (a : lists' α b) (l : lists' α tt) : sizeof (sigma.mk b a) < sizeof (lists'.cons' a l) := sorry instance mem.decidable {α : Type u_1} [DecidableEq α] (a : lists α) (l : lists' α tt) : Decidable (a ∈ l) := sorry end lists namespace lists' theorem mem_equiv_left {α : Type u_1} {l : lists' α tt} {a : lists α} {a' : lists α} : lists.equiv a a' → (a ∈ l ↔ a' ∈ l) := sorry theorem mem_of_subset {α : Type u_1} {a : lists α} {l₁ : lists' α tt} {l₂ : lists' α tt} (s : l₁ ⊆ l₂) : a ∈ l₁ → a ∈ l₂ := sorry theorem subset.trans {α : Type u_1} {l₁ : lists' α tt} {l₂ : lists' α tt} {l₃ : lists' α tt} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := iff.mpr subset_def fun (a₁ : lists α) (m₁ : a₁ ∈ to_list l₁) => mem_of_subset h₂ (mem_of_subset' h₁ m₁) end lists' def finsets (α : Type u_1) := quotient lists.setoid namespace finsets protected instance has_emptyc {α : Type u_1} : has_emptyc (finsets α) := has_emptyc.mk (quotient.mk (lists.of' lists'.nil)) protected instance inhabited {α : Type u_1} : Inhabited (finsets α) := { default := ∅ } protected instance decidable_eq {α : Type u_1} [DecidableEq α] : DecidableEq (finsets α) := eq.mpr sorry fun (a b : quotient lists.setoid) => quotient.decidable_eq a b end Mathlib
936e7871f1fc3a4c1cf7175bb7bd5a4199a6286c
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/constantCompilerBug.lean
1ab5b8f4e00764cc9c90a38bd9f4f2f14e176f56
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
268
lean
import Lean new_frontend open Lean open Lean.Parser def regBlaParserAttribute : IO Unit := registerBuiltinDynamicParserAttribute (mkNameSimple "blaParser") (mkNameSimple "bla") @[inline] def parser : Parser := categoryParser (mkNameSimple "bla") 0 #check @parser
2b07ac5a99c9ae5940c2a20a117ce5dd783d6c10
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/Compiler.lean
dde2963667f18c21146d256842e496594e33e5a3
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
464
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.Compiler.InlineAttrs import Lean.Compiler.Specialize import Lean.Compiler.ConstFolding import Lean.Compiler.ClosedTermCache import Lean.Compiler.ExternAttr import Lean.Compiler.ImplementedByAttr import Lean.Compiler.NeverExtractAttr import Lean.Compiler.IR import Lean.Compiler.CSimpAttr
ea88c4f2746a3e432a52e65c8d807d91e344936a
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/apply_auto_opt.lean
d8109bc1d0eb85524ee699a3848a2af96c87b462
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
328
lean
def p (a : nat) (b := tt) : nat := a + cond b 1 2 def q (a b : nat) (h : a ≠ b . tactic.contradiction) : nat := a + b def val1 : nat := begin apply @p, exact 2, apply_opt_param end example : val1 = 3 := rfl def val2 : nat := begin fapply @q, exact 1, exact 0, apply_auto_param end example : val2 = 1 := rfl
b6bf2badff9ec72fb1039aa4260e0cc844a631b2
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/fin.lean
fd8ed505d6380e26aa16eb860e0229ede8fe7bc2
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
18,506
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Haitao Zhang, Leonardo de Moura Finite ordinal types. -/ import data.list.basic data.finset.basic data.fintype.card algebra.group data.equiv open eq.ops nat function list finset fintype structure fin (n : nat) := (val : nat) (is_lt : val < n) definition less_than [reducible] := fin namespace fin attribute fin.val [coercion] section def_equal variable {n : nat} lemma eq_of_veq : ∀ {i j : fin n}, (val i) = j → i = j | (mk iv ilt) (mk jv jlt) := assume (veq : iv = jv), begin congruence, assumption end lemma veq_of_eq : ∀ {i j : fin n}, i = j → (val i) = j | (mk iv ilt) (mk jv jlt) := assume Peq, show iv = jv, from fin.no_confusion Peq (λ Pe Pqe, Pe) lemma eq_iff_veq {i j : fin n} : (val i) = j ↔ i = j := iff.intro eq_of_veq veq_of_eq definition val_inj := @eq_of_veq n end def_equal section open decidable protected definition has_decidable_eq [instance] (n : nat) : ∀ (i j : fin n), decidable (i = j) | (mk ival ilt) (mk jval jlt) := decidable_of_decidable_of_iff (nat.has_decidable_eq ival jval) eq_iff_veq end lemma dinj_lt (n : nat) : dinj (λ i, i < n) fin.mk := take a1 a2 Pa1 Pa2 Pmkeq, fin.no_confusion Pmkeq (λ Pe Pqe, Pe) lemma val_mk (n i : nat) (Plt : i < n) : fin.val (fin.mk i Plt) = i := rfl definition upto [reducible] (n : nat) : list (fin n) := dmap (λ i, i < n) fin.mk (list.upto n) lemma nodup_upto (n : nat) : nodup (upto n) := dmap_nodup_of_dinj (dinj_lt n) (list.nodup_upto n) lemma mem_upto (n : nat) : ∀ (i : fin n), i ∈ upto n := take i, fin.destruct i (take ival Piltn, have ival ∈ list.upto n, from mem_upto_of_lt Piltn, mem_dmap Piltn this) lemma upto_zero : upto 0 = [] := by rewrite [↑upto, list.upto_nil, dmap_nil] lemma map_val_upto (n : nat) : map fin.val (upto n) = list.upto n := map_dmap_of_inv_of_pos (val_mk n) (@lt_of_mem_upto n) lemma length_upto (n : nat) : length (upto n) = n := calc length (upto n) = length (list.upto n) : (map_val_upto n ▸ length_map fin.val (upto n))⁻¹ ... = n : list.length_upto n lemma upto_ne_nil_of_ne_zero (n : nat) (Hn : n ≠ 0) : upto n ≠ [] := begin intro Hup, apply Hn, rewrite [-(@length_nil (fin n)), -Hup], apply eq.symm !length_upto end definition is_fintype [instance] (n : nat) : fintype (fin n) := fintype.mk (upto n) (nodup_upto n) (mem_upto n) section pigeonhole open fintype lemma card_fin (n : nat) : card (fin n) = n := length_upto n theorem pigeonhole {n m : nat} (Pmltn : m < n) : ¬∃ f : fin n → fin m, injective f := assume Pex, absurd Pmltn (not_lt_of_ge (calc n = card (fin n) : card_fin ... ≤ card (fin m) : card_le_of_inj (fin n) (fin m) Pex ... = m : card_fin)) end pigeonhole protected definition zero (n : nat) : fin (succ n) := mk 0 !zero_lt_succ definition fin_has_zero [instance] (n : nat) : has_zero (fin (succ n)) := has_zero.mk (fin.zero n) theorem val_zero (n : nat) : val (0 : fin (succ n)) = 0 := rfl definition mk_mod [reducible] (n i : nat) : fin (succ n) := mk (i % (succ n)) (mod_lt _ !zero_lt_succ) theorem mk_mod_zero_eq (n : nat) : mk_mod n 0 = 0 := rfl variable {n : nat} theorem val_lt : ∀ i : fin n, val i < n | (mk v h) := h lemma max_lt (i j : fin n) : max i j < n := max_lt (is_lt i) (is_lt j) definition lift : fin n → Π m : nat, fin (n + m) | (mk v h) m := mk v (lt_add_of_lt_right h m) definition lift_succ (i : fin n) : fin (nat.succ n) := have r : fin (n+1), from lift i 1, r definition maxi [reducible] : fin (succ n) := mk n !lt_succ_self theorem val_lift : ∀ (i : fin n) (m : nat), val i = val (lift i m) | (mk v h) m := rfl lemma mk_succ_ne_zero {i : nat} : ∀ {P}, mk (succ i) P ≠ (0 : fin (succ n)) := assume P Pe, absurd (veq_of_eq Pe) !succ_ne_zero lemma mk_mod_eq {i : fin (succ n)} : i = mk_mod n i := eq_of_veq begin rewrite [↑mk_mod, mod_eq_of_lt !is_lt] end lemma mk_mod_of_lt {i : nat} (Plt : i < succ n) : mk_mod n i = mk i Plt := begin esimp [mk_mod], congruence, exact mod_eq_of_lt Plt end section lift_lower lemma lift_zero : lift_succ (0 : fin (succ n)) = (0 : fin (succ (succ n))) := rfl lemma ne_max_of_lt_max {i : fin (succ n)} : i < n → i ≠ maxi := by intro hlt he; substvars; exact absurd hlt (lt.irrefl n) lemma lt_max_of_ne_max {i : fin (succ n)} : i ≠ maxi → i < n := assume hne : i ≠ maxi, have vne : val i ≠ n, from assume he, have val (@maxi n) = n, from rfl, have val i = val (@maxi n), from he ⬝ this⁻¹, absurd (eq_of_veq this) hne, have val i < nat.succ n, from val_lt i, lt_of_le_of_ne (le_of_lt_succ this) vne lemma lift_succ_ne_max {i : fin n} : lift_succ i ≠ maxi := begin cases i with v hlt, esimp [lift_succ, lift, max], intro he, injection he, substvars, exact absurd hlt (lt.irrefl v) end lemma lift_succ_inj : injective (@lift_succ n) := take i j, destruct i (destruct j (take iv ilt jv jlt Pmkeq, begin congruence, apply fin.no_confusion Pmkeq, intros, assumption end)) lemma lt_of_inj_of_max (f : fin (succ n) → fin (succ n)) : injective f → (f maxi = maxi) → ∀ i : fin (succ n), i < n → f i < n := assume Pinj Peq, take i, assume Pilt, have P1 : f i = f maxi → i = maxi, from assume Peq, Pinj i maxi Peq, have f i ≠ maxi, from begin rewrite -Peq, intro P2, apply absurd (P1 P2) (ne_max_of_lt_max Pilt) end, lt_max_of_ne_max this definition lift_fun : (fin n → fin n) → (fin (succ n) → fin (succ n)) := λ f i, dite (i = maxi) (λ Pe, maxi) (λ Pne, lift_succ (f (mk i (lt_max_of_ne_max Pne)))) definition lower_inj (f : fin (succ n) → fin (succ n)) (inj : injective f) : f maxi = maxi → fin n → fin n := assume Peq, take i, mk (f (lift_succ i)) (lt_of_inj_of_max f inj Peq (lift_succ i) (lt_max_of_ne_max lift_succ_ne_max)) lemma lift_fun_max {f : fin n → fin n} : lift_fun f maxi = maxi := begin rewrite [↑lift_fun, dif_pos rfl] end lemma lift_fun_of_ne_max {f : fin n → fin n} {i} (Pne : i ≠ maxi) : lift_fun f i = lift_succ (f (mk i (lt_max_of_ne_max Pne))) := begin rewrite [↑lift_fun, dif_neg Pne] end lemma lift_fun_eq {f : fin n → fin n} {i : fin n} : lift_fun f (lift_succ i) = lift_succ (f i) := begin rewrite [lift_fun_of_ne_max lift_succ_ne_max], congruence, congruence, rewrite [-eq_iff_veq], esimp, rewrite [↑lift_succ, -val_lift] end lemma lift_fun_of_inj {f : fin n → fin n} : injective f → injective (lift_fun f) := assume Pinj, take i j, have Pdi : decidable (i = maxi), from _, have Pdj : decidable (j = maxi), from _, begin cases Pdi with Pimax Pinmax, cases Pdj with Pjmax Pjnmax, substvars, intros, exact rfl, substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pjnmax], intro Plmax, apply absurd Plmax⁻¹ lift_succ_ne_max, cases Pdj with Pjmax Pjnmax, substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pinmax], intro Plmax, apply absurd Plmax lift_succ_ne_max, rewrite [lift_fun_of_ne_max Pinmax, lift_fun_of_ne_max Pjnmax], intro Peq, rewrite [-eq_iff_veq], exact veq_of_eq (Pinj (lift_succ_inj Peq)) end lemma lift_fun_inj : injective (@lift_fun n) := take f₁ f₂ Peq, funext (λ i, have lift_fun f₁ (lift_succ i) = lift_fun f₂ (lift_succ i), from congr_fun Peq _, begin revert this, rewrite [*lift_fun_eq], apply lift_succ_inj end) lemma lower_inj_apply {f Pinj Pmax} (i : fin n) : val (lower_inj f Pinj Pmax i) = val (f (lift_succ i)) := by rewrite [↑lower_inj] end lift_lower section madd definition madd (i j : fin (succ n)) : fin (succ n) := mk ((i + j) % (succ n)) (mod_lt _ !zero_lt_succ) definition minv : ∀ i : fin (succ n), fin (succ n) | (mk iv ilt) := mk ((succ n - iv) % succ n) (mod_lt _ !zero_lt_succ) lemma val_madd : ∀ i j : fin (succ n), val (madd i j) = (i + j) % (succ n) | (mk iv ilt) (mk jv jlt) := by esimp lemma madd_inj : ∀ {i : fin (succ n)}, injective (madd i) | (mk iv ilt) := take j₁ j₂, fin.destruct j₁ (fin.destruct j₂ (λ jv₁ jlt₁ jv₂ jlt₂, begin rewrite [↑madd, -eq_iff_veq], intro Peq, congruence, rewrite [-(mod_eq_of_lt jlt₁), -(mod_eq_of_lt jlt₂)], apply mod_eq_mod_of_add_mod_eq_add_mod_left Peq end)) lemma madd_mk_mod {i j : nat} : madd (mk_mod n i) (mk_mod n j) = mk_mod n (i+j) := eq_of_veq begin esimp [madd, mk_mod], rewrite [ mod_add_mod, add_mod_mod ] end lemma val_mod : ∀ i : fin (succ n), (val i) % (succ n) = val i | (mk iv ilt) := by esimp; rewrite [(mod_eq_of_lt ilt)] lemma madd_comm (i j : fin (succ n)) : madd i j = madd j i := by apply eq_of_veq; rewrite [*val_madd, add.comm (val i)] lemma zero_madd (i : fin (succ n)) : madd 0 i = i := have H : madd (fin.zero n) i = i, by apply eq_of_veq; rewrite [val_madd, ↑fin.zero, nat.zero_add, mod_eq_of_lt (is_lt i)], H lemma madd_zero (i : fin (succ n)) : madd i (fin.zero n) = i := !madd_comm ▸ zero_madd i lemma madd_assoc (i j k : fin (succ n)) : madd (madd i j) k = madd i (madd j k) := by apply eq_of_veq; rewrite [*val_madd, mod_add_mod, add_mod_mod, add.assoc (val i)] lemma madd_left_inv : ∀ i : fin (succ n), madd (minv i) i = fin.zero n | (mk iv ilt) := eq_of_veq (by rewrite [val_madd, ↑minv, ↑fin.zero, mod_add_mod, nat.sub_add_cancel (le_of_lt ilt), mod_self]) definition madd_is_comm_group [instance] : add_comm_group (fin (succ n)) := add_comm_group.mk madd madd_assoc (fin.zero n) zero_madd madd_zero minv madd_left_inv madd_comm end madd definition pred : fin n → fin n | (mk v h) := mk (nat.pred v) (pre_lt_of_lt h) lemma val_pred : ∀ (i : fin n), val (pred i) = nat.pred (val i) | (mk v h) := rfl lemma pred_zero : pred (fin.zero n) = fin.zero n := rfl definition mk_pred (i : nat) (h : succ i < succ n) : fin n := mk i (lt_of_succ_lt_succ h) definition succ : fin n → fin (succ n) | (mk v h) := mk (nat.succ v) (succ_lt_succ h) lemma val_succ : ∀ (i : fin n), val (succ i) = nat.succ (val i) | (mk v h) := rfl lemma succ_max : fin.succ maxi = (@maxi (nat.succ n)) := rfl lemma lift_succ.comm : lift_succ ∘ (@succ n) = succ ∘ lift_succ := funext take i, eq_of_veq (begin rewrite [↑lift_succ, -val_lift, *val_succ, -val_lift] end) definition elim0 {C : fin 0 → Type} : Π i : fin 0, C i | (mk v h) := absurd h !not_lt_zero definition zero_succ_cases {C : fin (nat.succ n) → Type} : C (fin.zero n) → (Π j : fin n, C (succ j)) → (Π k : fin (nat.succ n), C k) := begin intros CO CS k, induction k with [vk, pk], induction (nat.decidable_lt 0 vk) with [HT, HF], { show C (mk vk pk), from let vj := nat.pred vk in have vk = vj+1, from eq.symm (succ_pred_of_pos HT), have vj < n, from lt_of_succ_lt_succ (eq.subst `vk = vj+1` pk), have succ (mk vj `vj < n`) = mk vk pk, from val_inj (eq.symm `vk = vj+1`), eq.rec_on this (CS (mk vj `vj < n`)) }, { show C (mk vk pk), from have vk = 0, from eq_zero_of_le_zero (le_of_not_gt HF), have fin.zero n = mk vk pk, from val_inj (eq.symm this), eq.rec_on this CO } end definition succ_maxi_cases {C : fin (nat.succ n) → Type} : (Π j : fin n, C (lift_succ j)) → C maxi → (Π k : fin (nat.succ n), C k) := begin intros CL CM k, induction k with [vk, pk], induction (nat.decidable_lt vk n) with [HT, HF], { show C (mk vk pk), from have HL : lift_succ (mk vk HT) = mk vk pk, from val_inj rfl, eq.rec_on HL (CL (mk vk HT)) }, { show C (mk vk pk), from have HMv : vk = n, from le.antisymm (le_of_lt_succ pk) (le_of_not_gt HF), have HM : maxi = mk vk pk, from val_inj (eq.symm HMv), eq.rec_on HM CM } end definition foldr {A B : Type} (m : A → B → B) (b : B) : ∀ {n : nat}, (fin n → A) → B := nat.rec (λ f, b) (λ n IH f, m (f (fin.zero n)) (IH (λ i : fin n, f (succ i)))) definition foldl {A B : Type} (m : B → A → B) (b : B) : ∀ {n : nat}, (fin n → A) → B := nat.rec (λ f, b) (λ n IH f, m (IH (λ i : fin n, f (lift_succ i))) (f maxi)) theorem choice {C : fin n → Type} : (∀ i : fin n, nonempty (C i)) → nonempty (Π i : fin n, C i) := begin revert C, induction n with [n, IH], { intros C H, apply nonempty.intro, exact elim0 }, { intros C H, fapply nonempty.elim (H (fin.zero n)), intro CO, fapply nonempty.elim (IH (λ i, C (succ i)) (λ i, H (succ i))), intro CS, apply nonempty.intro, exact zero_succ_cases CO CS } end section open list local postfix `+1`:100 := nat.succ lemma dmap_map_lift {n : nat} : ∀ l : list nat, (∀ i, i ∈ l → i < n) → dmap (λ i, i < n +1) mk l = map lift_succ (dmap (λ i, i < n) mk l) | [] := assume Plt, rfl | (i::l) := assume Plt, begin rewrite [@dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (lt_succ_of_lt (Plt i !mem_cons)), @dmap_cons_of_pos _ _ (λ i, i < n) _ _ _ (Plt i !mem_cons), map_cons], congruence, apply dmap_map_lift, intro j Pjinl, apply Plt, apply mem_cons_of_mem, assumption end lemma upto_succ (n : nat) : upto (n +1) = maxi :: map lift_succ (upto n) := begin rewrite [↑fin.upto, list.upto_succ, @dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (nat.self_lt_succ n)], congruence, apply dmap_map_lift, apply @list.lt_of_mem_upto end definition upto_step : ∀ {n : nat}, fin.upto (n +1) = (map succ (upto n))++[0] | 0 := rfl | (i +1) := begin rewrite [upto_succ i, map_cons, append_cons, succ_max, upto_succ, -lift_zero], congruence, rewrite [map_map, -lift_succ.comm, -map_map, -(map_singleton _ 0), -map_append, -upto_step] end end open sum equiv decidable definition fin_zero_equiv_empty : fin 0 ≃ empty := ⦃ equiv, to_fun := λ f : (fin 0), elim0 f, inv_fun := λ e : empty, empty.rec _ e, left_inv := λ f : (fin 0), elim0 f, right_inv := λ e : empty, empty.rec _ e ⦄ theorem false_of_fin_zero (x : fin 0) : false := have t : empty, from equiv.fn (fin.fin_zero_equiv_empty) x, empty.induction_on (λ c, false) t definition fin_one_equiv_unit : fin 1 ≃ unit := ⦃ equiv, to_fun := λ f : (fin 1), unit.star, inv_fun := λ u : unit, fin.zero 0, left_inv := begin intro f, change mk 0 !zero_lt_succ = f, cases f with v h, congruence, have v +1 ≤ 1, from succ_le_of_lt h, have v ≤ 0, from le_of_succ_le_succ this, have v = 0, from eq_zero_of_le_zero this, subst v end, right_inv := begin intro u, cases u, reflexivity end ⦄ theorem fin_one_eq_zero (x : fin 1) : x = !fin.zero := begin induction x with [xv, xlt], unfold fin.zero, congruence, apply eq_zero_of_le_zero, apply le_of_lt_succ xlt end definition fin_sum_equiv (n m : nat) : (fin n + fin m) ≃ fin (n+m) := have aux₁ : ∀ {v}, v < m → (v + n) < (n + m), from take v, suppose v < m, calc v + n < m + n : add_lt_add_of_lt_of_le this !le.refl ... = n + m : add.comm, ⦃ equiv, to_fun := λ s : sum (fin n) (fin m), match s with | sum.inl (mk v hlt) := mk v (lt_add_of_lt_right hlt m) | sum.inr (mk v hlt) := mk (v+n) (aux₁ hlt) end, inv_fun := λ f : fin (n + m), match f with | mk v hlt := if h : v < n then sum.inl (mk v h) else sum.inr (mk (v-n) (nat.sub_lt_of_lt_add hlt (le_of_not_gt h))) end, left_inv := begin intro s, cases s with f₁ f₂, { cases f₁ with v hlt, esimp, rewrite [dif_pos hlt] }, { cases f₂ with v hlt, esimp, have ¬ v + n < n, from suppose v + n < n, have v < n - n, from nat.lt_sub_of_add_lt this !le.refl, have v < 0, by rewrite [nat.sub_self at this]; exact this, absurd this !not_lt_zero, rewrite [dif_neg this], congruence, congruence, rewrite [nat.add_sub_cancel] } end, right_inv := begin intro f, cases f with v hlt, esimp, apply @by_cases (v < n), { intro h₁, rewrite [dif_pos h₁] }, { intro h₁, rewrite [dif_neg h₁], esimp, congruence, rewrite [nat.sub_add_cancel (le_of_not_gt h₁)] } end ⦄ definition fin_prod_equiv_of_pos (n m : nat) : n > 0 → (fin n × fin m) ≃ fin (n*m) := suppose n > 0, have aux₁ : ∀ {v₁ v₂}, v₁ < n → v₂ < m → v₁ + v₂ * n < n*m, from take v₁ v₂, assume h₁ h₂, have nat.succ v₂ ≤ m, from succ_le_of_lt h₂, have nat.succ v₂ * n ≤ m * n, from mul_le_mul_right _ this, have v₂ * n + n ≤ n * m, by rewrite [-add_one at this, right_distrib at this, one_mul at this, mul.comm m n at this]; exact this, have v₁ + (v₂ * n + n) < n + n * m, from add_lt_add_of_lt_of_le h₁ this, have v₁ + v₂ * n + n < n * m + n, by rewrite [add.assoc, add.comm (n*m) n]; exact this, lt_of_add_lt_add_right this, have aux₂ : ∀ v, v % n < n, from take v, mod_lt _ `n > 0`, have aux₃ : ∀ {v}, v < n * m → v / n < m, from take v, assume h, by rewrite mul.comm at h; exact nat.div_lt_of_lt_mul h, ⦃ equiv, to_fun := λ p : (fin n × fin m), match p with (mk v₁ hlt₁, mk v₂ hlt₂) := mk (v₁ + v₂ * n) (aux₁ hlt₁ hlt₂) end, inv_fun := λ f : fin (n*m), match f with (mk v hlt) := (mk (v % n) (aux₂ v), mk (v / n) (aux₃ hlt)) end, left_inv := begin intro p, cases p with f₁ f₂, cases f₁ with v₁ hlt₁, cases f₂ with v₂ hlt₂, esimp, congruence, {congruence, rewrite [add_mul_mod_self, mod_eq_of_lt hlt₁] }, {congruence, rewrite [add_mul_div_self `n > 0`, div_eq_zero_of_lt hlt₁, zero_add]} end, right_inv := begin intro f, cases f with v hlt, esimp, congruence, rewrite [add.comm, -eq_div_mul_add_mod] end ⦄ definition fin_prod_equiv : Π (n m : nat), (fin n × fin m) ≃ fin (n*m) | 0 b := calc (fin 0 × fin b) ≃ (empty × fin b) : prod_congr fin_zero_equiv_empty !equiv.refl ... ≃ empty : prod_empty_left ... ≃ fin 0 : fin_zero_equiv_empty ... ≃ fin (0 * b) : by rewrite zero_mul | (a+1) b := fin_prod_equiv_of_pos (a+1) b dec_trivial definition fin_two_equiv_bool : fin 2 ≃ bool := calc fin 2 ≃ fin (1 + 1) : equiv.refl ... ≃ fin 1 + fin 1 : fin_sum_equiv ... ≃ unit + unit : sum_congr fin_one_equiv_unit fin_one_equiv_unit ... ≃ bool : bool_equiv_unit_sum_unit definition fin_sum_unit_equiv (n : nat) : fin n + unit ≃ fin (n+1) := calc fin n + unit ≃ fin n + fin 1 : sum_congr !equiv.refl (equiv.symm fin_one_equiv_unit) ... ≃ fin (n+1) : fin_sum_equiv end fin
ffe54e76abde70e5cbc0710c701d32c257a665d0
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/lift2.lean
c045e507e97993f27bd3d041226e04a83fd48319
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
288
lean
namespace test inductive {u₁ u₂} lift (A : Type u₁) : Type (max 1 u₁ u₂) | inj : A → lift set_option pp.universes true variables (A : Type 3) (B : Type 1) check A = lift.{1 3} B universe variables u variables (C : Type (u+2)) (D : Type u) check C = lift.{u u+2} D end test
792f9ff7fff20c5382dbdde6789ddaf0ffa6c32f
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Lean/Meta/Check.lean
868bea313b2bbfff8f43138d6049ec139cbdd40b
[ "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
6,212
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.Meta.InferType import Lean.Meta.LevelDefEq /- This is not the Kernel type checker, but an auxiliary method for checking whether terms produced by tactics and `isDefEq` are type correct. -/ namespace Lean.Meta private def ensureType (e : Expr) : MetaM Unit := do discard <| getLevel e def throwLetTypeMismatchMessage {α} (fvarId : FVarId) : MetaM α := do let lctx ← getLCtx match lctx.find? fvarId with | some (LocalDecl.ldecl _ _ n t v _) => do let vType ← inferType v throwError! "invalid let declaration, term{indentExpr v}\nhas type{indentExpr vType}\nbut is expected to have type{indentExpr t}" | _ => unreachable! private def checkConstant (constName : Name) (us : List Level) : MetaM Unit := do let cinfo ← getConstInfo constName unless us.length == cinfo.lparams.length do throwIncorrectNumberOfLevels constName us private def getFunctionDomain (f : Expr) : MetaM (Expr × BinderInfo) := do let fType ← inferType f let fType ← whnfD fType match fType with | Expr.forallE _ d _ c => return (d, c.binderInfo) | _ => throwFunctionExpected f /- Given to expressions `a` and `b`, this method tries to annotate terms with `pp.explicit := true` to expose "implicit" differences. For example, suppose `a` and `b` are of the form ```lean @HashMap Nat Nat eqInst hasInst1 @HashMap Nat Nat eqInst hasInst2 ``` By default, the pretty printer formats both of them as `HashMap Nat Nat`. So, counterintuitive error messages such as ```lean error: application type mismatch HashMap.insert m argument m has type HashMap Nat Nat but is expected to have type HashMap Nat Nat ``` would be produced. By adding `pp.explicit := true`, we can generate the more informative error ```lean error: application type mismatch HashMap.insert m argument m has type @HashMap Nat Nat eqInst hasInst1 but is expected to have type @HashMap Nat Nat eqInst hasInst2 ``` Remark: this method implements a simple heuristic, we should extend it as we find other counterintuitive error messages. -/ partial def addPPExplicitToExposeDiff (a b : Expr) : MetaM (Expr × Expr) := do if (← getOptions).getBool `pp.all false || (← getOptions).getBool `pp.explicit false then return (a, b) else visit a b where visit (a b : Expr) : MetaM (Expr × Expr) := do try if !a.isApp || !b.isApp then return (a, b) else if a.getAppNumArgs != b.getAppNumArgs then return (a, b) else if not (← isDefEq a.getAppFn b.getAppFn) then return (a, b) else let fType ← inferType a.getAppFn forallBoundedTelescope fType a.getAppNumArgs fun xs _ => do let mut as := a.getAppArgs let mut bs := b.getAppArgs if (← hasExplicitDiff xs as bs) then return (a, b) else for i in [:as.size] do let (ai, bi) ← visit as[i] bs[i] as := as.set! i ai bs := bs.set! i bi let a := mkAppN a.getAppFn as let b := mkAppN b.getAppFn bs return (a.setAppPPExplicit, b.setAppPPExplicit) catch _ => return (a, b) hasExplicitDiff (xs as bs : Array Expr) : MetaM Bool := do for i in [:xs.size] do let localDecl ← getLocalDecl xs[i].fvarId! if localDecl.binderInfo.isExplicit then if not (← isDefEq as[i] bs[i]) then return true return false /- Return error message "has type{givenType}\nbut is expected to have type{expectedType}" -/ def mkHasTypeButIsExpectedMsg (givenType expectedType : Expr) : MetaM MessageData := do let (givenType, expectedType) ← addPPExplicitToExposeDiff givenType expectedType m!"has type{indentExpr givenType}\nbut is expected to have type{indentExpr expectedType}" def throwAppTypeMismatch {α} (f a : Expr) (extraMsg : MessageData := Format.nil) : MetaM α := do let (expectedType, binfo) ← getFunctionDomain f let mut e := mkApp f a unless binfo.isExplicit do e := e.setAppPPExplicit let aType ← inferType a throwError! "application type mismatch{indentExpr e}\nargument{indentExpr a}\n{← mkHasTypeButIsExpectedMsg aType expectedType}" def checkApp (f a : Expr) : MetaM Unit := do let fType ← inferType f let fType ← whnf fType match fType with | Expr.forallE _ d _ _ => let aType ← inferType a unless (← isDefEq d aType) do throwAppTypeMismatch f a | _ => throwFunctionExpected (mkApp f a) private partial def checkAux : Expr → MetaM Unit | e@(Expr.forallE ..) => checkForall e | e@(Expr.lam ..) => checkLambdaLet e | e@(Expr.letE ..) => checkLambdaLet e | Expr.const c lvls _ => checkConstant c lvls | Expr.app f a _ => do checkAux f; checkAux a; checkApp f a | Expr.mdata _ e _ => checkAux e | Expr.proj _ _ e _ => checkAux e | _ => pure () where checkLambdaLet (e : Expr) : MetaM Unit := lambdaLetTelescope e fun xs b => do xs.forM fun x => do let xDecl ← getFVarLocalDecl x; match xDecl with | LocalDecl.cdecl (type := t) .. => ensureType t checkAux t | LocalDecl.ldecl (type := t) (value := v) .. => ensureType t checkAux t let vType ← inferType v unless (← isDefEq t vType) do throwLetTypeMismatchMessage x.fvarId! checkAux v checkAux b checkForall (e : Expr) : MetaM Unit := forallTelescope e fun xs b => do xs.forM fun x => do let xDecl ← getFVarLocalDecl x ensureType xDecl.type checkAux xDecl.type ensureType b checkAux b def check (e : Expr) : MetaM Unit := traceCtx `Meta.check do withTransparency TransparencyMode.all $ checkAux e def isTypeCorrect (e : Expr) : MetaM Bool := do try check e pure true catch ex => trace[Meta.typeError]! ex.toMessageData pure false builtin_initialize registerTraceClass `Meta.check registerTraceClass `Meta.typeError end Lean.Meta
808437e668defa6b2edd9e6ebffe5a17e47bd557
947b78d97130d56365ae2ec264df196ce769371a
/src/Init/Data/Int/Basic.lean
530bc983329d44443b3ea7275f6d7d6285871579
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,596
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura The integers, with addition, multiplication, and subtraction. -/ prelude import Init.Data.Nat.Basic import Init.Data.List import Init.Data.Repr import Init.Data.ToString open Nat /- the Type, coercions, and notation -/ inductive Int : Type | ofNat : Nat → Int | negSucc : Nat → Int attribute [extern "lean_nat_to_int"] Int.ofNat attribute [extern "lean_int_neg_succ_of_nat"] Int.negSucc instance : HasCoe Nat Int := ⟨Int.ofNat⟩ namespace Int protected def zero : Int := ofNat 0 protected def one : Int := ofNat 1 instance : HasZero Int := ⟨Int.zero⟩ instance : HasOne Int := ⟨Int.one⟩ instance : Inhabited Int := ⟨ofNat 0⟩ def negOfNat : Nat → Int | 0 => 0 | succ m => negSucc m @[extern "lean_int_neg"] protected def neg (n : @& Int) : Int := match n with | ofNat n => negOfNat n | negSucc n => succ n def subNatNat (m n : Nat) : Int := match (n - m : Nat) with | 0 => ofNat (m - n) -- m ≥ n | (succ k) => negSucc k @[extern "lean_int_add"] protected def add (m n : @& Int) : Int := match m, n with | ofNat m, ofNat n => ofNat (m + n) | ofNat m, negSucc n => subNatNat m (succ n) | negSucc m, ofNat n => subNatNat n (succ m) | negSucc m, negSucc n => negSucc (succ (m + n)) @[extern "lean_int_mul"] protected def mul (m n : @& Int) : Int := match m, n with | ofNat m, ofNat n => ofNat (m * n) | ofNat m, negSucc n => negOfNat (m * succ n) | negSucc m, ofNat n => negOfNat (succ m * n) | negSucc m, negSucc n => ofNat (succ m * succ n) instance : HasNeg Int := ⟨Int.neg⟩ instance : HasAdd Int := ⟨Int.add⟩ instance : HasMul Int := ⟨Int.mul⟩ @[extern "lean_int_sub"] protected def sub (m n : @& Int) : Int := m + -n instance : HasSub Int := ⟨Int.sub⟩ inductive NonNeg : Int → Prop | mk (n : Nat) : NonNeg (ofNat n) protected def LessEq (a b : Int) : Prop := NonNeg (b - a) instance : HasLessEq Int := ⟨Int.LessEq⟩ protected def Less (a b : Int) : Prop := (a + 1) ≤ b instance : HasLess Int := ⟨Int.Less⟩ @[extern "lean_int_dec_eq"] protected def decEq (a b : @& Int) : Decidable (a = b) := match a, b with | ofNat a, ofNat b => match decEq a b with | isTrue h => isTrue $ h ▸ rfl | isFalse h => isFalse $ fun h' => Int.noConfusion h' (fun h' => absurd h' h) | negSucc a, negSucc b => match decEq a b with | isTrue h => isTrue $ h ▸ rfl | isFalse h => isFalse $ fun h' => Int.noConfusion h' (fun h' => absurd h' h) | ofNat a, negSucc b => isFalse $ fun h => Int.noConfusion h | negSucc a, ofNat b => isFalse $ fun h => Int.noConfusion h instance Int.DecidableEq : DecidableEq Int := Int.decEq @[extern "lean_int_dec_nonneg"] private def decNonneg (m : @& Int) : Decidable (NonNeg m) := match m with | ofNat m => isTrue $ NonNeg.mk m | negSucc m => isFalse $ fun h => nomatch h @[extern "lean_int_dec_le"] instance decLe (a b : @& Int) : Decidable (a ≤ b) := decNonneg _ @[extern "lean_int_dec_lt"] instance decLt (a b : @& Int) : Decidable (a < b) := decNonneg _ @[extern "lean_nat_abs"] def natAbs (m : @& Int) : Nat := match m with | ofNat m => m | negSucc m => m.succ protected def repr : Int → String | ofNat m => Nat.repr m | negSucc m => "-" ++ Nat.repr (succ m) instance : HasRepr Int := ⟨Int.repr⟩ instance : HasToString Int := ⟨Int.repr⟩ instance : HasOfNat Int := ⟨Int.ofNat⟩ @[extern "lean_int_div"] def div : (@& Int) → (@& Int) → Int | ofNat m, ofNat n => ofNat (m / n) | ofNat m, negSucc n => -ofNat (m / succ n) | negSucc m, ofNat n => -ofNat (succ m / n) | negSucc m, negSucc n => ofNat (succ m / succ n) @[extern "lean_int_mod"] def mod : (@& Int) → (@& Int) → Int | ofNat m, ofNat n => ofNat (m % n) | ofNat m, negSucc n => ofNat (m % succ n) | negSucc m, ofNat n => -ofNat (succ m % n) | negSucc m, negSucc n => -ofNat (succ m % succ n) instance : HasDiv Int := ⟨Int.div⟩ instance : HasMod Int := ⟨Int.mod⟩ def toNat : Int → Nat | ofNat n => n | negSucc n => 0 def natMod (m n : Int) : Nat := (m % n).toNat end Int namespace String def toInt? (s : String) : Option Int := if s.get 0 = '-' then do v ← (s.toSubstring.drop 1).toNat?; pure $ - Int.ofNat v else Int.ofNat <$> s.toNat? def isInt (s : String) : Bool := if s.get 0 = '-' then (s.toSubstring.drop 1).isNat else s.isNat def toInt! (s : String) : Int := match s.toInt? with | some v => v | none => panic! "Int expected" end String
1501d0841b4cd014e09e1257e423801a60f28e0c
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/combinator.lean
cfcd1535bbb90e8dd3cd3170ba11987de269181e
[ "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
492
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 /- Combinator calculus -/ namespace combinator universe variables u₁ u₂ u₃ definition I {A : Type u₁} (a : A) := a definition K {A : Type u₁} {B : Type u₂} (a : A) (b : B) := a definition S {A : Type u₁} {B : Type u₂} {C : Type u₃} (x : A → B → C) (y : A → B) (z : A) := x z (y z) end combinator
8d32ed51d17201dbbcde1fa6628ccfa381551267
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/auto_cases_auto.lean
8759d7be80bb7fc0f75c64c56019ffb842c054b3
[]
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
432
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.hint import Mathlib.PostPort namespace Mathlib namespace tactic namespace auto_cases /-- Structure representing a tactic which can be used by `tactic.auto_cases`. -/ end Mathlib
6daeabac8bab1e2eb44070a16a6b1dfd2ea7d202
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/archive/imo/imo2008_q4.lean
ae03758ea597da3150c01ea527014b285b4c97eb
[ "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
5,555
lean
/- Copyright (c) 2021 Manuel Candales. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Manuel Candales -/ import data.real.basic import data.real.sqrt import data.real.nnreal /-! # IMO 2008 Q4 Find all functions `f : (0,∞) → (0,∞)` (so, `f` is a function from the positive real numbers to the positive real numbers) such that ``` (f(w)^2 + f(x)^2)/(f(y^2) + f(z^2)) = (w^2 + x^2)/(y^2 + z^2) ``` for all positive real numbers `w`, `x`, `y`, `z`, satisfying `wx = yz`. # Solution The desired theorem is that either `f = λ x, x` or `f = λ x, 1/x` -/ open real lemma abs_eq_one_of_pow_eq_one (x : ℝ) (n : ℕ) (hn : n ≠ 0) (h : x ^ n = 1) : |x| = 1 := by rw [← pow_left_inj (abs_nonneg x) zero_le_one (pos_iff_ne_zero.2 hn), one_pow, pow_abs, h, abs_one] theorem imo2008_q4 (f : ℝ → ℝ) (H₁ : ∀ x > 0, f(x) > 0) : (∀ w x y z : ℝ, 0 < w → 0 < x → 0 < y → 0 < z → w * x = y * z → (f(w) ^ 2 + f(x) ^ 2) / (f(y ^ 2) + f(z ^ 2)) = (w ^ 2 + x ^ 2) / (y ^ 2 + z ^ 2)) ↔ ((∀ x > 0, f(x) = x) ∨ (∀ x > 0, f(x) = 1 / x)) := begin split, swap, -- proof that f(x) = x and f(x) = 1/x satisfy the condition { rintros (h | h), { intros w x y z hw hx hy hz hprod, rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)] }, { intros w x y z hw hx hy hz hprod, rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)], have hy2z2 : y ^ 2 + z ^ 2 ≠ 0 := ne_of_gt (add_pos (pow_pos hy 2) (pow_pos hz 2)), have hz2y2 : z ^ 2 + y ^ 2 ≠ 0 := ne_of_gt (add_pos (pow_pos hz 2) (pow_pos hy 2)), have hp2 : w ^ 2 * x ^ 2 = y ^ 2 * z ^ 2, { rw [← mul_pow w x 2, ← mul_pow y z 2, hprod] }, field_simp [ne_of_gt hw, ne_of_gt hx, ne_of_gt hy, ne_of_gt hz, hy2z2, hz2y2, hp2], ring } }, -- proof that the only solutions are f(x) = x or f(x) = 1/x intro H₂, have h₀ : f(1) ≠ 0, { specialize H₁ 1 zero_lt_one, exact ne_of_gt H₁ }, have h₁ : f(1) = 1, { specialize H₂ 1 1 1 1 zero_lt_one zero_lt_one zero_lt_one zero_lt_one rfl, norm_num at H₂, simp only [← two_mul] at H₂, rw mul_div_mul_left (f(1) ^ 2) (f 1) two_ne_zero at H₂, rwa ← (div_eq_iff h₀).mpr (sq (f 1)) }, have h₂ : ∀ x > 0, (f(x) - x) * (f(x) - 1 / x) = 0, { intros x hx, have h1xss : 1 * x = (sqrt x) * (sqrt x), { rw [one_mul, mul_self_sqrt (le_of_lt hx)] }, specialize H₂ 1 x (sqrt x) (sqrt x) zero_lt_one hx (sqrt_pos.mpr hx) (sqrt_pos.mpr hx) h1xss, rw [h₁, one_pow 2, sq_sqrt (le_of_lt hx), ← two_mul (f(x)), ← two_mul x] at H₂, have hx_ne_0 : x ≠ 0 := ne_of_gt hx, have hfx_ne_0 : f(x) ≠ 0, { specialize H₁ x hx, exact ne_of_gt H₁ }, field_simp at H₂, have h1 : (2 * x) * ((f(x) - x) * (f(x) - 1 / x)) = 0, { calc (2 * x) * ((f(x) - x) * (f(x) - 1 / x)) = 2 * (f(x) - x) * (x * f(x) - x * 1 / x) : by ring ... = 2 * (f(x) - x) * (x * f(x) - 1) : by rw (mul_div_cancel_left 1 hx_ne_0) ... = ((1 + f(x) ^ 2) * (2 * x) - (1 + x ^ 2) * (2 * f(x))) : by ring ... = 0 : sub_eq_zero.mpr H₂ }, have h2x_ne_0 : 2 * x ≠ 0 := mul_ne_zero two_ne_zero hx_ne_0, calc ((f(x) - x) * (f(x) - 1 / x)) = (2 * x) * ((f(x) - x) * (f(x) - 1 / x)) / (2 * x) : (mul_div_cancel_left _ h2x_ne_0).symm ... = 0 : by { rw h1, exact zero_div (2 * x) } }, have h₃ : ∀ x > 0, f(x) = x ∨ f(x) = 1 / x, { simpa [sub_eq_zero] using h₂ }, by_contradiction, push_neg at h, rcases h with ⟨⟨b, hb, hfb₁⟩, ⟨a, ha, hfa₁⟩⟩, obtain hfa₂ := or.resolve_right (h₃ a ha) hfa₁, -- f(a) ≠ 1/a, f(a) = a obtain hfb₂ := or.resolve_left (h₃ b hb) hfb₁, -- f(b) ≠ b, f(b) = 1/b have hab : a * b > 0 := mul_pos ha hb, have habss : a * b = sqrt(a * b) * sqrt(a * b) := (mul_self_sqrt (le_of_lt hab)).symm, specialize H₂ a b (sqrt (a * b)) (sqrt (a * b)) ha hb (sqrt_pos.mpr hab) (sqrt_pos.mpr hab) habss, rw [sq_sqrt (le_of_lt hab), ← two_mul (f(a * b)), ← two_mul (a * b)] at H₂, rw [hfa₂, hfb₂] at H₂, have h2ab_ne_0 : 2 * (a * b) ≠ 0 := mul_ne_zero two_ne_zero (ne_of_gt hab), specialize h₃ (a * b) hab, cases h₃ with hab₁ hab₂, -- f(ab) = ab → b^4 = 1 → b = 1 → f(b) = b → false { have H₃ : (a ^ 2 + (1 / b) ^ 2) / (2 * (a * b)) = (a ^ 2 + b ^ 2) / (2 * (a * b)) ↔ 1 / b ^ 2 = b ^ 2 ∨ 2 * (a * b) = 0, { field_simp [h2ab_ne_0], }, rw [hab₁, H₃] at H₂, obtain hb₁ := or.resolve_right H₂ h2ab_ne_0, field_simp [ne_of_gt hb] at hb₁, rw (show b ^ 2 * b ^ 2 = b ^ 4, by ring) at hb₁, obtain hb₂ := abs_eq_one_of_pow_eq_one b 4 (show 4 ≠ 0, by norm_num) hb₁.symm, rw abs_of_pos hb at hb₂, rw hb₂ at hfb₁, exact hfb₁ h₁ }, -- f(ab) = 1/ab → a^4 = 1 → a = 1 → f(a) = 1/a → false { have hb_ne_0 : b ≠ 0 := ne_of_gt hb, rw hab₂ at H₂, field_simp at H₂, rw ← sub_eq_zero at H₂, rw (show (a ^ 2 * b ^ 2 + 1) * (a * b) * (2 * (a * b)) - (a ^ 2 + b ^ 2) * (b ^ 2 * 2) = 2 * (b ^ 4) * (a ^ 4 - 1), by ring) at H₂, have h2b4_ne_0 : 2 * (b ^ 4) ≠ 0 := mul_ne_zero two_ne_zero (pow_ne_zero 4 hb_ne_0), have ha₁ : a ^ 4 = 1, { simpa [sub_eq_zero, h2b4_ne_0] using H₂ }, obtain ha₂ := abs_eq_one_of_pow_eq_one a 4 (show 4 ≠ 0, by norm_num) ha₁, rw abs_of_pos ha at ha₂, rw ha₂ at hfa₁, norm_num at hfa₁ }, end
673187022a0799ffd853e0e383223fe54aceec5c
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/identifiers/2020-01-23-notes-002.lean
1b1815534f894b5a09de3576d7119e0766a99be8
[]
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
1,189
lean
def pop := prod.mk (prod.mk 2 tt) (prod.mk "Hello" 3) #eval prod.mk (prod.mk 2 tt) (prod.mk "Hello" 3) #eval pop -- Oops. Immutable. So this won't work. def pop := prod.mk (prod.mk 2 tt) (prod.mk "Hello" 3) /- Big conversation about mutable vs immutable, functional vs imperative, referential transparency. -/ def b := tt /- Rule for evaluating identifier expressions. -/ #eval tt #eval b def n := 2 #eval n def s := "Hello" #eval s /- Every term has exactly one type A type defines a set of terms Types are disjoint -/ #check 0 #check n #check b #check prod.mk (prod.mk 2 tt) (prod.mk "Hello" 3) #reduce (ℕ × bool) × string × ℕ /- -/ #check 3 #check ℕ #check bool #check string #check Prop #check Type #check Type 2 /- Abstract data type (ADT) data type + set of functions -/ #eval band tt tt #eval tt && tt #eval tt || ff #eval bor tt ff #eval bor (band tt tt) ff #eval nat.add 3 4 #eval nat.mul 3 4 #eval nat.sub 4 3 #eval nat.sub 3 4 #eval string.append "I love " "Logic" #eval string.length "I love Logic" #eval "I love " ++ "Logic" #check bor
a518ce7de0360cbd26fa79b8cf2989e85a5b4dc8
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/972.lean
f84f6574c379fe9de677b0bd99433cd4e4b4c893
[ "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
851
lean
class Semigroup (M : Type u) extends Mul M where mul_assoc (a b c : M) : (a * b) * c = a * (b * c) export Semigroup (mul_assoc) class CommSemigroup (M : Type u) extends Semigroup M where mul_comm (a b : M) : a * b = b * a export CommSemigroup (mul_comm) class Monoid (M : Type u) extends Semigroup M, OfNat M 1 where mul_one (m : M) : m * 1 = m one_mul (m : M) : 1 * m = m class CommMonoid (M : Type u) extends Monoid M, CommSemigroup M theorem mul_left_comm {M} [CommSemigroup M] (a b c : M) : a * (b * c) = b * (a * c) := by rw [← mul_assoc, mul_comm a b, mul_assoc] example {M} [CommMonoid M] (a b c d : M) : a * (b * (c * d)) = (a * c) * (b * d) := by simp only [mul_left_comm, mul_comm, mul_assoc] example {M} [CommMonoid M] (a b c d : M) : (b * (c * d)) = (c) * (b * d) := by simp only [mul_left_comm, mul_comm, mul_assoc]
eb47811f5de0fc899322fc9e313f6e69132b7fd5
54f4ad05b219d444b709f56c2f619dd87d14ec29
/my_project/src/love02_backward_proofs_demo.lean
c7be2326669c35d6b235296ddf2bf8f702996db5
[]
no_license
yizhou7/learning-lean
8efcf838c7276e235a81bd291f467fa43ce56e0a
91fb366c624df6e56e19555b2e482ce767cd8224
refs/heads/master
1,675,649,087,737
1,609,022,281,000
1,609,022,281,000
272,072,779
0
0
null
null
null
null
UTF-8
Lean
false
false
7,740
lean
import .love01_definitions_and_statements_demo /-! # LoVe Demo 2: Backward Proofs A __tactic__ operates on a proof goal and either proves it or creates new subgoals. Tactics are a __backward__ proof mechanism: They start from the goal and work towards the available hypotheses and lemmas. -/ set_option pp.beta true namespace LoVe /-! ## Tactic Mode Syntax of tactical proofs: begin _tactic₁_, …, _tacticN_ end -/ lemma fst_of_two_props : ∀a b : Prop, a → b → a := begin intros a b, intros ha hb, apply ha end #check fst_of_two_props /-! ## Basic Tactics `intro`(`s`) moves `∀`-quantified variables, or the assumptions of implications `→`, from the goal's conclusion (after `⊢`) into the goal's hypotheses (before `⊢`). `apply` matches the goal's conclusion with the conclusion of the specified lemma and adds the lemma's hypotheses as new goals. -/ lemma fst_of_two_props₂ (a b : Prop) (ha : a) (hb : b) : a := begin apply ha end /-! Terminal tactic syntax: by _tactic_ abbreviates begin _tactic_ end -/ lemma fst_of_two_props₃ (a b : Prop) (ha : a) (hb : b) : a := by apply ha lemma prop_comp (a b c : Prop) (hab : a → b) (hbc : b → c) : a → c := begin intro ha, apply hbc, apply hab, assumption, end /-! `exact` matches the goal's conclusion with the specified lemma, closing the goal. We can often use `apply` in such situations, but `exact` communicates our intentions better. -/ lemma fst_of_two_props₄ (a b : Prop) (ha : a) (hb : b) : a := by exact ha /-! `assumption` finds a hypothesis from the local context that matches the goal's conclusion and applies it to prove the goal. -/ lemma fst_of_two_props₅ (a b : Prop) (ha : a) (hb : b) : a := by assumption /-! `refl` proves `l = r`, where the two sides are equal up to computation. Computation means unfolding of definitions, β-reduction (application of λ to an argument), `let`, and more. -/ lemma α_example {α β : Type} (f : α → β) : (λx, f x) = (λy, f y) := begin refl end lemma α_example₂ {α β : Type} (f : α → β) : (λx, f x) = (λy, f y) := by refl lemma β_example {α β : Type} (f : α → β) (a : α) : (λx, f x) a = f a := by refl def double (n : ℕ) : ℕ := n + n lemma δ_example : double 5 = 5 + 5 := by refl lemma ζ_example : (let n : ℕ := 2 in n + n) = 4 := by refl lemma η_example {α β : Type} (f : α → β) : (λx, f x) = f := by refl lemma ι_example {α β : Type} (a : α) (b : β) : prod.fst (a, b) = a := by refl /-! ## Reasoning about Logical Connectives and Quantifiers Introduction rules: -/ #check true.intro #check not.intro #check and.intro #check or.intro_left #check or.intro_right #check iff.intro #check exists.intro /-! Elimination rules: -/ #check false.elim #check and.elim_left #check and.elim_right #check or.elim #check iff.elim_left #check iff.elim_right #check exists.elim /-! Definition of `¬` and related lemmas: -/ #print not #check not_def #check classical.em #check classical.by_contradiction lemma and_swap (a b : Prop) : a ∧ b → b ∧ a := begin intro hab, apply and.intro, apply and.elim_right, exact hab, apply and.elim_left, exact hab end /-! The `{ … }` combinator focuses on the first subgoal. The tactic inside must fully prove it. -/ lemma and_swap₂ : ∀a b : Prop, a ∧ b → b ∧ a := begin intros a b hab, apply and.intro, { exact and.elim_right hab }, { exact and.elim_left hab } end /-! Notice above how we pass the hypothesis `hab` directly to the lemmas `and.elim_right` and `and.elim_left`, instead of waiting for the lemmas's assumptions to appear as new subgoals. This is a small forward step in an otherwise backward proof. -/ lemma or_swap (a b : Prop) : a ∨ b → b ∨ a := begin intros hab, apply or.elim hab, { intros ha, exact or.intro_right _ ha }, { intros hb, exact or.intro_left _ hb } end lemma modus_ponens (a b : Prop) : (a → b) → a → b := begin intros hab ha, apply hab, exact ha end lemma not_not_intro (a : Prop) : a → ¬¬ a := begin intro ha, apply not.intro, intro hna, apply hna, exact ha end lemma not_not_intro₂ (a : Prop) : a → ¬¬ a := begin intros ha hna, apply hna, exact ha end lemma nat_exists_double_iden : ∃n : ℕ, double n = n := begin apply exists.intro 0, refl end /-! ## Reasoning about Equality -/ #check eq.refl #check eq.symm #check eq.trans #check eq.subst /-! The above rules can be used directly: -/ lemma cong_fst_arg {α : Type} (a a' b : α) (f : α → α → α) (ha : a = a') : f a b = f a' b := begin cc end lemma cong_two_args {α : Type} (a a' b b' : α) (f : α → α → α) (ha : a = a') (hb : b = b') : f a b = f a' b' := begin apply eq.subst ha, apply eq.subst hb, apply eq.refl end /-! `rewrite` applies a single equation as a left-to-right rewrite rule, once. To apply an equation right-to-left, prefix its name with `←`. -/ lemma cong_two_args₂ {α : Type} (a a' b b' : α) (f : α → α → α) (ha : a = a') (hb : b = b') : f a b = f a' b' := begin rw ha, rw hb end lemma a_proof_of_negation₃ (a : Prop) : a → ¬¬ a := begin rewrite not_def, rewrite not_def, intro ha, apply not.intro, intro hna, apply hna, exact ha end /-! `simp` applies a standard set of rewrite rules (the __simp set__) exhaustively. The set can be extended using the `@[simp]` attribute. Lemmas can be temporarily added to the simp set with the syntax `simp [_lemma₁_, …, _lemmaN_]`. -/ lemma cong_two_args_etc {α : Type} (a a' b b' : α) (g : α → α → ℕ → α) (ha : a = a') (hb : b = b') : g a b (1 + 1) = g a' b' 2 := by simp [ha, hb] /-! `cc` applies __congruence closure__ to derive new equalities. -/ lemma cong_two_args₃ {α : Type} (a a' b b' : α) (f : α → α → α) (ha : a = a') (hb : b = b') : f a b = f a' b' := by cc /-! `cc` can also reason up to associativity and commutativity of `+`, `*`, and other binary operators. -/ lemma cong_assoc_comm (a a' b c : ℝ) (f : ℝ → ℝ) (ha : a = a') : f (a + b + c) = f (c + b + a') := by cc /-! ## Proofs by Mathematical Induction `induction` performs induction on the specified variable. It gives rise to one subgoal per constructor. -/ lemma add_zero (n : ℕ) : add 0 n = n := begin induction n, { refl }, { simp [add, n_ih] } end lemma add_succ (m n : ℕ) : add (nat.succ m) n = nat.succ (add m n) := begin induction n, { refl }, { simp [add, n_ih] } end lemma add_comm (m n : ℕ) : add m n = add n m := begin induction n, { simp [add, add_zero] }, { simp [add, add_succ, n_ih] } end lemma add_assoc (l m n : ℕ) : add (add l m) n = add l (add m n) := begin induction n, { refl }, { simp [add, n_ih] } end /-! `cc` is extensible. We can register `add` as a commutative and associative operator using the type class instance mechanism (explained in lecture 11). This is useful for the `cc` invocation below. -/ @[instance] def add.is_commutative : is_commutative ℕ add := { comm := add_comm } @[instance] def add.is_associative : is_associative ℕ add := { assoc := add_assoc } lemma mul_add (l m n : ℕ) : mul l (add m n) = add (mul l m) (mul l n) := begin induction n, { refl }, { simp [add, mul, n_ih], cc } end /-! ## Cleanup Tactics `rename` changes the name of a variable or hypothesis. `clear` removes unused variables or hypotheses. -/ lemma cleanup_example (a b c : Prop) (ha : a) (hb : b) (hab : a → b) (hbc : b → c) : c := begin clear ha hab a, apply hbc, clear hbc c, rename hb h, exact h end end LoVe
32cd312fae10bf112eea82ccb68d58b7f5d71822
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/634c.lean
32ae348a7781502773f28210585bd10f52bcc40a
[ "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
937
lean
open nat section parameter (X : Type) definition A {n : ℕ} : Type := X definition B : Type := X variable {n : ℕ} check @A n check _root_.A nat check _root_.A (X × B) check @_root_.A (X × B) 10 check @_root_.A (_root_.B (@_root_.A X n)) n check @_root_.A (@_root_.B (@_root_.A nat n)) n set_option pp.full_names true check A check _root_.A nat check @_root_.A (X × B) 10 check @_root_.A (@_root_.B (@_root_.A X n)) n check @_root_.A (@_root_.B (@_root_.A nat n)) n set_option pp.full_names false set_option pp.implicit true check @A n check @_root_.A nat 10 check @_root_.A X n set_option pp.full_names true check @_root_.A X n check @_root_.A B n set_option pp.full_names false check @_root_.A X n check @_root_.A B n check @_root_.A (@_root_.B (@A n)) n check @_root_.A (@_root_.B (@_root_.A X n)) n check @_root_.A (@_root_.B (@_root_.A nat n)) n check @A n end
4900be08b149621cda4675c870e38a0b9ef1bf27
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/run/unfold_crash.lean
ab00a3ef76f79443b0eedc89b9b68632b224601c
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,641
lean
open tactic -- TODO(Leo): remove the following command. -- It has been added to avoid a crash in the code generator noncomputable theory inductive vector (A : Type) : nat → Type | nil {} : vector 0 | cons : Π {n}, A -> vector n -> vector (nat.succ n) definition vmap {A B : Type} (f : A -> B) : Π {n}, vector A n -> vector B n | 0 vector.nil := vector.nil | (n+1) (vector.cons x xs) := vector.cons (f x) (vmap xs) noncomputable definition vappend {A} : Π {n m}, vector A n → vector A m → vector A (m + n) | 0 0 vector.nil vector.nil := vector.nil | 0 (m+1) vector.nil (vector.cons x xs) := vector.cons x xs | (n+1) 0 (vector.cons x xs) vector.nil := vector.cons x (vappend xs vector.nil) | (n+1) (m+1) (vector.cons x xs) (vector.cons y ys) := vector.cons x (vappend xs (vector.cons y ys)) axiom Sorry : ∀ A, A theorem vappend_assoc : Π {A : Type} {n m k : nat} (v1 : vector A n) (v2 : vector A m) (v3 : vector A k), vappend (vappend v1 v2) v3 == vappend v1 (vappend v2 v3) := by do intros, v <- get_local `v1, induction_core semireducible v (`vector.rec_on) [], v2 ← get_local `v2, cases_using v2 [`m, `h2, `t2], trace_state, trace "------", -- unfold only the first occurrence (i.e., the one of the form (vappend nil nil) dunfold_occs_of [1] `vappend, trace_state, trace "------", mk_const `Sorry >>= apply, -- unfold only the first occurrence (i.e., the one of the form (vappend nil (cons ...)) dunfold_occs_of [1] `vappend, trace_state, trace "------", repeat $ mk_const `Sorry >>= apply
e796af0adb6d583516d0165f387b188892817459
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/10_Structures_and_Records.org.14.lean
dbeb91c5893457939f02dbfc700c770a85fa245b
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
606
lean
import standard open num structure point (A : Type) := mk :: (x : A) (y : A) inductive color := red | green | blue structure color_point (A : Type) extends point A := mk :: (c : color) -- BEGIN definition x_plus_y (p : point num) := point.x p + point.y p definition green_point : color_point num := {| color_point, x := 10, y := 20, c := color.green |} eval x_plus_y green_point -- 30 -- display implicit coercions set_option pp.coercions true check x_plus_y green_point -- num example : green_point = point.mk 10 20 := rfl check color_point.to_point -- color_point ?A → point ?A -- END
306d4fe9f6b0e504008e16eca98e1f452ef05829
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/list/defs.lean
b20ef680b6575e54ea64c385599b339730cf6ab2
[ "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
41,607
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import logic.basic import tactic.cache import data.rbmap.basic import data.rbtree.default_lt /-! ## Definitions on lists > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains various definitions on lists. It does not contain proofs about these definitions, those are contained in other files in `data/list` -/ namespace list open function nat universes u v w x variables {α β γ δ ε ζ : Type*} instance [decidable_eq α] : has_sdiff (list α) := ⟨ list.diff ⟩ /-- Split a list at an index. split_at 2 [a, b, c] = ([a, b], [c]) -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) /-- An auxiliary function for `split_on_p`. -/ def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] : list α → (list α → list α) → list (list α) | [] f := [f []] | (h :: t) f := if P h then f [] :: split_on_p_aux t id else split_on_p_aux t (λ l, f (h :: l)) /-- Split a list at every element satisfying a predicate. -/ def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) := split_on_p_aux P l id /-- Split a list at every occurrence of an element. [1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/ def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) := as.split_on_p (=a) /-- Concatenate an element at the end of a list. concat [a, b] c = [a, b, c] -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a /-- `head' xs` returns the first element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def head' : list α → option α | [] := none | (a :: l) := some a /-- Convert a list into an array (whose length is the length of `l`). -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "default" `nth` function: returns `d` instead of `none` in the case that the index is out of bounds. -/ def nthd (d : α) : Π (l : list α) (n : ℕ), α | [] _ := d | (x::xs) 0 := x | (x::xs) (n + 1) := nthd xs n /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ def inth [h : inhabited α] (l : list α) (n : nat) : α := nthd default l n /-- Apply a function to the nth tail of `l`. Returns the input without using `f` if the index is larger than the length of the list. modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) /-- Apply `f` to the last element of `l`, if it exists. -/ @[simp] def modify_last (f : α → α) : list α → list α | [] := [] | [x] := [f x] | (x :: xs) := x :: modify_last xs /-- `insert_nth n a l` inserts `a` into the list `l` after the first `n` elements of `l` `insert_nth 2 1 [1, 2, 3, 4] = [1, 2, 1, 3, 4]`-/ def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n section take' variable [inhabited α] /-- Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l` elements `default`. -/ def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail end take' /-- Get the longest initial segment of the list whose members all satisfy `p`. take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /-- Fold a function `f` over the list from the left, returning the list of partial results. scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l /-- Auxiliary definition used to define `scanr`. If `scanr_aux f b l = (b', l')` then `scanr f b l = b' :: l'` -/ def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' /-- Product of a list. prod [a, b, c] = ((1 * a) * b) * c -/ def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 /-- Sum of a list. sum [a, b, c] = ((0 + a) + b) + c -/ -- Later this will be tagged with `to_additive`, but this can't be done yet because of import -- dependencies. def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0 /-- The alternating sum of a list. -/ def alternating_sum {G : Type*} [has_zero G] [has_add G] [has_neg G] : list G → G | [] := 0 | (g :: []) := g | (g :: h :: t) := g + -h + alternating_sum t /-- The alternating product of a list. -/ def alternating_prod {G : Type*} [has_one G] [has_mul G] [has_inv G] : list G → G | [] := 1 | (g :: []) := g | (g :: h :: t) := g * h⁻¹ * alternating_prod t /-- Given a function `f : α → β ⊕ γ`, `partition_map f l` maps the list by `f` whilst partitioning the result it into a pair of lists, `list β × list γ`, partitioning the `sum.inl _` into the left list, and the `sum.inr _` into the right list. `partition_map (id : ℕ ⊕ ℕ → ℕ ⊕ ℕ) [inl 0, inr 1, inl 2] = ([0,2], [1])` -/ def partition_map (f : α → β ⊕ γ) : list α → list β × list γ | [] := ([],[]) | (x::xs) := match f x with | (sum.inr r) := prod.map id (cons r) $ partition_map xs | (sum.inl l) := prod.map (cons l) id $ partition_map xs end /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l /-- `mfind tac l` returns the first element of `l` on which `tac` succeeds, and fails otherwise. -/ def mfind {α} {m : Type u → Type v} [monad m] [alternative m] (tac : α → m punit) : list α → m α := list.mfirst $ λ a, tac a $> a /-- `mbfind' p l` returns the first element `a` of `l` for which `p a` returns true. `mbfind'` short-circuits, so `p` is not necessarily run on every `a` in `l`. This is a monadic version of `list.find`. -/ def mbfind' {m : Type u → Type v} [monad m] {α : Type u} (p : α → m (ulift bool)) : list α → m (option α) | [] := pure none | (x :: xs) := do ⟨px⟩ ← p x, if px then pure (some x) else mbfind' xs section variables {m : Type → Type v} [monad m] /-- A variant of `mbfind'` with more restrictive universe levels. -/ def mbfind {α} (p : α → m bool) (xs : list α) : m (option α) := xs.mbfind' (functor.map ulift.up ∘ p) /-- `many p as` returns true iff `p` returns true for any element of `l`. `many` short-circuits, so if `p` returns true for any element of `l`, later elements are not checked. This is a monadic version of `list.any`. -/ -- Implementing this via `mbfind` would give us less universe polymorphism. def many {α : Type u} (p : α → m bool) : list α → m bool | [] := pure false | (x :: xs) := do px ← p x, if px then pure tt else many xs /-- `mall p as` returns true iff `p` returns true for all elements of `l`. `mall` short-circuits, so if `p` returns false for any element of `l`, later elements are not checked. This is a monadic version of `list.all`. -/ def mall {α : Type u} (p : α → m bool) (as : list α) : m bool := bnot <$> many (λ a, bnot <$> p a) as /-- `mbor xs` runs the actions in `xs`, returning true if any of them returns true. `mbor` short-circuits, so if an action returns true, later actions are not run. This is a monadic version of `list.bor`. -/ def mbor : list (m bool) → m bool := many id /-- `mband xs` runs the actions in `xs`, returning true if all of them return true. `mband` short-circuits, so if an action returns false, later actions are not run. This is a monadic version of `list.band`. -/ def mband : list (m bool) → m bool := mall id end /-- Auxiliary definition for `foldl_with_index`. -/ def foldl_with_index_aux (f : ℕ → α → β → α) : ℕ → α → list β → α | _ a [] := a | i a (b :: l) := foldl_with_index_aux (i + 1) (f i a b) l /-- Fold a list from left to right as with `foldl`, but the combining function also receives each element's index. -/ def foldl_with_index (f : ℕ → α → β → α) (a : α) (l : list β) : α := foldl_with_index_aux f 0 a l /-- Auxiliary definition for `foldr_with_index`. -/ def foldr_with_index_aux (f : ℕ → α → β → β) : ℕ → β → list α → β | _ b [] := b | i b (a :: l) := f i a (foldr_with_index_aux (i + 1) b l) /-- Fold a list from right to left as with `foldr`, but the combining function also receives each element's index. -/ def foldr_with_index (f : ℕ → α → β → β) (b : β) (l : list α) : β := foldr_with_index_aux f 0 b l /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := foldr_with_index (λ i a is, if p a then i :: is else is) [] l /-- Returns the elements of `l` that satisfy `p` together with their indexes in `l`. The returned list is ordered by index. -/ def indexes_values (p : α → Prop) [decidable_pred p] (l : list α) : list (ℕ × α) := foldr_with_index (λ i a l, if p a then (i , a) :: l else l) [] l /-- `indexes_of a l` is the list of all indexes of `a` in `l`. For example: ``` indexes_of a [a, b, a, a] = [0, 2, 3] ``` -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) section mfold_with_index variables {m : Type v → Type w} [monad m] /-- Monadic variant of `foldl_with_index`. -/ def mfoldl_with_index {α β} (f : ℕ → β → α → m β) (b : β) (as : list α) : m β := as.foldl_with_index (λ i ma b, do a ← ma, f i a b) (pure b) /-- Monadic variant of `foldr_with_index`. -/ def mfoldr_with_index {α β} (f : ℕ → α → β → m β) (b : β) (as : list α) : m β := as.foldr_with_index (λ i a mb, do b ← mb, f i a b) (pure b) end mfold_with_index section mmap_with_index variables {m : Type v → Type w} [applicative m] /-- Auxiliary definition for `mmap_with_index`. -/ def mmap_with_index_aux {α β} (f : ℕ → α → m β) : ℕ → list α → m (list β) | _ [] := pure [] | i (a :: as) := list.cons <$> f i a <*> mmap_with_index_aux (i + 1) as /-- Applicative variant of `map_with_index`. -/ def mmap_with_index {α β} (f : ℕ → α → m β) (as : list α) : m (list β) := mmap_with_index_aux f 0 as /-- Auxiliary definition for `mmap_with_index'`. -/ def mmap_with_index'_aux {α} (f : ℕ → α → m punit) : ℕ → list α → m punit | _ [] := pure ⟨⟩ | i (a :: as) := f i a *> mmap_with_index'_aux (i + 1) as /-- A variant of `mmap_with_index` specialised to applicative actions which return `unit`. -/ def mmap_with_index' {α} (f : ℕ → α → m punit) (as : list α) : m punit := mmap_with_index'_aux f 0 as end mmap_with_index /-- `lookmap` is a combination of `lookup` and `filter_map`. `lookmap f l` will apply `f : α → option α` to each element of the list, replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/ def lookmap (f : α → option α) : list α → list α | [] := [] | (a::l) := match f a with | some b := b :: l | none := a :: lookmap l end /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count [decidable_eq α] (a : α) : list α → nat := countp (eq a) /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_infix /-- `inits l` is the list of initial segments of `l`. inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) /-- `tails l` is the list of terminal segments of `l`. tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'` for a different ordering. sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} /-- `forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length, and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`, then `R a b` is satisfied. -/ inductive forall₂ (R : α → β → Prop) : list α → list β → Prop | nil : forall₂ [] [] | cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂) attribute [simp] forall₂.nil end forall₂ /-- `l.all₂ p` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction, i.e. `list.all₂ p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ @[simp] def all₂ (p : α → Prop) : list α → Prop | [] := true | (x :: []) := p x | (x :: l) := p x ∧ all₂ l /-- Auxiliary definition used to define `transpose`. `transpose_aux l L` takes each element of `l` and appends it to the start of each element of `L`. `transpose_aux [a, b, c] [l₁, l₂, l₃] = [a::l₁, b::l₂, c::l₃]` -/ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ def sections : list (list α) → list (list α) | [] := [[]] | (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l section permutations /-- An auxiliary function for defining `permutations`. `permutations_aux2 t ts r ys f` is equal to `(ys ++ ts, (insert_left ys t ts).map f ++ r)`, where `insert_left ys t ts` (not explicitly defined) is the list of lists of the form `insert_nth n t (ys ++ ts)` for `0 ≤ n < length ys`. permutations_aux2 10 [4, 5, 6] [] [1, 2, 3] id = ([1, 2, 3, 4, 5, 6], [[10, 1, 2, 3, 4, 5, 6], [1, 10, 2, 3, 4, 5, 6], [1, 2, 10, 3, 4, 5, 6]]) -/ def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas /-- A recursor for pairs of lists. To have `C l₁ l₂` for all `l₁`, `l₂`, it suffices to have it for `l₂ = []` and to be able to pour the elements of `l₁` into `l₂`. -/ @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ (nat.lt_add_of_pos_left (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } /-- An auxiliary function for defining `permutations`. `permutations_aux ts is` is the set of all permutations of `is ++ ts` that do not fix `ts`. -/ def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] /-- `permutations'_aux t ts` inserts `t` into every position in `ts`, including the last. This function is intended for use in specifications, so it is simpler than `permutations_aux2`, which plays roughly the same role in `permutations`. Note that `(permutations_aux2 t [] [] ts id).2` is similar to this function, but skips the last position: permutations'_aux 10 [1, 2, 3] = [[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3], [1, 2, 3, 10]] (permutations_aux2 10 [] [] [1, 2, 3] id).2 = [[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3]] -/ @[simp] def permutations'_aux (t : α) : list α → list (list α) | [] := [[t]] | (y::ys) := (t :: y :: ys) :: (permutations'_aux ys).map (cons y) /-- List of all permutations of `l`. This version of `permutations` is less efficient but has simpler definitional equations. The permutations are in a different order, but are equal up to permutation, as shown by `list.permutations_perm_permutations'`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]] -/ @[simp] def permutations' : list α → list (list α) | [] := [[]] | (t::ts) := (permutations' ts).bind $ permutations'_aux t end permutations /-- `erasep p l` removes the first element of `l` satisfying the predicate `p`. -/ def erasep (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then l else a :: erasep l /-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate `p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/ def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α | [] := (none, []) | (a::l) := if p a then (some a, l) else let (a', l') := extractp l in (a', a :: l') /-- `revzip l` returns a list of pairs of the elements of `l` paired with the elements of `l` in reverse order. `revzip [1,2,3,4,5] = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]` -/ def revzip (l : list α) : list (α × α) := zip l l.reverse /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a /- This notation binds more strongly than (pre)images, unions and intersections. -/ infixr (name := list.product) ` ×ˢ `:82 := list.product /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a /-- Auxliary definition used to define `of_fn`. `of_fn_aux f m h l` returns the first `m` elements of `of_fn f` appended to `l` -/ def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α | 0 h l := l | (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l) /-- `of_fn f` with `f : fin n → α` returns the list whose ith element is `f i` `of_fun f = [f 0, f 1, ... , f(n - 1)]` -/ def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] /-- `of_fn_nth_val f i` returns `some (f i)` if `i < n` and `none` otherwise. -/ def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : i < n then some (f ⟨i, h⟩) else none /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false section pairwise variables (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) variables {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ attribute [simp] pairwise.nil instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) := by induction l with hd tl ih; [exact is_true pairwise.nil, exactI decidable_of_iff' _ pairwise_cons] end pairwise /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function (cf. `dedup`), and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH section chain variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ inductive chain : α → list α → Prop | nil {a : α} : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) /-- `chain' R l` means that `R` holds between adjacent elements of `l`. chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ def chain' : list α → Prop | [] := true | (a :: l) := chain R a l variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ attribute [simp] chain.nil instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance instance decidable_chain' [decidable_rel R] (l : list α) : decidable (chain' R l) := by cases l; dunfold chain'; apply_instance end chain /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise /-- `dedup l` removes duplicates from `l` (taking only the last occurrence). Defined as `pw_filter (≠)`. dedup [1, 0, 2, 2, 1] = [0, 2, 1] -/ def dedup [decidable_eq α] : list α → list α := pw_filter (≠) /-- Greedily create a sublist of `a :: l` such that, for every two adjacent elements `a, b`, `R a b` holds. Mostly used with ≠; for example, `destutter' (≠) 1 [2, 2, 1, 1] = [1, 2, 1]`, `destutter' (≠) 1, [2, 3, 3] = [1, 2, 3]`, `destutter' (<) 1 [2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/ def destutter' (R : α → α → Prop) [decidable_rel R] : α → list α → list α | a [] := [a] | a (h :: l) := if R a h then a :: destutter' h l else destutter' a l /-- Greedily create a sublist of `l` such that, for every two adjacent elements `a, b ∈ l`, `R a b` holds. Mostly used with ≠; for example, `destutter (≠) [1, 2, 2, 1, 1] = [1, 2, 1]`, `destutter (≠) [1, 2, 3, 3] = [1, 2, 3]`, `destutter (<) [1, 2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/ def destutter (R : α → α → Prop) [decidable_rel R] : list α → list α | (h :: l) := destutter' R h l | [] := [] /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n /-- Drop `none`s from a list, and replace each remaining `some a` with `a`. -/ def reduce_option {α} : list (option α) → list α := list.filter_map id /-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty; it returns `x` otherwise -/ @[simp] def ilast' {α} : α → list α → α | a [] := a | a (b::l) := ilast' b l /-- `last' xs` returns the last element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def last' {α} : list α → option α | [] := none | [a] := some a | (b::l) := last' l /-- `rotate l n` rotates the elements of `l` to the left by `n` rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/ def rotate (l : list α) (n : ℕ) : list α := let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁ /-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/ def rotate' : list α → ℕ → list α | [] n := [] | l 0 := l | (a::l) (n+1) := rotate' (l ++ [a]) n section choose variables (p : α → Prop) [decidable_pred p] (l : list α) /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns both `a` and proofs of `a ∈ l` and `p a`. -/ def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } | [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left)) | (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp (λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in ⟨a, ⟨or.inr a_mem_ls, pa⟩⟩ /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns `a : α`, and properties are given by `choose_mem` and `choose_property`. -/ def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp end choose /-- Filters and maps elements of a list -/ def mmap_filter {m : Type → Type v} [monad m] {α β} (f : α → m (option β)) : list α → m (list β) | [] := return [] | (h :: t) := do b ← f h, t' ← t.mmap_filter, return $ match b with none := t' | (some x) := x::t' end /-- `mmap_upper_triangle f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. Example: suppose `l = [1, 2, 3]`. `mmap_upper_triangle f l` will produce the list `[f 1 1, f 1 2, f 1 3, f 2 2, f 2 3, f 3 3]`. -/ def mmap_upper_triangle {m} [monad m] {α β : Type u} (f : α → α → m β) : list α → m (list β) | [] := return [] | (h::t) := do v ← f h h, l ← t.mmap (f h), t ← t.mmap_upper_triangle, return $ (v::l) ++ t /-- `mmap'_diag f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. Example: suppose `l = [1, 2, 3]`. `mmap'_diag f l` will evaluate, in this order, `f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`. -/ def mmap'_diag {m} [monad m] {α} (f : α → α → m unit) : list α → m unit | [] := return () | (h::t) := f h h >> t.mmap' (f h) >> t.mmap'_diag protected def traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) : list α → F (list β) | [] := pure [] | (x :: xs) := list.cons <$> f x <*> traverse xs /-- `get_rest l l₁` returns `some l₂` if `l = l₁ ++ l₂`. If `l₁` is not a prefix of `l`, returns `none` -/ def get_rest [decidable_eq α] : list α → list α → option (list α) | l [] := some l | [] _ := none | (x::l) (y::l₁) := if x = y then get_rest l l₁ else none /-- `list.slice n m xs` removes a slice of length `m` at index `n` in list `xs`. -/ def slice {α} : ℕ → ℕ → list α → list α | 0 n xs := xs.drop n | (succ n) m [] := [] | (succ n) m (x :: xs) := x :: slice n m xs /-- Left-biased version of `list.map₂`. `map₂_left' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. Returns the results of the `f` applications and the remaining `bs`. ``` map₂_left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) map₂_left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b']) ``` -/ @[simp] def map₂_left' (f : α → option β → γ) : list α → list β → (list γ × list β) | [] bs := ([], bs) | (a :: as) [] := ((a :: as).map (λ a, f a none), []) | (a :: as) (b :: bs) := let rec := map₂_left' as bs in (f a (some b) :: rec.fst, rec.snd) /-- Right-biased version of `list.map₂`. `map₂_right' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. Returns the results of the `f` applications and the remaining `as`. ``` map₂_right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) map₂_right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2]) ``` -/ def map₂_right' (f : option α → β → γ) (as : list α) (bs : list β) : (list γ × list α) := map₂_left' (flip f) bs as /-- Left-biased version of `list.zip`. `zip_left' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. Also returns the remaining `bs`. ``` zip_left' [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) zip_left' [1] ['a', 'b'] = ([(1, some 'a')], ['b']) zip_left' = map₂_left' prod.mk ``` -/ def zip_left' : list α → list β → list (α × option β) × list β := map₂_left' prod.mk /-- Right-biased version of `list.zip`. `zip_right' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. Also returns the remaining `as`. ``` zip_right' [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) zip_right' [1, 2] ['a'] = ([(some 1, 'a')], [2]) zip_right' = map₂_right' prod.mk ``` -/ def zip_right' : list α → list β → list (option α × β) × list α := map₂_right' prod.mk /-- Left-biased version of `list.map₂`. `map₂_left f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. ``` map₂_left prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)] map₂_left prod.mk [1] ['a', 'b'] = [(1, some 'a')] map₂_left f as bs = (map₂_left' f as bs).fst ``` -/ @[simp] def map₂_left (f : α → option β → γ) : list α → list β → list γ | [] _ := [] | (a :: as) [] := (a :: as).map (λ a, f a none) | (a :: as) (b :: bs) := f a (some b) :: map₂_left as bs /-- Right-biased version of `list.map₂`. `map₂_right f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. ``` map₂_right prod.mk [1, 2] ['a'] = [(some 1, 'a')] map₂_right prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] map₂_right f as bs = (map₂_right' f as bs).fst ``` -/ def map₂_right (f : option α → β → γ) (as : list α) (bs : list β) : list γ := map₂_left (flip f) bs as /-- Left-biased version of `list.zip`. `zip_left as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. ``` zip_left [1, 2] ['a'] = [(1, some 'a'), (2, none)] zip_left [1] ['a', 'b'] = [(1, some 'a')] zip_left = map₂_left prod.mk ``` -/ def zip_left : list α → list β → list (α × option β) := map₂_left prod.mk /-- Right-biased version of `list.zip`. `zip_right as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. ``` zip_right [1, 2] ['a'] = [(some 1, 'a')] zip_right [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] zip_right = map₂_right prod.mk ``` -/ def zip_right : list α → list β → list (option α × β) := map₂_right prod.mk /-- If all elements of `xs` are `some xᵢ`, `all_some xs` returns the `xᵢ`. Otherwise it returns `none`. ``` all_some [some 1, some 2] = some [1, 2] all_some [some 1, none ] = none ``` -/ def all_some : list (option α) → option (list α) | [] := some [] | (some a :: as) := cons a <$> all_some as | (none :: as) := none /-- `fill_nones xs ys` replaces the `none`s in `xs` with elements of `ys`. If there are not enough `ys` to replace all the `none`s, the remaining `none`s are dropped from `xs`. ``` fill_nones [none, some 1, none, none] [2, 3] = [2, 1, 3] ``` -/ def fill_nones {α} : list (option α) → list α → list α | [] _ := [] | (some a :: as) as' := a :: fill_nones as as' | (none :: as) [] := as.reduce_option | (none :: as) (a :: as') := a :: fill_nones as as' /-- `take_list as ns` extracts successive sublists from `as`. For `ns = n₁ ... nₘ`, it first takes the `n₁` initial elements from `as`, then the next `n₂` ones, etc. It returns the sublists of `as` -- one for each `nᵢ` -- and the remaining elements of `as`. If `as` does not have at least as many elements as the sum of the `nᵢ`, the corresponding sublists will have less than `nᵢ` elements. ``` take_list ['a', 'b', 'c', 'd', 'e'] [2, 1, 1] = ([['a', 'b'], ['c'], ['d']], ['e']) take_list ['a', 'b'] [3, 1] = ([['a', 'b'], []], []) ``` -/ def take_list {α} : list α → list ℕ → list (list α) × list α | xs [] := ([], xs) | xs (n :: ns) := let ⟨xs₁, xs₂⟩ := xs.split_at n in let ⟨xss, rest⟩ := take_list xs₂ ns in (xs₁ :: xss, rest) /-- `to_rbmap as` is the map that associates each index `i` of `as` with the corresponding element of `as`. ``` to_rbmap ['a', 'b', 'c'] = rbmap_of [(0, 'a'), (1, 'b'), (2, 'c')] ``` -/ def to_rbmap {α : Type*} : list α → rbmap ℕ α := foldl_with_index (λ i mapp a, mapp.insert i a) (mk_rbmap ℕ α) /-- Auxliary definition used to define `to_chunks`. `to_chunks_aux n xs i` returns `(xs.take i, (xs.drop i).to_chunks (n+1))`, that is, the first `i` elements of `xs`, and the remaining elements chunked into sublists of length `n+1`. -/ def to_chunks_aux {α} (n : ℕ) : list α → ℕ → list α × list (list α) | [] i := ([], []) | (x::xs) 0 := let (l, L) := to_chunks_aux xs n in ([], (x::l)::L) | (x::xs) (i+1) := let (l, L) := to_chunks_aux xs i in (x::l, L) /-- `xs.to_chunks n` splits the list into sublists of size at most `n`, such that `(xs.to_chunks n).join = xs`. ``` [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 10 = [[1, 2, 3, 4, 5, 6, 7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 3 = [[1, 2, 3], [4, 5, 6], [7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 2 = [[1, 2], [3, 4], [5, 6], [7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 0 = [[1, 2, 3, 4, 5, 6, 7, 8]] ``` -/ def to_chunks {α} : ℕ → list α → list (list α) | _ [] := [] | 0 xs := [xs] | (n+1) (x::xs) := let (l, L) := to_chunks_aux n xs n in (x::l)::L /-- Asynchronous version of `list.map`. -/ meta def map_async_chunked {α β} (f : α → β) (xs : list α) (chunk_size := 1024) : list β := ((xs.to_chunks chunk_size).map (λ xs, task.delay (λ _, list.map f xs))).bind task.get /-! We add some n-ary versions of `list.zip_with` for functions with more than two arguments. These can also be written in terms of `list.zip` or `list.zip_with`. For example, `zip_with3 f xs ys zs` could also be written as `zip_with id (zip_with f xs ys) zs` or as `(zip xs $ zip ys zs).map $ λ ⟨x, y, z⟩, f x y z`. -/ /-- Ternary version of `list.zip_with`. -/ def zip_with3 (f : α → β → γ → δ) : list α → list β → list γ → list δ | (x::xs) (y::ys) (z::zs) := f x y z :: zip_with3 xs ys zs | _ _ _ := [] /-- Quaternary version of `list.zip_with`. -/ def zip_with4 (f : α → β → γ → δ → ε) : list α → list β → list γ → list δ → list ε | (x::xs) (y::ys) (z::zs) (u::us) := f x y z u :: zip_with4 xs ys zs us | _ _ _ _ := [] /-- Quinary version of `list.zip_with`. -/ def zip_with5 (f : α → β → γ → δ → ε → ζ) : list α → list β → list γ → list δ → list ε → list ζ | (x::xs) (y::ys) (z::zs) (u::us) (v::vs) := f x y z u v :: zip_with5 xs ys zs us vs | _ _ _ _ _ := [] /-- Given a starting list `old`, a list of booleans and a replacement list `new`, read the items in `old` in succession and either replace them with the next element of `new` or not, according as to whether the corresponding boolean is `tt` or `ff`. -/ def replace_if : list α → list bool → list α → list α | l _ [] := l | [] _ _ := [] | l [] _ := l | (n::ns) (tf::bs) e@(c::cs) := if tf then c :: ns.replace_if bs cs else n :: ns.replace_if bs e /-- An auxiliary function for `list.map_with_prefix_suffix`. -/ def map_with_prefix_suffix_aux {α β} (f : list α → α → list α → β) : list α → list α → list β | prev [] := [] | prev (h::t) := f prev h t :: map_with_prefix_suffix_aux (prev.concat h) t /-- `list.map_with_prefix_suffix f l` maps `f` across a list `l`. For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f pref a suff`. Example: if `f : list ℕ → ℕ → list ℕ → β`, `list.map_with_prefix_suffix f [1, 2, 3]` will produce the list `[f [] 1 [2, 3], f [1] 2 [3], f [1, 2] 3 []]`. -/ def map_with_prefix_suffix {α β} (f : list α → α → list α → β) (l : list α) : list β := map_with_prefix_suffix_aux f [] l /-- `list.map_with_complement f l` is a variant of `list.map_with_prefix_suffix` that maps `f` across a list `l`. For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f a (pref ++ suff)`, i.e., the list input to `f` is `l` with `a` removed. Example: if `f : ℕ → list ℕ → β`, `list.map_with_complement f [1, 2, 3]` will produce the list `[f 1 [2, 3], f 2 [1, 3], f 3 [1, 2]]`. -/ def map_with_complement {α β} (f : α → list α → β) : list α → list β := map_with_prefix_suffix $ λ pref a suff, f a (pref ++ suff) end list
9365db051fc6761b60d12e1498eb3e0c8cebb9b6
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/field_power.lean
cb78fd34547b3f298a1ea9b58e26d76aa7000757
[ "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
5,834
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 /-! # 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 neg_fpow_bit0 {K : Type*} [division_ring K] (x : K) (n : ℤ) : (-x) ^ (bit0 n) = x ^ bit0 n := by rw [fpow_bit0', fpow_bit0', neg_mul_neg] @[simp] lemma neg_fpow_bit1 {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] lemma fpow_nonneg_of_nonneg {a : K} (ha : 0 ≤ a) : ∀ (z : ℤ), 0 ≤ a ^ z | (of_nat n) := pow_nonneg ha _ | -[1+n] := inv_nonneg.2 $ pow_nonneg ha _ lemma fpow_pos_of_pos {a : K} (ha : 0 < a) : ∀ (z : ℤ), 0 < a ^ z | (of_nat n) := pow_pos ha _ | -[1+n] := 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 [fpow_of_nat, of_nat_eq_coe], 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 [fpow_neg_succ_of_nat, one_div], apply le_trans (inv_le_one _); apply one_le_pow_of_one_le hx }, { simp only [fpow_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 end ordered_field_power lemma one_lt_pow {K} [linear_ordered_semiring K] {p : K} (hp : 1 < p) : ∀ {n : ℕ}, 1 ≤ n → 1 < p ^ n | 1 h := by simp; assumption | (k+2) h := begin rw ←one_mul (1 : K), apply mul_lt_mul, { assumption }, { apply le_of_lt, simpa using one_lt_pow (nat.le_add_left 1 k)}, { apply zero_lt_one }, { apply le_of_lt (lt_trans zero_lt_one hp) } end section local attribute [semireducible] int.nonneg lemma one_lt_fpow {K} [linear_ordered_field K] {p : K} (hp : 1 < p) : ∀ z : ℤ, 0 < z → 1 < p ^ z | (int.of_nat n) h := one_lt_pow hp (nat.succ_le_of_lt (int.lt_of_coe_nat_lt_coe_nat h)) end 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 := by linarith, have h₀ : x ≠ 0 := by linarith, have hxm : 0 < x^m := fpow_pos_of_pos xpos m, have hxm₀ : x^m ≠ 0 := ne_of_gt hxm, suffices : 1 < x^(n-m), { replace := mul_lt_mul_of_pos_right this hxm, simp [sub_eq_add_neg] at this, simpa [*, fpow_add, mul_assoc, fpow_neg, inv_mul_cancel], }, apply one_lt_fpow hx, linarith, 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 lt_trichotomy x 1 with H|rfl|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], }, { contradiction }, { 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
7640c7ebb55c68d179aab4babfbaf2618cff6e9e
76ce87faa6bc3c2aa9af5962009e01e04f2a074a
/06_Negation/00_intro.lean
b9fa3b7ba2b3aa61ca80f4caee0cfbabb7ed132d
[]
no_license
Mnormansell/Discrete-Notes
db423dd9206bbe7080aecb84b4c2d275b758af97
61f13b98be590269fc4822be7b47924a6ddc1261
refs/heads/master
1,585,412,435,424
1,540,919,483,000
1,540,919,483,000
148,684,638
0
0
null
null
null
null
UTF-8
Lean
false
false
21,581
lean
/- * proposition built using ¬ * the formal meaning of ¬ * proofs of inequalities, ¬a=b * disjointness of constructors * strategy: proof by negation * inference rule: modus tollens * principle: non-contradiction * rule: negation elimination * axiom: excluded middle * classical vs constructive logic * double-negation elimination * proof by contradiction * proof by contrapositive -/ /- ********************** *** ¬ Introduction *** ********************** -/ /- In constructive logic, if we can construct a proof of a proposition, P, then we can judge it to be true. What does it mean in constructive logic for a proposition, P, to be false? It means that there is a proof that there can be no proof of P. The way we express this is that from a proof of P we could derive a contradiction: a proof of false. Because there can be no such thing, there must be no proof of P. In other words, to show that ¬ P is true we prove P → false. Indeed, the proposition ¬ P is just defined as the proposition P → false. A proof of P → false, as with any proof of an implication, will be given as a function: one that takes a proof of P as an argument and derives a proof of false. As there is no proof of false, such an argument cannot exist. From the existence of the function we conclude the non-existence of any proof of P: that is, ¬ P. From now on, when working in constructive logic, when you see a proof of a proposition, ¬ P, it is worthwhile viewing it as a value of type P → false, which is to say as a function taking proofs of P and returning proofs of false. -/ /- Check it: ¬ P is the same as P → false -/ variable P : Prop -- assume P is some Prop -- now show ¬ P = P → false from (using) rfl. theorem same : (¬ P) = (P → false) := rfl /- In previous chapters we've worked with many equality propositions. What about inequality propositions? By x ≠ y, we mean simply ¬ x = y. As an example, 0 ≠ 1 is just different notation for ¬ 0 = 1. Note that in Lean, = binds more tightly (has a higher precedence) than ¬, so ¬ 0 = 1 means ¬ (0 = 1), rather than (¬ 0) = 1. -/ /- Now in turn we understand ¬ 0 = 1 to mean 0 = 1 → false. How can we prove such an implication? We already know it will be with a function that derives a proof of false from a proof of 0 = 1. -/ /- The short, satisfying, but ultimately unenlightening answer is that Lean just knows that it's true. We write the proposition, then write a period, and Lean does the rest! Here it is. -/ theorem zneqo : 0 ≠ 1. -- note period #check zneqo theorem zneqoeqzneqo : (0 ≠ 1) = ¬(0 = 1) := rfl /- Note that the types, 0 ≠ 1, ¬ 0 = 1, and 0 = 1 → false, look different but in fact they are just different ways of expressing the same type. -/ /- We' now explain in a little more detail what's going on. How does "Lean know" there's a proof and how to construct it? We present the following elaborated proof, and then explain it after the code. They thing to focus on is that nat.no_confusion construct. It in turn is using what we call "disjointness of constructors" to construct a proof of false. Let's start by just looking at the actual proof of 0 ≠ 1, which we write here as 0 = 1 → false to make it clear that 0 ≠ 1 is really a proposition in the form of an implication. -/ #reduce nat.zero #reduce nat.succ(0) #reduce nat.succ(nat.succ(0)) theorem zneqo' : 0 = 1 → false := λ h : (0 = 1), nat.no_confusion h #check zneqo' /- You can see that the proof, being a proof of an implication, is in form of a function, as expected. The function takes an argument, h (a proof of 0 = 1). It then constructs and returns a proof of false. It constructs this proof by applying nat.no_confusion to h. The nat.no_confusion function, in turn, was generated by Lean when the nat type was defined. It was generated precisely to enable us to reason about inequalities of terms of type nat. -/ /- So, one major mystery remains here. What is nat.no_confusion really doing? The key to understanding is in a principle we haven't discussed yet. Let's look ahead just a little to see what it is. -/ /- Values of a type can be built by different "constructors" of that type. In particular, 0 and 1 are built by different constructors of the nat type. The nat type has two constructors: 0 is a nat, and if n is any nat, then succ n is a nat. In particular, 1 is actually just succ 0 (which we can read as "the successor of, one more than, 0".) The principle that nat.no_confusion uses is that values of a type that are built by different constructors are, by definition, never equal. We say that "constructors are disjoint" as a shorthand for saying that the sets of values generated by different constructors are disjoint, which is to say they have no values in common. Lean can thus tell immediately that it's impossible for 0 = 1 because the terms 0 and 1 were built by different constructors. The nat.no_confusion function is defined to return false if it could ever be given a proof of such an impossibility. Our proof of our theorem uses the no_confusion rule/principle that Lean provides, following from the definition of the nat type. From a proof of 0 = 1 we use nat.no_confusion to derive a proof of false, showing that 0 = 1 → false, thus ¬ 0 = 1, and thus 0 ≠ 1. -/ /- The Assume-Show-From proof pattern -/ /- Here's a equivalent tactic script for generating the same proof of 0 ≠ 1. -/ theorem zneqo'' : ¬ 0 = 1 := begin assume h : (0 = 1), show false, from nat.no_confusion h end /- This example introduces what we will call the "assume, show, from" proof pattern. The assume h corresponds to h being an argument of the function we are defining to prove ¬ 0 = 1. The show false states what is to be proved (the "return type"). And the from then provides the function body, the code that actually constructs the proof, using what has been assumed. Be sure to open the Messages View in VSCode, click through the script line by line, and watch how the tactic state changes. -/ /- Translation to an informal proof. -/ /- An English language rendition of this proof would go like this. We prove that 0 ≠ 1 by assuming 0 = 1 and by showing that this assumption leads to a contradiction. As that is impossible, there must be no such proof of 0 = 1. That proves ¬ 0 = 1, i.e., 0 ≠ 1. -/ /- Disjointness of Constructors in General -/ /- Proofs of inequalities for values of types other than nat can be produced using the no_confusion principles of the respective other types. Here's a proof that tt ≠ ff using the principle for the bool type. -/ theorem ttneqff' : ¬ tt = ff := begin assume h : (tt = ff), show false, from bool.no_confusion h end /- We're thankful we can use the period (dot) notation here as well. -/ theorem ttneqff : tt ≠ ff. /- EXERCISE: Is it true that "Hello, Lean!" ≠ "Hello Lean!"? Can you prove it? If so, how? If not, why not? EXERCISE: What about 2 ≠ 1? -/ /- *************************** *** Proof by Negation *** *************************** -/ /- We've thus got our introduction rule for ¬. To derive ¬ P, show that from an assumption of (a proof of P) some kind of contradiction that cannot occur, and thus a proof of false, would follow, leading to the conclusion that there must be no proof of P, that it isn't true, and that ¬ P therefore is true. This is called "proof by negation." -/ /- What are some of the consequence of the the understanding of negation that we've developed so far? Perhaps of the most important concept at this point is that we have a strategy for proving propositions of the form, ¬ P. Again, we call it "proof by negation." To use this strategy to prove ¬ P, we first assume that we P is true (we have a proof) and we show this leads to a contradiction (we can build a proof of false). That then justifies the conclusion that P is cannot be true, thus ¬ P. Negation introduction, or proof by negation, starts by assuming P, derives a contradiction, and concludes with ¬ P. Here's the principle in the form of a simple theorem that simply restates that from a proof of P → false we can derive ¬ P. Give the lambda expression a careful reading: it says, if you assume P is a proposition, and p is a proof of (P → false) then you can produce a proof of ¬ P, and it's just p itself. A value (function) of type P → false *is* a proof of ¬ P. This is the simple inference rule for ¬ introduction, and the "strategy" of proof by negation. -/ theorem proof_by_negation : ∀ P : Prop, (P → false) → ¬ P := λ (P: Prop) (p: P → false), p /- To show ¬ P, show that assuming P leads to a contradiction. That's just what we just did. Here's a more concrete example. -/ lemma zneqo''': ¬ (0 = 1) := begin apply proof_by_negation, assume h: (0 = 1), show false, from (nat.no_confusion h) end /- A classic example of a proof by negation is a proof that the square root of two is irrational. You have to analyze the English a little. This is really a proposition, P = "the square root of two is NOT rational, or ¬ (rational (sqrt 2)). To prove it "by negation", assume that the square root of two IS rational. From that, derive a contradiction. From that, conclude that the square root of two is not rational. And now you have proved it is irrational. -/ /- ********************* *** Modus Tollens *** ********************* -/ /- Aristotle's reasoning principle, modus tollens, allows one to deduce ¬ Q → ¬ P from P → Q. Here's an example: if you know that "if it's raining then the streets are wet" then you can deduce that "if the streets are not wet, it is not raining. -/ /- We first validate this rule by writing it as a function that takes a proof of P → Q and then it takes a proof of ¬ Q, and from it, it derives a proof of ¬ P. This shows that (P → Q) → (¬ Q → ¬ P). -/ theorem modus_tollens' { P Q : Prop } (pfPtoQ : P → Q) (pfnQ : ¬ Q) : ¬ P:= λ (pfP : P), pfnQ (pfPtoQ pfP) /- EXERCISE: present this same construction using a lambda expression. This presentation style makes the proposition, modus tollens, explicit: for all P and Q : Prop, (P → Q) → (¬ Q → ¬ P). Fill in the blank. -/ theorem modus_tollens: ∀ P Q: Prop, (P → Q) → (¬ Q → ¬ P) := λ (P Q: Prop) (pfPtoQ: P → Q), λ pfnQ : ¬ Q, λ pfP : P, pfnQ (pfPtoQ pfP) /- There are two ways to view the modus tollens rule. The first view is that the aim is to produce a proof of ¬ Q → ¬ P and the way it is done is to prove P → Q. The other view is that the aim is to produce a proof of ¬ P, and the way to do it is by proving both a proof of P → Q and a proof of ¬ Q. In the first case, the goal is ¬ Q → ¬ P, but of course the first step in proving this implication is to assume ¬ Q. So in the first approach, we assume ¬ Q by making (a value of type) ¬ Q an argument. In the second case, we assume ¬ Q using a lambda -- and you guessed it, ¬ Q is an argument. You should be sure you understand why these two theorems say the same things and why the proofs are really the same, even though they're presented a bit differently. -/ /- Let's use this strategy to prove ... EXAMPLE -/ /- *************************** **** Non-contradiction **** *************************** -/ /- The principle of non-contradiction says that a proof of any proposition, Q, and also of its negation, ¬ Q, gives rise to a contradiction, i.e., to a proof of false. Therefore such a contradiction cannot arise. That is, for any proposition Q, it's the case that ¬ (Q ∧ ¬ Q). -/ theorem no_contra : ∀ Q: Prop, ¬ (Q ∧ ¬ Q) := λ (Q : Prop) (pf : Q ∧ ¬ Q), (and.elim_right pf) (and.elim_left pf) #check no_contra variables a b : nat theorem ncab : ¬ ((a = b) ∧ (a ≠ b)) := begin apply no_contra end /- What happens when we apply no_contra here is that Lean matches up ((a = b) ∧ (a ≠ b)) with Q ∧ ¬ Q by matching up Q with (a = b), and then deriving false from the result to polish off the proof (false is a get out of jail free card). -/ /- A longer, less clear version that does the same thing. -/ theorem ncab' : ¬ ((a = b) ∧ (a ≠ b)) := begin assume c : ((a = b) ∧ (a ≠ b)), have l := c.1, -- short for left elim have r := c.2, -- same for right elim have f := r l, -- now a proof of false assumption -- and that proves it end /- The assumption tactic tells lean that the goal to be proved is already proved by an assumption in the context, so just go find it. Watch how the tactic state changes as you move through the proof script steps. -/ /- ******************************** *** NEGATION ELIMINATION *** ******************************** -/ /- What about negation elimination? Negation elimination works in a closely related way. Rather than deriving a contradiction from a proof of P and concluding ¬ P, you show that assuming ¬ P leads to a contraction, thus to the conclusion that ¬ P is false, there can be no proof it, thus ¬ ¬ P; and then, by the principle of double negation elimination one deduces that P must be true. This is called proving P by contradiction. Proof by contradiction is not accepted as a valid principle in constructive logic, because it relies on ¬ ¬ P → P. This issue is that this rule is not constructive. To see the problem, expand the ¬ signs into their corresponding arrow notations. Then ¬ ¬ P, ¬ (¬ P), is ((P → false) → false). P → ¬ ¬ P means P → (false) → ¬ P means P → What this says is that from a function that converts assumed proofs of P into proofs of false, one can derive a proof of false: there can be no function of this kind. But no where buried in any of this is an actual proof of P to be found! There's no way to convert a function of type ((P → false) → false) into a proof of P, so there is no proof of ¬ ¬ P → P. That is, double negation elimination is not a valid inference rule in constructive logic. Because proofs by contradiction rely on double negation elimination, they are not valid or available either in a constructive logic, such as Lean's. Lean can be extended by a single axiom, however, to make it classical, rather than constructive. One simple asserts the law of the excluded middle. P : Prop -------- P ∨ ¬ P axiom excluded_middle: ∀ P : Prop, P ∨ ¬ P -/ /- ******************************* ** Classical Excluded Middle ** ******************************* -/ /- In constructive logic, a proof of ¬ P is a proof of P → false, which we interpret as a proof that there can be no proof of P. A proof of ¬ ¬ P is thus a proof that there is no proof of ¬ P. In a constructive logic, however, knowing that there no proof of ¬ P is not the same as having a proof of P. In symbolic terms, from the assumption that (P → false) → false (in one view a proof that there can be no program that converts proofs of P into proofs of false), you can't derive a proof of P. -/ axiom excluded_middle : ∀ P, P ∨ ¬ P axiom excluded_middle' (P : Prop) : P ∨ ¬ P /- The axiom of the excluded middle is thus added to the other rules of the constructive logic of Lean, making the logic classical. We gain an ability to prove more theorems, at the cost of a loss of constructiveness. (We don't need a proof of either P or of not P to derive a proof of P ∨ ¬ P. Thus no proof of either P or of ¬ P can be obtained from a proof of P ∨ ¬ P. In our constructive logic, as we will see soon, in our constructive logic a proof of P ∨ ¬ P has to contain either a proof of P or a proof of ¬ P. The elimination rule gets us back to these proofs in a certain way. -/ /- ********************************* ** Double Negation Elimination ** ********************************* -/ /- What the axiom of the excluded middle let's you assume is that there are only two possibilities: either P or ¬ P, so because ¬ ¬ P is clearly not ¬ P, the only remaining possibility is that it is P, so it must be P. Thus ¬ ¬ P is P. -/ theorem double_neg_elim: ∀ { P }, ¬ ¬ P → P := begin assume P : Prop, assume pfNotNotP : ¬ ¬ P, cases excluded_middle P, show P, from h, have f: false := pfNotNotP h, exact false.elim f end /- THe proof uses a technique that we haven't discussed yet: by case analysis. For now it is enough to see that the principle can be proved, at least if one accepts excluded middle. -/ variable notNotP : ¬ ¬ P -- assume ¬ ¬ P -- derive P by double negation elimination theorem pfP : P := double_neg_elim notNotP /- Note: the expression double_neg_elim notNotP takes advantage of the type inference that we asked for by surrounding { P } with the curly braces in the statement of the theorem. -/ /- ****************************** *** Proof By Contradiction *** ****************************** -/ /- We thus have the fundamental classical logical "strategy" of proof by contradiction. Read the proposition. If assuming ¬ P leads to a contradiction, then P must be true. The reliance on double elimination is clear. The term ¬ P → false is the same as ¬ ¬ P. The natural reasoning is like this: if ¬ P leads to a contraction then it must be true that ¬ P is not true, so ¬ ¬ P must be. But this, by classical double negation elimination, is just P, so P must be true. This is negation elimination in the sense that one starts with an assumption of ¬ P and concludes with P, albeit by way of ¬ ¬ P. A proof by contradiction aims to prove P. -/ theorem proof_by_contradiction : ∀ P : Prop, (¬ P → false) → P := @double_neg_elim /- The @ here turns off type inferencing for this one reference to double_neg_elim. It is a detail here. We'll discuss @ later. The point is that proof by contradiction relies on double negation elimination. -/ /- Proving in Lean that these laws are valid might seem unmotivated at first. But once we have these rules, we can use them as our own higher-level inference rules. Here's a proof by contradiction of 0 = 0. The goal to start is a proof of 0 = 0. By applying our proof_by_contradiction theorem to effect backwards (through the theorem) reasoning, we convert the goal of showing 0 = 0 into the goal of showing that ¬ 0 = 0 → false. This is exactly the strategy of a proof by contradiction. The rest of our script does the construction of false from the assumed proof of 0 = 0 → false. We just use eq.refl 0 to produce a proof of 0 = 0, to which we then apply this function, yielding a false. -/ theorem zeqz : 0 = 0 := begin apply proof_by_contradiction, assume pf: 0 = 0 → false, show false, from pf (eq.refl 0) end /- The standard method for introducing the law of the excluded middle, so as to enable classical reasoning, in Lean, is to use the "open classical" command to make various classical axioms and derived theorems available for use. -/ open classical /- The example keyword lets us write a theorem without giving it a name. It is useful for giving examples! -/ example { P Q : Prop } (pf: ¬ P → (Q ∧ ¬ Q)) : P := begin apply proof_by_contradiction, assume notP: ¬ P, have contra := (pf notP), show false, from no_contra Q contra end /- Remember: To use proof by contradiction we have to use the axiom (or the so-called "law") of the excluded middle. Clearly it's optional as a "law", as constructive logic does without it. We thus generally call it the *axiom* of the excluded middle. Take it if you're classicist; leave it if you're constructivist. -/ /- ***************************** ** Proof By Contrapositive ** ***************************** -/ /- The aim in a proof by contrapositive is to show P ∧ Q from an assumption of ¬ P ∧ ¬ Q, i.e., (¬ Q → ¬ P) → (P → Q). Another way to view this rule is that it aims to show Q from, first, a proof of ¬ Q → ¬ P, and, second, a proof of P. The way to think about this latter view is that it says, if Q being false implies that P is false, and if we know that P is true, then Q must not be false and so (by the axiom of the excluded middle) Q must be true. -/ theorem proof_by_contrapositive: ∀ P Q : Prop, (¬ Q → ¬ P) → (P → Q) := begin assume P Q: Prop, assume nqnp: (¬ Q → ¬ P), assume p : P, have nqf : ¬ Q → false := λ nq : ¬ Q, no_contra P (and.intro p (nqnp nq)), have nnq : ¬ ¬ Q := nqf, show Q, from double_neg_elim nnq end /- http://zimmer.csufresno.edu/~larryc/proofs/proofs.contrapositive.html -/ theorem zeqz' : 0 = 0 → true := begin apply proof_by_contrapositive, assume nt : ¬true, have pff := nt true.intro, show ¬ 0 = 0, from false.elim pff end /- Compare what by_contrapositive does to goal with what by_contradiction does to the goal. -/ theorem zeqz'' : 0 = 0 → true := begin apply proof_by_contradiction (0 = 0 → true), sorry end /- EXERCISE: Does it appear that one needs to use proof by contradiction (and thus classical, non-constructive, reasoning) to prove that the square root of two is irrational? -/
b4e747a1ac5c52c3e99db9fdf32d28a04edcf20b
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/multiplication/4.lean
30be0d86965e220604adf03df5d9abcb9c007139
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
172
lean
lemma mul_add (t a b : mynat) : t * (a + b) = t * a + t * b := induction a with n hn, rw mul_zero, simp, rw succ_add, repeat {rw mul_succ}, rw hn, simp, end
ae50a0da9c12f7fb39bfa1e6a28b96d672d8ae90
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/geometry/manifold/whitney_embedding.lean
c47bcd133c47e9b2dd3cb05d1da9289946c3314c
[ "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
6,508
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import geometry.manifold.diffeomorph import geometry.manifold.instances.real import geometry.manifold.partition_of_unity /-! # Whitney embedding theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. ## TODO * Prove the weak Whitney embedding theorem: any `σ`-compact smooth `m`-dimensional manifold can be embedded into `ℝ^(2m+1)`. This requires a version of Sard's theorem: for a locally Lipschitz continuous map `f : ℝ^m → ℝ^n`, `m < n`, the range has Hausdorff dimension at most `m`, hence it has measure zero. ## Tags partition of unity, smooth bump function, whitney theorem -/ universes uι uE uH uM variables {ι : Type uι} {E : Type uE} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {H : Type uH} [topological_space H] {I : model_with_corners ℝ E H} {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] open function filter finite_dimensional set open_locale topology manifold classical filter big_operators noncomputable theory namespace smooth_bump_covering /-! ### Whitney embedding theorem In this section we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. -/ variables [t2_space M] [hi : fintype ι] {s : set M} (f : smooth_bump_covering ι I M s) include hi /-- Smooth embedding of `M` into `(E × ℝ) ^ ι`. -/ def embedding_pi_tangent : C^∞⟮I, M; 𝓘(ℝ, ι → (E × ℝ)), ι → (E × ℝ)⟯ := { val := λ x i, (f i x • ext_chart_at I (f.c i) x, f i x), property := cont_mdiff_pi_space.2 $ λ i, ((f i).smooth_smul cont_mdiff_on_ext_chart_at).prod_mk_space ((f i).smooth) } local attribute [simp] lemma embedding_pi_tangent_coe : ⇑f.embedding_pi_tangent = λ x i, (f i x • ext_chart_at I (f.c i) x, f i x) := rfl lemma embedding_pi_tangent_inj_on : inj_on f.embedding_pi_tangent s := begin intros x hx y hy h, simp only [embedding_pi_tangent_coe, funext_iff] at h, obtain ⟨h₁, h₂⟩ := prod.mk.inj_iff.1 (h (f.ind x hx)), rw [f.apply_ind x hx] at h₂, rw [← h₂, f.apply_ind x hx, one_smul, one_smul] at h₁, have := f.mem_ext_chart_at_source_of_eq_one h₂.symm, exact (ext_chart_at I (f.c _)).inj_on (f.mem_ext_chart_at_ind_source x hx) this h₁ end lemma embedding_pi_tangent_injective (f : smooth_bump_covering ι I M) : injective f.embedding_pi_tangent := injective_iff_inj_on_univ.2 f.embedding_pi_tangent_inj_on lemma comp_embedding_pi_tangent_mfderiv (x : M) (hx : x ∈ s) : ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (f.ind x hx))).comp (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x) = mfderiv I I (chart_at H (f.c (f.ind x hx))) x := begin set L := ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (f.ind x hx))), have := L.has_mfderiv_at.comp x f.embedding_pi_tangent.mdifferentiable_at.has_mfderiv_at, convert has_mfderiv_at_unique this _, refine (has_mfderiv_at_ext_chart_at I (f.mem_chart_at_ind_source x hx)).congr_of_eventually_eq _, refine (f.eventually_eq_one x hx).mono (λ y hy, _), simp only [embedding_pi_tangent_coe, continuous_linear_map.coe_comp', (∘), continuous_linear_map.coe_fst', continuous_linear_map.proj_apply], rw [hy, pi.one_apply, one_smul] end lemma embedding_pi_tangent_ker_mfderiv (x : M) (hx : x ∈ s) : linear_map.ker (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x) = ⊥ := begin apply bot_unique, rw [← (mdifferentiable_chart I (f.c (f.ind x hx))).ker_mfderiv_eq_bot (f.mem_chart_at_ind_source x hx), ← comp_embedding_pi_tangent_mfderiv], exact linear_map.ker_le_ker_comp _ _ end lemma embedding_pi_tangent_injective_mfderiv (x : M) (hx : x ∈ s) : injective (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x) := linear_map.ker_eq_bot.1 (f.embedding_pi_tangent_ker_mfderiv x hx) omit hi /-- Baby version of the **Whitney weak embedding theorem**: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be immersed into the `n`-dimensional Euclidean space. -/ lemma exists_immersion_euclidean [finite ι] (f : smooth_bump_covering ι I M) : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ injective e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin casesI nonempty_fintype ι, set F := euclidean_space ℝ (fin $ finrank ℝ (ι → (E × ℝ))), letI : is_noetherian ℝ (E × ℝ) := is_noetherian.iff_fg.2 infer_instance, letI : finite_dimensional ℝ (ι → E × ℝ) := is_noetherian.iff_fg.1 infer_instance, set eEF : (ι → (E × ℝ)) ≃L[ℝ] F := continuous_linear_equiv.of_finrank_eq finrank_euclidean_space_fin.symm, refine ⟨_, eEF ∘ f.embedding_pi_tangent, eEF.to_diffeomorph.smooth.comp f.embedding_pi_tangent.smooth, eEF.injective.comp f.embedding_pi_tangent_injective, λ x, _⟩, rw [mfderiv_comp _ eEF.differentiable_at.mdifferentiable_at f.embedding_pi_tangent.mdifferentiable_at, eEF.mfderiv_eq], exact eEF.injective.comp (f.embedding_pi_tangent_injective_mfderiv _ trivial) end end smooth_bump_covering /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be embedded into the `n`-dimensional Euclidean space. -/ lemma exists_embedding_euclidean_of_compact [t2_space M] [compact_space M] : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ closed_embedding e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin rcases smooth_bump_covering.exists_is_subordinate I is_closed_univ (λ (x : M) _, univ_mem) with ⟨ι, f, -⟩, haveI := f.fintype, rcases f.exists_immersion_euclidean with ⟨n, e, hsmooth, hinj, hinj_mfderiv⟩, exact ⟨n, e, hsmooth, hsmooth.continuous.closed_embedding hinj, hinj_mfderiv⟩ end
d72435189689a93cb85b59c5b012286c587db244
4727251e0cd73359b15b664c3170e5d754078599
/src/data/rbtree/basic.lean
a9b4f43579a2e1d71b85931319fb33b5ab4a6f22
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,831
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import tactic.interactive import data.rbtree.init universe u meta def tactic.interactive.blast_disjs : tactic unit := `[cases_type* or] namespace rbnode variables {α : Type u} open color nat inductive is_node_of : rbnode α → rbnode α → α → rbnode α → Prop | of_red (l v r) : is_node_of (red_node l v r) l v r | of_black (l v r) : is_node_of (black_node l v r) l v r def lift (lt : α → α → Prop) : option α → option α → Prop | (some a) (some b) := lt a b | _ _ := true inductive is_searchable (lt : α → α → Prop) : rbnode α → option α → option α → Prop | leaf_s {lo hi} (hlt : lift lt lo hi) : is_searchable leaf lo hi | red_s {l r v lo hi} (hs₁ : is_searchable l lo (some v)) (hs₂ : is_searchable r (some v) hi) : is_searchable (red_node l v r) lo hi | black_s {l r v lo hi} (hs₁ : is_searchable l lo (some v)) (hs₂ : is_searchable r (some v) hi) : is_searchable (black_node l v r) lo hi meta def is_searchable_tactic : tactic unit := `[ constructor_matching* [is_searchable _ leaf _ _, is_searchable _ (red_node _ _ _) _ _, is_searchable _ (black_node _ _ _) _ _]; cases_matching* [is_searchable _ leaf _ _, is_searchable _ (red_node _ _ _) _ _, is_searchable _ (black_node _ _ _) _ _]; try { assumption } ] open rbnode (mem) open is_searchable section is_searchable_lemmas variable {lt : α → α → Prop} lemma lo_lt_hi {t : rbnode α} {lt} [is_trans α lt] : ∀ {lo hi}, is_searchable lt t lo hi → lift lt lo hi := begin induction t; intros lo hi hs, case leaf { cases hs, assumption }, all_goals { cases hs, have h₁ := t_ih_lchild hs_hs₁, have h₂ := t_ih_rchild hs_hs₂, cases lo; cases hi; simp [lift] at *, apply trans_of lt h₁ h₂, } end lemma is_searchable_of_is_searchable_of_incomp [is_strict_weak_order α lt] {t} : ∀ {lo hi hi'} (hc : ¬ lt hi' hi ∧ ¬ lt hi hi') (hs : is_searchable lt t lo (some hi)), is_searchable lt t lo (some hi') := begin classical, induction t; intros; is_searchable_tactic, { cases lo; simp [lift, *] at *, apply lt_of_lt_of_incomp, assumption, exact ⟨hc.2, hc.1⟩ }, all_goals { apply t_ih_rchild hc hs_hs₂ } end lemma is_searchable_of_incomp_of_is_searchable [is_strict_weak_order α lt] {t} : ∀ {lo lo' hi} (hc : ¬ lt lo' lo ∧ ¬ lt lo lo') (hs : is_searchable lt t (some lo) hi), is_searchable lt t (some lo') hi := begin classical, induction t; intros; is_searchable_tactic, { cases hi; simp [lift, *] at *, apply lt_of_incomp_of_lt, assumption, assumption }, all_goals { apply t_ih_lchild hc hs_hs₁ } end lemma is_searchable_some_low_of_is_searchable_of_lt {t} [is_trans α lt] : ∀ {lo hi lo'} (hlt : lt lo' lo) (hs : is_searchable lt t (some lo) hi), is_searchable lt t (some lo') hi := begin induction t; intros; is_searchable_tactic, { cases hi; simp [lift, *] at *, apply trans_of lt hlt, assumption }, all_goals { apply t_ih_lchild hlt hs_hs₁ } end lemma is_searchable_none_low_of_is_searchable_some_low {t} : ∀ {y hi} (hlt : is_searchable lt t (some y) hi), is_searchable lt t none hi := begin induction t; intros; is_searchable_tactic, { simp [lift] }, all_goals { apply t_ih_lchild hlt_hs₁ } end lemma is_searchable_some_high_of_is_searchable_of_lt {t} [is_trans α lt] : ∀ {lo hi hi'} (hlt : lt hi hi') (hs : is_searchable lt t lo (some hi)), is_searchable lt t lo (some hi') := begin induction t; intros; is_searchable_tactic, { cases lo; simp [lift, *] at *, apply trans_of lt, assumption, assumption}, all_goals { apply t_ih_rchild hlt hs_hs₂ } end lemma is_searchable_none_high_of_is_searchable_some_high {t} : ∀ {lo y} (hlt : is_searchable lt t lo (some y)), is_searchable lt t lo none := begin induction t; intros; is_searchable_tactic, { cases lo; simp [lift] }, all_goals { apply t_ih_rchild hlt_hs₂ } end lemma range [is_strict_weak_order α lt] {t : rbnode α} {x} : ∀ {lo hi}, is_searchable lt t lo hi → mem lt x t → lift lt lo (some x) ∧ lift lt (some x) hi := begin classical, induction t, case leaf { simp [mem] }, all_goals { -- red_node and black_node are identical intros lo hi h₁ h₂, cases h₁, simp only [mem] at h₂, have val_hi : lift lt (some t_val) hi, { apply lo_lt_hi, assumption }, have lo_val : lift lt lo (some t_val), { apply lo_lt_hi, assumption }, blast_disjs, { have h₃ : lift lt lo (some x) ∧ lift lt (some x) (some t_val), { apply t_ih_lchild, assumption, assumption }, cases h₃ with lo_x x_val, split, show lift lt lo (some x), { assumption }, show lift lt (some x ) hi, { cases hi with hi; simp [lift] at *, apply trans_of lt x_val val_hi } }, { cases h₂, cases lo with lo; cases hi with hi; simp [lift] at *, { apply lt_of_incomp_of_lt _ val_hi, simp [*] }, { apply lt_of_lt_of_incomp lo_val, simp [*] }, split, { apply lt_of_lt_of_incomp lo_val, simp [*] }, { apply lt_of_incomp_of_lt _ val_hi, simp [*] } }, { have h₃ : lift lt (some t_val) (some x) ∧ lift lt (some x) hi, { apply t_ih_rchild, assumption, assumption }, cases h₃ with val_x x_hi, cases lo with lo; cases hi with hi; simp [lift] at *, { assumption }, { apply trans_of lt lo_val val_x }, split, { apply trans_of lt lo_val val_x, }, { assumption } } } end lemma lt_of_mem_left [is_strict_weak_order α lt] {y : α} {t l r : rbnode α} : ∀ {lo hi}, is_searchable lt t lo hi → is_node_of t l y r → ∀ {x}, mem lt x l → lt x y := begin intros _ _ hs hn x hm, cases hn; cases hs, all_goals { exact (range hs_hs₁ hm).2 } end lemma lt_of_mem_right [is_strict_weak_order α lt] {y : α} {t l r : rbnode α} : ∀ {lo hi}, is_searchable lt t lo hi → is_node_of t l y r → ∀ {z}, mem lt z r → lt y z := begin intros _ _ hs hn z hm, cases hn; cases hs, all_goals { exact (range hs_hs₂ hm).1 } end lemma lt_of_mem_left_right [is_strict_weak_order α lt] {y : α} {t l r : rbnode α} : ∀ {lo hi}, is_searchable lt t lo hi → is_node_of t l y r → ∀ {x z}, mem lt x l → mem lt z r → lt x z := begin intros _ _ hs hn x z hm₁ hm₂, cases hn; cases hs, all_goals { have h₁ := range hs_hs₁ hm₁, have h₂ := range hs_hs₂ hm₂, exact trans_of lt h₁.2 h₂.1, } end end is_searchable_lemmas inductive is_red_black : rbnode α → color → nat → Prop | leaf_rb : is_red_black leaf black 0 | red_rb {v l r n} (rb_l : is_red_black l black n) (rb_r : is_red_black r black n) : is_red_black (red_node l v r) red n | black_rb {v l r n c₁ c₂} (rb_l : is_red_black l c₁ n) (rb_r : is_red_black r c₂ n) : is_red_black (black_node l v r) black (succ n) open is_red_black lemma depth_min : ∀ {c n} {t : rbnode α}, is_red_black t c n → n ≤ depth min t := begin intros c n' t h, induction h, case leaf_rb {exact le_refl _}, case red_rb { simp [depth], have : min (depth min h_l) (depth min h_r) ≥ h_n, { apply le_min; assumption }, apply le_succ_of_le, assumption }, case black_rb { simp [depth], apply succ_le_succ, apply le_min; assumption } end private def upper : color → nat → nat | red n := 2*n + 1 | black n := 2*n private lemma upper_le : ∀ c n, upper c n ≤ 2 * n + 1 | red n := by exact le_refl _ | black n := by apply le_succ lemma depth_max' : ∀ {c n} {t : rbnode α}, is_red_black t c n → depth max t ≤ upper c n := begin intros c n' t h, induction h, case leaf_rb { simp [max, depth, upper, nat.mul_zero] }, case red_rb { suffices : succ (max (depth max h_l) (depth max h_r)) ≤ 2 * h_n + 1, { simp [depth, upper, *] at * }, apply succ_le_succ, apply max_le; assumption }, case black_rb { have : depth max h_l ≤ 2*h_n + 1, from le_trans h_ih_rb_l (upper_le _ _), have : depth max h_r ≤ 2*h_n + 1, from le_trans h_ih_rb_r (upper_le _ _), suffices new : max (depth max h_l) (depth max h_r) + 1 ≤ 2 * h_n + 2*1, { simp [depth, upper, succ_eq_add_one, nat.left_distrib, *] at * }, apply succ_le_succ, apply max_le; assumption } end lemma depth_max {c n} {t : rbnode α} (h : is_red_black t c n) : depth max t ≤ 2 * n + 1:= le_trans (depth_max' h) (upper_le _ _) lemma balanced {c n} {t : rbnode α} (h : is_red_black t c n) : depth max t ≤ 2 * depth min t + 1 := begin have : 2 * depth min t + 1 ≥ 2 * n + 1, { apply succ_le_succ, apply nat.mul_le_mul_left, apply depth_min h }, apply le_trans, apply depth_max h, apply this end end rbnode
9e83f240d95abb586674e19c05dadf6924c1a034
9845f9502cdf644282e3a34b74fa995fc33d6752
/REDUNDANCY[VS].lean
35dc8ae5e042aa2a40feadd01cf3bb60fdb50f48
[]
no_license
Robilsu/Theorem-of-Branch-Redundancy
cc430d761dade4bb723c88a2a8709b7e47081171
918803bc047f2340e0f01d470939d077f7acefce
refs/heads/main
1,691,744,940,519
1,632,346,370,000
1,632,346,370,000
365,813,983
0
0
null
null
null
null
UTF-8
Lean
false
false
90,516
lean
reserve prefix `#` : 9999 -- #_ reserve infix ` >> ` : 1000 -- _ >> _ /- Useful Properties -/ namespace use universes u v /- Proofs from L∃∀N's library regarding negation, conjunction, and disjunction -/ lemma Not_Or {a b : Prop} : ¬ a → ¬ b → ¬ (a ∨ b) | hna hnb (or.inl ha) := absurd ha hna | hna hnb (or.inr hb) := absurd hb hnb lemma Not_Or_iff_And_Not (p q) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := false.elim $ h (or.inl h₁) | is_false h₁ := match d₂ with | is_true h₂ := false.elim $ h (or.inr h₂) | is_false h₂ := ⟨h₁, h₂⟩ end end) (λ ⟨np, nq⟩ h, or.elim h np nq) /- Proving the distributive property of "IF-THEN-ELSE" -/ lemma ITE_Distribution {α : Type u}{β : Type v} {IF : Prop}{THEN ELSE : α} [decIF : decidable IF] : ∀(f : α → β), --------------------------- ( f (ite IF THEN ELSE) = ite IF (f THEN) (f ELSE) ) := begin with_cases { by_cases IFs : IF }, case pos { simp [IFs] }, case neg { simp [IFs] } end /- Useful properties regarding Products -/ lemma EQ_Prod_iff_EQ_and_EQ {α : Type u} {β : Type v} : ∀{a1 a2 : α}{b1 b2 : β}, --------------------------- ( (a1,b1) = (a2,b2) ) ↔ ( (a1 = a2) ∧ (b1 = b2) ) | a1 a2 b1 b2 := begin have case_to : ∀{a1 a2 : α}{b1 b2 : β}, (a1,b1) = (a2,b2) → (a1 = a2) ∧ (b1 = b2), from begin assume a1 a2 b1 b2 eq_prod, from prod.mk.inj eq_prod end, have case_from : ∀{a1 a2 : α}{b1 b2 : β}, (a1 = a2) ∧ (b1 = b2) → (a1,b1) = (a2,b2), from begin assume a1 a2 b1 b2 and_eq, simp [and_eq] end, from iff.intro case_to case_from end /- Useful properties regarding Lists -/ lemma Index_LT_Length_of_Mem {α : Type u} [eqα : decidable_eq α] : ∀{a : α}{l : list α}, ( a ∈ l ) → --------------------------- ( list.index_of a l < list.length l ) | a [] := begin assume a_mem, simp [has_mem.mem, list.mem] at a_mem, from false.elim a_mem end | a (HEAD::TAIL) := begin assume a_mem, simp [has_mem.mem, list.mem] at a_mem, simp [list.index_of, list.find_index, list.length], with_cases { by_cases a_eq_head : a = HEAD }, case pos { simp [a_eq_head], have one_le_succ, from nat.add_le_add_left (nat.zero_le (list.length TAIL)) 1, rewrite [nat.add_zero] at one_le_succ, from nat.lt_of_lt_of_le nat.zero_lt_one one_le_succ }, case neg { simp [a_eq_head] at ⊢ a_mem, rewrite [nat.succ_eq_add_one, add_comm], have loop, from Index_LT_Length_of_Mem a_mem, from nat.add_le_add_left loop 1 } end lemma Mem_Remove_of_Mem_of_Not_Mem {α : Type u} [eqα : decidable_eq α] : ∀{nth : α}{l1 l2 : list α}, ( nth ∉ l1 ) → ( nth ∈ l2 ) → --------------------------- ( ∀(a : α), a ∈ l1 → a ∈ l2 → a ∈ list.remove_nth l2 (list.index_of nth l2) ) | nth l1 [] := begin assume nth_not_l1 nth_mem_l2, simp [has_mem.mem, list.mem] at nth_mem_l2, from false.elim nth_mem_l2 end | nth l1 (HEAD2::TAIL2) := begin assume nth_not_l1 nth_mem_l2, simp [list.index_of, list.find_index], with_cases { by_cases nth_eq_head2 : nth = HEAD2 }, case pos { simp [nth_eq_head2] at ⊢ nth_not_l1, simp [list.index_of, list.find_index, list.remove_nth], have case_loop : ∀(a : α), a ∈ l1 → a ∈ (HEAD2::TAIL2) → a ∈ TAIL2, from begin assume loop loop_mem_l1 loop_mem_l2, simp [has_mem.mem, list.mem] at loop_mem_l2, cases loop_mem_l2 with loop_eq_head2 loop_mem_tail2, case or.inl { rewrite [loop_eq_head2] at loop_mem_l1, from absurd loop_mem_l1 nth_not_l1 }, case or.inr { from loop_mem_tail2 } end, from case_loop }, case neg { simp [nth_eq_head2] at ⊢ nth_mem_l2, simp [list.remove_nth], have case_loop : ∀(a : α), a ∈ l1 → a ∈ (HEAD2::TAIL2) → a = HEAD2 ∨ a ∈ list.remove_nth TAIL2 (list.find_index (eq nth) TAIL2), from begin assume loop loop_mem_l1 loop_mem_l2, simp [has_mem.mem, list.mem] at loop_mem_l2, cases loop_mem_l2 with loop_eq_head2 loop_mem_tail2, case or.inl { simp [loop_eq_head2] }, case or.inr { apply (or.intro_right), from Mem_Remove_of_Mem_of_Not_Mem nth_not_l1 nth_mem_l2 loop loop_mem_l1 loop_mem_tail2 } end, from case_loop } end lemma Subset_Self {α : Type u} : ∀(l : list α), --------------------------- ( ∀(a : α), ( a ∈ l ) → ( a ∈ l ) ) | l := begin have subset_self : ∀(a : α), a ∈ l → a ∈ l, from begin assume a a_mem_l, from a_mem_l end, from subset_self end /- Lemmata taken from L∃∀N's library about Lists -/ lemma EQ_NIL_of_Length_EQ_ZERO {α : Type u} : ∀{l : list α}, ( list.length l = 0 ) → --------------------------- ( l = [] ) | l := by from list.eq_nil_of_length_eq_zero lemma Mem_Append {α : Type u} : ∀{a : α}{l1 l2 : list α}, --------------------------- ( list.mem a (l1++l2) ) ↔ ( (list.mem a l1) ∨ (list.mem a l2) ) | a l1 l2 := by from list.mem_append lemma Length_Remove_Nth {α : Type u} : ∀{l : list α}{n : ℕ}, ( n < list.length l ) → --------------------------- ( list.length (list.remove_nth l n) = list.length l - 1 ) | l n := by from list.length_remove_nth l n /- Useful properties regarding Natural Numbers (Must be in Order) -/ lemma EQ_of_LT_ONE_of_GE : ∀{a b : ℕ}, ( a ≥ b ) → ( a < 1 + b ) → --------------------------------- ( a = b ) | 0 0 := begin assume a_ge_b a_lt_oneb, from refl 0 end | (a+1) 0 := begin assume a_ge_b a_lt_oneb, rewrite [add_comm] at a_lt_oneb, have zero_lt_a, from lt_of_add_lt_add_left a_lt_oneb, have not_zero_lt_a, from nat.not_lt_zero a, from absurd zero_lt_a not_zero_lt_a end | 0 (b+1) := begin assume a_ge_b a_lt_oneb, have zero_le_b, from nat.zero_le b, have b_le_oneb, from le_trans a_ge_b zero_le_b, rewrite [nat.add_one] at b_le_oneb, from absurd b_le_oneb (nat.not_succ_le_self b) end | (a+1) (b+1) := begin assume a_ge_b a_lt_oneb, have loop_ge : a ≥ b , from nat.le_of_succ_le_succ a_ge_b, rewrite [add_comm] at a_lt_oneb, have loop_lt, from lt_of_add_lt_add_left a_lt_oneb, rewrite [add_comm] at loop_lt, rewrite [EQ_of_LT_ONE_of_GE loop_ge loop_lt] end lemma LT_of_Mul_LT_of_Pos : ∀{a b c : ℕ}, ( 0 < a ) → ( a * b < c ) → --------------------------------- ( b < c ) | a 0 c := begin assume zero_lt_a ab_lt_c, simp [nat.mul_zero] at ⊢ ab_lt_c, from ab_lt_c end | a (b+1) c := begin assume zero_lt_a ab_lt_c, with_cases { by_cases a_eq_1 : 1 = a }, case pos { rewrite [←a_eq_1, nat.one_mul] at ab_lt_c, from ab_lt_c }, case neg { have one_le_a, from nat.le_of_lt_succ (nat.succ_lt_succ zero_lt_a), have one_lt_a, from nat.lt_of_le_and_ne one_le_a a_eq_1, have b_le_b, from nat.le_refl (b+1), have zero_lt_b, from lt_add_of_le_of_pos (nat.zero_le b) nat.zero_lt_one, have zero_le_a, from nat.zero_le a, --( 1 < a ) → ( (b+1) ≤ (b+1) ) → ( 0 < (b+1) ) → ( 0 ≤ a ) → ( 1 * (b+1) < a * (b+1) ) have b_lt_ab, from mul_lt_mul one_lt_a b_le_b zero_lt_b zero_le_a, rewrite [nat.one_mul] at b_lt_ab, from nat.lt_trans b_lt_ab ab_lt_c } end lemma LE_Mul_Left_of_Pos : ∀{a : ℕ}, ( 0 < a ) → --------------------------------- ( ∀(b : ℕ), b ≤ a * b ) | a := begin assume zero_lt_a b, induction b, case nat.zero { simp [mul_zero] }, case nat.succ { have one_le_a, from nat.le_of_lt_succ (nat.succ_lt_succ zero_lt_a), rewrite [nat.succ_eq_add_one, mul_comm a, add_comm, right_distrib, one_mul, mul_comm], from add_le_add one_le_a b_ih } end /- Useful properties regarding Natural Numbers -/ lemma Add_GE_Add : ∀{a b c d : ℕ}, ( a ≥ b ) → ( c ≥ d ) → --------------------------------- ( a + c ≥ b + d ) | a b c d := begin assume a_ge_b c_ge_d, from add_le_add a_ge_b c_ge_d end lemma EQ_or_SUCC_LE_iff_LE : ∀{a b : ℕ}, --------------------------- ( a ≤ b ) ↔ ( (a = b) ∨ (a+1 ≤ b) ) := begin have case_to : ∀{a b : ℕ}, a ≤ b → (a = b) ∨ (a+1 ≤ b), from begin assume a b le_a_b, from nat.eq_or_lt_of_le le_a_b end, have case_from : ∀{a b : ℕ}, (a = b) ∨ (a+1 ≤ b) → a ≤ b, from begin assume a b eq_or_succ_le_a_b, cases eq_or_succ_le_a_b with eq_a_b succ_le_a_b, case or.inl { simp [eq_a_b] }, case or.inr { from nat.le_of_succ_le succ_le_a_b } end, assume a b, from iff.intro case_to case_from end lemma EQ_PRED_of_SUCC_EQ : -- Notice that the other way does not hold true, since 0 ≠ 0 - 1 ∀{a b : ℕ}, ( a+1 = b ) → --------------------------- ( a = b-1 ) | a b := begin assume eq_succ_a_b, rewrite [←eq_succ_a_b, eq_comm], from nat.add_sub_cancel a 1 end lemma GE_Cancel_Right : ∀{a b c : ℕ}, ( a ≥ b + c ) → --------------------------------- ( a ≥ b ) | a b c := begin assume a_ge_bc, have bc_ge_b : b + c ≥ b, from begin have b_le_bc, from add_le_add_left (nat.zero_le c) b, rewrite [add_zero] at b_le_bc, from b_le_bc end, from ge_trans a_ge_bc bc_ge_b end lemma GE_iff_Not_LT : ∀{a b : ℕ}, --------------------------- ( a ≥ b ) ↔ ( ¬( a < b ) ) := begin have case_to : ∀{m n : ℕ}, ( m ≥ n ) → ( ¬( m < n ) ), from begin assume m n m_ge_n, from not_lt_of_ge m_ge_n end, have case_from : ∀{m n : ℕ}, ( ¬( m < n ) ) → ( m ≥ n ), from begin assume m n not_m_lt_n, have eq_or_lt, from nat.eq_or_lt_of_not_lt not_m_lt_n, cases eq_or_lt with m_eq_n m_lt_n, case or.inl { apply nat.le_of_eq, from (iff.elim_right eq_comm) m_eq_n }, case or.inr { apply nat.le_of_lt, from m_lt_n }, end, assume a b, from iff.intro case_to case_from end lemma LE_Add_Left : ∀{a b : ℕ}, ( a ≤ b ) → --------------------------------- ( ∀(c : ℕ), ( a ≤ c + b ) ) | a b := begin assume a_le_b c, from le_trans a_le_b (nat.le_add_left b c) end lemma LE_Add_Right : ∀{a b : ℕ}, ( a ≤ b ) → --------------------------------- ( ∀(c : ℕ), ( a ≤ b + c ) ) | a b := begin assume a_le_b c, from le_trans a_le_b (nat.le_add_right b c) end lemma LE_Mul_of_LE : ∀{a b : ℕ}, ∀(c : ℕ), ( a ≤ b ) → --------------------------- ( a * c ≤ b * c ) | a b 0 := begin assume a_le_b, simp [nat.mul_zero] end | a b (c+1) := begin assume a_le_b, rewrite [←mul_comm (c+1), right_distrib, nat.one_mul, mul_comm c], rewrite [←mul_comm (c+1), right_distrib, nat.one_mul, mul_comm c], have loop, from LE_Mul_of_LE c a_le_b, from add_le_add loop a_le_b end lemma LT_Add_Left : ∀{a b : ℕ}, ( a < b ) → --------------------------------- ( ∀(c : ℕ), ( a < c + b ) ) | a b := begin assume a_lt_b c, with_cases {by_cases c_eq_zero : c = 0 }, case pos { simp [c_eq_zero], from a_lt_b }, case neg { rewrite [eq_comm] at c_eq_zero, have c_pos, from lt_of_le_of_ne (nat.zero_le c) (c_eq_zero), from lt_add_of_pos_of_lt c_pos a_lt_b } end lemma LT_Add_Right : ∀{a b : ℕ}, ( a < b ) → --------------------------------- ( ∀(c : ℕ), ( a < b + c ) ) | a b := begin assume a_lt_b c, with_cases {by_cases c_eq_zero : c = 0 }, case pos { simp [c_eq_zero], from a_lt_b }, case neg { rewrite [eq_comm] at c_eq_zero, have c_pos, from lt_of_le_of_ne (nat.zero_le c) (c_eq_zero), from lt_add_of_lt_of_pos a_lt_b c_pos } end lemma LT_ZERO_iff_LE_ONE : ∀{a : ℕ}, --------------------------- ( 0 < a ) ↔ ( 1 ≤ a ) := begin have case_to : ∀{a : ℕ}, ( 0 < a ) → ( 1 ≤ a ), from begin assume a zero_lt_a, from nat.le_of_lt_succ (nat.succ_lt_succ zero_lt_a) end, have case_from : ∀{a : ℕ}, ( 1 ≤ a ) → ( 0 < a ), from begin assume a one_le_a, from nat.lt_of_lt_of_le nat.zero_lt_one one_le_a end, assume a, from iff.intro case_to case_from end lemma Not_EQ_of_SUCC_EQ_SUB : ∀{a b c : ℕ}, ( c+1 = a-b ) → --------------------------------- ¬ ( b = a ) | a b c := begin assume succ_eq_sub eq_a_b, rewrite [eq_a_b] at succ_eq_sub, rewrite [nat.sub_self] at succ_eq_sub, simp [nat.add_one_ne_zero] at succ_eq_sub, from succ_eq_sub end lemma Not_SUCC_LE_of_ZERO_EQ_SUB : ∀{a b : ℕ}, ( 0 = a-b ) → --------------------------------- ¬ ( b+1 ≤ a ) | a b := begin assume zero_eq_sub succ_le, rewrite [eq_comm] at zero_eq_sub, have le_a_b, from nat.le_of_sub_eq_zero zero_eq_sub, have le_succ_b_b, from nat.le_trans succ_le le_a_b, simp [nat.not_succ_le_self] at le_succ_b_b, from le_succ_b_b end lemma Sub_Add_Cancel : ∀{a b : ℕ}, ( b ≤ a ) → --------------------------------- ( a - b + b = a ) | a b := begin assume b_le_a, from nat.sub_add_cancel b_le_a end lemma ZERO_LT_Mul_iff_AND_ZERO_LT : ∀{a b : ℕ}, --------------------------------- ( 0 < a * b ) ↔ ( 0 < a ∧ 0 < b ) := begin have case_to : ∀{a b : ℕ}, ( 0 < a * b ) → ( 0 < a ∧ 0 < b ), from begin assume a b zero_lt_ab, with_cases {by_cases a_eq_zero : a = 0 }, case pos { rewrite [a_eq_zero, nat.zero_mul] at zero_lt_ab, from false.elim (nat.not_lt_zero 0 zero_lt_ab) }, case neg { with_cases {by_cases b_eq_zero : b = 0 }, case pos { rewrite [b_eq_zero, nat.mul_zero] at zero_lt_ab, from false.elim (nat.not_lt_zero 0 zero_lt_ab) }, case neg { have zero_le_a, from nat.lt_of_le_and_ne (nat.zero_le a), have zero_le_b, from nat.lt_of_le_and_ne (nat.zero_le b), rewrite [ne.def, eq_comm] at zero_le_a zero_le_b, from and.intro (zero_le_a a_eq_zero) (zero_le_b b_eq_zero) }, } end, have case_from : ∀{a b : ℕ}, ( 0 < a ∧ 0 < b ) → ( 0 < a * b ), from begin assume a b zero_lt_a_and_b, cases zero_lt_a_and_b with zero_lt_a zero_lt_b, have zero_lt_ab, from mul_lt_mul_of_pos_left zero_lt_b zero_lt_a, rewrite [nat.mul_zero] at zero_lt_ab, from zero_lt_ab end, assume a b, from iff.intro case_to case_from end lemma ZERO_LT_of_Not_EQ_ZERO : ∀{a : ℕ}, ¬ ( a = 0 ) → --------------------------------- ( 0 < a ) | 0 := begin assume not_refl_zero, from absurd (eq.refl 0) not_refl_zero end | (a+1) := begin assume not_succ_eq_zero, rewrite [add_comm], from nat.zero_lt_one_add a end /- Lemmata taken from L∃∀N's library about Natural Numbers -/ lemma Add_LE_Add : ∀{a b c d : ℕ}, ( a ≤ b ) → ( c ≤ d ) → --------------------------------- ( a + c ≤ b + d ) | a b c d := begin assume a_le_b c_le_d, from add_le_add a_le_b c_le_d end lemma Add_LT_Add_Left : ∀{a b : ℕ}, ( a < b ) → --------------------------------- ( ∀(c : ℕ), ( c + a < c + b ) ) | a b := begin assume a_lt_b c, from add_lt_add_left a_lt_b c end lemma Add_LT_Add_Right : ∀{a b : ℕ}, ( a < b ) → --------------------------------- ( ∀(c : ℕ), ( a + c < b + c ) ) | a b := begin assume a_lt_b c, from add_lt_add_right a_lt_b c end lemma Add_ZERO : ∀(a : ℕ), --------------------------------- ( a + 0 = a ) | a := by from add_zero a lemma EQ_Refl {α : Sort u} : ∀(a : α), --------------------------------- ( a = a ) | a := by from eq.refl a lemma LE_of_SUCC_LE : ∀{n m : ℕ}, ( nat.succ n ≤ m ) → --------------------------- ( n ≤ m ) | n m := by from nat.le_of_succ_le lemma LE_SUCC_of_LE : ∀{n m : ℕ}, ( n ≤ m ) → --------------------------- ( n ≤ nat.succ m ) | n m := by from nat.le_succ_of_le lemma LE_Refl : ∀(a : ℕ), --------------------------- ( a ≤ a ) | a := by from nat.le_refl a lemma LE_Trans : ∀{a b c : ℕ}, ( a ≤ b ) → ( b ≤ c ) → --------------------------- ( a ≤ c ) | a b c := by from nat.le_trans lemma LT_Irrefl : ∀{a : ℕ}, --------------------------------- ¬ ( a < a ) | a := by from lt_irrefl a lemma LT_of_LT_of_LE : ∀{n m k : ℕ}, ( n < m ) → ( m ≤ k ) → --------------------------- ( n < k ) | n m k := by from nat.lt_of_lt_of_le lemma LT_of_LE_of_LT : ∀{n m k : ℕ}, ( n ≤ m ) → ( m < k ) → --------------------------- ( n < k ) | n m k := by from nat.lt_of_le_of_lt lemma Mul_Assoc : ∀{a b c : ℕ}, --------------------------- ( a * b * c = a * (b * c) ) | a b c := by from mul_assoc a b c lemma Mul_ZERO : ∀{a : ℕ}, --------------------------- ( a * 0 = 0 ) | a := by from nat.mul_zero a lemma Not_LT_ZERO : ∀{a : ℕ}, --------------------------- ¬ ( a < 0 ) | a := by from nat.not_lt_zero a lemma Not_SUCC_LE_Self : ∀{a : ℕ}, --------------------------- ¬ ( nat.succ a ≤ a ) | a := by from nat.not_succ_le_self a lemma ONE_Mul : ∀(a : ℕ), --------------------------- ( 1 * a = a ) | a := by from nat.one_mul a lemma Right_Distrib : ∀{a b c : ℕ}, --------------------------------- ( (a + b) * c = a * c + b * c ) | a b c := by from right_distrib a b c lemma SUCC_EQ_Add_ONE : ∀{a : ℕ}, --------------------------- ( nat.succ a = a + 1 ) | a := by from nat.succ_eq_add_one a lemma SUCC_Mul : ∀{n m : ℕ}, --------------------------- ( (nat.succ n) * m = n * m + m ) | n m := by from nat.succ_mul n m lemma ZERO_LE : ∀(a : ℕ), --------------------------------- ( 0 ≤ a ) | a := by from nat.zero_le a lemma ZERO_LT_ONE_Add : ∀(a : ℕ), --------------------------------- ( 0 < 1 + a ) | a := by from nat.zero_lt_one_add a lemma ZERO_LT_ONE : --------------------------------- 0 < (1:nat) := by from nat.zero_lt_one end use /- Auxiliary Definitions -/ namespace aux universes u v /- Methods for determining the size of nested lists -/ -- The order of the following definitions is important class has_size (α : Type u) := (size : α → ℕ) instance is_default_size (α : Type u) : has_size α := ⟨ (λx, 1) ⟩ -- First the size method checks if it has been given a list, if not it goes to its default case def size {α : Type u} [hcα : has_size α] : α → ℕ := has_size.size def list_size {α : Type u} [hcα : has_size α] : list α → ℕ | [] := 0 | (h::l) := size h + list_size l -- Writing [hcα : has_size α] means that α ay have either is_list_size or is_default_size -- If [hcα : has_size α] is omitted, than α must have is_default_size instance is_list_size (α : Type u) [hcα : has_size α] : has_size (list α) := ⟨list_size⟩ /- Properties about list size -/ lemma Deafault_Size_EQ_Length {α : Type} : ∀{l : list α}, --------------------------- ( list_size l = list.length l ) | [] := by simp [list.length, list_size] | (HEAD::TAIL) := begin simp [list.length, list_size], simp [size, has_size.size], rewrite [Deafault_Size_EQ_Length] end lemma ZERO_LT_Length_of_LT_Size {α : Type} [hcα : has_size α] : ∀{l : list α}{num : ℕ}, ( num < list_size l ) → --------------------------- ( 0 < list.length l ) | [] num := begin assume num_lt_size, simp [list_size] at num_lt_size, from absurd num_lt_size use.Not_LT_ZERO end | (HEAD::TAIL) num := begin assume num_lt_size, simp [list.length], from use.ZERO_LT_ONE_Add (list.length TAIL) end /- Combinatory theorem about nested lists -/ theorem Main_Combinatory_Nested {α : Type} [hsα : has_size α] : ∀{num : ℕ}{ll : list (list α)}, ( (list.length ll) * num < list_size ll ) → --------------------------------- ( ∃(l : list α), l ∈ ll ∧ num < list_size l ) | num [] := begin assume mul_lt_ll, simp [list_size] at mul_lt_ll, from false.elim (use.Not_LT_ZERO mul_lt_ll) end | num (HEAD::TAIL) := begin assume mul_lt_ll, simp [list_size] at mul_lt_ll, with_cases { by_cases num_lt_head : num < size HEAD }, case pos { --If HEAD is big apply exists.intro HEAD, simp [has_mem.mem, list.mem], from num_lt_head }, case neg { --If HEAD isn't big with_cases { by_cases mul_lt_tail : (list.length TAIL) * num < list_size TAIL }, case pos { --If TAIL is big have main_combinatory, from Main_Combinatory_Nested mul_lt_tail, cases main_combinatory with la main_combinatory, cases main_combinatory with mem_la_tail num_lt_la, apply exists.intro la, simp [has_mem.mem, list.mem] at ⊢ mem_la_tail, simp [mem_la_tail], from num_lt_la }, case neg { --If TAIL isn't big rewrite [use.Right_Distrib, use.ONE_Mul, add_comm] at mul_lt_ll, rewrite [←use.GE_iff_Not_LT] at num_lt_head, rewrite [←use.GE_iff_Not_LT] at mul_lt_tail, have not_mul_lt_ll, from use.Add_GE_Add mul_lt_tail num_lt_head, rewrite [use.GE_iff_Not_LT] at not_mul_lt_ll, from absurd mul_lt_ll not_mul_lt_ll } } end /- Methods for counting the number diferent elements in a list -/ def list_set {α : Type u} [eqα : decidable_eq α] : list α → list α | [] := [] | (HEAD::TAIL) := if HEAD ∈ TAIL then list_set TAIL else HEAD :: list_set TAIL def list_filter {α : Type u} [eqα : decidable_eq α] : α → list α → list α | _ [] := [] | a (HEAD::TAIL) := if a = HEAD then HEAD :: list_filter a TAIL else list_filter a TAIL def list_delete {α : Type u} [eqα : decidable_eq α] : α → list α → list α | _ [] := [] | a (HEAD::TAIL) := if a = HEAD then list_delete a TAIL else HEAD :: list_delete a TAIL /- Properties about list set, filter, and delete -/ lemma Length_Set_LE_Length_of_Subset {α : Type u} [eqα : decidable_eq α] : ∀{l1 l2 : list α}, ( ∀(a : α), ( a ∈ l1 ) → ( a ∈ l2 ) ) → --------------------------- ( list.length (list_set l1) ≤ list.length l2 ) | [] l2 := begin assume case_mem, simp [list_set], from use.ZERO_LE (list.length l2) end | (HEAD1::TAIL1) l2 := begin assume case_mem, have head1_mem_l2 : HEAD1 ∈ l2, from begin apply (case_mem HEAD1), simp [has_mem.mem, list.mem] end, have case_mem_tail1 : ∀ (a : α), a ∈ TAIL1 → a ∈ l2, from begin assume loop loop_mem_tail1, simp [has_mem.mem, list.mem] at case_mem, apply (case_mem loop), simp [has_mem.mem, list.mem] at loop_mem_tail1, simp [loop_mem_tail1] end, simp [list_set], with_cases { by_cases head1_mem_tail1 : HEAD1 ∈ TAIL1 }, -- case pos { simp [head1_mem_tail1], from Length_Set_LE_Length_of_Subset case_mem_tail1 }, case neg { simp [head1_mem_tail1], have case_loop : ∀ (a : α), a ∈ TAIL1 → a ∈ list.remove_nth l2 (list.index_of HEAD1 l2), from begin assume loop loop_mem_tail1, have loop_mem_l2, from case_mem_tail1 loop loop_mem_tail1, have case_remove, from use.Mem_Remove_of_Mem_of_Not_Mem head1_mem_tail1 head1_mem_l2, from case_remove loop loop_mem_tail1 loop_mem_l2 end, have loop, from Length_Set_LE_Length_of_Subset case_loop, have case_index, from use.Index_LT_Length_of_Mem head1_mem_l2, rewrite [use.Length_Remove_Nth case_index] at loop, have one_le_l2, from use.LT_of_LE_of_LT (use.ZERO_LE (list.index_of HEAD1 l2)) case_index, rewrite [use.LT_ZERO_iff_LE_ONE] at one_le_l2, rewrite [add_comm, ←use.Sub_Add_Cancel one_le_l2], from use.Add_LE_Add loop (use.LE_Refl 1) } end lemma Mem_of_Mem_Delete {α : Type u} [eqα : decidable_eq α] : ∀{a1 a2 : α}{l : list α}, ( a1 ∈ (list_delete a2 l) ) → --------------------------- ( a1 ∈ l ) | a1 a2 [] := begin assume a1_mem_del, simp [list_delete, has_mem.mem, list.mem] at a1_mem_del, from false.elim a1_mem_del end | a1 a2 (HEAD::TAIL) := begin assume a1_mem_del, simp [list_delete, has_mem.mem, list.mem] at ⊢ a1_mem_del, with_cases { by_cases a2_eq_head : a2 = HEAD }, case pos { -- If HEAD = a2 simp [a2_eq_head] at a1_mem_del, have loop, from Mem_of_Mem_Delete a1_mem_del, simp [has_mem.mem, list.mem] at ⊢ loop, simp [loop] }, case neg { -- If HEAD ≠ a2 simp [a2_eq_head, list.mem] at a1_mem_del, cases a1_mem_del with a1_eq_head a1_mem_del, case or.inl { simp [a1_eq_head] }, case or.inr { have loop, from Mem_of_Mem_Delete a1_mem_del, simp [has_mem.mem, list.mem] at ⊢ loop, simp [loop] } } end lemma Size_Filter_Delete {α : Type u} [eqα : decidable_eq α] : ∀(a : α)(l : list α), --------------------------- ( list_size (list_filter a (list_delete a l)) = 0 ) | a [] := by simp [list_delete, list_filter, list_size] | a (HEAD::TAIL) := begin with_cases { by_cases a_eq_head : a = HEAD }, case pos { -- If a = HEAD simp [a_eq_head, list_delete], from Size_Filter_Delete HEAD TAIL }, case neg { -- If a ≠ HEAD simp [a_eq_head, list_delete, list_filter], from Size_Filter_Delete a TAIL } end lemma Size_Delete_LE_Size {α : Type u} [eqα : decidable_eq α] : ∀(a1 a2 : α)(l : list α), --------------------------- ( list_size (list_filter a1 (list_delete a2 l)) ≤ list_size (list_filter a1 l) ) | a1 a2 [] := by simp [list_delete, list_filter] | a1 a2 (HEAD::TAIL) := begin simp [list_delete], with_cases { by_cases a2_eq_head : a2 = HEAD }, case pos { -- If a2 = HEAD simp [a2_eq_head, list_filter], with_cases { by_cases a1_eq_head : a1 = HEAD }, case pos { -- If a1 = HEAD simp [a1_eq_head, list_size], from use.LE_Add_Left (Size_Delete_LE_Size HEAD HEAD TAIL) (size HEAD) }, case neg { -- If a1 ≠ HEAD simp [a1_eq_head, list_size], from Size_Delete_LE_Size a1 HEAD TAIL } }, case neg { -- If a2 ≠ HEAD simp [a2_eq_head, list_filter], with_cases { by_cases a1_eq_head : a1 = HEAD }, case pos { -- If a1 = HEAD simp [a1_eq_head, list_size], from use.Add_LE_Add (use.LE_Refl (size HEAD)) (Size_Delete_LE_Size HEAD a2 TAIL) }, case neg { -- If a1 ≠ HEAD simp [a1_eq_head, list_size], from Size_Delete_LE_Size a1 a2 TAIL } } end lemma Size_Filter_Delete_EQ_Size {α : Type u} [eqα : decidable_eq α] : ∀(a : α)(l : list α), --------------------------- ( list_size (list_filter a l) + list_size (list_delete a l) = list_size l ) | a [] := by simp [list_delete, list_filter, list_size] | a (HEAD::TAIL) := begin simp [list_filter, list_delete], with_cases { by_cases a_eq_head : a = HEAD }, case pos { -- If a = HEAD simp [a_eq_head, list_size], have loop, from Size_Filter_Delete_EQ_Size HEAD TAIL, rewrite [add_comm] at loop, rewrite [loop, add_comm] }, case neg { -- If a ≠ HEAD simp [a_eq_head, list_size], have loop, from Size_Filter_Delete_EQ_Size a TAIL, rewrite [add_comm] at loop, rewrite [loop, add_comm] } end /- Properties about list set, filter, and delete (Must be left in order) -/ lemma Case_Not_Mem_Del {α : Type u} [eqα : decidable_eq α] : ∀{a1 a2 : α}{l : list α}, ( a2 ≠ a1 ) → ( a1 ∉ l ) → --------------------------- ( a1 ∉ list_delete a2 l ) | a1 a2 [] := by simp [list_delete] | a1 a2 (HEAD::TAIL) := begin assume a1_ne_a2 a1_not_mem, simp [has_mem.mem, list.mem] at a1_not_mem, rewrite [use.Not_Or_iff_And_Not] at a1_not_mem, cases a1_not_mem with a1_ne_head a1_not_mem_tail, -- with_cases { by_cases a2_eq_head : a2 = HEAD }, case pos { -- If a2 = HEAD simp [a2_eq_head, list_delete] at ⊢ a1_ne_a2, rewrite [eq_comm] at a1_ne_head, from Case_Not_Mem_Del a1_ne_head a1_not_mem_tail }, case neg { -- If a2 ≠ HEAD simp [a2_eq_head, list_delete], from use.Not_Or a1_ne_head (Case_Not_Mem_Del a1_ne_a2 a1_not_mem_tail) } end lemma Case_Mem_Del {α : Type u} [eqα : decidable_eq α] : ∀{a1 a2 : α}{l : list α}, ( a2 ≠ a1 ) → ( a1 ∈ l ) → --------------------------- ( a1 ∈ list_delete a2 l ) | a1 a2 [] := by simp [list_delete] | a1 a2 (HEAD::TAIL) := begin assume a1_ne_a2 a1_mem, simp [has_mem.mem, list.mem] at a1_mem, -- with_cases { by_cases a2_eq_head : a2 = HEAD }, case pos { -- If a2 = HEAD simp [a2_eq_head, list_delete] at ⊢ a1_ne_a2, cases a1_mem with a1_eq_head a1_mem_tail, case or.inl { rewrite [eq_comm] at a1_eq_head, from absurd a1_eq_head a1_ne_a2 }, case or.inr { from Case_Mem_Del a1_ne_a2 a1_mem_tail } }, case neg { -- If a2 ≠ HEAD simp [a2_eq_head, list_delete], cases a1_mem with a1_eq_head a1_mem_tail, case or.inl { simp [a1_eq_head] }, case or.inr { simp [Case_Mem_Del a1_ne_a2 a1_mem_tail] } } end lemma Lenght_EQ_Lenght_Set_Delete {α : Type u} [eqα : decidable_eq α] : ∀(a : α)(l : list α), --------------------------- ( list.length (list_set (a::l)) = 1 + list.length (list_set (list_delete a l)) ) | a [] := by simp [list_delete, list_set] | a (HEAD::TAIL) := begin have loop_head, from Lenght_EQ_Lenght_Set_Delete HEAD TAIL, have loop_a, from Lenght_EQ_Lenght_Set_Delete a TAIL, simp [list_delete] at ⊢ loop_head loop_a, with_cases { by_cases a_eq_head : a = HEAD }, case pos { -- If a = HEAD simp [a_eq_head, list_set] at ⊢ loop_head, with_cases { by_cases head_mem_tail : HEAD ∈ TAIL }, case pos { -- If HEAD ∈ TAIL simp [head_mem_tail, list.length] at ⊢ loop_head, from loop_head }, case neg { -- If HEAD ∉ TAIL simp [head_mem_tail, list.length] at ⊢ loop_head, from loop_head } }, case neg { -- If a ≠ HEAD simp [a_eq_head, list_set] at ⊢ loop_a, with_cases { by_cases a_mem_tail : a ∈ TAIL }, case pos { -- If a ∈ TAIL simp [a_mem_tail, list.length] at ⊢ loop_a, with_cases { by_cases head_mem_tail : HEAD ∈ TAIL }, case pos { -- If HEAD ∈ TAIL simp [head_mem_tail, list.length] at ⊢ loop_a, simp [Case_Mem_Del a_eq_head head_mem_tail], from loop_a }, case neg { -- If HEAD ∉ TAIL simp [head_mem_tail, list.length] at ⊢ loop_a, simp [Case_Not_Mem_Del a_eq_head head_mem_tail], simp [loop_a] } }, case neg { -- If a ∉ TAIL simp [a_mem_tail, list.length] at ⊢ loop_a, with_cases { by_cases head_mem_tail : HEAD ∈ TAIL }, case pos { -- If HEAD ∈ TAIL simp [head_mem_tail, list.length] at ⊢ loop_a, simp [Case_Mem_Del a_eq_head head_mem_tail], from loop_a }, case neg { -- If HEAD ∉ TAIL simp [head_mem_tail, list.length] at ⊢ loop_a, simp [Case_Not_Mem_Del a_eq_head head_mem_tail], simp [loop_a] } } } end /- Combinatory theorem about lists (Filter) -/ theorem Main_Combinatory_Filter {α : Type} [eqα : decidable_eq α] : ∀(num : ℕ)(l : list α), ( list.length (list_set l) * num < list_size l ) → --------------------------------- ( ∃(a : α), a ∈ l ∧ num < list_size (list_filter a l) ) | num [] := begin assume mul_lt_l, simp [list_size] at mul_lt_l, from false.elim (use.Not_LT_ZERO mul_lt_l) end | num (HEAD::TAIL) := begin assume mul_lt_l, with_cases { by_cases num_lt_head : num < 1 + list_size (list_filter HEAD TAIL) }, case pos { -- If list_filter HEAD (HEAD::TAIL) is big apply exists.intro HEAD, simp [list_filter, list_size, has_mem.mem, list.mem, size, has_size.size], from num_lt_head }, case neg { -- If list_filter HEAD (HEAD::TAIL) isn't big with_cases { by_cases mul_lt_del : list.length (list_set (list_delete HEAD TAIL)) * num < list_size (list_delete HEAD TAIL) }, case pos { -- If list_delete HEAD (HEAD::TAIL) is big have main_combinatory : ∃(a : α), a ∈ list_delete HEAD TAIL ∧ num < list_size (list_filter a (list_delete HEAD TAIL)), from Main_Combinatory_Filter num (list_delete HEAD TAIL) mul_lt_del, -- sorry, cases main_combinatory with a main_combinatory, cases main_combinatory with a_mem_del num_lt_a, apply exists.intro a, simp [has_mem.mem, list.mem] at ⊢ a_mem_del, simp [a_mem_del, list_filter], with_cases { by_cases a_eq_head : a = HEAD }, case pos { -- If a = HEAD rewrite [a_eq_head] at num_lt_a a_mem_del, rewrite [Size_Filter_Delete HEAD TAIL] at num_lt_a, from absurd num_lt_a use.Not_LT_ZERO }, case neg { -- If a ≠ HEAD simp [a_eq_head], have a_mem_tail, from Mem_of_Mem_Delete a_mem_del, simp [has_mem.mem] at a_mem_tail, simp [a_mem_tail], from use.LT_of_LT_of_LE num_lt_a (Size_Delete_LE_Size a HEAD TAIL) } }, case neg { --If list_delete HEAD (HEAD::TAIL) isn't big rewrite [Lenght_EQ_Lenght_Set_Delete, use.Right_Distrib] at mul_lt_l, simp [list_delete, list_size, size, has_size.size] at mul_lt_l, rewrite [←use.GE_iff_Not_LT] at mul_lt_del, rewrite [←use.GE_iff_Not_LT] at num_lt_head, have mul_ge_l, from use.Add_GE_Add num_lt_head mul_lt_del, rewrite [add_assoc, Size_Filter_Delete_EQ_Size] at mul_ge_l, rewrite [use.GE_iff_Not_LT] at mul_ge_l, -- This proof is the same as Main_Combinatory_Nested from absurd mul_lt_l mul_ge_l } } end using_well_founded -- So that the recursion is explicitly done over the list-type { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ t, list.sizeof t.snd)⟩] } -- L∃∀N gives us a warning that the recursion at Main_Combinatory_Filter is not well-founded: -- @has_well_founded.r (Σ' (num : ℕ), list α) -- (@has_well_founded.mk (Σ' (num : ℕ), list α) -- (@measure (Σ' (num : ℕ), list α) -- (λ (t : Σ' (num : ℕ), list α), -- @list.sizeof α (default_has_sizeof α) (@psigma.snd ℕ (λ (num : ℕ), list α) t))) -- _) -- The nested exception message contains the failure state for the decreasing tactic: -- ⊢ list.sizeof (list_delete HEAD TAIL) < 1 + list.sizeof TAIL -- However, we show this target is true for all type-instances -- Proving that, despite the warning, the recursion used in Main_Combinatory_Filter is well-founded lemma Well_Founded_Delete {α : Type u} [eqα : decidable_eq α] : ∀(head : α)(tail : list α), --------------------------------- ( list.sizeof (list_delete head tail) < 1 + list.sizeof tail ) | head [] := begin simp [list_delete], simp [list.sizeof], have del_lt_sizeof, from use.Add_LT_Add_Left use.ZERO_LT_ONE 1, rewrite [use.Add_ZERO] at del_lt_sizeof, from del_lt_sizeof end | head (HEAD::TAIL) := begin simp [list_delete], with_cases { by_cases eq_head : head = HEAD }, case pos { -- If head = HEAD simp [eq_head], simp [list.sizeof], have loop_0, from Well_Founded_Delete HEAD TAIL, have loop_1, from use.LT_Add_Right loop_0 (sizeof HEAD), rewrite [add_assoc] at loop_1, from use.LT_Add_Left loop_1 1 }, case neg { -- If head ≠ HEAD simp [eq_head], simp [list.sizeof], have loop_0, from Well_Founded_Delete head TAIL, have loop_1, from use.Add_LT_Add_Right loop_0 (sizeof HEAD), rewrite [add_assoc, add_comm] at loop_1, from use.Add_LT_Add_Left loop_1 1 } end end aux /- Type Definitions and Properties -/ namespace types /- Inductive Types: Formula -/ inductive formula | atom (SBL : ℕ) : formula | implication (ANT CON : formula) : formula export formula (atom implication) notation #SBL := formula.atom SBL notation ANT >> CON := formula.implication ANT CON /- Inductive Types: Proof-Graph -/ inductive node_option | leaf : node_option | node : node_option export node_option (leaf node) inductive tree -- Top Formulas and Hypotheses | leaf (LVL : ℕ) (FML : formula) : tree -- Nodes resulting from →Introduction | u_tree (LVL : ℕ) (FML : formula) (UNI : tree) : tree -- Nodes resulting from →Elimination | lr_tree (LVL : ℕ) (FML : formula) (MNR MJR : tree) : tree export tree (leaf u_tree lr_tree) inductive branch -- The First Node of the Branch (Always a leaf when a Proof-Branch) | leaf (BRC : branch) (OPT : node_option) (LVL : ℕ) (FML : formula) : branch -- Nodes resulting from →Introduction | u_branch (BRC : branch) (OPT : node_option) (LVL : ℕ) (FML : formula) : branch -- Nodes resulting from →Elimination, connected to their Minor Premise | l_branch (BRC : branch) (OPT : node_option) (LVL : ℕ) (FML : formula) : branch -- Nodes resulting from →Elimination, connected to their Major Premise | r_branch (BRC : branch) (OPT : node_option) (LVL : ℕ) (FML : formula) : branch -- Pointer to the Ending of the Branch (Always the Root of the Proof-Tree before Pruning) | root : branch export branch (leaf u_branch l_branch r_branch root) /- Instances of Decidability (Equality): Formula -/ instance formula.decidable_eq : ∀(f1 f2 : formula), --------------------------------- decidable (f1 = f2) -- ATOM: | (atom SBL1) (atom SBL2) := begin simp [eq.decidable], from @nat.decidable_eq SBL1 SBL2 end | (atom _) (implication _ _) := begin simp [eq.decidable], from is_false not_false end -- IMPLICATION: | (implication _ _) (atom _) := begin simp [eq.decidable], from is_false not_false end | (implication ANT1 CON1) (implication ANT2 CON2) := begin simp [eq.decidable], from @and.decidable (ANT1 = ANT2) (CON1 = CON2) (@formula.decidable_eq ANT1 ANT2) (@formula.decidable_eq CON1 CON2) end /- Instances of Decidability (Equality): Proof-Graph -/ instance node_option.decidable_eq : ∀(opt1 opt2 : node_option), --------------------------------- decidable (opt1 = opt2) -- LEAF: | leaf leaf := begin simp [eq.decidable], from is_true trivial end | leaf node := begin simp [eq.decidable], from is_false not_false end -- NODE: | node leaf := begin simp [eq.decidable], from is_false not_false end | node node := begin simp [eq.decidable], from is_true trivial end instance tree.decidable_eq : ∀(t1 t2 : tree), --------------------------------- decidable (t1 = t2) -- LEAF: | (leaf LVL1 FML1) (leaf LVL2 FML2) := begin simp [eq.decidable], from @and.decidable (LVL1 = LVL2) (FML1 = FML2) (@nat.decidable_eq LVL1 LVL2) (@formula.decidable_eq FML1 FML2) end | (leaf _ _) (u_tree _ _ _) := begin simp [eq.decidable], from is_false not_false end | (leaf _ _) (lr_tree _ _ _ _) := begin simp [eq.decidable], from is_false not_false end -- U_Tree: | (u_tree _ _ UNI1) (leaf _ _) := begin simp [eq.decidable], from is_false not_false end | (u_tree LVL1 FML1 UNI1) (u_tree LVL2 FML2 UNI2) := begin simp [eq.decidable], have dec_and1, from @and.decidable (FML1 = FML2) (UNI1 = UNI2) (@formula.decidable_eq FML1 FML2) (@tree.decidable_eq UNI1 UNI2), from @and.decidable (LVL1 = LVL2) (FML1 = FML2 ∧ UNI1 = UNI2) (@nat.decidable_eq LVL1 LVL2) dec_and1 end | (u_tree _ _ _) (lr_tree _ _ _ _) := begin simp [eq.decidable], from is_false not_false end -- LR_Tree: | (lr_tree _ _ MNR1 MJR1) (leaf _ _) := begin simp [eq.decidable], from is_false not_false end | (lr_tree _ _ MNR1 MJR1) (u_tree _ _ _) := begin simp [eq.decidable], from is_false not_false end | (lr_tree LVL1 FML1 MNR1 MJR1) (lr_tree LVL2 FML2 MNR2 MJR2) := begin simp [eq.decidable], have dec_and1, from @and.decidable (MNR1 = MNR2) (MJR1 = MJR2) (@tree.decidable_eq MNR1 MNR2) (@tree.decidable_eq MJR1 MJR2), have dec_and2, from @and.decidable (FML1 = FML2) (MNR1 = MNR2 ∧ MJR1 = MJR2) (@formula.decidable_eq FML1 FML2) dec_and1, from @and.decidable (LVL1 = LVL2) (FML1 = FML2 ∧ MNR1 = MNR2 ∧ MJR1 = MJR2) (@nat.decidable_eq LVL1 LVL2) dec_and2 end instance branch.decidable_eq : ∀(p1 p2 : branch), --------------------------------- decidable (p1 = p2) -- LEAF: | (leaf BRC1 OPT1 LVL1 FML1) (leaf BRC2 OPT2 LVL2 FML2) := begin simp [eq.decidable], have dec_and1, from @and.decidable (LVL1 = LVL2) (FML1 = FML2) (@nat.decidable_eq LVL1 LVL2) (@formula.decidable_eq FML1 FML2), have dec_and2, from @and.decidable (OPT1 = OPT2) (LVL1 = LVL2 ∧ FML1 = FML2) (@node_option.decidable_eq OPT1 OPT2) dec_and1, from @and.decidable (BRC1 = BRC2) (OPT1 = OPT2 ∧ LVL1 = LVL2 ∧ FML1 = FML2) (@branch.decidable_eq BRC1 BRC2) dec_and2 end | (leaf _ _ _ _) (u_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (leaf _ _ _ _) (l_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (leaf _ _ _ _) (r_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (leaf _ _ _ _) root := begin simp [eq.decidable], from is_false not_false end -- U_Path: | (u_branch _ _ _ _) (leaf _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (u_branch BRC1 OPT1 LVL1 FML1) (u_branch BRC2 OPT2 LVL2 FML2) := begin simp [eq.decidable], have dec_and1, from @and.decidable (LVL1 = LVL2) (FML1 = FML2) (@nat.decidable_eq LVL1 LVL2) (@formula.decidable_eq FML1 FML2), have dec_and2, from @and.decidable (OPT1 = OPT2) (LVL1 = LVL2 ∧ FML1 = FML2) (@node_option.decidable_eq OPT1 OPT2) dec_and1, from @and.decidable (BRC1 = BRC2) (OPT1 = OPT2 ∧ LVL1 = LVL2 ∧ FML1 = FML2) (@branch.decidable_eq BRC1 BRC2) dec_and2 end | (u_branch _ _ _ _) (l_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (u_branch _ _ _ _) (r_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (u_branch _ _ _ _) root := begin simp [eq.decidable], from is_false not_false end -- L_Path: | (l_branch _ _ _ _) (leaf _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (l_branch _ _ _ _) (u_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (l_branch BRC1 OPT1 LVL1 FML1) (l_branch BRC2 OPT2 LVL2 FML2) := begin simp [eq.decidable], have dec_and1, from @and.decidable (LVL1 = LVL2) (FML1 = FML2) (@nat.decidable_eq LVL1 LVL2) (@formula.decidable_eq FML1 FML2), have dec_and2, from @and.decidable (OPT1 = OPT2) (LVL1 = LVL2 ∧ FML1 = FML2) (@node_option.decidable_eq OPT1 OPT2) dec_and1, from @and.decidable (BRC1 = BRC2) (OPT1 = OPT2 ∧ LVL1 = LVL2 ∧ FML1 = FML2) (@branch.decidable_eq BRC1 BRC2) dec_and2 end | (l_branch _ _ _ _) (r_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (l_branch _ _ _ _) root := begin simp [eq.decidable], from is_false not_false end -- R_Path: | (r_branch _ _ _ _) (leaf _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (r_branch _ _ _ _) (u_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (r_branch _ _ _ _) (l_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | (r_branch BRC1 OPT1 LVL1 FML1) (r_branch BRC2 OPT2 LVL2 FML2) := begin simp [eq.decidable], have dec_and1, from @and.decidable (LVL1 = LVL2) (FML1 = FML2) (@nat.decidable_eq LVL1 LVL2) (@formula.decidable_eq FML1 FML2), have dec_and2, from @and.decidable (OPT1 = OPT2) (LVL1 = LVL2 ∧ FML1 = FML2) (@node_option.decidable_eq OPT1 OPT2) dec_and1, from @and.decidable (BRC1 = BRC2) (OPT1 = OPT2 ∧ LVL1 = LVL2 ∧ FML1 = FML2) (@branch.decidable_eq BRC1 BRC2) dec_and2 end | (r_branch _ _ _ _) root := begin simp [eq.decidable], from is_false not_false end -- ROOT: | root (leaf _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | root (u_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | root (l_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | root (r_branch _ _ _ _) := begin simp [eq.decidable], from is_false not_false end | root root := begin simp [eq.decidable], from is_true trivial end /- Get Methods: Formula -/ def is_atomic : formula → Prop | (atom _) := true | (implication _ _) := false instance formula.is_atomic : ∀(f : formula), --------------------------------- decidable (is_atomic f) | (atom _) := begin simp [is_atomic], from is_true trivial end | (implication _ _) := begin simp [is_atomic], from is_false not_false end def not_atomic : formula → Prop | (atom _) := false | (implication _ _) := true instance formula.not_atomic : ∀(f : formula), --------------------------------- decidable (not_atomic f) | (atom _) := begin simp [not_atomic], from is_false not_false end | (implication _ _) := begin simp [not_atomic], from is_true trivial end def get_antecedent : formula → formula | (atom SBL) := #0 -- NULL | (implication ANT _) := ANT def get_consequent : formula → formula | (atom SBL) := #0 -- NULL | (implication _ CON) := CON /- Get Methods: Proof-Graph -/ def not_root : branch → Prop | (leaf _ _ _ _) := true | (u_branch _ _ _ _) := true | (l_branch _ _ _ _) := true | (r_branch _ _ _ _) := true | root := false instance branch.not_root : ∀(b : branch), --------------------------------- decidable (not_root b) | (leaf _ _ _ _) := begin simp [not_root], from is_true trivial end | (u_branch _ _ _ _) := begin simp [not_root], from is_true trivial end | (l_branch _ _ _ _) := begin simp [not_root], from is_true trivial end | (r_branch _ _ _ _) := begin simp [not_root], from is_true trivial end | root := begin simp [not_root], from is_false not_false end def get_option : branch → node_option | (leaf _ OPT _ _) := OPT | (u_branch _ OPT _ _) := OPT | (l_branch _ OPT _ _) := OPT | (r_branch _ OPT _ _) := OPT | root := node -- NULL def get_level : branch → ℕ | (leaf _ _ LVL _) := LVL | (u_branch _ _ LVL _) := LVL | (l_branch _ _ LVL _) := LVL | (r_branch _ _ LVL _) := LVL | root := 0 -- NULL def get_formula : branch → formula | (leaf _ _ _ FML) := FML | (u_branch _ _ _ FML) := FML | (l_branch _ _ _ FML) := FML | (r_branch _ _ _ FML) := FML | root := #0 -- NULL /- Numbber of Levels and Formulas -/ def list_levels : tree → list (ℕ) | (leaf LVL _) := [LVL] | (u_tree LVL _ UNI) := if LVL ∈ list_levels UNI then list_levels UNI else [LVL] ++ list_levels UNI | (lr_tree LVL _ MNR MJR) := if LVL ∈ (list_levels MNR ∩ list_levels MJR) then (list_levels MNR ∩ list_levels MJR) else [LVL] ++ (list_levels MNR ∩ list_levels MJR) def list_formulas : tree → list (formula) | (leaf _ FML) := [FML] | (u_tree _ FML UNI) := if FML ∈ list_formulas UNI then list_formulas UNI else [FML] ++ list_formulas UNI | (lr_tree _ FML MNR MJR) := if FML ∈ (list_formulas MNR ∩ list_formulas MJR) then (list_formulas MNR ∩ list_formulas MJR) else [FML] ++ (list_formulas MNR ∩ list_formulas MJR) def count_levels : tree → ℕ | t := list.length (list_levels t) def count_formulas : tree → ℕ | t := list.length (list_formulas t) /- For this proof, trees are viewed as lists of nodes(which are also trees) -/ -- The lists are arranged in an orderly fashion, splitting the tree by types of node, levels, and formulas -- The lists return a branch from the original tree's root to a node given by the by type/level/formula def loop_tree_option_level_formula : branch → tree → node_option → ℕ → formula → list (branch) -- Matched node_option with the type of tree constructor | BRC (leaf LVL FML) leaf lvl fml := if LVL=lvl ∧ FML=fml then [leaf BRC leaf LVL FML] else [] | BRC (u_tree LVL FML UNI) node lvl fml := if LVL=lvl ∧ FML=fml then [leaf BRC node LVL FML] else loop_tree_option_level_formula (u_branch BRC node LVL FML) UNI node lvl fml | BRC (lr_tree LVL FML MNR MJR) node lvl fml := if LVL=lvl ∧ FML=fml then [leaf BRC node LVL FML] else loop_tree_option_level_formula (l_branch BRC node LVL FML) MNR node lvl fml ++ loop_tree_option_level_formula (r_branch BRC node LVL FML) MJR node lvl fml -- Mismatched node_option with the type of tree constructor | BRC (leaf LVL FML) node lvl fml := [] | BRC (u_tree LVL FML UNI) leaf lvl fml := loop_tree_option_level_formula (u_branch BRC node LVL FML) UNI leaf lvl fml | BRC (lr_tree LVL FML MNR MJR) leaf lvl fml := loop_tree_option_level_formula (l_branch BRC node LVL FML) MNR leaf lvl fml ++ loop_tree_option_level_formula (r_branch BRC node LVL FML) MJR leaf lvl fml -- Returns all the nodes in the tree, with a given constructor, at a given level, and with a specific formula def list_tree_option_level_formula : tree → node_option → ℕ → formula → list (branch) | t opt lvl fml := loop_tree_option_level_formula root t opt lvl fml -- Returns all the nodes in the tree, with a given constructor, and at a given level def loop_tree_option_level : tree → node_option → ℕ → list (formula) → list (list (branch)) | t opt lvl [] := [] | t opt lvl (HEAD::TAIL) := [list_tree_option_level_formula t opt lvl HEAD] ++ loop_tree_option_level t opt lvl TAIL def list_tree_option_level : tree → node_option → ℕ → list (list (branch)) | t opt lvl := loop_tree_option_level t opt lvl (list_formulas t) -- Returns all the nodes in the tree, with a given constructor def loop_tree_option :tree → node_option → list (ℕ) → list (list (list (branch))) | t opt [] := [] | t opt (HEAD::TAIL) := [list_tree_option_level t opt HEAD] ++ loop_tree_option t opt TAIL def list_tree_option : tree → node_option → list (list (list (branch))) | t opt := loop_tree_option t opt (list_levels t) -- Returns all the nodes in the tree def list_tree : tree → list (list (list (list (branch)))) | t := [list_tree_option t leaf] ++ [list_tree_option t node] /- Prooving the correctness of the list_tree_option_level_formula method -/ lemma Loop_Level_Formula_Option : ∀(mem b : branch)(t : tree)(opt : node_option)(lvl : ℕ)(fml : formula), ( mem ∈ loop_tree_option_level_formula b t opt lvl fml ) → --------------------------- ( (get_option mem = opt) ∧ (get_level mem = lvl) ∧ (get_formula mem = fml) ) -- When mem and opt match | mem BRC (leaf LVL FML) leaf lvl fml := begin assume mem_node, -- Simplifying ∈ at the condition(mem_node) simp [loop_tree_option_level_formula] at mem_node, simp [has_mem.mem] at mem_node, simp [use.ITE_Distribution (list.mem mem)] at mem_node, simp [list.mem] at mem_node, -- Cases over (LVL=lvl ∧ FML=fml) with_cases { by_cases and_eq : (LVL=lvl ∧ FML=fml) }, case pos { simp [and_eq] at mem_node, simp [mem_node, get_option, get_level, get_formula] }, -- The case where ¬(LVL=lvl ∧ FML=fml) is impossible, since b ∉ [] case neg { simp [and_eq] at mem_node, from false.elim mem_node } end | mem BRC (u_tree LVL FML UNI) node lvl fml := begin assume mem_node, -- Simplifying ∈ at the condition(mem_node) simp [loop_tree_option_level_formula] at mem_node, simp [has_mem.mem] at mem_node, simp [use.ITE_Distribution (list.mem mem)] at mem_node, simp [list.mem] at mem_node, -- Cases over (LVL=lvl ∧ FML=fml) with_cases { by_cases and_eq : (LVL=lvl ∧ FML=fml) }, case pos { simp [and_eq] at mem_node, simp [mem_node, get_option, get_level, get_formula] }, -- The case where ¬(LVL=lvl ∧ FML=fml) continues up the single child case neg { simp [and_eq] at mem_node, from Loop_Level_Formula_Option mem (u_branch BRC node LVL FML) UNI node lvl fml mem_node } end | mem BRC (lr_tree LVL FML MNR MJR) node lvl fml := begin assume mem_node, -- Simplifying ∈ at the condition(mem_node) simp [loop_tree_option_level_formula] at mem_node, simp [has_mem.mem] at mem_node, simp [use.ITE_Distribution (list.mem mem)] at mem_node, simp [list.mem] at mem_node, -- Cases over (LVL=lvl ∧ FML=fml) with_cases { by_cases and_eq : (LVL=lvl ∧ FML=fml) }, case pos { simp [and_eq] at mem_node, simp [mem_node, get_option, get_level, get_formula] }, -- The case where ¬(LVL=lvl ∧ FML=fml) continues up both children case neg { simp [and_eq] at mem_node, -- Using the relation between append[++] and or[∨] regarding item membership over lists rewrite [use.Mem_Append] at mem_node, cases mem_node with mem_node mem_node, case or.inl { from Loop_Level_Formula_Option mem (l_branch BRC node LVL FML) MNR node lvl fml mem_node }, case or.inr { from Loop_Level_Formula_Option mem (r_branch BRC node LVL FML) MJR node lvl fml mem_node } } end -- When mem and opt don't match | mem BRC (leaf LVL FML) node lvl fml := by simp [loop_tree_option_level_formula] | mem BRC (u_tree LVL FML UNI) leaf lvl fml := begin assume mem_node, simp [loop_tree_option_level_formula] at mem_node, from Loop_Level_Formula_Option mem (u_branch BRC node LVL FML) UNI leaf lvl fml mem_node end | mem BRC (lr_tree LVL FML MNR MJR) leaf lvl fml := begin simp [loop_tree_option_level_formula], assume mem_node, cases mem_node, case or.inl { from Loop_Level_Formula_Option mem (l_branch BRC node LVL FML) MNR leaf lvl fml mem_node }, case or.inr { from Loop_Level_Formula_Option mem (r_branch BRC node LVL FML) MJR leaf lvl fml mem_node } end lemma From_Level_Formula_Option : ∀(mem : branch)(t : tree)(opt : node_option)(lvl : ℕ)(fml : formula), ( mem ∈ list_tree_option_level_formula t opt lvl fml ) → --------------------------- ( (get_option mem = opt) ∧ (get_level mem = lvl) ∧ (get_formula mem = fml) ) | mem t opt lvl fml := begin assume mem_node, simp [list_tree_option_level_formula] at mem_node, from Loop_Level_Formula_Option mem root t opt lvl fml mem_node end end types export types.formula (atom implication) export types.node_option (leaf node) export types.tree (leaf u_tree lr_tree) export types.branch (leaf u_branch l_branch r_branch root) /- Proof: Leaf Redundancy -/ namespace p_leaf /- Restrictions Regarding Proof-Trees -/ -- Trees must be finite, meaning that every node must have a path ending on a leaf def is_finite : types.tree → Prop | t := ∀(lvl : ℕ), --------------------------- ( aux.list_size (types.list_tree_option_level t node lvl) ≤ aux.list_size (types.list_tree_option t leaf) ) lemma Case_Option : ∀(t : types.tree), ∀(lll : list (list (list (types.branch)))), ( lll ∈ (types.list_tree t ) ) → --------------------------- ( ∃(opt : types.node_option), lll = types.list_tree_option t opt ) | t lll := begin assume or_eq, simp [types.list_tree] at or_eq, -- ∨-Elimination cases or_eq with eq_leaf eq_node, case or.inl { from exists.intro leaf eq_leaf }, case or.inr { from exists.intro node eq_node } end lemma Length_Tree : ∀(t : types.tree), --------------------------- ( 2 = list.length (types.list_tree t) ) | t := by simp [types.list_tree] lemma Tree_to_Option : ∀(t : types.tree), ∀{num : ℕ}, ( 2 * num < aux.list_size (types.list_tree t) ) → --------------------------- ( ∃(opt : types.node_option), num < aux.list_size (types.list_tree_option t opt) ) | t n := begin assume big_tree, -- Combinatory Property rewrite [Length_Tree t] at big_tree, have main_combinatory, from aux.Main_Combinatory_Nested big_tree, cases main_combinatory with list_opt main_combinatory, cases main_combinatory with list_mem main_combinatory, -- Substitution have case_opt, from Case_Option t list_opt list_mem, cases case_opt with opt case_opt, rewrite [case_opt] at main_combinatory, -- ∃-Introduction from exists.intro opt main_combinatory end lemma Case_Level : ∀(t : types.tree)(opt : types.node_option)(loop : list (ℕ)), ∀(ll : list (list (types.branch))), ( ll ∈ types.loop_tree_option t opt loop ) → --------------------------- ( ∃(lvl : ℕ), lvl ∈ loop ∧ ll = types.list_tree_option_level t opt lvl ) | t opt [] ll := by simp [types.loop_tree_option] | t opt (HEAD::TAIL) ll := begin simp [types.loop_tree_option], assume or_eq_mem, cases or_eq_mem with eq_head list_mem, case or.inl { apply exists.intro HEAD, simp [use.EQ_Refl HEAD], from eq_head }, case or.inr { have case_inductive, from Case_Level t opt TAIL ll list_mem, cases case_inductive with lvl case_inductive, apply exists.intro lvl, cases case_inductive with mem_lvl eq_lllt, simp [mem_lvl], from eq_lllt } end lemma Length_Tree_Option : ∀(t : types.tree)(opt : types.node_option), --------------------------- ( types.count_levels t = list.length (types.list_tree_option t opt) ) | t opt := begin simp [types.list_tree_option, types.count_levels], induction (types.list_levels t), case list.nil { simp [types.loop_tree_option] }, case list.cons { simp [types.loop_tree_option, ih] } end lemma Option_to_Level : ∀(t : types.tree)(opt : types.node_option), ∀{num : ℕ}, ( (types.count_levels t) * num < aux.list_size (types.list_tree_option t opt) ) → --------------------------- ( ∃(lvl : ℕ), lvl ∈ types.list_levels t ∧ num < aux.list_size (types.list_tree_option_level t opt lvl) ) | t opt num := begin assume big_option, -- Combinatory Property rewrite [Length_Tree_Option t opt] at big_option, have main_combinatory, from aux.Main_Combinatory_Nested big_option, cases main_combinatory with list_lvl main_combinatory, cases main_combinatory with list_mem main_combinatory, -- Substitution have case_level, from Case_Level t opt (types.list_levels t) list_lvl list_mem, cases case_level with lvl case_level, cases case_level with mem_lvl case_level, rewrite [case_level] at main_combinatory, -- ∃-Introduction and ∧-Introduction apply exists.intro lvl, from and.intro mem_lvl main_combinatory end lemma Case_Formula : ∀(t : types.tree)(opt : types.node_option)(lvl : ℕ)(loop : list (types.formula)), ∀(l : list (types.branch)), ( l ∈ types.loop_tree_option_level t opt lvl loop ) → --------------------------- ( ∃(fml : types.formula), fml ∈ loop ∧ l = types.list_tree_option_level_formula t opt lvl fml ) | t opt lvl [] ll := by simp [types.loop_tree_option_level] | t opt lvl (HEAD::TAIL) ll := begin simp [types.loop_tree_option_level], assume or_eq_mem, cases or_eq_mem with eq_head list_mem, case or.inl { apply exists.intro HEAD, simp [use.EQ_Refl HEAD], from eq_head }, case or.inr { have case_inductive, from Case_Formula t opt lvl TAIL ll list_mem, cases case_inductive with fml case_inductive, apply exists.intro fml, cases case_inductive with mem_fml eq_llt, simp [mem_fml], from eq_llt } end lemma Length_Tree_Option_Level: ∀(t : types.tree)(opt : types.node_option)(lvl : ℕ), --------------------------- ( types.count_formulas t = list.length (types.list_tree_option_level t opt lvl) ) | t opt lvl := begin simp [types.list_tree_option_level, types.count_formulas], induction (types.list_formulas t), case list.nil { simp [types.loop_tree_option_level] }, case list.cons { simp [types.loop_tree_option_level, ih] } end lemma Level_to_Formula : ∀(t : types.tree)(opt : types.node_option)(lvl : ℕ), ∀{num : ℕ}, ( (types.count_formulas t) * num < aux.list_size (types.list_tree_option_level t opt lvl) ) → --------------------------- ( ∃(fml : types.formula), fml ∈ types.list_formulas t ∧ num < aux.list_size (types.list_tree_option_level_formula t opt lvl fml) ) | t opt lvl num := begin assume big_option_level, -- Combinatory Property rewrite [Length_Tree_Option_Level t opt lvl] at big_option_level, have main_combinatory, from aux.Main_Combinatory_Nested big_option_level, cases main_combinatory with list_fml main_combinatory, cases main_combinatory with list_mem main_combinatory, -- Substitution have case_fml, from Case_Formula t opt lvl (types.list_formulas t) list_fml list_mem, cases case_fml with fml case_fml, cases case_fml with mem_fml case_fml, rewrite [case_fml] at main_combinatory, -- ∃-Introduction and ∧-Introduction apply exists.intro fml, from and.intro mem_fml main_combinatory end lemma Option_to_Leaf : ∀(t : types.tree)(opt : types.node_option), ∀{num : ℕ}, ( is_finite t ) → ( (types.count_levels t) * num < aux.list_size (types.list_tree_option t opt) ) → --------------------------- ( num < aux.list_size (types.list_tree_option t leaf) ) | t leaf num := begin assume finite big_option, have levels_pos, from aux.ZERO_LT_Length_of_LT_Size big_option, rewrite [←Length_Tree_Option t leaf] at levels_pos, have le_mul, from use.LE_Mul_Left_of_Pos levels_pos num, from use.LT_of_LE_of_LT le_mul big_option end | t node num := begin assume finite big_option, have big_lrnode_level, from Option_to_Level t node big_option, cases big_lrnode_level with lvl big_lrnode_level, cases big_lrnode_level with mem_lvl big_lrnode, from use.LT_of_LT_of_LE big_lrnode (finite lvl) end theorem Main_Theorem_Leaves : ∀(t : types.tree)(mul num : ℕ), ( is_finite t ) → ( mul = (2 * (types.count_levels t * (types.count_levels t * (types.count_formulas t * (types.count_formulas t * num))))) ) → ( mul < aux.list_size (types.list_tree t) ) → --------------------------- ( ∃(lvl : ℕ)(fml : types.formula), lvl ∈ types.list_levels t ∧ fml ∈ types.list_formulas t ∧ (types.count_formulas t) * num < aux.list_size (types.list_tree_option_level_formula t leaf lvl fml) ) | t mul num := begin assume finite mul_constant big_tree, rewrite [mul_constant] at big_tree, -- Find a redundant type-constructor within the tree: have big_option, from Tree_to_Option t big_tree, cases big_option with opt big_option, -- Since the tree is finite, there must be a redundant number of leaves within the tree: have big_leaf, from Option_to_Leaf t opt finite big_option, -- Find a redundant level within the repeating leaf-constructor: have big_leaf_level, from Option_to_Level t leaf big_leaf, cases big_leaf_level with lvl big_leaf_level, cases big_leaf_level with mem_lvl big_leaf_level, apply exists.intro lvl, simp [mem_lvl], -- Find a redundant formula within the repeating leaf-constructor/level: have big_leaf_level_formula, from Level_to_Formula t leaf lvl big_leaf_level, cases big_leaf_level_formula with fml big_leaf_level_formula, cases big_leaf_level_formula with mem_fml big_leaf_level_formula, apply exists.intro fml, simp [mem_fml], from big_leaf_level_formula end end p_leaf /- Proof: Leaf Redundancy Implies Proof-Branch Redundancy -/ namespace p_branch /- Methods Regarding Proof-Branchs (Prop) -/ -- Proofs and Derivations in Natural Deduction can be seen as Proof-Trees -- Proofs have no open formulas, while Derivations may have open formulas -- In a Normal Proof-Tree, every Leaf is part of a Proof-Branch -- A Proof-Branch can be obtained by pruning the Branch which connects its Leaf to the proof's conclusion -- This pruning is done top-down, from the Leaf to either the minor premise of an →ELIMINATION or the proof's conclusion -- Along the pruning, if a visited node in the unpruned Branch is the result of an: -- →ELIMINATION from its major premise: visited node = CON; visited premise = _ >> CON; the Proof-Branch continues -- →ELIMINATION from its minor premise: visited node = some formula; the Proof-Branch ends at the visited premise -- →INTRODUCTION: -- In a Normal Proof-Tree, an →INTRODUCTION can only be followed by an: -- →INTRODUCTION: visited node = _ >> CON; visited premise = CON; the Proof-Branch continues -- →ELIMINATION from its minor premise: visited node = some formula; the Proof-Branch ends at the visited premise -- The proof's conclusion: the Proof-Branch ends at the proof's conclusion -- But no matter where this →INTRODUCTION sequence ends, the formula where it ends determines the sequence -- Every Proof-Branch of a Normal Proof-Tree is either: -- Composed of an →ELIMINATION (from its major premise) part followed by an →INTRODUCTION part -- Composed of an →ELIMINATION (from its major premise) only -- Composed of an →INTRODUCTION only -- A Leaf that is the minor premise of an →ELIMINATION -- In an Atomicaly Expanded Normal Proof-Tree: -- If there is an →ELIMINATION part, it ends in a atomic formula -- If there is an →INTRODUCTION part, it begins in a atomic formula -- That is to say, in an Atomicaly Expanded Normal Proof-Tree: -- The Proof-Branch's Leaf determines completely the →ELIMINATION part -- The Proof-Branch's Ending Formula completely determines the →INTRODUCTION part -- Loops over the →INTRODUCTION part def loop_check_intro : ℕ → types.formula → types.branch → Prop | lvl1 fml1 (u_branch BRC OPT LVL0 FML0) := ( OPT = node ) ∧ ( lvl1 = LVL0+1 ) ∧ ( types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1 ) ∧ loop_check_intro LVL0 FML0 BRC | lvl1 fml1 (l_branch BRC OPT LVL0 FML0) := ( OPT = node ) ∧ ( lvl1 = LVL0+1 ) | lvl1 fml1 root := ( lvl1 = 1 ) | _ _ _ := false -- Loops over the →ELIMINATION part and verifies if the minimal formula is atomic def loop_check_elim : ℕ → types.formula → types.branch → Prop | lvl1 fml1 (u_branch BRC OPT LVL0 FML0) := ( OPT = node ) ∧ ( lvl1 = LVL0+1 ) ∧ ( types.is_atomic fml1 ∧ types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1 ) ∧ loop_check_intro LVL0 FML0 BRC | lvl1 fml1 (l_branch BRC OPT LVL0 FML0) := ( OPT = node ) ∧ ( lvl1 = LVL0+1 ) ∧ ( types.is_atomic fml1 ) | lvl1 fml1 (r_branch BRC OPT LVL0 FML0) := ( OPT = node ) ∧ ( lvl1 = LVL0+1 ) ∧ ( types.not_atomic fml1 ∧ types.get_consequent fml1 = FML0 ) ∧ loop_check_elim LVL0 FML0 BRC | lvl1 fml1 root := ( lvl1 = 1 ) ∧ ( types.is_atomic fml1 ) | _ _ _ := false -- Verifies the type of branch (→ELIMINATION→INTRODUCTION; →ELIMINATION; →INTRODUCTION; Leaf) def check_leaf : ℕ → types.formula → types.branch → Prop | lvl1 fml1 (u_branch BRC OPT LVL0 FML0) := ( OPT = node ) ∧ ( lvl1 = LVL0+1 ) ∧ ( types.is_atomic fml1 ∧ types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1 ) ∧ loop_check_intro LVL0 FML0 BRC | lvl1 fml1 (l_branch BRC OPT LVL0 FML0) := ( OPT = node ) ∧ ( lvl1 = LVL0+1 ) | lvl1 fml1 (r_branch BRC OPT LVL0 FML0) := ( OPT = node ) ∧ ( lvl1 = LVL0+1 ) ∧ ( types.not_atomic fml1 ∧ types.get_consequent fml1 = FML0 ) ∧ loop_check_elim LVL0 FML0 BRC | _ _ _ := false -- To check if a regular Branch, ending at the Proof-Tree's conclusion, can be pruned into a Proof-Branch def check_proof_branch : types.branch → Prop | (leaf BRC leaf LVL0 FML0) := check_leaf LVL0 FML0 BRC | _ := false -- Using check_proof_branch as an if-clause demands a proof of decidability for each method instance types.branch.loop_check_intro : ∀(lvl1 : ℕ)(fml1 : types.formula)(b : types.branch), --------------------------------- decidable (loop_check_intro lvl1 fml1 b) | _ _ (leaf _ _ _ _) := begin simp [loop_check_intro], from is_false not_false end | lvl1 fml1 (u_branch BRC OPT LVL0 FML0) := begin simp [loop_check_intro], have dec_and1, from @and.decidable (types.not_atomic FML0) (types.get_consequent FML0 = fml1) (@types.formula.not_atomic FML0) (@types.formula.decidable_eq (types.get_consequent FML0) fml1), have dec_and2, from @and.decidable (types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1) (loop_check_intro LVL0 FML0 BRC) dec_and1 (@types.branch.loop_check_intro LVL0 FML0 BRC), have dec_and3, from @and.decidable (lvl1 = LVL0+1) ((types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1) ∧ loop_check_intro LVL0 FML0 BRC) (@nat.decidable_eq lvl1 (LVL0+1)) dec_and2, from @and.decidable (OPT = node) (lvl1 = LVL0+1 ∧ (types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1) ∧ loop_check_intro LVL0 FML0 BRC) (@types.node_option.decidable_eq OPT node) dec_and3 end | lvl1 fml1 (l_branch BRC OPT LVL0 FML0) := begin simp [loop_check_intro], from @and.decidable (OPT = node) (lvl1 = LVL0 + 1) (@types.node_option.decidable_eq OPT node) (@nat.decidable_eq lvl1 (LVL0+1)) end | _ _ (r_branch _ _ _ _) := begin simp [loop_check_intro], from is_false not_false end | lvl1 fml1 root := begin simp [loop_check_intro], from @nat.decidable_eq lvl1 1 end instance types.branch.loop_check_elim : ∀(lvl1 : ℕ)(fml1 : types.formula)(b : types.branch), --------------------------------- decidable (loop_check_elim lvl1 fml1 b) | _ _ (leaf _ _ _ _) := begin simp [loop_check_elim], from is_false not_false end | lvl1 fml1 (u_branch BRC OPT LVL0 FML0) := begin simp [loop_check_elim], have dec_and1, from @and.decidable (types.not_atomic FML0) (types.get_consequent FML0 = fml1) (@types.formula.not_atomic FML0) (@types.formula.decidable_eq (types.get_consequent FML0) fml1), have dec_and2, from @and.decidable (types.is_atomic fml1) (types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1) (@types.formula.is_atomic fml1) dec_and1, have dec_and3, from @and.decidable (types.is_atomic fml1 ∧ types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1) (loop_check_intro LVL0 FML0 BRC) dec_and2 (@types.branch.loop_check_intro LVL0 FML0 BRC), have dec_and4, from @and.decidable (lvl1 = LVL0+1) ((types.is_atomic fml1 ∧ types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1) ∧ loop_check_intro LVL0 FML0 BRC) (@nat.decidable_eq lvl1 (LVL0+1)) dec_and3, from @and.decidable (OPT = node) (lvl1 = LVL0+1 ∧ (types.is_atomic fml1 ∧ types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1) ∧ loop_check_intro LVL0 FML0 BRC) (@types.node_option.decidable_eq OPT node) dec_and4 end | lvl1 fml1 (l_branch BRC OPT LVL0 FML0) := begin simp [loop_check_elim], have dec_and1, from @and.decidable (lvl1 = LVL0 + 1) (types.is_atomic fml1) (@nat.decidable_eq lvl1 (LVL0+1)) (@types.formula.is_atomic fml1), from @and.decidable (OPT = node) (lvl1 = LVL0 + 1 ∧ types.is_atomic fml1) (@types.node_option.decidable_eq OPT node) dec_and1 end | lvl1 fml1 (r_branch BRC OPT LVL0 FML0) := begin simp [loop_check_elim], have dec_and1, from @and.decidable (types.not_atomic fml1) (types.get_consequent fml1 = FML0) (@types.formula.not_atomic fml1) (@types.formula.decidable_eq (types.get_consequent fml1) FML0), have dec_and2, from @and.decidable (types.not_atomic fml1 ∧ types.get_consequent fml1 = FML0) (loop_check_elim LVL0 FML0 BRC) dec_and1 (@types.branch.loop_check_elim LVL0 FML0 BRC), have dec_and3, from @and.decidable (lvl1 = LVL0+1) ((types.not_atomic fml1 ∧ types.get_consequent fml1 = FML0) ∧ loop_check_elim LVL0 FML0 BRC) (@nat.decidable_eq lvl1 (LVL0+1)) dec_and2, from @and.decidable (OPT = node) (lvl1 = LVL0+1 ∧ (types.not_atomic fml1 ∧ types.get_consequent fml1 = FML0) ∧ loop_check_elim LVL0 FML0 BRC) (@types.node_option.decidable_eq OPT node) dec_and3 end | lvl1 fml1 root := begin simp [loop_check_elim], from @and.decidable (lvl1 = 1) (types.is_atomic fml1) (@nat.decidable_eq lvl1 1) (@types.formula.is_atomic fml1) end instance types.branch.check_leaf : ∀(lvl1 : ℕ)(fml1 : types.formula)(b : types.branch), --------------------------------- decidable (check_leaf lvl1 fml1 b) | _ _ (leaf _ _ _ _) := begin simp [check_leaf], from is_false not_false end | lvl1 fml1 (u_branch BRC OPT LVL0 FML0) := begin simp [check_leaf], have dec_and1, from @and.decidable (types.not_atomic FML0) (types.get_consequent FML0 = fml1) (@types.formula.not_atomic FML0) (@types.formula.decidable_eq (types.get_consequent FML0) fml1), have dec_and2, from @and.decidable (types.is_atomic fml1) (types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1) (@types.formula.is_atomic fml1) dec_and1, have dec_and3, from @and.decidable (types.is_atomic fml1 ∧ types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1) (loop_check_intro LVL0 FML0 BRC) dec_and2 (@types.branch.loop_check_intro LVL0 FML0 BRC), have dec_and4, from @and.decidable (lvl1 = LVL0+1) ((types.is_atomic fml1 ∧ types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1) ∧ loop_check_intro LVL0 FML0 BRC) (@nat.decidable_eq lvl1 (LVL0+1)) dec_and3, from @and.decidable (OPT = node) (lvl1 = LVL0+1 ∧ (types.is_atomic fml1 ∧ types.not_atomic FML0 ∧ types.get_consequent FML0 = fml1) ∧ loop_check_intro LVL0 FML0 BRC) (@types.node_option.decidable_eq OPT node) dec_and4 end | lvl1 fml1 (l_branch BRC OPT LVL0 FML0) := begin simp [check_leaf], from @and.decidable (OPT = node) (lvl1 = LVL0 + 1) (@types.node_option.decidable_eq OPT node) (@nat.decidable_eq lvl1 (LVL0+1)) end | lvl1 fml1 (r_branch BRC OPT LVL0 FML0) := begin simp [check_leaf], have dec_and1, from @and.decidable (types.not_atomic fml1) (types.get_consequent fml1 = FML0) (@types.formula.not_atomic fml1) (@types.formula.decidable_eq (types.get_consequent fml1) FML0), have dec_and2, from @and.decidable (types.not_atomic fml1 ∧ types.get_consequent fml1 = FML0) (loop_check_elim LVL0 FML0 BRC) dec_and1 (@types.branch.loop_check_elim LVL0 FML0 BRC), have dec_and3, from @and.decidable (lvl1 = LVL0+1) ((types.not_atomic fml1 ∧ types.get_consequent fml1 = FML0) ∧ loop_check_elim LVL0 FML0 BRC) (@nat.decidable_eq lvl1 (LVL0+1)) dec_and2, from @and.decidable (OPT = node) (lvl1 = LVL0+1 ∧ (types.not_atomic fml1 ∧ types.get_consequent fml1 = FML0) ∧ loop_check_elim LVL0 FML0 BRC) (@types.node_option.decidable_eq OPT node) dec_and3 end | _ _ root := begin simp [check_leaf], from is_false not_false end instance types.branch.check_proof_branch : ∀(b : types.branch), --------------------------------- decidable (check_proof_branch b) | (leaf BRC leaf LVL0 FML0) := begin simp [check_proof_branch], from @types.branch.check_leaf LVL0 FML0 BRC end | (leaf _ node _ _) := begin simp [check_proof_branch], from is_false not_false end | (u_branch _ _ _ _) := begin simp [check_proof_branch], from is_false not_false end | (l_branch _ _ _ _) := begin simp [check_proof_branch], from is_false not_false end | (r_branch _ _ _ _) := begin simp [check_proof_branch], from is_false not_false end | root := begin simp [check_proof_branch], from is_false not_false end /- Methods Regarding Proof-Branchs (Formulas) -/ -- Finally, the pruning, per se def loop_prune_intro : ℕ → types.formula → types.branch → types.formula | lvl1 fml1 (u_branch BRC OPT LVL0 FML0) := if loop_check_intro lvl1 fml1 (u_branch BRC OPT LVL0 FML0) then loop_prune_intro LVL0 FML0 BRC else #0 --false | lvl1 fml1 (l_branch BRC OPT LVL0 FML0) := if loop_check_intro lvl1 fml1 (l_branch BRC OPT LVL0 FML0) then fml1 else #0 --false | lvl1 fml1 root := if loop_check_intro lvl1 fml1 root then fml1 else #0 --false | _ _ _ := #0 --false def loop_prune_elim : ℕ → types.formula → types.branch → types.formula | lvl1 fml1 (u_branch BRC OPT LVL0 FML0) := if loop_check_elim lvl1 fml1 (u_branch BRC OPT LVL0 FML0) then loop_prune_intro LVL0 FML0 BRC else #0 --false | lvl1 fml1 (l_branch BRC OPT LVL0 FML0) := if loop_check_elim lvl1 fml1 (l_branch BRC OPT LVL0 FML0) then fml1 else #0 --false | lvl1 fml1 (r_branch BRC OPT LVL0 FML0) := if loop_check_elim lvl1 fml1 (r_branch BRC OPT LVL0 FML0) then loop_prune_elim LVL0 FML0 BRC else #0 --false | lvl1 fml1 root := if loop_check_elim lvl1 fml1 root then fml1 else #0 --false | _ _ _ := #0 --false def prune_leaf : ℕ → types.formula → types.branch → types.formula | lvl1 fml1 (u_branch BRC OPT LVL0 FML0) := if check_leaf lvl1 fml1 (u_branch BRC OPT LVL0 FML0) then loop_prune_intro LVL0 FML0 BRC else #0 --false | lvl1 fml1 (l_branch BRC OPT LVL0 FML0) := if check_leaf lvl1 fml1 (l_branch BRC OPT LVL0 FML0) then fml1 else #0 --false | lvl1 fml1 (r_branch BRC OPT LVL0 FML0) := if check_leaf lvl1 fml1 (r_branch BRC OPT LVL0 FML0) then loop_prune_elim LVL0 FML0 BRC else #0 --false | _ _ _ := #0 --false def prune_proof_branch : types.branch → types.formula | (leaf BRC leaf LVL0 FML0) := prune_leaf LVL0 FML0 BRC | _ := #0 --false def prune_branch : types.branch → (types.formula) | (leaf BRC leaf LVL FML) := #0 | _ := #0 --false -- Defining a method to prune all the branches in a list of branches def prune_list_branch : list (types.branch) → list (types.formula) | [] := [] | (HEAD::TAIL) := if check_proof_branch HEAD then [prune_branch HEAD] ++ prune_list_branch TAIL else prune_list_branch TAIL -- def list_proof_branch_root : types.tree → types.node_option → ℕ → types.formula→ types.formula → list (types.formula) | t opt lvl1 fml1 fml0 := aux.list_filter fml0 (prune_list_branch (types.list_tree_option_level_formula t leaf lvl1 fml1)) /- Restrictions Regarding Proof-Branchs -/ -- In a Normal Proof-Tree, every Leaf is part of a Proof-Branch def is_normal_check : types.tree → Prop | t := ∀(lvl1 : ℕ)(fml1 : types.formula)(b : types.branch), ( b ∈ (types.list_tree_option_level_formula t leaf lvl1 fml1) ) → --------------------------- ( check_proof_branch b ) def is_normal_mem : types.tree → Prop | t := ∀(lvl1 : ℕ)(fml1 fml0 : types.formula), ( fml0 ∈ prune_list_branch (types.list_tree_option_level_formula t leaf lvl1 fml1) ) → --------------------------- ( fml0 ∈ types.list_formulas t ) lemma Case_Size : ∀{t : types.tree}{lvl1 : ℕ}{fml1 : types.formula}, ∀{l : list (types.branch)}, ( is_normal_check t ) → ( ∀(b : types.branch), b ∈ l → b ∈ types.list_tree_option_level_formula t leaf lvl1 fml1 ) → --------------------------- ( aux.list_size l = aux.list_size (prune_list_branch l) ) | t lvl1 fml1 [] := begin assume normal_check subset, simp [prune_list_branch, aux.list_size] end | t lvl1 fml1 (HEAD::TAIL) := begin assume normal_check subset, have head_mem : HEAD ∈ types.list_tree_option_level_formula t leaf lvl1 fml1, from begin apply (subset HEAD), simp [has_mem.mem, list.mem] end, have tail_subset : ∀(b : types.branch), b ∈ TAIL → b ∈ types.list_tree_option_level_formula t leaf lvl1 fml1, from begin assume loop loop_mem_tail, apply (subset loop), simp [has_mem.mem, list.mem] at ⊢ loop_mem_tail, simp [loop_mem_tail] end, simp [prune_list_branch], rewrite [use.ITE_Distribution (aux.list_size)], simp [aux.list_size, aux.size, aux.has_size.size], have check_head, from normal_check lvl1 fml1 HEAD head_mem, simp [implies, has_mem.mem, list.mem] at check_head, simp [check_head], rewrite [Case_Size normal_check tail_subset] end lemma Normal_Size : ∀(t : types.tree)(lvl1 : ℕ)(fml1 : types.formula), ( is_normal_check t ) → --------------------------- ( aux.list_size (types.list_tree_option_level_formula t leaf lvl1 fml1) = aux.list_size (prune_list_branch (types.list_tree_option_level_formula t leaf lvl1 fml1)) ) | t lvl1 fml1 := begin assume normal_check, from Case_Size normal_check (use.Subset_Self (types.list_tree_option_level_formula t leaf lvl1 fml1)) end lemma Case_Set : ∀(t : types.tree)(lvl1 : ℕ)(fml1 : types.formula)(n : ℕ), ( is_normal_mem t ) → --------------------------- ( list.length (aux.list_set (prune_list_branch (types.list_tree_option_level_formula t leaf lvl1 fml1))) * n ≤ list.length (types.list_formulas t) * n ) | t lvl1 fml1 n := begin assume normal_mem, have set_le_formulas, from aux.Length_Set_LE_Length_of_Subset (normal_mem lvl1 fml1), from use.LE_Mul_of_LE n set_le_formulas end theorem Main_Theorem_Branchs : ∀(t : types.tree)(lvl1 : ℕ)(fml1 : types.formula)(num : ℕ), ( is_normal_check t ) → ( is_normal_mem t ) → ( (types.count_formulas t) * num < aux.list_size (types.list_tree_option_level_formula t leaf lvl1 fml1) ) → --------------------------- ( ∃(fml0 : types.formula), fml0 ∈ prune_list_branch (types.list_tree_option_level_formula t leaf lvl1 fml1) ∧ num < aux.list_size (list_proof_branch_root t leaf lvl1 fml1 fml0) ) | t lvl1 fml1 num := begin assume normal_check normal_mem big_leaf_level_formula, simp [list_proof_branch_root, aux.list_size] at ⊢ big_leaf_level_formula, simp [types.count_formulas, mul_assoc] at big_leaf_level_formula, rewrite [Normal_Size t lvl1 fml1 normal_check] at big_leaf_level_formula, -- have main_combinatory, from aux.Main_Combinatory_Filter num (prune_list_branch (types.list_tree_option_level_formula t leaf lvl1 fml1)), -- have case_set, from Case_Set t lvl1 fml1 num normal_mem, have big_branch, from main_combinatory (use.LT_of_LE_of_LT case_set big_leaf_level_formula), cases big_branch with fml0 big_branch, cases big_branch with mem_fml0 big_branch, apply exists.intro fml0, simp [mem_fml0], from big_branch end end p_branch /- Proof: Theorem of Proof-Branch Redundancy -/ theorem Proof_Branch_Redundancy : ∀(t : types.tree)(mul num : ℕ), ( p_leaf.is_finite t ) → ( p_branch.is_normal_check t ) → ( p_branch.is_normal_mem t ) → ( mul = (2 * (types.count_levels t * (types.count_levels t * (types.count_formulas t * (types.count_formulas t * num))))) ) → ( mul < aux.list_size (types.list_tree t) ) → --------------------------- ( ∃(lvl1 : ℕ)(fml1 fml0 : types.formula), lvl1 ∈ types.list_levels t ∧ fml1 ∈ types.list_formulas t ∧ fml0 ∈ p_branch.prune_list_branch (types.list_tree_option_level_formula t leaf lvl1 fml1) ∧ num < aux.list_size (p_branch.list_proof_branch_root t leaf lvl1 fml1 fml0) ) | t mul num := begin assume finite normal_check normal_mem mul_constant big_tree, -- Find a repeating leaf-constructor/level/formula: have big_leaf_level_formula, from p_leaf.Main_Theorem_Leaves t mul num finite mul_constant big_tree, cases big_leaf_level_formula with lvl1 big_leaf_level_formula, cases big_leaf_level_formula with fml1 big_leaf_level_formula, cases big_leaf_level_formula with mem_lvl1 big_leaf_level_formula, cases big_leaf_level_formula with mem_fml1 big_leaf_level_formula, apply exists.intro lvl1, simp [mem_lvl1], apply exists.intro fml1, simp [mem_fml1], -- Find a redundant proof-branch from the repeating leaf-constructor/level/formula: have big_branch, from p_branch.Main_Theorem_Branchs t lvl1 fml1 num normal_check normal_mem big_leaf_level_formula, cases big_branch with fml0 big_branch, cases big_branch with mem_fml0 big_branch, apply exists.intro fml0, simp [mem_fml0], from big_branch end
d2acf3436c8dc62b59887b2d545fe22c382c8f83
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/standard/logic/axioms/default.lean
0c549c5059442526c779b7a0b2f078f6ec17e226
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
492
lean
---------------------------------------------------------------------------------------------------- --- Copyright (c) 2014 Microsoft Corporation. All rights reserved. --- Released under Apache 2.0 license as described in the file LICENSE. --- Author: Jeremy Avigad ---------------------------------------------------------------------------------------------------- import logic.axioms.classical logic.axioms.funext logic.axioms.hilbert logic.axioms.piext import logic.axioms.prop_decidable
43ac74245b348d7c2924efe651574afbd8309c59
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/DeclModifiers.lean
0aac7f80f5e13731118d5e4250fa931872740b9a
[ "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
8,033
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.Modifiers import Lean.DocString import Lean.Structure import Lean.Elab.Attributes import Lean.Elab.Exception import Lean.Elab.DeclUtil namespace Lean.Elab def checkNotAlreadyDeclared {m} [Monad m] [MonadEnv m] [MonadError m] (declName : Name) : m Unit := do let env ← getEnv if env.contains declName then match privateToUserName? declName with | none => throwError "'{declName}' has already been declared" | some declName => throwError "private declaration '{declName}' has already been declared" if env.contains (mkPrivateName env declName) then throwError "a private declaration '{declName}' has already been declared" match privateToUserName? declName with | none => pure () | some declName => if env.contains declName then throwError "a non-private declaration '{declName}' has already been declared" inductive Visibility where | regular | «protected» | «private» deriving Inhabited instance : ToString Visibility := ⟨fun | Visibility.regular => "regular" | Visibility.«private» => "private" | Visibility.«protected» => "protected"⟩ inductive RecKind where | «partial» | «nonrec» | default deriving Inhabited structure Modifiers where docString? : Option String := none visibility : Visibility := Visibility.regular isNoncomputable : Bool := false recKind : RecKind := RecKind.default isUnsafe : Bool := false attrs : Array Attribute := #[] deriving Inhabited def Modifiers.isPrivate : Modifiers → Bool | { visibility := Visibility.private, .. } => true | _ => false def Modifiers.isProtected : Modifiers → Bool | { visibility := Visibility.protected, .. } => true | _ => false def Modifiers.isPartial : Modifiers → Bool | { recKind := RecKind.partial, .. } => true | _ => false def Modifiers.isNonrec : Modifiers → Bool | { recKind := RecKind.nonrec, .. } => true | _ => false def Modifiers.addAttribute (modifiers : Modifiers) (attr : Attribute) : Modifiers := { modifiers with attrs := modifiers.attrs.push attr } instance : ToFormat Modifiers := ⟨fun m => let components : List Format := (match m.docString? with | some str => [f!"/--{str}-/"] | none => []) ++ (match m.visibility with | Visibility.regular => [] | Visibility.protected => [f!"protected"] | Visibility.private => [f!"private"]) ++ (if m.isNoncomputable then [f!"noncomputable"] else []) ++ (match m.recKind with | RecKind.partial => [f!"partial"] | RecKind.nonrec => [f!"nonrec"] | _ => []) ++ (if m.isUnsafe then [f!"unsafe"] else []) ++ m.attrs.toList.map (fun attr => format attr) Format.bracket "{" (Format.joinSep components ("," ++ Format.line)) "}"⟩ instance : ToString Modifiers := ⟨toString ∘ format⟩ def expandOptDocComment? [Monad m] [MonadError m] (optDocComment : Syntax) : m (Option String) := match optDocComment.getOptional? with | none => pure none | some s => match s[1] with | Syntax.atom _ val => pure (some (val.extract 0 (val.bsize - 2))) | _ => throwErrorAt s "unexpected doc string{indentD s[1]}" section Methods variable [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] def elabModifiers (stx : Syntax) : m Modifiers := do let docCommentStx := stx[0] let attrsStx := stx[1] let visibilityStx := stx[2] let noncompStx := stx[3] let unsafeStx := stx[4] let recKind := if stx[5].isNone then RecKind.default else if stx[5][0].getKind == ``Parser.Command.partial then RecKind.partial else RecKind.nonrec let docString? ← match docCommentStx.getOptional? with | none => pure none | some s => match s[1] with | Syntax.atom _ val => pure (some (val.extract 0 (val.bsize - 2))) | _ => throwErrorAt s "unexpected doc string{indentD s[1]}" let visibility ← match visibilityStx.getOptional? with | none => pure Visibility.regular | some v => let kind := v.getKind if kind == `Lean.Parser.Command.private then pure Visibility.private else if kind == `Lean.Parser.Command.protected then pure Visibility.protected else throwErrorAt v "unexpected visibility modifier" let attrs ← match attrsStx.getOptional? with | none => pure #[] | some attrs => elabDeclAttrs attrs return { docString?, visibility, recKind, attrs, isUnsafe := !unsafeStx.isNone isNoncomputable := !noncompStx.isNone } def applyVisibility (visibility : Visibility) (declName : Name) : m Name := do match visibility with | Visibility.private => let env ← getEnv let declName := mkPrivateName env declName checkNotAlreadyDeclared declName pure declName | Visibility.protected => checkNotAlreadyDeclared declName let env ← getEnv let env := addProtected env declName setEnv env pure declName | _ => checkNotAlreadyDeclared declName pure declName def checkIfShadowingStructureField (declName : Name) : m Unit := do match declName with | Name.str pre .. => if isStructure (← getEnv) pre then let fieldNames := getStructureFieldsFlattened (← getEnv) pre for fieldName in fieldNames do if pre ++ fieldName == declName then throwError "invalid declaration name '{declName}', structure '{pre}' has field '{fieldName}'" | _ => pure () def mkDeclName (currNamespace : Name) (modifiers : Modifiers) (shortName : Name) : m (Name × Name) := do let name := (extractMacroScopes shortName).name unless name.isAtomic || isFreshInstanceName name do throwError "atomic identifier expected '{shortName}'" let declName := currNamespace ++ shortName checkIfShadowingStructureField declName let declName ← applyVisibility modifiers.visibility declName match modifiers.visibility with | Visibility.protected => match currNamespace with | Name.str _ s _ => pure (declName, Name.mkSimple s ++ shortName) | _ => throwError "protected declarations must be in a namespace" | _ => pure (declName, shortName) /- `declId` is of the form ``` leading_parser ident >> optional (".{" >> sepBy1 ident ", " >> "}") ``` but we also accept a single identifier to users to make macro writing more convenient . -/ def expandDeclIdCore (declId : Syntax) : Name × Syntax := if declId.isIdent then (declId.getId, mkNullNode) else let id := declId[0].getId let optUnivDeclStx := declId[1] (id, optUnivDeclStx) structure ExpandDeclIdResult where shortName : Name declName : Name levelNames : List Name def expandDeclId (currNamespace : Name) (currLevelNames : List Name) (declId : Syntax) (modifiers : Modifiers) : m ExpandDeclIdResult := do -- ident >> optional (".{" >> sepBy1 ident ", " >> "}") let (shortName, optUnivDeclStx) := expandDeclIdCore declId let levelNames ← if optUnivDeclStx.isNone then pure currLevelNames else let extraLevels := optUnivDeclStx[1].getArgs.getEvenElems extraLevels.foldlM (fun levelNames idStx => let id := idStx.getId if levelNames.elem id then withRef idStx $ throwAlreadyDeclaredUniverseLevel id else pure (id :: levelNames)) currLevelNames let (declName, shortName) ← withRef declId $ mkDeclName currNamespace modifiers shortName addDocString' declName modifiers.docString? pure { shortName := shortName, declName := declName, levelNames := levelNames } end Methods end Lean.Elab
2cab21f8effbfc14543d7bf5fb515600e9b80645
b7b549d2cf38ac9d4e49372b7ad4d37f70449409
/src/LeanLLVM/ORCTest.lean
8e6906aae8d65d6b5de7e8aa196417525a0e3c36
[ "Apache-2.0" ]
permissive
GaloisInc/lean-llvm
7cc196172fe02ff3554edba6cc82f333c30fdc2b
36e2ec604ae22d8ec1b1b66eca0f8887880db6c6
refs/heads/master
1,637,359,020,356
1,629,332,114,000
1,629,402,464,000
146,700,234
29
1
Apache-2.0
1,631,225,695,000
1,535,607,191,000
Lean
UTF-8
Lean
false
false
657
lean
import .llvm_ffi import .clang_ffi def main (xs : List String) : IO UInt32 := do llvm.ffi.initNativeFns; s ← llvm.ffi.newCompilerSession (llvm.ffi.newTriple (llvm.ffi.processTriple Unit.unit)); let args := [xs.head, "-stdlib=libc++", "-fcxx-exceptions", "-I/Users/jhendrix/opt/lean4/include", "-I/Users/jhendrix/opt/llvm-8.0.0/include/c++/v1", "-I/Users/jhendrix/opt/llvm-8.0.0/lib/clang/8.0.0/include" ]; llvm.ffi.addFromClang s args.toArray; f ← llvm.ffi.lookupFn s "__Z5l_addPN4lean6objectES1_" (Nat → Nat → Nat); IO.println (f 1 2); pure 0
f614f274e556d104976ff82dd88e7b9212be9bd1
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/proj.lean
1fcd06a86ebd0f435c42230f2fba5cb096f6a293
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
468
lean
import logic data.nat.basic inductive vector (T : Type) : nat → Type := nil {} : vector T nat.zero, cons : T → ∀{n}, vector T n → vector T (nat.succ n) #projections or #projections and #projections eq.refl #projections eq #projections vector inductive point := mk : nat → nat → point #projections point :: x y z #projections point :: x y #projections point :: x y inductive funny : nat → Type := mk : Π (a : nat), funny a #projections funny
50f43cc408f4ff8453fdbde0e84bf92cf476af54
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/category_theory/isomorphism.lean
07fbae06f644127885a67aa679b363ee2e7e411f
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
10,394
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor import tactic.reassoc_axiom /-! # Isomorphisms This file defines isomorphisms between objects of a category. ## Main definitions - `structure iso` : a bundled isomorphism between two objects of a category; - `class is_iso` : an unbundled version of `iso`; note that `is_iso f` is usually *not* a `Prop`, because it holds the inverse morphism; - `as_iso` : convert from `is_iso` to `iso`; - `of_iso` : convert from `iso` to `is_iso`; - standard operations on isomorphisms (composition, inverse etc) ## Notations - `X ≅ Y` : same as `iso X Y`; - `α ≪≫ β` : composition of two isomorphisms; it is called `iso.trans` ## Tags category, category theory, isomorphism -/ universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open category structure iso {C : Type u} [category.{v} C] (X Y : C) := (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id' : hom ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ hom = 𝟙 Y . obviously) restate_axiom iso.hom_inv_id' restate_axiom iso.inv_hom_id' attribute [simp, reassoc] iso.hom_inv_id iso.inv_hom_id infixr ` ≅ `:10 := iso -- type as \cong or \iso variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 variables {X Y Z : C} namespace iso @[ext] lemma ext ⦃α β : X ≅ Y⦄ (w : α.hom = β.hom) : α = β := suffices α.inv = β.inv, by cases α; cases β; cc, calc α.inv = α.inv ≫ (β.hom ≫ β.inv) : by rw [iso.hom_inv_id, category.comp_id] ... = (α.inv ≫ α.hom) ≫ β.inv : by rw [category.assoc, ←w] ... = β.inv : by rw [iso.inv_hom_id, category.id_comp] @[symm] def symm (I : X ≅ Y) : Y ≅ X := { hom := I.inv, inv := I.hom, hom_inv_id' := I.inv_hom_id', inv_hom_id' := I.hom_inv_id' } @[simp] lemma symm_hom (α : X ≅ Y) : α.symm.hom = α.inv := rfl @[simp] lemma symm_inv (α : X ≅ Y) : α.symm.inv = α.hom := rfl @[simp] lemma symm_mk {X Y : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) : iso.symm {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} = {hom := inv, inv := hom, hom_inv_id' := inv_hom_id, inv_hom_id' := hom_inv_id} := rfl @[simp] lemma symm_symm_eq {X Y : C} (α : X ≅ Y) : α.symm.symm = α := by cases α; refl @[simp] lemma symm_eq_iff {X Y : C} {α β : X ≅ Y} : α.symm = β.symm ↔ α = β := ⟨λ h, symm_symm_eq α ▸ symm_symm_eq β ▸ congr_arg symm h, congr_arg symm⟩ @[refl] def refl (X : C) : X ≅ X := { hom := 𝟙 X, inv := 𝟙 X } @[simp] lemma refl_hom (X : C) : (iso.refl X).hom = 𝟙 X := rfl @[simp] lemma refl_inv (X : C) : (iso.refl X).inv = 𝟙 X := rfl @[simp] lemma refl_symm (X : C) : (iso.refl X).symm = iso.refl X := rfl @[trans] def trans (α : X ≅ Y) (β : Y ≅ Z) : X ≅ Z := { hom := α.hom ≫ β.hom, inv := β.inv ≫ α.inv } infixr ` ≪≫ `:80 := iso.trans -- type as `\ll \gg`. @[simp] lemma trans_hom (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).hom = α.hom ≫ β.hom := rfl @[simp] lemma trans_inv (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).inv = β.inv ≫ α.inv := rfl @[simp] lemma trans_mk {X Y Z : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) (hom' : Y ⟶ Z) (inv' : Z ⟶ Y) (hom_inv_id') (inv_hom_id') (hom_inv_id'') (inv_hom_id'') : iso.trans {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} {hom := hom', inv := inv', hom_inv_id' := hom_inv_id', inv_hom_id' := inv_hom_id'} = {hom := hom ≫ hom', inv := inv' ≫ inv, hom_inv_id' := hom_inv_id'', inv_hom_id' := inv_hom_id''} := rfl @[simp] lemma trans_symm (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).symm = β.symm ≪≫ α.symm := rfl @[simp] lemma trans_assoc {Z' : C} (α : X ≅ Y) (β : Y ≅ Z) (γ : Z ≅ Z') : (α ≪≫ β) ≪≫ γ = α ≪≫ β ≪≫ γ := by ext; simp only [trans_hom, category.assoc] @[simp] lemma refl_trans (α : X ≅ Y) : (iso.refl X) ≪≫ α = α := by ext; apply category.id_comp @[simp] lemma trans_refl (α : X ≅ Y) : α ≪≫ (iso.refl Y) = α := by ext; apply category.comp_id @[simp] lemma symm_self_id (α : X ≅ Y) : α.symm ≪≫ α = iso.refl Y := ext α.inv_hom_id @[simp] lemma self_symm_id (α : X ≅ Y) : α ≪≫ α.symm = iso.refl X := ext α.hom_inv_id @[simp] lemma symm_self_id_assoc (α : X ≅ Y) (β : Y ≅ Z) : α.symm ≪≫ α ≪≫ β = β := by rw [← trans_assoc, symm_self_id, refl_trans] @[simp] lemma self_symm_id_assoc (α : X ≅ Y) (β : X ≅ Z) : α ≪≫ α.symm ≪≫ β = β := by rw [← trans_assoc, self_symm_id, refl_trans] lemma inv_comp_eq (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : α.inv ≫ f = g ↔ f = α.hom ≫ g := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_inv_comp (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : g = α.inv ≫ f ↔ α.hom ≫ g = f := (inv_comp_eq α.symm).symm lemma comp_inv_eq (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ α.inv = g ↔ f = g ≫ α.hom := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_comp_inv (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ α.inv ↔ g ≫ α.hom = f := (comp_inv_eq α.symm).symm lemma inv_eq_inv (f g : X ≅ Y) : f.inv = g.inv ↔ f.hom = g.hom := have ∀{X Y : C} (f g : X ≅ Y), f.hom = g.hom → f.inv = g.inv, from λ X Y f g h, by rw [ext h], ⟨this f.symm g.symm, this f g⟩ lemma hom_comp_eq_id (α : X ≅ Y) {f : Y ⟶ X} : α.hom ≫ f = 𝟙 X ↔ f = α.inv := by rw [←eq_inv_comp, comp_id] lemma comp_hom_eq_id (α : X ≅ Y) {f : Y ⟶ X} : f ≫ α.hom = 𝟙 Y ↔ f = α.inv := by rw [←eq_comp_inv, id_comp] lemma hom_eq_inv (α : X ≅ Y) (β : Y ≅ X) : α.hom = β.inv ↔ β.hom = α.inv := by { erw [inv_eq_inv α.symm β, eq_comm], refl } end iso /-- `is_iso` typeclass expressing that a morphism is invertible. This contains the data of the inverse, but is a subsingleton type. -/ class is_iso (f : X ⟶ Y) := (inv : Y ⟶ X) (hom_inv_id' : f ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ f = 𝟙 Y . obviously) export is_iso (inv) def as_iso (f : X ⟶ Y) [h : is_iso f] : X ≅ Y := { hom := f, ..h } @[simp] lemma as_iso_hom (f : X ⟶ Y) [is_iso f] : (as_iso f).hom = f := rfl @[simp] lemma as_iso_inv (f : X ⟶ Y) [is_iso f] : (as_iso f).inv = inv f := rfl namespace is_iso @[simp] lemma hom_inv_id (f : X ⟶ Y) [is_iso f] : f ≫ inv f = 𝟙 X := is_iso.hom_inv_id' f @[simp] lemma inv_hom_id (f : X ⟶ Y) [is_iso f] : inv f ≫ f = 𝟙 Y := is_iso.inv_hom_id' f @[simp] lemma hom_inv_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : X ⟶ Z) : f ≫ inv f ≫ g = g := (as_iso f).hom_inv_id_assoc g @[simp] lemma inv_hom_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : Y ⟶ Z) : inv f ≫ f ≫ g = g := (as_iso f).inv_hom_id_assoc g instance (X : C) : is_iso (𝟙 X) := { inv := 𝟙 X } instance of_iso (f : X ≅ Y) : is_iso f.hom := { .. f } instance of_iso_inverse (f : X ≅ Y) : is_iso f.inv := is_iso.of_iso f.symm variables {f g : X ⟶ Y} {h : Y ⟶ Z} instance inv_is_iso [is_iso f] : is_iso (inv f) := is_iso.of_iso_inverse (as_iso f) instance comp_is_iso [is_iso f] [is_iso h] : is_iso (f ≫ h) := is_iso.of_iso $ (as_iso f) ≪≫ (as_iso h) @[simp] lemma inv_id : inv (𝟙 X) = 𝟙 X := rfl @[simp] lemma inv_comp [is_iso f] [is_iso h] : inv (f ≫ h) = inv h ≫ inv f := rfl @[simp] lemma inv_inv [is_iso f] : inv (inv f) = f := rfl @[simp] lemma iso.inv_inv (f : X ≅ Y) : inv (f.inv) = f.hom := rfl @[simp] lemma iso.inv_hom (f : X ≅ Y) : inv (f.hom) = f.inv := rfl instance epi_of_iso (f : X ⟶ Y) [is_iso f] : epi f := { left_cancellation := λ Z g h w, -- This is an interesting test case for better rewrite automation. by rw [← is_iso.inv_hom_id_assoc f g, w, is_iso.inv_hom_id_assoc f h] } instance mono_of_iso (f : X ⟶ Y) [is_iso f] : mono f := { right_cancellation := λ Z g h w, by rw [←category.comp_id C g, ←category.comp_id C h, ←is_iso.hom_inv_id f, ←category.assoc, w, ←category.assoc] } end is_iso open is_iso lemma eq_of_inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] (p : inv f = inv g) : f = g := begin apply (cancel_epi (inv f)).1, erw [inv_hom_id, p, inv_hom_id], end instance (f : X ⟶ Y) : subsingleton (is_iso f) := ⟨λ a b, suffices a.inv = b.inv, by cases a; cases b; congr; exact this, show (@as_iso C _ _ _ f a).inv = (@as_iso C _ _ _ f b).inv, by congr' 1; ext; refl⟩ lemma is_iso.inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] : inv f = inv g ↔ f = g := iso.inv_eq_inv (as_iso f) (as_iso g) namespace functor universes u₁ v₁ u₂ v₂ variables {D : Type u₂} variables [𝒟 : category.{v₂} D] include 𝒟 def map_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.obj X ≅ F.obj Y := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id], inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] } @[simp] lemma map_iso_hom (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.map_iso i).hom = F.map i.hom := rfl @[simp] lemma map_iso_inv (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.map_iso i).inv = F.map i.inv := rfl @[simp] lemma map_iso_symm (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.map_iso i.symm = (F.map_iso i).symm := rfl @[simp] lemma map_iso_trans (F : C ⥤ D) {X Y Z : C} (i : X ≅ Y) (j : Y ≅ Z) : F.map_iso (i ≪≫ j) = (F.map_iso i) ≪≫ (F.map_iso j) := by ext; apply functor.map_comp @[simp] lemma map_iso_refl (F : C ⥤ D) (X : C) : F.map_iso (iso.refl X) = iso.refl (F.obj X) := iso.ext $ F.map_id X instance map_is_iso (F : C ⥤ D) (f : X ⟶ Y) [is_iso f] : is_iso (F.map f) := is_iso.of_iso $ F.map_iso (as_iso f) @[simp] lemma map_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) = inv (F.map f) := rfl @[simp] lemma map_hom_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map f ≫ F.map (inv f) = 𝟙 (F.obj X) := by rw [map_inv, is_iso.hom_inv_id] @[simp] lemma map_inv_hom (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) ≫ F.map f = 𝟙 (F.obj Y) := by rw [map_inv, is_iso.inv_hom_id] end functor end category_theory
e6baa7a866c011be369c02b1416756f011c0c4c2
9dc8cecdf3c4634764a18254e94d43da07142918
/src/tactic/core.lean
7524e2a649cc3e6caa25c95a8c9f1de3e8aa7310
[ "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
99,472
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import control.basic import data.dlist.basic import meta.expr import system.io import tactic.binder_matching import tactic.interactive_expr import tactic.lean_core_docs import tactic.project_dir universe u attribute [derive [has_reflect, decidable_eq]] tactic.transparency -- Rather than import data.prod.lex here, we can get away with defining the order by hand. instance : has_lt pos := { lt := λ x y, x.line < y.line ∨ x.line = y.line ∧ x.column < y.column } namespace tactic /-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/ meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) /-- Turns a conversion tactic into one that always succeeds, where failure is interpreted as a proof by reflexivity. -/ meta def or_refl_conv (tac : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := tac e <|> refl_conv e /-- Transitivity conversion: given two conversions (which take an expression `e` and returns `(e', ⊢ e = e')`), produces another conversion that combines them with transitivity, treating failures as reflexivity conversions. -/ meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e end tactic open tactic namespace expr /-- Given an expr `α` representing a type with numeral structure, `of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) /-- Given an expr `α` representing a type with numeral structure, `of_int α n` creates the `α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] /-- Convert a list of expressions to an expression denoting the list of those expressions. -/ meta def of_list (α : expr) : list expr → tactic expr | [] := tactic.mk_app ``list.nil [α] | (x :: xs) := do exs ← of_list xs, tactic.mk_app ``list.cons [α, x, exs] /-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/ meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner /-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/ meta def traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es /-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`, with initial value `a`. -/ meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) /-- `kreplace e old new` replaces all occurrences of the expression `old` in `e` with `new`. The occurrences of `old` in `e` are determined using keyed matching with transparency `md`; see `kabstract` for details. If `unify` is true, we may assign metavariables in `e` as we match subterms of `e` against `old`. -/ meta def kreplace (e old new : expr) (md := semireducible) (unify := tt) : tactic expr := do e ← kabstract e old md unify, pure $ e.instantiate_var new end expr namespace name /-- `pre.contains_sorry_aux nm` checks whether `sorry` occurs in the value of the declaration `nm` or (recusively) in any declarations occurring in the value of `nm` with namespace `pre`. Auxiliary function for `name.contains_sorry`. -/ meta def contains_sorry_aux (pre : name) : name → tactic bool | nm := do env ← get_env, decl ← get_decl nm, ff ← return decl.value.contains_sorry | return tt, (decl.value.list_names_with_prefix pre).mfold ff $ λ n b, if b then return tt else n.contains_sorry_aux /-- `nm.contains_sorry` checks whether `sorry` occurs in the value of the declaration `nm` or in any declarations `nm._proof_i` (or to be more precise: any declaration in namespace `nm`). See also `expr.contains_sorry`. -/ meta def contains_sorry (nm : name) : tactic bool := nm.contains_sorry_aux nm end name namespace interaction_monad open result variables {σ : Type} {α : Type u} /-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.read` in core. meta def get_state : interaction_monad σ σ := λ state, success state state /-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.write` in core. meta def set_state (state : σ) : interaction_monad σ unit := λ _, success () state /-- `run_with_state state tac` applies `tac` to the given state `state` and returns the result, subsequently restoring the original state. If `tac` fails, then `run_with_state` does too. -/ meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α := λ s, match tac state with | success val _ := success val s | exception fn pos _ := exception fn pos s end end interaction_monad namespace format /-- `join' [a,b,c]` produces the format object `abc`. It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/ meta def join' (xs : list format) : format := xs.foldl compose nil /-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`, where `.` represents `format.join`. -/ meta def intercalate (x : format) : list format → format := join' ∘ list.intersperse x /-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)` the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z` each line break is decided independently -/ meta def soft_break : format := group line /-- Format a list as a comma separated list, without any brackets. -/ meta def comma_separated {α : Type*} [has_to_format α] : list α → format | [] := nil | xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) end format section format open format /-- format a `list` by separating elements with `soft_break` instead of `line` -/ meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format := bracket "[" "]" (comma_separated l) end format namespace tactic open function export interaction_monad (get_state set_state run_with_state) /-- Private work function for `add_local_consts_as_local_hyps`: given `mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local hypothesis created as a result and `(var :: rest) : list expr` of more local variables we examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the back of the queue and recurse. If it does not, then we perform replacements inside the type of `var` using the `mappings`, create a new associate local hypothesis, add this to the list of mappings, and recurse. We are done once all local hypotheses have been processed. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ private meta def add_local_consts_as_local_hyps_aux : list (expr × expr) → list expr → tactic (list (expr × expr)) | mappings [] := return mappings | mappings (var :: rest) := do /- Determine if `var` contains any local variables in the lift `rest`. -/ let is_dependent := var.local_type.fold ff $ λ e n b, if b then b else e ∈ rest, /- If so, then skip it---add it to the end of the variable queue. -/ if is_dependent then add_local_consts_as_local_hyps_aux mappings (rest ++ [var]) else do /- Otherwise, replace all of the local constants referenced by the type of `var` with the respective new corresponding local hypotheses as recorded in the list `mappings`. -/ let new_type := var.local_type.replace_subexprs mappings, /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/ hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type), /- Process the next variable in the queue, with the mapping list updated to include the local hypothesis which we just created. -/ add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest /-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the tactic state. This is harder than it sounds, since the list of local constants which we have been passed can have dependencies between their types. For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as a new local hypothesis, not the old local constant `n` with the same name. Of course, these dependencies can be nested arbitrarily deep. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) := /- The `list.reverse` below is a performance optimisation since the list of available variables reported by the system is often mostly the reverse of the order in which they are dependent. -/ add_local_consts_as_local_hyps_aux [] vars.reverse.dedup private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of `type`. -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of `fn`'s type. -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity private meta def get_app_fn_args_whnf_aux (md : transparency) (unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) := λ args e, do e ← whnf e md unfold_ginductive, match e with | (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t | _ := pure (e, args) end /-- For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e` is normalised as necessary; for example: ``` get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)]) ``` The returned expression is in whnf, but the arguments are generally not. -/ meta def get_app_fn_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (expr × list expr) := get_app_fn_args_whnf_aux md unfold_ginductive [] e /-- `get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expression is in whnf. -/ meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr | e md unfold_ginductive := do e ← whnf e md unfold_ginductive, match e with | (expr.app f _) := get_app_fn_whnf f md unfold_ginductive | _ := pure e end /-- `get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x₁ ... xₙ`, where `C` is a constant, after normalisation with transparency `md`. If so, the name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. -/ meta def get_app_fn_const_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic name := do f ← get_app_fn_whnf e md unfold_ginductive, match f with | (expr.const n _) := pure n | _ := fail format! "expected a constant (possibly applied to some arguments), but got:\n{e}" end /-- `get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expressions are not necessarily in whnf. -/ meta def get_app_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr) := prod.snd <$> get_app_fn_args_whnf e md unfold_ginductive /-- `pis loc_consts f` is used to create a pi expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with pi binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``pis [a, b] `(f a b)`` will return the expression `Π (a : Ta) (b : Tb), f a b`. -/ meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with lambda binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``lambdas [a, b] `(f a b)`` will return the expression `λ (a : Ta) (b : Tb), f a b`. -/ meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- Given an expression `f` (likely a binary operation) and a further expression `x`, calling `list_binary_operands f x` breaks `x` apart into successions of applications of `f` until this can no longer be done and returns a list of the leaves of the process. This matches `f` up to semireducible unification. In particular, it will match applications of the same polymorphic function with different type-class arguments. E.g., if `i1` and `i2` are both instances of `has_add T` and `e := has_add.add T i1 x (has_add.add T i2 y z)`, then ``list_binary_operands `((+) : T → T → T) e`` returns `[x, y, z]`. For example: ```lean #eval list_binary_operands `(@has_add.add ℕ _) `(3 + (4 * 5 + 6) + 7 / 3) >>= tactic.trace -- [3, 4 * 5, 6, 7 / 3] #eval list_binary_operands `(@list.append ℕ) `([1, 2] ++ [3, 4] ++ (1 :: [])) >>= tactic.trace -- [[1, 2], [3, 4], [1]] ``` -/ meta def list_binary_operands (f : expr) : expr → tactic (list expr) | x@(expr.app (expr.app g a) b) := do some _ ← try_core (unify f g) | pure [x], as ← list_binary_operands a, bs ← list_binary_operands b, pure (as ++ bs) | a := pure [a] -- TODO: move to `declaration` namespace in `meta/expr.lean` /-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named `ls`, type `t`, and body `e`. -/ meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) /-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this to the environment as a theorem with name `n` and universe parameters `ls`. -/ meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ expr.const n $ ls.map level.param /-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`. This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare situations the latter will fail but the former will succeed. -/ meta def eval_expr' (α : Type*) [reflected _ α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α /-- `mk_fresh_name` returns identifiers starting with underscores, which are not legal when emitted by tactic programs. `mk_user_fresh_name` turns the useful source of random names provided by `mk_fresh_name` into names which are usable by tactic programs. The returned name has four components which are all strings. -/ meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ /-- `has_attribute' attr_name decl_name` checks whether `decl_name` exists and has attribute `attr_name`. -/ meta def has_attribute' (attr_name decl_name : name) : tactic bool := succeeds (has_attribute attr_name decl_name) /-- Checks whether the name is a simp lemma -/ meta def is_simp_lemma : name → tactic bool := has_attribute' `simp /-- Checks whether the name is an instance. -/ meta def is_instance : name → tactic bool := has_attribute' `instance /-- `local_decls` returns a dictionary mapping names to their corresponding declarations. Covers all declarations from the current file. -/ meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file e d.to_name then s.insert d.to_name d else s), pure xs /-- `get_decls_from` returns a dictionary mapping names to their corresponding declarations. Covers all declarations the files listed in `fs`, with the current file listed as `none`. The path of the file names is expected to be relative to the root of the project (i.e. the location of `leanpkg.toml` when it is present); e.g. `"src/tactic/core.lean"` Possible issue: `get_decls_from` uses `get_cwd`, the current working directory, which may not always point at the root of the project. It would work better if it searched for the root directory or, better yet, if Lean exposed its path information. -/ meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) := do root ← unsafe_run_io $ io.env.get_cwd, let fs := fs.map (option.map $ λ path, root ++ "/" ++ path), err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists, guard (err = []) <|> fail format!"File not found: {err}", e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, let source := e.decl_olean d.to_name in if source ∈ fs ∧ (source = none → e.in_current_file d.to_name) then s.insert d.to_name d else s), pure xs /-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/ meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n := let nm' := nm.append_suffix ("_" ++ to_string n) in if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm' /-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it returns that, otherwise it tries `nm_2`, `nm_3`, ... -/ meta def get_unused_decl_name (nm : name) : tactic name := get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm /-- Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type` but with universe params updated to match the fresh universe metavariables in `e`. This should have the same effect as just ```lean do e ← mk_const d.to_name, t ← infer_type e, return (e, t) ``` but is hopefully faster. -/ meta def decl_mk_const (d : declaration) : tactic (expr × expr) := do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ, let e : expr := expr.const d.to_name (prod.snd <$> subst), return (e, d.type.instantiate_univ_params subst) /-- Replace every universe metavariable in an expression with a universe parameter. (This is useful when making new declarations.) -/ meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr := do e.list_univ_meta_vars.enum.mmap (λ n, do let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)), unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))), instantiate_mvars e /-- `mk_local n` creates a dummy local variable with name `n`. The type of this local constant is a constant with name `n`, so it is very unlikely to be a meaningful expression. -/ meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) /-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`, `y : ty x` and `z : tz x y`, creates an expression of sigma type: `⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`. -/ meta def mk_psigma : list expr → tactic expr | [] := mk_const ``punit | [x@(expr.local_const _ _ _ _)] := pure x | (x@(expr.local_const _ _ _ _) :: xs) := do y ← mk_psigma xs, α ← infer_type x, β ← infer_type y, t ← lambdas [x] β >>= instantiate_mvars, r ← mk_mapp ``psigma.mk [α,t], pure $ r x y | _ := fail "mk_psigma expects a list of local constants" /-- Update the type of a local constant or metavariable. For local constants and metavariables obtained via, for example, `tactic.get_local`, the type stored in the expression is not necessarily the same as the type returned by `infer_type`. This tactic, given a local constant or metavariable, updates the stored type to match the output of `infer_type`. If the input is not a local constant or metavariable, `update_type` does nothing. -/ meta def update_type : expr → tactic expr | e@(expr.local_const ppname uname binfo _) := expr.local_const ppname uname binfo <$> infer_type e | e@(expr.mvar ppname uname _) := expr.mvar ppname uname <$> infer_type e | e := pure e /-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n` times and uses `ns` to name the resulting variables. Returns a triple: list of new variables, remaining term and unused variable names. -/ meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name) | 0 e hs ns := return (hs.reverse, e, ns) | (n + 1) e hs ns := do t ← infer_type e, if t.is_app_of `eq then return (hs.reverse, e, ns) else do [(_, [h, h'], _)] ← cases_core e (ns.take 1), elim_gen_prod n h' (h :: hs) (ns.drop 1) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) /-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`. -/ meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] /-- Given `elab_def`, a tactic to solve the current goal, `extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it to close the goal. If `trusted` is false, it will be a meta definition. -/ meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map expr.to_implicit_local_const <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n /-- Attempts to close the goal with `dec_trivial`. -/ meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion. -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Runs a tactic for a result, reverting the state after completion or error. -/ meta def retrieve' {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) (λ msg pos s', result.exception msg pos s) /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t /-- Given a tactic `tac` that takes an expression and returns a new expression and a proof of equality, use that tactic to change the type of the hypotheses listed in `hs`, as well as the goal if `tgt = tt`. Returns `tt` if any types were successfully changed. -/ meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) /-- `revert_after e` reverts all local constants after local constant `e`. -/ meta def revert_after (e : expr) : tactic ℕ := do l ← local_context, [pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}", let l := l.drop pos.succ, -- all local hypotheses after `e` revert_lst l /-- `revert_target_deps` reverts all local constants on which the target depends (recursively). Returns the number of local constants that have been reverted. -/ meta def revert_target_deps : tactic ℕ := do tgt ← target, ctx ← local_context, l ← ctx.mfilter (kdepends_on tgt), n ← revert_lst l, if l = [] then return n else do m ← revert_target_deps, return (m + n) /-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`. `generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the goal, in which case it just calls `assert`. In contrast to `generalize` it already introduces the generalized variable. -/ meta def generalize' (e : expr) (n : name) : tactic expr := (generalize e n >> intro n) <|> note n none e /-- `intron_no_renames n` calls `intro` `n` times, using the pretty-printing name provided by the binder to name the new local constant. Unlike `intron`, it does not rename introduced constants if the names shadow existing constants. -/ meta def intron_no_renames : ℕ → tactic unit | 0 := pure () | (n+1) := do expr.pi pp_n _ _ _ ← target, intro pp_n, intron_no_renames n /-- `get_univ_level t` returns the universe level of a type `t` -/ meta def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := tt) : tactic level := do expr.sort u ← infer_type t >>= λ s, whnf s md unfold_ginductive | fail "get_univ_level: argument is not a type", return u /-! ### Various tactics related to local definitions (local constants of the form `x : α := t`) We call `t` the value of `x`. -/ /-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined locally using a `let` expression. Otherwise it fails. -/ meta def local_def_value (e : expr) : tactic expr := pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad. tactic.unsafe.type_context.run $ do lctx <- tactic.unsafe.type_context.get_local_context, some ldecl <- return $ lctx.get_local_decl e.local_uniq_name | tactic.unsafe.type_context.fail format!"No such hypothesis {s}.", some let_val <- return ldecl.value | tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.", return let_val /-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form `e : α := t`) and otherwise fails. -/ meta def is_local_def (e : expr) : tactic unit := do ctx ← unsafe.type_context.get_local_context.run, (some decl) ← pure $ ctx.get_local_decl e.local_uniq_name | fail format!"is_local_def: {e} is not a local constant", when decl.value.is_none $ fail format!"is_local_def: {e} is not a local definition" /-- Returns the local definitions from the context. A local definition is a local constant of the form `e : α := t`. The local definitions are returned in the order in which they appear in the context. -/ meta def local_defs : tactic (list expr) := do ctx ← unsafe.type_context.get_local_context.run, ctx' ← local_context, ctx'.mfilter $ λ h, do (some decl) ← pure $ ctx.get_local_decl h.local_uniq_name | fail format!"local_defs: local {h} not found in the local context", pure decl.value.is_some /-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs` (using membership to `vs` instead of a predicate) and breaks `xs` when matches are found. whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition running up to the first match. -/ private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) : list α → list α → list (list α) | [] acc := [acc.reverse] | (l :: ls) acc := if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l] else partition_local_deps_aux ls (l :: acc) /-- `partition_local_deps vs`, with `vs` a list of local constants, reorders `vs` in the order they appear in the local context together with the variables that follow them. If local context is `[a,b,c,d,e,f]`, and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`. The head of each list is one of the variables given as a parameter. -/ meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) := do ls ← local_context, pure (partition_local_deps_aux vs ls []).tail.reverse /-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ... changing them into regular hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of locals `e₀`, `e₁`, `e₂` does not matter as a permutation will be chosen so as to preserve type correctness. This tactic is called `clearbody` in Coq. -/ meta def clear_value (vs : list expr) : tactic unit := do ls ← partition_local_deps vs, ls.mmap' $ λ vs, do { revert_lst vs, (expr.elet v t d b) ← target | fail format!"Cannot clear the body of {vs.head}. It is not a local definition.", let e := expr.pi v binder_info.default t b, type_check e <|> fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.", g ← mk_meta_var e, h ← note `h none g, tactic.exact $ h d, gs ← get_goals, set_goals $ g :: gs }, ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name /-- `context_has_local_def` is true iff there is at least one local definition in the context. -/ meta def context_has_local_def : tactic bool := do ctx ← local_context, ctx.many (succeeds ∘ local_def_value) /-- `context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the context up to and including `h` is a local definition. -/ meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do ff ← succeeds (local_def_value h) | pure tt, ctx ← local_context, let ctx := ctx.take_while (≠ h), ctx.many (succeeds ∘ local_def_value) /-- If the expression `h` is a local variable with type `x = t` or `t = x`, where `x` is a local constant, `tactic.subst' h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. If `h` is another local variable, then we find a local constant with type `h = t` or `t = h` and substitute `t` for `h`. This is like `tactic.subst`, but fails with a nicer error message if the substituted variable is a local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib. -/ meta def subst' (h : expr) : tactic unit := do e ← do { -- we first find the variable being substituted away t ← infer_type h, let (f, args) := t.get_app_fn_args, if (f.const_name = `eq ∨ f.const_name = `heq) then do { let lhs := args.inth 1, let rhs := args.ilast, if rhs.is_local_constant then return rhs else if lhs.is_local_constant then return lhs else fail "subst tactic failed, hypothesis '{h.local_pp_name}' is not of the form (x = t) or (t = x)." } else return h }, success_if_fail (is_local_def e) <|> fail format!("Cannot substitute variable {e.local_pp_name}, " ++ "it is a local definition. If you really want to do this, use `clear_value` first."), subst h /-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions, `simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting expression and a proof of equality. -/ meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg /-- Caches unary type classes on a type `α : Type.{univ}`. -/ meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) /-- Creates an `instance_cache` for the type `α`. -/ meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache /-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of `n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance via type class resolution, and updates the cache. -/ meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr /-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`, `append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/ meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) /-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`. -/ meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) /-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) := if n = 0 then c.mk_app ``has_zero.zero [] else do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, (c, one) ← c.mk_app ``has_one.one [], return (c, n.binary_rec one $ λ b n e, if n = 0 then one else cond b ((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) ((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])) /-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr) | (n : ℕ) := c.of_nat n | -[1+ n] := do (c, e) ← c.of_nat (n+1), c.mk_app ``has_neg.neg [e] end instance_cache /-- A variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) /-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/ meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] /-- When `struct_n` is the name of a structure type, `subobject_names struct_n` returns two lists of names `(instances, fields)`. The names in `instances` are the projections from `struct_n` to the structures that it extends (assuming it was defined with `old_structure_cmd false`). The names in `fields` are the standard fields of `struct_n`. -/ meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, c ← match env.constructors_of struct_n with | [c] := pure c | [] := if env.is_inductive struct_n then fail format!"{struct_n} does not have constructors" else fail format!"{struct_n} is not an inductive type" | _ := fail "too many constructors" end, vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do (_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function /-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name of the projection is `prefix.name`. `struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/ meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n /-- Return a list of all type classes which can be instantiated for the given expression. -/ meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) /-- Finds an instance of an implication `cond → tgt`. Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention `e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used, since it has been "proven" by a metavariable. -/ meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do f ← mk_meta_var cond, e ← assertv `c cond f, swap, reset_instance_cache, inst ← mk_instance tgt, return (e, inst) open nat /-- Create a list of `n` fresh metavariables. -/ meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /-- Returns the only goal, or fails if there isn't just one goal. -/ meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "there are no goals" | _ := fail "there are too many goals" end /-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- `apply_list l`, for `l : list (tactic expr)`, tries to apply the lemmas generated by the tactics in `l` on the first goal, and fail if none succeeds. -/ meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit | [] := fail "no matching rule" | (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t /-- Given the name of a user attribute, produces a list of `tactic expr`s, each of which is the application of `i_to_expr_for_apply` to a declaration with that attribute. -/ meta def resolve_attribute_expr_list (attr_name : name) : tactic (list (tactic expr)) := do l ← attribute.get_instances attr_name, list.map i_to_expr_for_apply <$> list.reverse <$> l.mmap resolve_name /--`apply_rules args attrs n`: apply the lists of rules `args` (given as pexprs) and `attrs` (given as names of attributes) and `the tactic assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies a lemma from the list until it can't. -/ meta def apply_rules (args : list pexpr) (attrs : list name) (n : nat) (opt : apply_cfg) : tactic unit := do attr_exprs ← lock_tactic_state $ attrs.mfoldl (λ l n, list.append l <$> resolve_attribute_expr_list n) [], let args_exprs := args.map i_to_expr_for_apply ++ attr_exprs, -- `args_exprs` is a list of `tactic expr`, rather than just `expr`, because these expressions will -- be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck. iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt args_exprs) /-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`. Fails if there is nothing named `h` in the local context. -/ meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' /-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp`` or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an `iff`, returns an expression with the `iff` converted to either the forwards or backwards implication, as requested. -/ meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0) | _ f := none /-- `iff_mp_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/ meta def iff_mp_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mp ty (λ_, e) /-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/ meta def iff_mpr_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mpr ty (λ_, e) /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the forward implication. -/ meta def iff_mp (e : expr) : tactic expr := do t ← infer_type e, iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the reverse implication. -/ meta def iff_mpr (e : expr) : tactic expr := do t ← infer_type e, iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Attempts to apply `e`, and if that fails, if `e` is an `iff`, try applying both directions separately. -/ meta def apply_iff (e : expr) : tactic (list (name × expr)) := let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap) /-- Configuration options for `apply_any`: * `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again. * `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again. * `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`. -/ meta structure apply_any_opt extends apply_cfg := (use_symmetry : bool := tt) (use_exfalso : bool := tt) /-- This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s, and evaluates these as thunks before trying to apply them. We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`. -/ meta def apply_any_thunk (lemmas : list (tactic expr)) (opt : apply_any_opt := {}) (tac : tactic unit := skip) (on_success : expr → tactic unit := (λ _, skip)) (on_failure : tactic unit := skip) : tactic unit := do let modes := [skip] ++ (if opt.use_symmetry then [symmetry] else []) ++ (if opt.use_exfalso then [exfalso] else []), modes.any_of (λ m, do m, lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|> (on_failure >> fail "apply_any tactic failed; no lemma could be applied") /-- `apply_any lemmas` tries to apply one of the list `lemmas` to the current goal. `apply_any lemmas opt` allows control over how lemmas are applied. `opt` has fields: * `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.) * `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.) * `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`). `apply_any lemmas tac` calls the tactic `tac` after a successful application. Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange recursive invocations of `apply_any`. -/ meta def apply_any (lemmas : list expr) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := apply_any_thunk (lemmas.map pure) opt tac /-- Try to apply a hypothesis from the local context to the goal. -/ meta def apply_assumption : tactic unit := local_context >>= apply_any /-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails if this is not a definitional equality. `change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e` by reverting `h`, changing the goal, and reintroducing hypotheses. -/ meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`, assuming `olde` and `newe` are defeq when elaborated. -/ meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit := do h ← get_local hyp, tp ← infer_type h, olde ← to_expr olde, newe ← to_expr newe, let repl_tp := tp.replace (λ a n, if a = olde then some newe else none), when (repl_tp ≠ tp) $ change_core repl_tp (some h) /-- Returns a list of all metavariables in the current partial proof. This can differ from the list of goals, since the goals can be manually edited. -/ meta def metavariables : tactic (list expr) := expr.list_meta_vars <$> result /-- `sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`, and fail otherwise. -/ meta def sorry_if_contains_sorry : tactic unit := do g ← target, guard g.contains_sorry <|> fail "goal does not contain `sorry`", tactic.admit /-- Fail if the target contains a metavariable. -/ meta def no_mvars_in_target : tactic unit := expr.has_meta_var <$> target >>= guardb ∘ bnot /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do g :: _ ← get_goals, is_proof g >>= guardb /-- Succeeds only if we can construct an instance showing the current goal is a subsingleton type. -/ meta def subsingleton_goal : tactic unit := do g :: _ ← get_goals, ty ← infer_type g >>= instantiate_mvars, to_expr ``(subsingleton %%ty) >>= mk_instance >> skip /-- Succeeds only if the current goal is "terminal", in the sense that no other goals depend on it (except possibly through shared metavariables; see `independent_goal`). -/ meta def terminal_goal : tactic unit := propositional_goal <|> subsingleton_goal <|> do g₀ :: _ ← get_goals, mvars ← (λ L, list.erase L g₀) <$> metavariables, mvars.mmap' $ λ g, do t ← infer_type g >>= instantiate_mvars, d ← kdepends_on t g₀, monad.whenb d $ pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.") /-- Succeeds only if the current goal is "independent", in the sense that no other goals depend on it, even through shared meta-variables. -/ meta def independent_goal : tactic unit := no_mvars_in_target >> terminal_goal /-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`, it only unfolds reducible definitions, so it sometimes fails faster. -/ meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} /-- Apply a tactic as many times as possible, collecting the results in a list. Fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate t, return (r :: L) /-- Introduces one or more variables and returns the new local constants. Fails if `intro` cannot be applied. -/ meta def intros1 : tactic (list expr) := iterate1 intro1 /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders {α : Type} (t : tactic α) : tactic α := do v ← intros, r ← t, revert_lst v, return r namespace interactive /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders (i : itactic) : itactic := tactic.under_binders i end interactive /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results, and reverting to the original `tactic_state`. -/ -- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`. meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) := λ s, result.success (tactics.map $ λ t : tactic α, match t s with | result.success a s' := [a] | _ := [] end).join s /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results sorted by the value produced by a subsequent execution of the `sort_by` tactic, and reverting to the original `tactic_state`. -/ meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) : tactic (list (α × ℕ)) := λ s, result.success ((tactics.map $ λ t : tactic α, match (do a ← t, n ← sort_by, return (a, n)) s with | result.success a s' := [a] | _ := [] end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s /-- Return target after instantiating metavars and whnf. -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] add_tactic_doc { name := "fsplit", category := doc_category.tactic, decl_names := [`tactic.interactive.fsplit], tags := ["logic", "goal management"] } /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] add_tactic_doc { name := "injections_and_clear", category := doc_category.tactic, decl_names := [`tactic.interactive.injections_and_clear], tags := ["context management"] } /-- Calls `cases` on every local hypothesis, succeeding if it succeeds on at least one hypothesis. -/ meta def case_bash : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, cases h >> skip)), when (r.empty) failed /-- `note_anon t v`, given a proof `v : t`, adds `h : t` to the current context, where the name `h` is fresh. `note_anon none v` will infer the type `t` from `v`. -/ -- While `note` provides a default value for `t`, it doesn't seem this could ever be used. meta def note_anon (t : option expr) (v : expr) : tactic expr := do h ← get_unused_name `h none, note h t v /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, (prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|> fail format!"No hypothesis found of the form: {t'}" /-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), old::other_goals ← get_goals, t ← infer_type old, new_goal ← mk_meta_var (t.pis lc), set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- Instantiates metavariables that appear in the current goal. -/ meta def instantiate_mvars_in_target : tactic unit := target >>= instantiate_mvars >>= change /-- Instantiates metavariables in all goals. -/ meta def instantiate_mvars_in_goals : tactic unit := all_goals' $ instantiate_mvars_in_target /-- Protect the declaration `n` -/ meta def mk_protected (n : name) : tactic unit := do env ← get_env, set_env (env.mk_protected n) end tactic namespace lean.parser open tactic interaction_monad /-- A version of `lean.parser.many` that requires at least `n` items -/ meta def repeat_at_least {α : Type} (p : lean.parser α) : ℕ → lean.parser (list α) | 0 := many p | (n + 1) := list.cons <$> p <*> repeat_at_least n /-- A version of `lean.parser.sep_by` that allows trailing delimiters, but requires at least one item. Like `lean.parser.sep_by`, as a result of the `lean.parser` monad not being pure, this is only well-behaved if `p` and `s` are backtrackable; which in practice means they must not consume the input when they do not have a match. -/ meta def sep_by_trailing {α : Type} (s : lean.parser unit) (p : lean.parser α) : lean.parser (list α) := do fst ← p, some () ← optional s | pure [fst], some rest ← optional sep_by_trailing | pure [fst], pure (fst :: rest) /-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the current line. -/ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left /-- Inner recursion for `emit_code_here`. -/ meta def emit_code_here_aux : string → ℕ → lean.parser unit | str slen := do left ← emit_command_here str, let llen := left.length, when (llen < slen ∧ llen ≠ 0) (emit_code_here_aux left llen) /-- `emit_code_here str` behaves as if the string `str` were placed at the current location in source code. -/ meta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length /-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the top level, giving access to operations like `emit_code_here`. -/ @[user_command] meta def run_parser_cmd (_ : interactive.parse $ tk "run_parser") : lean.parser unit := do e ← lean.parser.pexpr 0, p ← eval_pexpr (lean.parser unit) e, p add_tactic_doc { name := "run_parser", category := doc_category.cmd, decl_names := [``run_parser_cmd], tags := ["parsing"] } /-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`). This function deserves a C++ implementation in core lean, and will fail if it is not called from the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/ meta def get_current_namespace : lean.parser name := do env ← get_env, n ← tactic.mk_user_fresh_name, emit_code_here $ sformat!"def {n} := ()", nfull ← tactic.resolve_constant n, set_env env, return $ nfull.get_nth_prefix n.components.length /-- `get_variables` returns a list of existing variable names, along with their types and binder info. -/ meta def get_variables : lean.parser (list (name × binder_info × expr)) := list.map expr.get_local_const_kind <$> list_available_include_vars /-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been "included" by an `include v` statement and are not (yet) `omit`ed. -/ meta def get_included_variables : lean.parser (list (name × binder_info × expr)) := do ns ← list_include_var_names, list.filter (λ v, v.1 ∈ ns) <$> get_variables /-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the local context---precisely those variables which would be ambiently accessible if we were in a tactic-mode block where the goals had types `es.mmap to_expr`, for example. Returns a new `ts : tactic_state` with these local variables added, and `mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable `var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/ meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr) : lean.parser (tactic_state × list (expr × expr)) := do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the declared variables to a fake `tactic_state`, and perform the resolution. At the end, `to_expr e` has done the work of determining which variables were actually referenced, which we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for `pexpr`s). -/ vars ← list_available_include_vars, fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do { /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard them on this first pass. (We return the mappings generated by our second invocation of this function below.) -/ add_local_consts_as_local_hyps vars, es.mmap to_expr }, /- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were referenced in `e` when it was resolved to `fake_e`. It is important that we include variables of the kind a) because we want `simp` to have access to declared local instances, and it is important that we only restrict to variables of kind a) and b) together since we do not to recognise a hypothesis which is posited as a `variable` in the environment but not referenced in the `pexpr` we were passed. One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want simp to use arbitrary hypotheses which were declared as `variables` in the local environment but not referenced in the expression to simplify (as one would be expect generally in tactic mode). -/ included_vars ← list_include_var_names, let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name, /- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the `pexpr` list which we were passed.) -/ let directly_included_vars := vars.filter $ λ var, (var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars), /- Inflate the list `directly_included_vars` to include those variables which are "implicitly included" by virtue of reference to one or multiple others. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. -/ let all_implicitly_included_vars := expr.all_implicitly_included_variables vars directly_included_vars, /- Capture a tactic state where both of these kinds of variables have been added as local hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/ lean.parser.of_tactic $ do { mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars, ts ← get_state, return (ts, mappings) } end lean.parser namespace tactic variables {α : Type} /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ```lean instance : monad id := {! !} ``` invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under construction.") produces: ```lean instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target >>= whnf, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {fs} }}", return [(out,"")] } add_tactic_doc { name := "instance_stub", category := doc_category.hole_cmd, decl_names := [`tactic.instance_stub], tags := ["instances"] } /-- Like `resolve_name` except when the list of goals is empty. In that situation `resolve_name` fails whereas `resolve_name'` simply proceeds on a dummy goal -/ meta def resolve_name' (n : name) : tactic pexpr := do [] ← get_goals | resolve_name n, g ← mk_mvar, set_goals [g], resolve_name n <* set_goals [] private meta def strip_prefix' (n : name) : list string → name → tactic name | s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous | s (name.mk_string a p) := do let n' := s.foldl (flip name.mk_string) name.anonymous, do { n'' ← tactic.resolve_constant n', if n'' = n then pure n' else strip_prefix' (a :: s) p } <|> strip_prefix' (a :: s) p | s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n /-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/ meta def strip_prefix : name → tactic name | n@(name.mk_string a a_1) := if (`_private).is_prefix_of n then let n' := n.update_prefix name.anonymous in n' <$ resolve_name' n' <|> pure n else strip_prefix' n [a] a_1 | n := pure n /-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/ meta def mk_patterns (t : expr) : tactic (list format) := do let cl := t.get_app_fn.const_name, env ← get_env, let fs := env.constructors_of cl, fs.mmap $ λ f, do { (vs,_) ← mk_const f >>= infer_type >>= open_pis, let vs := vs.filter (λ v, v.is_default_local), vs ← vs.mmap (λ v, do v' ← get_unused_name v.local_pp_name, pose v' none `(()), pure v' ), vs.mmap' $ λ v, get_local v >>= clear, let args := list.intersperse (" " : format) $ vs.map to_fmt, f ← strip_prefix f, if args.empty then pure $ format!"| {f} := _\n" else pure format!"| ({f} {format.join args}) := _\n" } /-- Hole command used to generate a `match` expression. In the following: ```lean meta def foo (e : expr) : tactic unit := {! e !} ``` invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression") produces: ```lean meta def foo (e : expr) : tactic unit := match e with | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ end ``` -/ @[hole_command] meta def match_stub : hole_command := { name := "Match Stub", descr := "Generate a list of equations for a `match` expression.", action := λ es, do [e] ← pure es | fail "expecting one expression", e ← to_expr e, t ← infer_type e >>= whnf, fs ← mk_patterns t, e ← pp e, let out := format.to_string format!"match {e} with\n{format.join fs}end\n", return [(out,"")] } add_tactic_doc { name := "Match Stub", category := doc_category.hole_cmd, decl_names := [`tactic.match_stub], tags := ["pattern matching"] } /-- Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition") in the following: ```lean meta def foo : {! expr → tactic unit !} -- `:=` is omitted ``` produces: ```lean meta def foo : expr → tactic unit | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` A similar result can be obtained by invoking "Equations Stub" on the following: ```lean meta def foo : expr → tactic unit := -- do not forget to write `:=`!! {! !} ``` ```lean meta def foo : expr → tactic unit := -- don't forget to erase `:=`!! | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` -/ @[hole_command] meta def eqn_stub : hole_command := { name := "Equations Stub", descr := "Generate a list of equations for a recursive definition.", action := λ es, do t ← match es with | [t] := to_expr t | [] := target | _ := fail "expecting one type" end, e ← whnf t, (v :: _,_) ← open_pis e | fail "expecting a Pi-type", t' ← infer_type v, fs ← mk_patterns t', t ← pp t, let out := if es.empty then format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}" else format.to_string format!"{t}\n{format.join fs}", return [(out,"")] } add_tactic_doc { name := "Equations Stub", category := doc_category.hole_cmd, decl_names := [`tactic.eqn_stub], tags := ["pattern matching"] } /-- This command lists the constructors that can be used to satisfy the expected type. Invoking "List Constructors" ("Show the list of constructors of the expected type") in the following hole: ```lean def foo : ℤ ⊕ ℕ := {! !} ``` produces: ```lean def foo : ℤ ⊕ ℕ := {! sum.inl, sum.inr !} ``` and will display: ```lean sum.inl : ℤ → ℤ ⊕ ℕ sum.inr : ℕ → ℤ ⊕ ℕ ``` -/ @[hole_command] meta def list_constructors_hole : hole_command := { name := "List Constructors", descr := "Show the list of constructors of the expected type.", action := λ es, do t ← target >>= whnf, (_,t) ← open_pis t, let cl := t.get_app_fn.const_name, let args := t.get_app_args, env ← get_env, let cs := env.constructors_of cl, ts ← cs.mmap $ λ c, do { e ← mk_const c, t ← infer_type (e.mk_app args) >>= pp, c ← strip_prefix c, pure format!"\n{c} : {t}\n" }, fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt), let out := format.to_string format!"{{! {fs} !}}", trace (format.join ts).to_string, return [(out,"")] } add_tactic_doc { name := "List Constructors", category := doc_category.hole_cmd, decl_names := [`tactic.list_constructors_hole], tags := ["goal information"] } /-- Makes the declaration `classical.prop_decidable` available to type class inference. This asserts that all propositions are decidable, but does not have computational content. The `aggressive` argument controls whether the instance is added globally, where it has low priority, or in the local context, where it has very high priority. -/ meta def classical (aggressive : bool := ff) : tactic unit := if aggressive then do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache else do -- Turn on the `prop_decidable` instance. `9` is what we use in the `classical` locale tactic.set_basic_attribute `instance `classical.prop_decidable ff (some 9) open expr /-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so, returns the expression `f ∘ g ∘ h`. -/ meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] /-- Given two expressions `e₀` and `e₁`, return the expression `` `(%%e₀ ↔ %%e₁)``. -/ meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁) /-- From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types /-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`. It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime, add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm lmm', copy_attribute `functor_norm lmm lmm' } add_tactic_doc { name := "higher_order", category := doc_category.attr, decl_names := [`tactic.higher_order_attr], tags := ["lemma derivation"] } attribute [higher_order map_comp_pure] map_pure /-- Copies a definition into the `tactic.interactive` namespace to make it usable in proof scripts. It allows one to write ```lean @[interactive] meta def my_tactic := ... ``` instead of ```lean meta def my_tactic := ... run_cmd add_interactive [``my_tactic] ``` -/ @[user_attribute] meta def interactive_attr : user_attribute := { name := `interactive, descr := "Put a definition in the `tactic.interactive` namespace to make it usable in proof scripts.", after_set := some $ λ tac _ _, add_interactive [tac] } add_tactic_doc { name := "interactive", category := doc_category.attr, decl_names := [``tactic.interactive_attr], tags := ["environment"] } /-- Use `refine` to partially discharge the goal, or call `fconstructor` and try again. -/ private meta def use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> use_aux) /-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to the expected type. ```lean example : ∃ x : ℤ, x = x := by tactic.use ``(42) ``` See the doc string for `tactic.interactive.use` for more information. -/ protected meta def use (l : list pexpr) : tactic unit := focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}") instantiate_mvars_in_target /-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the local context. -/ meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l /-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/ meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux /-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`) finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/ meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr) | vs e (pi n bi d b) := do { v ← mk_meta_var d, apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|> (e arg, vs) <$ unify d t | vs e _ := failed /-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/ meta def apply_at (e h : expr) : tactic unit := do ht ← infer_type h, et ← infer_type e, (h', gs') ← apply_at_aux h ht [] e et, note h.local_pp_name none h', clear h, gs' ← gs'.mfilter is_assigned, (g :: gs) ← get_goals, set_goals (g :: gs' ++ gs) /-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/ meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit := do tgt ← infer_type h, env ← get_env, let r := get_app_fn tgt, match env.symm_for (const_name r) with | (some symm) := do s ← mk_const symm, apply_at s h | none := fail "symmetry tactic failed, target is not a relation application with the expected property." end /-- `setup_tactic_parser` is a user command that opens the namespaces used in writing interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`. It does *not* use the `namespace` command, so it will typically be used after `namespace tactic.interactive`. -/ @[user_command] meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") : lean.parser unit := emit_code_here " open _root_.lean open _root_.lean.parser open _root_.interactive _root_.interactive.types local postfix (name := parser.optional) `?`:9001 := optional local postfix (name := parser.many) *:9001 := many . " /-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if `tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/ meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α := λ s, match tac s with | (result.success r s') := (finalizer >> pure r) s' | (result.exception msg p s') := (finalizer >> result.exception msg p) s' end /-- `on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed. -/ meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s' := (handler *> result.exception msg p) s' | ok := ok end /-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/ meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s := let msg (_ : unit) : format := match msg with | some msg := add_msg ++ format.line ++ msg () | none := add_msg end in result.exception msg p s | ok := ok end /-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails, returns the error message. -/ meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/ meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s' | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`. -/ meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit := do x ← retrieve_or_report_error t, match x with | (sum.inl _) := skip | (sum.inr msg) := if p msg then skip else fail msg end add_tactic_doc { name := "setup_tactic_parser", category := doc_category.cmd, decl_names := [`tactic.setup_tactic_parser_cmd], tags := ["parsing", "notation"] } /-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message of `t`. -/ meta def trace_error (msg : string) (t : tactic α) : tactic α | s := match t s with | (result.success r s') := result.success r s' | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s' | (result.exception none p s') := result.exception none p s' end /-- ``trace_if_enabled `n msg`` traces the message `msg` only if tracing is enabled for the name `n`. Create new names registered for tracing with `declare_trace n`. Then use `set_option trace.n true/false` to enable or disable tracing for `n`. -/ meta def trace_if_enabled (n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit := when_tracing n (trace msg) /-- ``trace_state_if_enabled `n msg`` prints the tactic state, preceded by the optional string `msg`, only if tracing is enabled for the name `n`. -/ meta def trace_state_if_enabled (n : name) (msg : string := "") : tactic unit := when_tracing n ((if msg = "" then skip else trace msg) >> trace_state) /-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`, and fails otherwise. -/ meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit := λ s, match t s with | (interaction_monad.result.exception msg' _ s') := let expected_msg := (msg'.iget ()).to_string in if msg = expected_msg then result.success () s else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s | (interaction_monad.result.success a s) := mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s end /-- Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`. -/ meta def tactic_statement (g : expr) : tactic string := do g ← instantiate_mvars g, g ← head_beta g, r ← pp (replace_mvars g), if g.has_meta_var then return (sformat!"Try this: refine {r}") else return (sformat!"Try this: exact {r}") /-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the initial goals and returns the goals `tac` ended on. -/ meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) := do gs' ← get_goals, set_goals gs, finally (prod.mk <$> tac <*> get_goals) (set_goals gs') /-- like `with_local_goals` but discards the resulting goals -/ meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α := prod.fst <$> with_local_goals gs tac /-- Representation of a proof goal that lends itself to comparison. The following goal: ```lean l₀ : T, l₁ : T ⊢ ∀ v : T, foo ``` is represented as ``` (2, ∀ l₀ l₁ v : T, foo) ``` The number 2 indicates that first the two bound variables of the `∀` are actually local constant. Comparing two such goals with `=` rather than `=ₐ` or `is_def_eq` tells us that proof script should not see the difference between the two. -/ meta def packaged_goal := ℕ × expr /-- proof state made of multiple `goal` meant for comparing the result of running different tactics -/ meta def proof_state := list packaged_goal meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩ meta instance proof_state.inhabited : inhabited proof_state := (infer_instance : inhabited (list packaged_goal)) /-- create a `packaged_goal` corresponding to the current goal -/ meta def get_packaged_goal : tactic packaged_goal := do ls ← local_context, tgt ← target >>= instantiate_mvars, tgt ← pis ls tgt, pure (ls.length, tgt) /-- `goal_of_mvar g`, with `g` a meta variable, creates a `packaged_goal` corresponding to `g` interpretted as a proof goal -/ meta def goal_of_mvar (g : expr) : tactic packaged_goal := with_local_goals' [g] get_packaged_goal /-- `get_proof_state` lists the user visible goal for each goal of the current state and for each goal, abstracts all of the meta variables of the other gaols. This produces a list of goals in the form of `ℕ × expr` where the `expr` encodes the following proof state: ```lean 2 goals l₁ : t₁, l₂ : t₂, l₃ : t₃ ⊢ tgt₁ ⊢ tgt₂ ``` as ```lean [ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁), (0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ] ``` with 2 goals, the first 2 bound variables encode the meta variable of all the goals, the next 3 (in the first goal) and 0 (in the second goal) are the local constants. This representation allows us to compare goals and proof states while ignoring information like the unique name of local constants and the equality or difference of meta variables that encode the same goal. -/ meta def get_proof_state : tactic proof_state := do gs ← get_goals, gs.mmap $ λ g, do ⟨n,g⟩ ← goal_of_mvar g, g ← gs.mfoldl (λ g v, do g ← kabstract g v reducible ff, pure $ pi `goal binder_info.default `(true) g ) g, pure (n,g) /-- Run `tac` in a disposable proof state and return the state. See `proof_state`, `goal` and `get_proof_state`. -/ meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) := try_core $ retrieve $ tac >> get_proof_state open lean _root_.interactive /-- A type alias for `tactic format`, standing for "pretty print format". -/ meta def pformat := tactic format /-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/ meta def pformat.mk (fmt : format) : pformat := pure fmt /-- an alias for `pp`. -/ meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat := pp x meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat := ⟨ id ⟩ meta instance : has_append pformat := ⟨ λ x y, (++) <$> x <*> y ⟩ meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) := ⟨ λ x, x >>= to_pfmt ⟩ private meta def parse_pformat : string → list char → parser pexpr | acc [] := pure ``(to_pfmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f) | acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f) | acc (c::s) := parse_pformat (acc.str c) s /-- See `format!` in `init/meta/interactive_base.lean`. The main differences are that `pp` is called instead of `to_fmt` and that we can use arguments of type `tactic α` in the quotations. Now, consider the following: ```lean e ← to_expr ``(3 + 7), trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add -- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...` trace pformat!"{e}" -- outputs `3 + 7` ``` The difference is significant. And now, the following is expressible: ```lean e ← to_expr ``(3 + 7), trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ` ``` See also: `trace!` and `fail!` -/ @[user_notation] meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr := do e ← parse_pformat "" s.to_list, return ``(%%e : pformat) /-- The combination of `pformat` and `fail`. -/ @[user_notation] meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= fail) /-- The combination of `pformat` and `trace`. -/ @[user_notation] meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= trace) /-- A hackish way to get the `src` directory of any project. Requires as argument any declaration name `n` in that project, and `k`, the number of characters in the path of the file where `n` is declared not part of the `src` directory. Example: For `mathlib_dir_locator` this is the length of `tactic/project_dir.lean`, so `23`. Note: does not work in the file where `n` is declared. -/ meta def get_project_dir (n : name) (k : ℕ) : tactic string := do e ← get_env, s ← e.decl_olean n <|> fail!"Did not find declaration {n}. This command does not work in the file where {n} is declared.", return $ s.popn_back k /-- A hackish way to get the `src` directory of mathlib. -/ meta def get_mathlib_dir : tactic string := get_project_dir `mathlib_dir_locator 23 /-- Checks whether a declaration with the given name is declared in mathlib. If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead, since it is expensive to execute `get_mathlib_dir` many times. -/ meta def is_in_mathlib (n : name) : tactic bool := do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n /-- Runs a tactic by name. If it is a `tactic string`, return whatever string it returns. If it is a `tactic unit`, return the name. (This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.) -/ meta def name_to_tactic (n : name) : tactic string := do d ← get_decl n, e ← mk_const n, let t := d.type, if (t =ₐ `(tactic unit)) then (eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n)) else if (t =ₐ `(tactic string)) then (eval_expr (tactic string) e) >>= (λ t, t) else fail! "name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`" /-- auxiliary function for `apply_under_n_pis` -/ private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr | n 0 _ := let vars := ((list.range n).reverse.map (@expr.var ff)), bd := vars.foldl expr.app arg.mk_explicit in func bd | n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd) | n (k+1) t := apply_under_n_pis_aux n 0 t /-- Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr := apply_under_n_pis_aux func arg 0 n pi_expr /-- Assumes `pi_expr` is of the form `Π x1 ... xn, _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr := apply_under_n_pis func arg pi_expr pi_expr.pi_arity /-- If `func` is a `pexpr` representing a function that takes an argument `a`, `get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`. When `tgt` is a `pi` expr, `func` is elaborated in a context with the domain of `tgt`. Examples: * ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument. * ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`. * ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0 -/ meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ := lock_tactic_state $ do mv ← mk_mvar, solve_aux tgt $ intros >> to_expr ``(%%func %%mv), expr.pi_arity <$> (infer_type mv >>= instantiate_mvars) /-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files. `find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m` can be found. -/ meta def find_private_decl (n : name) (fr : option name) : tactic name := do env ← get_env, fn ← option_t.run (do fr ← option_t.mk (return fr), d ← monad_lift $ get_decl fr, option_t.mk (return $ env.decl_olean d.to_name) ), let p : string → bool := match fn with | (some fn) := λ x, fn = x | none := λ _, tt end, let xs := env.decl_filter_map (λ d, do fn ← env.decl_olean d.to_name, guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n), pure d.to_name), match xs with | [n] := pure n | [] := fail "no such private found" | _ := fail "many matches found" end open lean.parser interactive /-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar` and creates a local notation to refer to it. `import_private foo` looks for `foo` in all imported files. When possible, make `foo` non-private rather than using this feature. -/ @[user_command] meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit := do n ← ident, fr ← optional (tk "from" *> ident), n ← find_private_decl n fr, c ← resolve_constant n, d ← get_decl n, let c := @expr.const tt c d.univ_levels, new_n ← new_aux_decl_name, add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted, let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}", emit_command_here $ new_not, skip . add_tactic_doc { name := "import_private", category := doc_category.cmd, decl_names := [`tactic.import_private_cmd], tags := ["renaming"] } /-- The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`. Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called. `mk_simp_attribute simp_name none` will use a default description. Appending the command with `with attr1 attr2 ...` will include all declarations tagged with `attr1`, `attr2`, ... in the new simp set. This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string to the attribute that is defined. If you need to create a simp set in a file where this command is not available, you should use ```lean run_cmd mk_simp_attr `simp_name run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here" ``` -/ @[user_command] meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit := do n ← ident, d ← parser.pexpr, d ← to_expr ``(%%d : option string), descr ← eval_expr (option string) d, with_list ← (tk "with" *> many ident) <|> return [], mk_simp_attr n with_list, add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n add_tactic_doc { name := "mk_simp_attribute", category := doc_category.cmd, decl_names := [`tactic.mk_simp_attribute_cmd], tags := ["simplification"] } /-- Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns the name of the declaration that defines this attribute. Fails if there is no user attribute with this name. Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/ meta def get_user_attribute_name (attr_name : name) : tactic name := do ns ← attribute.get_instances `user_attribute, ns.mfirst (λ nm, do d ← get_decl nm, e ← mk_app `user_attribute.name [d.value], attr_nm ← eval_expr name e, guard $ attr_nm = attr_name, return nm) <|> fail!"'{attr_name}' is not a user attribute." /-- A tactic to set either a basic attribute or a user attribute. If the user attribute has a parameter, the default value will be used. This tactic raises an error if there is no `inhabited` instance for the parameter type. -/ meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt) (prio : option nat := none) : tactic unit := do get_decl c_name <|> fail!"unknown declaration {c_name}", s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio), sum.inr msg ← return s | skip, if msg = (format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string then do user_attr_nm ← get_user_attribute_name attr_name, user_attr_const ← mk_const user_attr_nm, tac ← eval_pexpr (tactic unit) ``(user_attribute.set %%user_attr_const %%`(c_name) default %%`(persistent)) <|> fail! ("Cannot set attribute @[{attr_name}].\n" ++ "The corresponding user attribute {user_attr_nm} " ++ "has a parameter without a default value.\n" ++ "Solution: provide an `inhabited` instance."), tac else fail msg end tactic /-- `find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`), and returns the value associated with this key if it exists. Otherwise, it fails. -/ meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) : tactic (expr × v) := m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
7d9396d77f52b9c9df65a7c2102741680891975c
92b13ae5cb04d78dd215ae736d93f5353e0e8e87
/broken/pretty.lean
8cbe532d30b46f0f1f061f66f260acf8c2c8dfe8
[]
no_license
jroesch/exp-compiler
f2dec4f17e769e7f3b41429c41ece1f004a3f209
6efd4512c80df947361bdada12415bc166db5e7f
refs/heads/master
1,585,267,520,150
1,469,047,597,000
1,469,047,597,000
63,471,055
0
0
null
null
null
null
UTF-8
Lean
false
false
121
lean
inductive doc := | nil | append : doc -> doc -> doc | nest : nat -> doc | text : string -> doc | line : doc | doc : doc
3f8c335b910c662d1f5b33087e5cee90bc6d1ff2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/category/pairwise_auto.lean
d48367e4b53589a985cb478c9e4d73e6ed4d91ad
[]
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
4,240
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.preserves.basic import Mathlib.category_theory.limits.lattice import Mathlib.PostPort universes v l namespace Mathlib /-! # The category of "pairwise intersections". Given `ι : Type v`, we build the diagram category `pairwise ι` with objects `single i` and `pair i j`, for `i j : ι`, whose only non-identity morphisms are `left : pair i j ⟶ single i` and `right : pair i j ⟶ single j`. We use this later in describing (one formulation of) the sheaf condition. Given any function `U : ι → α`, where `α` is some complete lattice (e.g. `(opens X)ᵒᵖ`), we produce a functor `pairwise ι ⥤ α` in the obvious way, and show that `supr U` provides a colimit cocone over this functor. -/ namespace category_theory /-- An inductive type representing either a single term of a type `ι`, or a pair of terms. We use this as the objects of a category to describe the sheaf condition. -/ inductive pairwise (ι : Type v) where | single : ι → pairwise ι | pair : ι → ι → pairwise ι namespace pairwise protected instance pairwise_inhabited {ι : Type v} [Inhabited ι] : Inhabited (pairwise ι) := { default := single Inhabited.default } /-- Morphisms in the category `pairwise ι`. The only non-identity morphisms are `left i j : single i ⟶ pair i j` and `right i j : single j ⟶ pair i j`. -/ inductive hom {ι : Type v} : pairwise ι → pairwise ι → Type v where | id_single : (i : ι) → hom (single i) (single i) | id_pair : (i j : ι) → hom (pair i j) (pair i j) | left : (i j : ι) → hom (pair i j) (single i) | right : (i j : ι) → hom (pair i j) (single j) protected instance hom_inhabited {ι : Type v} [Inhabited ι] : Inhabited (hom (single Inhabited.default) (single Inhabited.default)) := { default := hom.id_single Inhabited.default } /-- The identity morphism in `pairwise ι`. -/ def id {ι : Type v} (o : pairwise ι) : hom o o := sorry /-- Composition of morphisms in `pairwise ι`. -/ def comp {ι : Type v} {o₁ : pairwise ι} {o₂ : pairwise ι} {o₃ : pairwise ι} (f : hom o₁ o₂) (g : hom o₂ o₃) : hom o₁ o₃ := sorry protected instance category_theory.category {ι : Type v} : category (pairwise ι) := category.mk /-- Auxilliary definition for `diagram`. -/ @[simp] def diagram_obj {ι : Type v} {α : Type v} (U : ι → α) [semilattice_inf α] : pairwise ι → α := sorry /-- Auxilliary definition for `diagram`. -/ @[simp] def diagram_map {ι : Type v} {α : Type v} (U : ι → α) [semilattice_inf α] {o₁ : pairwise ι} {o₂ : pairwise ι} (f : o₁ ⟶ o₂) : diagram_obj U o₁ ⟶ diagram_obj U o₂ := sorry /-- Given a function `U : ι → α` for `[semilattice_inf α]`, we obtain a functor `pairwise ι ⥤ α`, sending `single i` to `U i` and `pair i j` to `U i ⊓ U j`, and the morphisms to the obvious inequalities. -/ def diagram {ι : Type v} {α : Type v} (U : ι → α) [semilattice_inf α] : pairwise ι ⥤ α := functor.mk (diagram_obj U) fun (X Y : pairwise ι) (f : X ⟶ Y) => diagram_map U f -- `complete_lattice` is not really needed, as we only ever use `inf`, -- but the appropriate structure has not been defined. /-- Auxilliary definition for `cocone`. -/ def cocone_ι_app {ι : Type v} {α : Type v} (U : ι → α) [complete_lattice α] (o : pairwise ι) : diagram_obj U o ⟶ supr U := sorry /-- Given a function `U : ι → α` for `[complete_lattice α]`, `supr U` provides a cocone over `diagram U`. -/ @[simp] theorem cocone_X {ι : Type v} {α : Type v} (U : ι → α) [complete_lattice α] : limits.cocone.X (cocone U) = supr U := Eq.refl (limits.cocone.X (cocone U)) /-- Given a function `U : ι → α` for `[complete_lattice α]`, `infi U` provides a limit cone over `diagram U`. -/ def cocone_is_colimit {ι : Type v} {α : Type v} (U : ι → α) [complete_lattice α] : limits.is_colimit (cocone U) := limits.is_colimit.mk fun (s : limits.cocone (diagram U)) => hom_of_le sorry end Mathlib
36d0415354722b7338c770ec6cf5fcfabf5e31d0
e6b8240a90527fd55d42d0ec6649253d5d0bd414
/src/category_theory/limits/preserves.lean
07cde04a38c73ae99b079237d63506b09160598f
[ "Apache-2.0" ]
permissive
mattearnshaw/mathlib
ac90f9fb8168aa642223bea3ffd0286b0cfde44f
d8dc1445cf8a8c74f8df60b9f7a1f5cf10946666
refs/heads/master
1,606,308,351,137
1,576,594,130,000
1,576,594,130,000
228,666,195
0
0
Apache-2.0
1,576,603,094,000
1,576,603,093,000
null
UTF-8
Lean
false
false
10,851
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton -/ import category_theory.limits.limits /-! # Preservation and reflection of (co)limits. -/ open category_theory namespace category_theory.limits universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v} C] variables {D : Type u₂} [𝒟 : category.{v} D] include 𝒞 𝒟 variables {J : Type v} [small_category J] {K : J ⥤ C} /- Note on "preservation of (co)limits" There are various distinct notions of "preserving limits". The one we aim to capture here is: A functor F : C → D "preserves limits" if it sends every limit cone in C to a limit cone in D. Informally, F preserves all the limits which exist in C. Note that: * Of course, we do not want to require F to *strictly* take chosen limit cones of C to chosen limit cones of D. Indeed, the above definition makes no reference to a choice of limit cones so it makes sense without any conditions on C or D. * Some diagrams in C may have no limit. In this case, there is no condition on the behavior of F on such diagrams. There are other notions (such as "flat functor") which impose conditions also on diagrams in C with no limits, but these are not considered here. In order to be able to express the property of preserving limits of a certain form, we say that a functor F preserves the limit of a diagram K if F sends every limit cone on K to a limit cone. This is vacuously satisfied when K does not admit a limit, which is consistent with the above definition of "preserves limits". -/ class preserves_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cone K}, is_limit c → is_limit (F.map_cone c)) class preserves_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cocone K}, is_colimit c → is_colimit (F.map_cocone c)) class preserves_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves_limit : Π {K : J ⥤ C}, preserves_limit K F) class preserves_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves_colimit : Π {K : J ⥤ C}, preserves_colimit K F) class preserves_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_limits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_limits_of_shape J F) class preserves_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_colimits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_colimits_of_shape J F) attribute [instance, priority 100] -- see Note [lower instance priority] preserves_limits_of_shape.preserves_limit preserves_limits.preserves_limits_of_shape preserves_colimits_of_shape.preserves_colimit preserves_colimits.preserves_colimits_of_shape instance preserves_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_limits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance preserves_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_colimits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance preserves_limits_subsingleton (F : C ⥤ D) : subsingleton (preserves_limits F) := by { split, intros, cases a, cases b, congr, funext J 𝒥, resetI, apply subsingleton.elim } instance preserves_colimits_subsingleton (F : C ⥤ D) : subsingleton (preserves_colimits F) := by { split, intros, cases a, cases b, congr, funext J 𝒥, resetI, apply subsingleton.elim } omit 𝒟 instance id_preserves_limits : preserves_limits (𝟭 C) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } instance id_preserves_colimits : preserves_colimits (𝟭 C) := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } include 𝒟 section variables {E : Type u₃} [ℰ : category.{v} E] variables (F : C ⥤ D) (G : D ⥤ E) local attribute [elab_simple] preserves_limit.preserves preserves_colimit.preserves instance comp_preserves_limit [preserves_limit K F] [preserves_limit (K ⋙ F) G] : preserves_limit K (F ⋙ G) := ⟨λ c h, preserves_limit.preserves G (preserves_limit.preserves F h)⟩ instance comp_preserves_colimit [preserves_colimit K F] [preserves_colimit (K ⋙ F) G] : preserves_colimit K (F ⋙ G) := ⟨λ c h, preserves_colimit.preserves G (preserves_colimit.preserves F h)⟩ end /-- If F preserves one limit cone for the diagram K, then it preserves any limit cone for K. -/ def preserves_limit_of_preserves_limit_cone {F : C ⥤ D} {t : cone K} (h : is_limit t) (hF : is_limit (F.map_cone t)) : preserves_limit K F := ⟨λ t' h', is_limit.of_iso_limit hF (functor.map_iso _ (is_limit.unique_up_to_iso h h'))⟩ /-- If F preserves one colimit cocone for the diagram K, then it preserves any colimit cocone for K. -/ def preserves_colimit_of_preserves_colimit_cocone {F : C ⥤ D} {t : cocone K} (h : is_colimit t) (hF : is_colimit (F.map_cocone t)) : preserves_colimit K F := ⟨λ t' h', is_colimit.of_iso_colimit hF (functor.map_iso _ (is_colimit.unique_up_to_iso h h'))⟩ /- A functor F : C → D reflects limits if whenever the image of a cone under F is a limit cone in D, the cone was already a limit cone in C. Note that again we do not assume a priori that D actually has any limits. -/ class reflects_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cone K}, is_limit (F.map_cone c) → is_limit c) class reflects_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cocone K}, is_colimit (F.map_cocone c) → is_colimit c) class reflects_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects_limit : Π {K : J ⥤ C}, reflects_limit K F) class reflects_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects_colimit : Π {K : J ⥤ C}, reflects_colimit K F) class reflects_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_limits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_limits_of_shape J F) class reflects_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_colimits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_colimits_of_shape J F) instance reflects_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_limits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance reflects_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_colimits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance reflects_limits_subsingleton (F : C ⥤ D) : subsingleton (reflects_limits F) := by { split, intros, cases a, cases b, congr, funext J 𝒥, resetI, apply subsingleton.elim } instance reflects_colimits_subsingleton (F : C ⥤ D) : subsingleton (reflects_colimits F) := by { split, intros, cases a, cases b, congr, funext J 𝒥, resetI, apply subsingleton.elim } @[priority 100] -- see Note [lower instance priority] instance reflects_limit_of_reflects_limits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_limits_of_shape J F] : reflects_limit K F := reflects_limits_of_shape.reflects_limit J F @[priority 100] -- see Note [lower instance priority] instance reflects_colimit_of_reflects_colimits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_colimits_of_shape J F] : reflects_colimit K F := reflects_colimits_of_shape.reflects_colimit J F @[priority 100] -- see Note [lower instance priority] instance reflects_limits_of_shape_of_reflects_limits (F : C ⥤ D) [H : reflects_limits F] : reflects_limits_of_shape J F := reflects_limits.reflects_limits_of_shape F @[priority 100] -- see Note [lower instance priority] instance reflects_colimits_of_shape_of_reflects_colimits (F : C ⥤ D) [H : reflects_colimits F] : reflects_colimits_of_shape J F := reflects_colimits.reflects_colimits_of_shape F omit 𝒟 instance id_reflects_limits : reflects_limits (𝟭 C) := { reflects_limits_of_shape := λ J 𝒥, { reflects_limit := λ K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } instance id_reflects_colimits : reflects_colimits (𝟭 C) := { reflects_colimits_of_shape := λ J 𝒥, { reflects_colimit := λ K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } include 𝒟 section variables {E : Type u₃} [ℰ : category.{v} E] variables (F : C ⥤ D) (G : D ⥤ E) instance comp_reflects_limit [reflects_limit K F] [reflects_limit (K ⋙ F) G] : reflects_limit K (F ⋙ G) := ⟨λ c h, reflects_limit.reflects (reflects_limit.reflects h)⟩ instance comp_reflects_colimit [reflects_colimit K F] [reflects_colimit (K ⋙ F) G] : reflects_colimit K (F ⋙ G) := ⟨λ c h, reflects_colimit.reflects (reflects_colimit.reflects h)⟩ end end category_theory.limits
6af158678fb8bfa507dd6bea29220869ba3087ba
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/data/sigma/default.lean
ae9f0b096e9e1b9b6d9d636bb56236a864a13b86
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
252
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura, Jeremy Avigad, Floris van Doorn import data.sigma.decl data.sigma.thms data.sigma.wf
1cf31c3dfddb2f1f19d095926e2d8efea3214c61
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/overload2.lean
633601e96c489727e57a03a6c9ffbadc79d2a019
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
745
lean
import standard inductive F2 : Type | O : F2 | I : F2 namespace F2 definition add : F2 → F2 → F2 | O O := O | O I := I | I O := I | I I := O infix + := F2.add end F2 open F2 nat #reduce (1 : nat) + 1 #reduce (1 : nat) + (1 : nat) example : true := begin assert H : (1 : nat) + (1 : nat) = 2, reflexivity, constructor end example : true := begin assert H : 1 + 1 = 2, reflexivity, constructor end example : true := begin assert H : (1:nat) + 1 = 2, reflexivity, constructor end example : true := begin assert H : I + O = I, reflexivity, constructor end example : true := begin assert H1 : I + O = I, reflexivity, assert H2 : 1 + 0 = 1, reflexivity, assert H3 : (1:int) + 0 = 1, reflexivity, constructor end
444785b76f97a75684da2eadd45aca8e2f8713c2
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/algebra/ordered_monoid.lean
a30337d72c7756c0b196cfd2ac6fd6e97b77ea9f
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
48,656
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.group.with_one import algebra.group.type_tags import algebra.group.prod import algebra.order_functions import order.bounded_lattice /-! # Ordered monoids This file develops the basics of ordered monoids. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ set_option old_structure_cmd true universe u variable {α : Type u} /-- An ordered commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c * a ≤ c * b` (multiplication is monotone) * `a * b < a * c → b < c`. -/ @[protect_proj, ancestor comm_monoid partial_order] class ordered_comm_monoid (α : Type*) extends comm_monoid α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (lt_of_mul_lt_mul_left : ∀ a b c : α, a * b < a * c → b < c) /-- An ordered (additive) commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c + a ≤ c + b` (addition is monotone) * `a + b < a + c → b < c`. -/ @[protect_proj, ancestor add_comm_monoid partial_order] class ordered_add_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c) attribute [to_additive] ordered_comm_monoid /-- An `ordered_comm_monoid` with one-sided 'division' in the sense that if `a ≤ b`, there is some `c` for which `a * c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_monoid`. -/ class has_exists_mul_of_le (α : Type u) [ordered_comm_monoid α] : Prop := (exists_mul_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a * c) export has_exists_mul_of_le (exists_mul_of_le) /-- An `ordered_add_comm_monoid` with one-sided 'subtraction' in the sense that if `a ≤ b`, then there is some `c` for which `a + c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_add_monoid`. -/ class has_exists_add_of_le (α : Type u) [ordered_add_comm_monoid α] : Prop := (exists_add_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a + c) export has_exists_add_of_le (exists_add_of_le) attribute [to_additive] has_exists_mul_of_le /-- A linearly ordered additive commutative monoid. -/ @[protect_proj, ancestor linear_order ordered_add_comm_monoid] class linear_ordered_add_comm_monoid (α : Type*) extends linear_order α, ordered_add_comm_monoid α := (lt_of_add_lt_add_left := λ x y z, by { apply imp_of_not_imp_not, intro h, apply not_lt_of_le, apply add_le_add_left, -- type-class inference uses `a : linear_order α` which it can't unfold, unless we provide this! -- `lt_iff_le_not_le` gets filled incorrectly with `autoparam` if we don't provide that field. letI : linear_order α := by refine { le := le, lt := lt, lt_iff_le_not_le := _, .. }; assumption, exact le_of_not_lt h }) /-- A linearly ordered commutative monoid. -/ @[protect_proj, ancestor linear_order ordered_comm_monoid, to_additive] class linear_ordered_comm_monoid (α : Type*) extends linear_order α, ordered_comm_monoid α := (lt_of_mul_lt_mul_left := λ x y z, by { apply imp_of_not_imp_not, intro h, apply not_lt_of_le, apply mul_le_mul_left, -- type-class inference uses `a : linear_order α` which it can't unfold, unless we provide this! -- `lt_iff_le_not_le` gets filled incorrectly with `autoparam` if we don't provide that field. letI : linear_order α := by refine { le := le, lt := lt, lt_iff_le_not_le := _, .. }; assumption, exact le_of_not_lt h }) /-- A linearly ordered commutative monoid with a zero element. -/ class linear_ordered_comm_monoid_with_zero (α : Type*) extends linear_ordered_comm_monoid α, comm_monoid_with_zero α := (zero_le_one : (0 : α) ≤ 1) /-- A linearly ordered commutative monoid with an additively absorbing `⊤` element. Instances should include number systems with an infinite element adjoined.` -/ @[protect_proj, ancestor linear_ordered_add_comm_monoid order_top] class linear_ordered_add_comm_monoid_with_top (α : Type*) extends linear_ordered_add_comm_monoid α, order_top α := (top_add' : ∀ x : α, ⊤ + x = ⊤) section linear_ordered_add_comm_monoid_with_top variables [linear_ordered_add_comm_monoid_with_top α] {a b : α} @[simp] lemma top_add (a : α) : ⊤ + a = ⊤ := linear_ordered_add_comm_monoid_with_top.top_add' a @[simp] lemma add_top (a : α) : a + ⊤ = ⊤ := by rw [add_comm, top_add] end linear_ordered_add_comm_monoid_with_top section ordered_comm_monoid variables [ordered_comm_monoid α] {a b c d : α} @[to_additive add_le_add_left] lemma mul_le_mul_left' (h : a ≤ b) (c) : c * a ≤ c * b := ordered_comm_monoid.mul_le_mul_left a b h c @[to_additive add_le_add_right] lemma mul_le_mul_right' (h : a ≤ b) (c) : a * c ≤ b * c := by { convert mul_le_mul_left' h c using 1; rw mul_comm } @[to_additive] lemma mul_lt_of_mul_lt_left (h : a * b < c) (hle : d ≤ b) : a * d < c := (mul_le_mul_left' hle a).trans_lt h @[to_additive] lemma mul_lt_of_mul_lt_right (h : a * b < c) (hle : d ≤ a) : d * b < c := (mul_le_mul_right' hle b).trans_lt h @[to_additive] lemma mul_le_of_mul_le_left (h : a * b ≤ c) (hle : d ≤ b) : a * d ≤ c := (mul_le_mul_left' hle a).trans h @[to_additive] lemma mul_le_of_mul_le_right (h : a * b ≤ c) (hle : d ≤ a) : d * b ≤ c := (mul_le_mul_right' hle b).trans h @[to_additive] lemma lt_mul_of_lt_mul_left (h : a < b * c) (hle : c ≤ d) : a < b * d := h.trans_le (mul_le_mul_left' hle b) @[to_additive] lemma lt_mul_of_lt_mul_right (h : a < b * c) (hle : b ≤ d) : a < d * c := h.trans_le (mul_le_mul_right' hle c) @[to_additive] lemma le_mul_of_le_mul_left (h : a ≤ b * c) (hle : c ≤ d) : a ≤ b * d := h.trans (mul_le_mul_left' hle b) @[to_additive] lemma le_mul_of_le_mul_right (h : a ≤ b * c) (hle : b ≤ d) : a ≤ d * c := h.trans (mul_le_mul_right' hle c) @[to_additive lt_of_add_lt_add_left] lemma lt_of_mul_lt_mul_left' : a * b < a * c → b < c := ordered_comm_monoid.lt_of_mul_lt_mul_left a b c @[to_additive lt_of_add_lt_add_right] lemma lt_of_mul_lt_mul_right' (h : a * b < c * b) : a < c := lt_of_mul_lt_mul_left' (show b * a < b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) @[to_additive add_le_add] lemma mul_le_mul' (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := (mul_le_mul_right' h₁ _).trans $ mul_le_mul_left' h₂ _ @[to_additive] lemma mul_le_mul_three {e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a * b * c ≤ d * e * f := mul_le_mul' (mul_le_mul' h₁ h₂) h₃ -- here we start using properties of one. @[to_additive le_add_of_nonneg_right] lemma le_mul_of_one_le_right' (h : 1 ≤ b) : a ≤ a * b := by simpa only [mul_one] using mul_le_mul_left' h a @[to_additive le_add_of_nonneg_left] lemma le_mul_of_one_le_left' (h : 1 ≤ b) : a ≤ b * a := by simpa only [one_mul] using mul_le_mul_right' h a @[to_additive add_le_of_nonpos_right] lemma mul_le_of_le_one_right' (h : b ≤ 1) : a * b ≤ a := by simpa only [mul_one] using mul_le_mul_left' h a @[to_additive add_le_of_nonpos_left] lemma mul_le_of_le_one_left' (h : b ≤ 1) : b * a ≤ a := by simpa only [one_mul] using mul_le_mul_right' h a @[to_additive] lemma lt_of_mul_lt_of_one_le_left (h : a * b < c) (hle : 1 ≤ b) : a < c := (le_mul_of_one_le_right' hle).trans_lt h @[to_additive] lemma lt_of_mul_lt_of_one_le_right (h : a * b < c) (hle : 1 ≤ a) : b < c := (le_mul_of_one_le_left' hle).trans_lt h @[to_additive] lemma le_of_mul_le_of_one_le_left (h : a * b ≤ c) (hle : 1 ≤ b) : a ≤ c := (le_mul_of_one_le_right' hle).trans h @[to_additive] lemma le_of_mul_le_of_one_le_right (h : a * b ≤ c) (hle : 1 ≤ a) : b ≤ c := (le_mul_of_one_le_left' hle).trans h @[to_additive] lemma lt_of_lt_mul_of_le_one_left (h : a < b * c) (hle : c ≤ 1) : a < b := h.trans_le (mul_le_of_le_one_right' hle) @[to_additive] lemma lt_of_lt_mul_of_le_one_right (h : a < b * c) (hle : b ≤ 1) : a < c := h.trans_le (mul_le_of_le_one_left' hle) @[to_additive] lemma le_of_le_mul_of_le_one_left (h : a ≤ b * c) (hle : c ≤ 1) : a ≤ b := h.trans (mul_le_of_le_one_right' hle) @[to_additive] lemma le_of_le_mul_of_le_one_right (h : a ≤ b * c) (hle : b ≤ 1) : a ≤ c := h.trans (mul_le_of_le_one_left' hle) @[to_additive] lemma le_mul_of_one_le_of_le (ha : 1 ≤ a) (hbc : b ≤ c) : b ≤ a * c := one_mul b ▸ mul_le_mul' ha hbc @[to_additive] lemma le_mul_of_le_of_one_le (hbc : b ≤ c) (ha : 1 ≤ a) : b ≤ c * a := mul_one b ▸ mul_le_mul' hbc ha @[to_additive add_nonneg] lemma one_le_mul (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := le_mul_of_one_le_of_le ha hb @[to_additive add_pos_of_pos_of_nonneg] lemma one_lt_mul_of_lt_of_le' (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := lt_of_lt_of_le ha $ le_mul_of_one_le_right' hb @[to_additive add_pos_of_nonneg_of_pos] lemma one_lt_mul_of_le_of_lt' (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := lt_of_lt_of_le hb $ le_mul_of_one_le_left' ha @[to_additive add_pos] lemma one_lt_mul' (ha : 1 < a) (hb : 1 < b) : 1 < a * b := one_lt_mul_of_lt_of_le' ha hb.le @[to_additive add_nonpos] lemma mul_le_one' (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := one_mul (1:α) ▸ (mul_le_mul' ha hb) @[to_additive] lemma mul_le_of_le_one_of_le' (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one' (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one' (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := (mul_le_of_le_of_le_one' le_rfl hb).trans_lt ha @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one' (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := (mul_le_of_le_one_of_le' ha le_rfl).trans_lt hb @[to_additive] lemma mul_lt_one' (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_one_of_le_one_of_lt_one' ha.le hb @[to_additive] lemma lt_mul_of_one_le_of_lt' (ha : 1 ≤ a) (hbc : b < c) : b < a * c := hbc.trans_le $ le_mul_of_one_le_left' ha @[to_additive] lemma lt_mul_of_lt_of_one_le' (hbc : b < c) (ha : 1 ≤ a) : b < c * a := hbc.trans_le $ le_mul_of_one_le_right' ha @[to_additive] lemma lt_mul_of_one_lt_of_lt' (ha : 1 < a) (hbc : b < c) : b < a * c := lt_mul_of_one_le_of_lt' ha.le hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt' (hbc : b < c) (ha : 1 < a) : b < c * a := lt_mul_of_lt_of_one_le' hbc ha.le @[to_additive] lemma mul_lt_of_le_one_of_lt' (ha : a ≤ 1) (hbc : b < c) : a * b < c := lt_of_le_of_lt (mul_le_of_le_one_of_le' ha le_rfl) hbc @[to_additive] lemma mul_lt_of_lt_of_le_one' (hbc : b < c) (ha : a ≤ 1) : b * a < c := lt_of_le_of_lt (mul_le_of_le_of_le_one' le_rfl ha) hbc @[to_additive] lemma mul_lt_of_lt_one_of_lt' (ha : a < 1) (hbc : b < c) : a * b < c := mul_lt_of_le_one_of_lt' ha.le hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one' (hbc : b < c) (ha : a < 1) : b * a < c := mul_lt_of_lt_of_le_one' hbc ha.le @[to_additive] lemma mul_eq_one_iff' (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := iff.intro (assume hab : a * b = 1, have a ≤ 1, from hab ▸ le_mul_of_le_of_one_le le_rfl hb, have a = 1, from le_antisymm this ha, have b ≤ 1, from hab ▸ le_mul_of_one_le_of_le ha le_rfl, have b = 1, from le_antisymm this hb, and.intro ‹a = 1› ‹b = 1›) (assume ⟨ha', hb'⟩, by rw [ha', hb', mul_one]) /-- Pullback an `ordered_comm_monoid` under an injective map. -/ @[to_additive function.injective.ordered_add_comm_monoid "Pullback an `ordered_add_comm_monoid` under an injective map."] def function.injective.ordered_comm_monoid {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_comm_monoid β := { mul_le_mul_left := λ a b ab c, show f (c * a) ≤ f (c * b), by simp [mul, mul_le_mul_left' ab], lt_of_mul_lt_mul_left := λ a b c bc, @lt_of_mul_lt_mul_left' _ _ (f a) _ _ (by rwa [← mul, ← mul]), ..partial_order.lift f hf, ..hf.comm_monoid f one mul } section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add] lemma monotone.mul' (hf : monotone f) (hg : monotone g) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul' (hf h) (hg h) @[to_additive monotone.add_const] lemma monotone.mul_const' (hf : monotone f) (a : α) : monotone (λ x, f x * a) := hf.mul' monotone_const @[to_additive monotone.const_add] lemma monotone.const_mul' (hf : monotone f) (a : α) : monotone (λ x, a * f x) := monotone_const.mul' hf end mono end ordered_comm_monoid /-- Pullback a `linear_ordered_comm_monoid` under an injective map. -/ @[to_additive function.injective.linear_ordered_add_comm_monoid "Pullback an `ordered_add_comm_monoid` under an injective map."] def function.injective.linear_ordered_comm_monoid [linear_ordered_comm_monoid α] {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : linear_ordered_comm_monoid β := { .. hf.ordered_comm_monoid f one mul, .. linear_order.lift f hf } lemma bit0_pos [ordered_add_comm_monoid α] {a : α} (h : 0 < a) : 0 < bit0 a := add_pos h h namespace units @[to_additive] instance [monoid α] [preorder α] : preorder (units α) := preorder.lift (coe : units α → α) @[simp, norm_cast, to_additive] theorem coe_le_coe [monoid α] [preorder α] {a b : units α} : (a : α) ≤ b ↔ a ≤ b := iff.rfl -- should `to_additive` do this? attribute [norm_cast] add_units.coe_le_coe @[simp, norm_cast, to_additive] theorem coe_lt_coe [monoid α] [preorder α] {a b : units α} : (a : α) < b ↔ a < b := iff.rfl attribute [norm_cast] add_units.coe_lt_coe @[to_additive] instance [monoid α] [partial_order α] : partial_order (units α) := partial_order.lift coe units.ext @[to_additive] instance [monoid α] [linear_order α] : linear_order (units α) := linear_order.lift coe units.ext @[simp, norm_cast, to_additive] theorem max_coe [monoid α] [linear_order α] {a b : units α} : (↑(max a b) : α) = max a b := by by_cases b ≤ a; simp [max, h] attribute [norm_cast] add_units.max_coe @[simp, norm_cast, to_additive] theorem min_coe [monoid α] [linear_order α] {a b : units α} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [min, h] attribute [norm_cast] add_units.min_coe end units namespace with_zero local attribute [semireducible] with_zero instance [preorder α] : preorder (with_zero α) := with_bot.preorder instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order instance [partial_order α] : order_bot (with_zero α) := with_bot.order_bot lemma zero_le [partial_order α] (a : with_zero α) : 0 ≤ a := order_bot.bot_le a lemma zero_lt_coe [partial_order α] (a : α) : (0 : with_zero α) < a := with_bot.bot_lt_coe a @[simp, norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_zero α) < b ↔ a < b := with_bot.coe_lt_coe @[simp, norm_cast] lemma coe_le_coe [partial_order α] {a b : α} : (a : with_zero α) ≤ b ↔ a ≤ b := with_bot.coe_le_coe instance [lattice α] : lattice (with_zero α) := with_bot.lattice instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order lemma mul_le_mul_left {α : Type u} [ordered_comm_monoid α] : ∀ (a b : with_zero α), a ≤ b → ∀ (c : with_zero α), c * a ≤ c * b := begin rintro (_ | a) (_ | b) h (_ | c), { apply with_zero.zero_le }, { apply with_zero.zero_le }, { apply with_zero.zero_le }, { apply with_zero.zero_le }, { apply with_zero.zero_le }, { exact false.elim (not_lt_of_le h (with_zero.zero_lt_coe a))}, { apply with_zero.zero_le }, { simp_rw [some_eq_coe] at h ⊢, norm_cast at h ⊢, exact mul_le_mul_left' h c } end lemma lt_of_mul_lt_mul_left {α : Type u} [ordered_comm_monoid α] : ∀ (a b c : with_zero α), a * b < a * c → b < c := begin rintro (_ | a) (_ | b) (_ | c) h, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact false.elim (lt_irrefl none h) }, { exact with_zero.zero_lt_coe c }, { exact false.elim (not_le_of_lt h (with_zero.zero_le _)) }, { simp_rw [some_eq_coe] at h ⊢, norm_cast at h ⊢, apply lt_of_mul_lt_mul_left' h } end instance [ordered_comm_monoid α] : ordered_comm_monoid (with_zero α) := { mul_le_mul_left := with_zero.mul_le_mul_left, lt_of_mul_lt_mul_left := with_zero.lt_of_mul_lt_mul_left, ..with_zero.comm_monoid_with_zero, ..with_zero.partial_order } /- Note 1 : the below is not an instance because it requires `zero_le`. It seems like a rather pathological definition because α already has a zero. Note 2 : there is no multiplicative analogue because it does not seem necessary. Mathematicians might be more likely to use the order-dual version, where all elements are ≤ 1 and then 1 is the top element. -/ /-- If `0` is the least element in `α`, then `with_zero α` is an `ordered_add_comm_monoid`. -/ def ordered_add_comm_monoid [ordered_add_comm_monoid α] (zero_le : ∀ a : α, 0 ≤ a) : ordered_add_comm_monoid (with_zero α) := begin suffices, refine { add_le_add_left := this, ..with_zero.partial_order, ..with_zero.add_comm_monoid, .. }, { intros a b c h, have h' := lt_iff_le_not_le.1 h, rw lt_iff_le_not_le at ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases c with c, { cases h'.2 (this _ _ bot_le a) }, { refine ⟨_, rfl, _⟩, cases a with a, { exact with_bot.some_le_some.1 h'.1 }, { exact le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h), } } }, { intros a b h c ca h₂, cases b with b, { rw le_antisymm h bot_le at h₂, exact ⟨_, h₂, le_refl _⟩ }, cases a with a, { change c + 0 = some ca at h₂, simp at h₂, simp [h₂], exact ⟨_, rfl, by simpa using add_le_add_left (zero_le b) _⟩ }, { simp at h, cases c with c; change some _ = _ at h₂; simp [-add_comm] at h₂; subst ca; refine ⟨_, rfl, _⟩, { exact h }, { exact add_le_add_left h _ } } } end end with_zero namespace with_top section has_one variables [has_one α] @[to_additive] instance : has_one (with_top α) := ⟨(1 : α)⟩ @[simp, to_additive] lemma coe_one : ((1 : α) : with_top α) = 1 := rfl @[simp, to_additive] lemma coe_eq_one {a : α} : (a : with_top α) = 1 ↔ a = 1 := coe_eq_coe @[simp, to_additive] theorem one_eq_coe {a : α} : 1 = (a : with_top α) ↔ a = 1 := by rw [eq_comm, coe_eq_one] attribute [norm_cast] coe_one coe_eq_one coe_zero coe_eq_zero one_eq_coe zero_eq_coe @[simp, to_additive] theorem top_ne_one : ⊤ ≠ (1 : with_top α) . @[simp, to_additive] theorem one_ne_top : (1 : with_top α) ≠ ⊤ . end has_one instance [has_add α] : has_add (with_top α) := ⟨λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a + b))⟩ local attribute [reducible] with_zero instance [add_semigroup α] : add_semigroup (with_top α) := { add := (+), ..(by apply_instance : add_semigroup (additive (with_zero (multiplicative α)))) } @[norm_cast] lemma coe_add [has_add α] {a b : α} : ((a + b : α) : with_top α) = a + b := rfl @[norm_cast] lemma coe_bit0 [has_add α] {a : α} : ((bit0 a : α) : with_top α) = bit0 a := rfl @[norm_cast] lemma coe_bit1 [has_add α] [has_one α] {a : α} : ((bit1 a : α) : with_top α) = bit1 a := rfl @[simp] lemma add_top [has_add α] : ∀{a : with_top α}, a + ⊤ = ⊤ | none := rfl | (some a) := rfl @[simp] lemma top_add [has_add α] {a : with_top α} : ⊤ + a = ⊤ := rfl lemma add_eq_top [has_add α] {a b : with_top α} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by {cases a; cases b; simp [none_eq_top, some_eq_coe, ←with_top.coe_add, ←with_zero.coe_add]} lemma add_lt_top [has_add α] [partial_order α] {a b : with_top α} : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ := by simp [lt_top_iff_ne_top, add_eq_top, not_or_distrib] lemma add_eq_coe [has_add α] : ∀ {a b : with_top α} {c : α}, a + b = c ↔ ∃ (a' b' : α), ↑a' = a ∧ ↑b' = b ∧ a' + b' = c | none b c := by simp [none_eq_top] | (some a) none c := by simp [none_eq_top] | (some a) (some b) c := by simp only [some_eq_coe, ← coe_add, coe_eq_coe, exists_and_distrib_left, exists_eq_left] instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) := { ..@additive.add_comm_semigroup _ $ @with_zero.comm_semigroup (multiplicative α) _ } instance [add_monoid α] : add_monoid (with_top α) := { zero := some 0, add := (+), ..@additive.add_monoid _ $ @monoid_with_zero.to_monoid _ $ @with_zero.monoid_with_zero (multiplicative α) _ } instance [add_comm_monoid α] : add_comm_monoid (with_top α) := { zero := 0, add := (+), ..@additive.add_comm_monoid _ $ @comm_monoid_with_zero.to_comm_monoid _ $ @with_zero.comm_monoid_with_zero (multiplicative α) _ } instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_top α) := { add_le_add_left := begin rintros a b h (_|c), { simp [none_eq_top] }, rcases b with (_|b), { simp [none_eq_top] }, rcases le_coe_iff.1 h with ⟨a, rfl, h⟩, simp only [some_eq_coe, ← coe_add, coe_le_coe] at h ⊢, exact add_le_add_left h c end, lt_of_add_lt_add_left := begin intros a b c h, rcases lt_iff_exists_coe.1 h with ⟨ab, hab, hlt⟩, rcases add_eq_coe.1 hab with ⟨a, b, rfl, rfl, rfl⟩, rw coe_lt_iff, rintro c rfl, exact lt_of_add_lt_add_left (coe_lt_coe.1 hlt) end, ..with_top.partial_order, ..with_top.add_comm_monoid } instance [linear_ordered_add_comm_monoid α] : linear_ordered_add_comm_monoid_with_top (with_top α) := { top_add' := λ x, with_top.top_add, ..with_top.order_top, ..with_top.linear_order, ..with_top.ordered_add_comm_monoid, ..option.nontrivial } /-- Coercion from `α` to `with_top α` as an `add_monoid_hom`. -/ def coe_add_hom [add_monoid α] : α →+ with_top α := ⟨coe, rfl, λ _ _, rfl⟩ @[simp] lemma coe_coe_add_hom [add_monoid α] : ⇑(coe_add_hom : α →+ with_top α) = coe := rfl @[simp] lemma zero_lt_top [ordered_add_comm_monoid α] : (0 : with_top α) < ⊤ := coe_lt_top 0 @[simp, norm_cast] lemma zero_lt_coe [ordered_add_comm_monoid α] (a : α) : (0 : with_top α) < a ↔ 0 < a := coe_lt_coe end with_top namespace with_bot instance [has_zero α] : has_zero (with_bot α) := with_top.has_zero instance [has_one α] : has_one (with_bot α) := with_top.has_one instance [add_semigroup α] : add_semigroup (with_bot α) := with_top.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (with_bot α) := with_top.add_comm_semigroup instance [add_monoid α] : add_monoid (with_bot α) := with_top.add_monoid instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_bot α) := begin suffices, refine { add_le_add_left := this, ..with_bot.partial_order, ..with_bot.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim bot_le }, cases c with c, { exact (not_le_of_lt h).elim bot_le }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases a with a; cases h₂, cases b with b, {cases le_antisymm h bot_le}, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_zero [has_zero α] : ((0 : α) : with_bot α) = 0 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_one [has_one α] : ((1 : α) : with_bot α) = 1 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_eq_zero {α : Type*} [add_monoid α] {a : α} : (a : with_bot α) = 0 ↔ a = 0 := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_add [add_semigroup α] (a b : α) : ((a + b : α) : with_bot α) = a + b := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit0 [add_semigroup α] {a : α} : ((bit0 a : α) : with_bot α) = bit0 a := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit1 [add_semigroup α] [has_one α] {a : α} : ((bit1 a : α) : with_bot α) = bit1 a := by norm_cast @[simp] lemma bot_add [ordered_add_comm_monoid α] (a : with_bot α) : ⊥ + a = ⊥ := rfl @[simp] lemma add_bot [ordered_add_comm_monoid α] (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl end with_bot /-- A canonically ordered additive monoid is an ordered commutative additive monoid in which the ordering coincides with the subtractibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other nontrivial `ordered_add_comm_group`s. -/ @[protect_proj, ancestor ordered_add_comm_monoid order_bot] class canonically_ordered_add_monoid (α : Type*) extends ordered_add_comm_monoid α, order_bot α := (le_iff_exists_add : ∀ a b : α, a ≤ b ↔ ∃ c, b = a + c) /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a * c`. Example seem rare; it seems more likely that the `order_dual` of a naturally-occurring lattice satisfies this than the lattice itself (for example, dual of the lattice of ideals of a PID or Dedekind domain satisfy this; collections of all things ≤ 1 seem to be more natural that collections of all things ≥ 1). -/ @[protect_proj, ancestor ordered_comm_monoid order_bot, to_additive] class canonically_ordered_monoid (α : Type*) extends ordered_comm_monoid α, order_bot α := (le_iff_exists_mul : ∀ a b : α, a ≤ b ↔ ∃ c, b = a * c) section canonically_ordered_monoid variables [canonically_ordered_monoid α] {a b c d : α} @[to_additive] lemma le_iff_exists_mul : a ≤ b ↔ ∃c, b = a * c := canonically_ordered_monoid.le_iff_exists_mul a b @[to_additive] lemma self_le_mul_right (a b : α) : a ≤ a * b := le_iff_exists_mul.mpr ⟨b, rfl⟩ @[to_additive] lemma self_le_mul_left (a b : α) : a ≤ b * a := by { rw [mul_comm], exact self_le_mul_right a b } @[simp, to_additive zero_le] lemma one_le (a : α) : 1 ≤ a := le_iff_exists_mul.mpr ⟨a, by simp⟩ @[simp, to_additive] lemma bot_eq_one : (⊥ : α) = 1 := le_antisymm bot_le (one_le ⊥) @[simp, to_additive] lemma mul_eq_one_iff : a * b = 1 ↔ a = 1 ∧ b = 1 := mul_eq_one_iff' (one_le _) (one_le _) @[simp, to_additive] lemma le_one_iff_eq_one : a ≤ 1 ↔ a = 1 := iff.intro (assume h, le_antisymm h (one_le a)) (assume h, h ▸ le_refl a) @[to_additive] lemma one_lt_iff_ne_one : 1 < a ↔ a ≠ 1 := iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (one_le _) hne.symm @[to_additive] lemma exists_pos_mul_of_lt (h : a < b) : ∃ c > 1, a * c = b := begin obtain ⟨c, hc⟩ := le_iff_exists_mul.1 h.le, refine ⟨c, one_lt_iff_ne_one.2 _, hc.symm⟩, rintro rfl, simpa [hc, lt_irrefl] using h end @[to_additive] lemma le_mul_left (h : a ≤ c) : a ≤ b * c := calc a = 1 * a : by simp ... ≤ b * c : mul_le_mul' (one_le _) h @[to_additive] lemma le_mul_right (h : a ≤ b) : a ≤ b * c := calc a = a * 1 : by simp ... ≤ b * c : mul_le_mul' h (one_le _) local attribute [semireducible] with_zero -- This instance looks absurd: a monoid already has a zero /-- Adding a new zero to a canonically ordered additive monoid produces another one. -/ instance with_zero.canonically_ordered_add_monoid {α : Type u} [canonically_ordered_add_monoid α] : canonically_ordered_add_monoid (with_zero α) := { le_iff_exists_add := λ a b, begin cases a with a, { exact iff_of_true bot_le ⟨b, (zero_add b).symm⟩ }, cases b with b, { exact iff_of_false (mt (le_antisymm bot_le) (by simp)) (λ ⟨c, h⟩, by cases c; cases h) }, { simp [le_iff_exists_add, -add_comm], split; intro h; rcases h with ⟨c, h⟩, { exact ⟨some c, congr_arg some h⟩ }, { cases c; cases h, { exact ⟨_, (add_zero _).symm⟩ }, { exact ⟨_, rfl⟩ } } } end, bot := 0, bot_le := assume a a' h, option.no_confusion h, .. with_zero.ordered_add_comm_monoid zero_le } instance with_top.canonically_ordered_add_monoid {α : Type u} [canonically_ordered_add_monoid α] : canonically_ordered_add_monoid (with_top α) := { le_iff_exists_add := assume a b, match a, b with | a, none := show a ≤ ⊤ ↔ ∃c, ⊤ = a + c, by simp; refine ⟨⊤, _⟩; cases a; refl | (some a), (some b) := show (a:with_top α) ≤ ↑b ↔ ∃c:with_top α, ↑b = ↑a + c, begin simp [canonically_ordered_add_monoid.le_iff_exists_add, -add_comm], split, { rintro ⟨c, rfl⟩, refine ⟨c, _⟩, norm_cast }, { exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end } end | none, some b := show (⊤ : with_top α) ≤ b ↔ ∃c:with_top α, ↑b = ⊤ + c, by simp end, .. with_top.order_bot, .. with_top.ordered_add_comm_monoid } @[priority 100, to_additive] instance canonically_ordered_monoid.has_exists_mul_of_le (α : Type u) [canonically_ordered_monoid α] : has_exists_mul_of_le α := { exists_mul_of_le := λ a b hab, le_iff_exists_mul.mp hab } end canonically_ordered_monoid lemma pos_of_gt {M : Type*} [canonically_ordered_add_monoid M] {n m : M} (h : n < m) : 0 < m := lt_of_le_of_lt (zero_le _) h /-- A canonically linear-ordered additive monoid is a canonically ordered additive monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_add_monoid linear_order] class canonically_linear_ordered_add_monoid (α : Type*) extends canonically_ordered_add_monoid α, linear_order α /-- A canonically linear-ordered monoid is a canonically ordered monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_monoid linear_order, to_additive] class canonically_linear_ordered_monoid (α : Type*) extends canonically_ordered_monoid α, linear_order α section canonically_linear_ordered_monoid variables @[priority 100, to_additive] -- see Note [lower instance priority] instance canonically_linear_ordered_monoid.semilattice_sup_bot [canonically_linear_ordered_monoid α] : semilattice_sup_bot α := { ..lattice_of_linear_order, ..canonically_ordered_monoid.to_order_bot α } instance with_top.canonically_linear_ordered_add_monoid (α : Type*) [canonically_linear_ordered_add_monoid α] : canonically_linear_ordered_add_monoid (with_top α) := { .. (infer_instance : canonically_ordered_add_monoid (with_top α)), .. (infer_instance : linear_order (with_top α)) } @[to_additive] lemma min_mul_distrib [canonically_linear_ordered_monoid α] (a b c : α) : min a (b * c) = min a (min a b * min a c) := begin cases le_total a b with hb hb, { simp [hb, le_mul_right] }, { cases le_total a c with hc hc, { simp [hc, le_mul_left] }, { simp [hb, hc] } } end @[to_additive] lemma min_mul_distrib' [canonically_linear_ordered_monoid α] (a b c : α) : min (a * b) c = min (min a c * min b c) c := by simpa [min_comm _ c] using min_mul_distrib c a b end canonically_linear_ordered_monoid /-- An ordered cancellative additive commutative monoid is an additive commutative monoid with a partial order, in which addition is cancellative and monotone. -/ @[protect_proj, ancestor add_cancel_comm_monoid partial_order] class ordered_cancel_add_comm_monoid (α : Type u) extends add_cancel_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (le_of_add_le_add_left : ∀ a b c : α, a + b ≤ a + c → b ≤ c) /-- An ordered cancellative commutative monoid is a commutative monoid with a partial order, in which multiplication is cancellative and monotone. -/ @[protect_proj, ancestor cancel_comm_monoid partial_order, to_additive] class ordered_cancel_comm_monoid (α : Type u) extends cancel_comm_monoid α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (le_of_mul_le_mul_left : ∀ a b c : α, a * b ≤ a * c → b ≤ c) section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] {a b c d : α} @[to_additive le_of_add_le_add_left] lemma le_of_mul_le_mul_left' : ∀ {a b c : α}, a * b ≤ a * c → b ≤ c := ordered_cancel_comm_monoid.le_of_mul_le_mul_left @[priority 100, to_additive] -- see Note [lower instance priority] instance ordered_cancel_comm_monoid.to_ordered_comm_monoid : ordered_comm_monoid α := { lt_of_mul_lt_mul_left := λ a b c h, lt_of_le_not_le (le_of_mul_le_mul_left' h.le) $ mt (λ h, ordered_cancel_comm_monoid.mul_le_mul_left _ _ h _) (not_le_of_gt h), ..‹ordered_cancel_comm_monoid α› } @[to_additive add_lt_add_left] lemma mul_lt_mul_left' (h : a < b) (c : α) : c * a < c * b := lt_of_le_not_le (mul_le_mul_left' h.le _) $ mt le_of_mul_le_mul_left' (not_le_of_gt h) @[to_additive add_lt_add_right] lemma mul_lt_mul_right' (h : a < b) (c : α) : a * c < b * c := begin rw [mul_comm a c, mul_comm b c], exact (mul_lt_mul_left' h c) end @[to_additive add_lt_add] lemma mul_lt_mul''' (h₁ : a < b) (h₂ : c < d) : a * c < b * d := lt_trans (mul_lt_mul_right' h₁ c) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_le_of_lt (h₁ : a ≤ b) (h₂ : c < d) : a * c < b * d := lt_of_le_of_lt (mul_le_mul_right' h₁ _) (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_lt_of_le (h₁ : a < b) (h₂ : c ≤ d) : a * c < b * d := lt_of_lt_of_le (mul_lt_mul_right' h₁ c) (mul_le_mul_left' h₂ _) @[to_additive lt_add_of_pos_right] lemma lt_mul_of_one_lt_right' (a : α) {b : α} (h : 1 < b) : a < a * b := have a * 1 < a * b, from mul_lt_mul_left' h a, by rwa [mul_one] at this @[to_additive lt_add_of_pos_left] lemma lt_mul_of_one_lt_left' (a : α) {b : α} (h : 1 < b) : a < b * a := have 1 * a < b * a, from mul_lt_mul_right' h a, by rwa [one_mul] at this @[to_additive le_of_add_le_add_right] lemma le_of_mul_le_mul_right' (h : a * b ≤ c * b) : a ≤ c := le_of_mul_le_mul_left' (show b * a ≤ b * c, begin rw [mul_comm b a, mul_comm b c], assumption end) @[to_additive] lemma mul_lt_one (ha : a < 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul''' ha hb) @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_lt_of_le ha hb) @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_le_of_lt ha hb) @[to_additive] lemma lt_mul_of_one_lt_of_le (ha : 1 < a) (hbc : b ≤ c) : b < a * c := one_mul b ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma lt_mul_of_le_of_one_lt (hbc : b ≤ c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma mul_le_of_le_one_of_le (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_le (ha : a < 1) (hbc : b ≤ c) : a * b < c := one_mul c ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma mul_lt_of_le_of_lt_one (hbc : b ≤ c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma lt_mul_of_one_le_of_lt (ha : 1 ≤ a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_le (hbc : b < c) (ha : 1 ≤ a) : b < c * a := mul_one b ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma lt_mul_of_one_lt_of_lt (ha : 1 < a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul''' ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt (hbc : b < c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul''' hbc ha @[to_additive] lemma mul_lt_of_le_one_of_lt (ha : a ≤ 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma mul_lt_of_lt_of_le_one (hbc : b < c) (ha : a ≤ 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_lt (ha : a < 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul''' ha hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one (hbc : b < c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul''' hbc ha @[simp, to_additive] lemma mul_le_mul_iff_left (a : α) {b c : α} : a * b ≤ a * c ↔ b ≤ c := ⟨le_of_mul_le_mul_left', λ h, mul_le_mul_left' h _⟩ @[simp, to_additive] lemma mul_le_mul_iff_right (c : α) : a * c ≤ b * c ↔ a ≤ b := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_iff_left c @[simp, to_additive] lemma mul_lt_mul_iff_left (a : α) {b c : α} : a * b < a * c ↔ b < c := ⟨lt_of_mul_lt_mul_left', λ h, mul_lt_mul_left' h _⟩ @[simp, to_additive] lemma mul_lt_mul_iff_right (c : α) : a * c < b * c ↔ a < b := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_iff_left c @[simp, to_additive le_add_iff_nonneg_right] lemma le_mul_iff_one_le_right' (a : α) {b : α} : a ≤ a * b ↔ 1 ≤ b := have a * 1 ≤ a * b ↔ 1 ≤ b, from mul_le_mul_iff_left a, by rwa mul_one at this @[simp, to_additive le_add_iff_nonneg_left] lemma le_mul_iff_one_le_left' (a : α) {b : α} : a ≤ b * a ↔ 1 ≤ b := by rw [mul_comm, le_mul_iff_one_le_right'] @[simp, to_additive lt_add_iff_pos_right] lemma lt_mul_iff_one_lt_right' (a : α) {b : α} : a < a * b ↔ 1 < b := have a * 1 < a * b ↔ 1 < b, from mul_lt_mul_iff_left a, by rwa mul_one at this @[simp, to_additive lt_add_iff_pos_left] lemma lt_mul_iff_one_lt_left' (a : α) {b : α} : a < b * a ↔ 1 < b := by rw [mul_comm, lt_mul_iff_one_lt_right'] @[simp, to_additive add_le_iff_nonpos_left] lemma mul_le_iff_le_one_left' : a * b ≤ b ↔ a ≤ 1 := by { convert mul_le_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_le_iff_nonpos_right] lemma mul_le_iff_le_one_right' : a * b ≤ a ↔ b ≤ 1 := by { convert mul_le_mul_iff_left a, rw [mul_one] } @[simp, to_additive add_lt_iff_neg_right] lemma mul_lt_iff_lt_one_right' : a * b < b ↔ a < 1 := by { convert mul_lt_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_lt_iff_neg_left] lemma mul_lt_iff_lt_one_left' : a * b < a ↔ b < 1 := by { convert mul_lt_mul_iff_left a, rw [mul_one] } @[to_additive] lemma mul_eq_one_iff_eq_one_of_one_le (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := ⟨λ hab : a * b = 1, by split; apply le_antisymm; try {assumption}; rw ← hab; simp [ha, hb], λ ⟨ha', hb'⟩, by rw [ha', hb', mul_one]⟩ /-- Pullback an `ordered_cancel_comm_monoid` under an injective map. -/ @[to_additive function.injective.ordered_cancel_add_comm_monoid "Pullback an `ordered_cancel_add_comm_monoid` under an injective map."] def function.injective.ordered_cancel_comm_monoid {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_cancel_comm_monoid β := { le_of_mul_le_mul_left := λ a b c (ab : f (a * b) ≤ f (a * c)), (by { rw [mul, mul] at ab, exact le_of_mul_le_mul_left' ab }), ..hf.left_cancel_semigroup f mul, ..hf.ordered_comm_monoid f one mul } section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add_strict_mono] lemma monotone.mul_strict_mono' (hf : monotone f) (hg : strict_mono g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_le_of_lt (hf $ le_of_lt h) (hg h) @[to_additive strict_mono.add_monotone] lemma strict_mono.mul_monotone' (hf : strict_mono f) (hg : monotone g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_lt_of_le (hf h) (hg $ le_of_lt h) @[to_additive strict_mono.add_const] lemma strict_mono.mul_const' (hf : strict_mono f) (c : α) : strict_mono (λ x, f x * c) := hf.mul_monotone' monotone_const @[to_additive strict_mono.const_add] lemma strict_mono.const_mul' (hf : strict_mono f) (c : α) : strict_mono (λ x, c * f x) := monotone_const.mul_strict_mono' hf end mono end ordered_cancel_comm_monoid section ordered_cancel_add_comm_monoid variable [ordered_cancel_add_comm_monoid α] lemma with_top.add_lt_add_iff_left : ∀{a b c : with_top α}, a < ⊤ → (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊤ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe], { norm_cast, exact with_top.coe_lt_top _ }, { norm_cast, exact add_lt_add_iff_left _ } end lemma with_bot.add_lt_add_iff_left : ∀{a b c : with_bot α}, ⊥ < a → (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊥ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_bot.none_eq_bot, with_bot.some_eq_coe, with_bot.bot_lt_coe, with_bot.coe_lt_coe], { norm_cast, exact with_bot.bot_lt_coe _ }, { norm_cast, exact add_lt_add_iff_left _ } end local attribute [reducible] with_zero lemma with_top.add_lt_add_iff_right {a b c : with_top α} : a < ⊤ → (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c lemma with_bot.add_lt_add_iff_right {a b c : with_bot α} : ⊥ < a → (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_bot.add_lt_add_iff_left _ _ a b c end ordered_cancel_add_comm_monoid /-! Some lemmas about types that have an ordering and a binary operation, with no rules relating them. -/ @[to_additive] lemma fn_min_mul_fn_max {β} [linear_order α] [comm_semigroup β] (f : α → β) (n m : α) : f (min n m) * f (max n m) = f n * f m := by { cases le_total n m with h h; simp [h, mul_comm] } @[to_additive] lemma min_mul_max [linear_order α] [comm_semigroup α] (n m : α) : min n m * max n m = n * m := fn_min_mul_fn_max id n m /-- A linearly ordered cancellative additive commutative monoid is an additive commutative monoid with a decidable linear order in which addition is cancellative and monotone. -/ @[protect_proj, ancestor ordered_cancel_add_comm_monoid linear_ordered_add_comm_monoid] class linear_ordered_cancel_add_comm_monoid (α : Type u) extends ordered_cancel_add_comm_monoid α, linear_ordered_add_comm_monoid α /-- A linearly ordered cancellative commutative monoid is a commutative monoid with a linear order in which multiplication is cancellative and monotone. -/ @[protect_proj, ancestor ordered_cancel_comm_monoid linear_ordered_comm_monoid, to_additive] class linear_ordered_cancel_comm_monoid (α : Type u) extends ordered_cancel_comm_monoid α, linear_ordered_comm_monoid α section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_comm_monoid α] @[to_additive] lemma min_mul_mul_left (a b c : α) : min (a * b) (a * c) = a * min b c := (monotone_id.const_mul' a).map_min.symm @[to_additive] lemma min_mul_mul_right (a b c : α) : min (a * c) (b * c) = min a b * c := (monotone_id.mul_const' c).map_min.symm @[to_additive] lemma max_mul_mul_left (a b c : α) : max (a * b) (a * c) = a * max b c := (monotone_id.const_mul' a).map_max.symm @[to_additive] lemma max_mul_mul_right (a b c : α) : max (a * c) (b * c) = max a b * c := (monotone_id.mul_const' c).map_max.symm @[to_additive] lemma min_le_mul_of_one_le_right {a b : α} (hb : 1 ≤ b) : min a b ≤ a * b := min_le_iff.2 $ or.inl $ le_mul_of_one_le_right' hb @[to_additive] lemma min_le_mul_of_one_le_left {a b : α} (ha : 1 ≤ a) : min a b ≤ a * b := min_le_iff.2 $ or.inr $ le_mul_of_one_le_left' ha @[to_additive] lemma max_le_mul_of_one_le {a b : α} (ha : 1 ≤ a) (hb : 1 ≤ b) : max a b ≤ a * b := max_le_iff.2 ⟨le_mul_of_one_le_right' hb, le_mul_of_one_le_left' ha⟩ /-- Pullback a `linear_ordered_cancel_comm_monoid` under an injective map. -/ @[to_additive function.injective.linear_ordered_cancel_add_comm_monoid "Pullback a `linear_ordered_cancel_add_comm_monoid` under an injective map."] def function.injective.linear_ordered_cancel_comm_monoid {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : linear_ordered_cancel_comm_monoid β := { ..hf.linear_ordered_comm_monoid f one mul, ..hf.ordered_cancel_comm_monoid f one mul } end linear_ordered_cancel_comm_monoid namespace order_dual @[to_additive] instance [ordered_comm_monoid α] : ordered_comm_monoid (order_dual α) := { mul_le_mul_left := λ a b h c, @mul_le_mul_left' α _ b a h _, lt_of_mul_lt_mul_left := λ a b c h, @lt_of_mul_lt_mul_left' α _ a c b h, ..order_dual.partial_order α, ..show comm_monoid α, by apply_instance } @[to_additive] instance [ordered_cancel_comm_monoid α] : ordered_cancel_comm_monoid (order_dual α) := { le_of_mul_le_mul_left := λ a b c : α, le_of_mul_le_mul_left', mul_left_cancel := @mul_left_cancel α _, ..order_dual.ordered_comm_monoid } @[to_additive] instance [linear_ordered_cancel_comm_monoid α] : linear_ordered_cancel_comm_monoid (order_dual α) := { .. order_dual.linear_order α, .. order_dual.ordered_cancel_comm_monoid } end order_dual namespace prod variables {M N : Type*} @[to_additive] instance [ordered_cancel_comm_monoid M] [ordered_cancel_comm_monoid N] : ordered_cancel_comm_monoid (M × N) := { mul_le_mul_left := λ a b h c, ⟨mul_le_mul_left' h.1 _, mul_le_mul_left' h.2 _⟩, le_of_mul_le_mul_left := λ a b c h, ⟨le_of_mul_le_mul_left' h.1, le_of_mul_le_mul_left' h.2⟩, .. prod.cancel_comm_monoid, .. prod.partial_order M N } end prod section type_tags instance : Π [preorder α], preorder (multiplicative α) := id instance : Π [preorder α], preorder (additive α) := id instance : Π [partial_order α], partial_order (multiplicative α) := id instance : Π [partial_order α], partial_order (additive α) := id instance : Π [linear_order α], linear_order (multiplicative α) := id instance : Π [linear_order α], linear_order (additive α) := id instance [ordered_add_comm_monoid α] : ordered_comm_monoid (multiplicative α) := { mul_le_mul_left := @ordered_add_comm_monoid.add_le_add_left α _, lt_of_mul_lt_mul_left := @ordered_add_comm_monoid.lt_of_add_lt_add_left α _, ..multiplicative.partial_order, ..multiplicative.comm_monoid } instance [ordered_comm_monoid α] : ordered_add_comm_monoid (additive α) := { add_le_add_left := @ordered_comm_monoid.mul_le_mul_left α _, lt_of_add_lt_add_left := @ordered_comm_monoid.lt_of_mul_lt_mul_left α _, ..additive.partial_order, ..additive.add_comm_monoid } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_comm_monoid (multiplicative α) := { le_of_mul_le_mul_left := @ordered_cancel_add_comm_monoid.le_of_add_le_add_left α _, ..multiplicative.left_cancel_semigroup, ..multiplicative.ordered_comm_monoid } instance [ordered_cancel_comm_monoid α] : ordered_cancel_add_comm_monoid (additive α) := { le_of_add_le_add_left := @ordered_cancel_comm_monoid.le_of_mul_le_mul_left α _, ..additive.add_left_cancel_semigroup, ..additive.ordered_add_comm_monoid } instance [linear_ordered_add_comm_monoid α] : linear_ordered_comm_monoid (multiplicative α) := { ..multiplicative.linear_order, ..multiplicative.ordered_comm_monoid } instance [linear_ordered_comm_monoid α] : linear_ordered_add_comm_monoid (additive α) := { ..additive.linear_order, ..additive.ordered_add_comm_monoid } end type_tags
7c6ce604a1ac46659be1b4cd3f9a899f88cb3067
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/calculus/deriv.lean
ea118f7898554192e33a53b33785c2df40aa8dda
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
91,850
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv import data.polynomial.derivative import linear_algebra.affine_space.slope /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.html). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. - `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x` in the sense of strict differentiability, i.e., `f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - sum of finitely many functions - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. We set up the simplifier so that it can compute the derivative of simple functions. For instance, ```lean example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } ``` ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. The strategy to construct simp lemmas that give the simplifier the possibility to compute derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`. See the explanations there. -/ universes u v w noncomputable theory open_locale classical topological_space big_operators filter ennreal polynomial open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝[s] x) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability. That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/ def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := fderiv_within 𝕜 f s x 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := fderiv 𝕜 f x 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L := has_fderiv_at_filter_iff_has_deriv_at_filter.mp /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := has_fderiv_at_filter_iff_has_deriv_at_filter /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x := iff.rfl lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x := has_fderiv_within_at_iff_has_deriv_within_at.mp lemma has_deriv_within_at.has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x := has_deriv_within_at_iff_has_fderiv_within_at.mp /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := has_fderiv_at_filter_iff_has_deriv_at_filter lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x → has_deriv_at f (f' 1) x := has_fderiv_at_iff_has_deriv_at.mp lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x := by simp [has_strict_deriv_at, has_strict_fderiv_at] protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x := has_strict_fderiv_at_iff_has_strict_deriv_at.mp lemma has_strict_deriv_at_iff_has_strict_fderiv_at : has_strict_deriv_at f f' x ↔ has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x := iff.rfl alias has_strict_deriv_at_iff_has_strict_fderiv_at ↔ has_strict_deriv_at.has_strict_fderiv_at _ /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x := iff.rfl alias has_deriv_at_iff_has_fderiv_at ↔ has_deriv_at.has_fderiv_at _ lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma differentiable_within_at_of_deriv_within_ne_zero (h : deriv_within f s x ≠ 0) : differentiable_within_at 𝕜 f s x := not_imp_comm.1 deriv_within_zero_of_not_differentiable_within_at h lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } lemma differentiable_at_of_deriv_ne_zero (h : deriv f x ≠ 0) : differentiable_at 𝕜 f x := not_imp_comm.1 deriv_zero_of_not_differentiable_at h theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_is_o : has_deriv_at_filter f f' x L ↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[L] (λ x', x' - x) := iff.rfl theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_is_o : has_deriv_within_at f f' s x ↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[𝓝[s] x] (λ x', x' - x) := iff.rfl theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_is_o : has_deriv_at f f' x ↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[𝓝 x] (λ x', x' - x) := iff.rfl theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) : has_deriv_at f f' x := h.has_fderiv_at /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (slope f x) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation_sub f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right, simp only [(∘)], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul, slope_def_module] end lemma has_deriv_within_at_iff_tendsto_slope : has_deriv_within_at f f' s x ↔ tendsto (slope f x) (𝓝[s \ {x}] x) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (slope f x) (𝓝[s] x) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope : has_deriv_at f f' x ↔ tendsto (slope f x) (𝓝[≠] x) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope theorem has_deriv_within_at_congr_set {s t u : set 𝕜} (hu : u ∈ 𝓝 x) (h : s ∩ u = t ∩ u) : has_deriv_within_at f f' s x ↔ has_deriv_within_at f f' t x := by simp_rw [has_deriv_within_at, nhds_within_eq_nhds_within' hu h] alias has_deriv_within_at_congr_set ↔ has_deriv_within_at.congr_set _ @[simp] lemma has_deriv_within_at_diff_singleton : has_deriv_within_at f f' (s \ {x}) x ↔ has_deriv_within_at f f' s x := by simp only [has_deriv_within_at_iff_tendsto_slope, sdiff_idem] @[simp] lemma has_deriv_within_at_Ioi_iff_Ici [partial_order 𝕜] : has_deriv_within_at f f' (Ioi x) x ↔ has_deriv_within_at f f' (Ici x) x := by rw [← Ici_diff_left, has_deriv_within_at_diff_singleton] alias has_deriv_within_at_Ioi_iff_Ici ↔ has_deriv_within_at.Ici_of_Ioi has_deriv_within_at.Ioi_of_Ici @[simp] lemma has_deriv_within_at_Iio_iff_Iic [partial_order 𝕜] : has_deriv_within_at f f' (Iio x) x ↔ has_deriv_within_at f f' (Iic x) x := by rw [← Iic_diff_right, has_deriv_within_at_diff_singleton] alias has_deriv_within_at_Iio_iff_Iic ↔ has_deriv_within_at.Iic_of_Iio has_deriv_within_at.Iio_of_Iic theorem has_deriv_within_at.Ioi_iff_Ioo [linear_order 𝕜] [order_closed_topology 𝕜] {x y : 𝕜} (h : x < y) : has_deriv_within_at f f' (Ioo x y) x ↔ has_deriv_within_at f f' (Ioi x) x := has_deriv_within_at_congr_set (is_open_Iio.mem_nhds h) $ by { rw [Ioi_inter_Iio, inter_eq_left_iff_subset], exact Ioo_subset_Iio_self } alias has_deriv_within_at.Ioi_iff_Ioo ↔ has_deriv_within_at.Ioi_of_Ioo has_deriv_within_at.Ioo_of_Ioi theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ (λh, f (x + h) - f x - h • f') =o[𝓝 0] (λh, h) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at.unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ h₀.has_fderiv_at.unique h₁ lemma has_deriv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := hs.has_fderiv_within_at.union ht.has_fderiv_within_at lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := h.has_fderiv_within_at.has_deriv_within_at lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := h.has_fderiv_at.has_deriv_at @[simp] lemma has_deriv_at_deriv_iff : has_deriv_at f (deriv f x) x ↔ differentiable_at 𝕜 f x := ⟨λ h, h.differentiable_at, λ h, h.has_deriv_at⟩ @[simp] lemma has_deriv_within_at_deriv_within_iff : has_deriv_within_at f (deriv_within f s x) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, h.differentiable_within_at, λ h, h.has_deriv_within_at⟩ lemma differentiable_on.has_deriv_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) : has_deriv_at f (deriv f x) x := (h.has_fderiv_at hs).has_deriv_at lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := h.differentiable_at.has_deriv_at.unique h lemma deriv_eq {f' : 𝕜 → F} (h : ∀ x, has_deriv_at f (f' x) x) : deriv f = f' := funext $ λ x, (h x).deriv lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } theorem has_deriv_within_at.deriv_eq_zero (hd : has_deriv_within_at f 0 s x) (H : unique_diff_within_at 𝕜 s x) : deriv f x = 0 := (em' (differentiable_at 𝕜 f x)).elim deriv_zero_of_not_differentiable_at $ λ h, H.eq_deriv _ h.has_deriv_at.has_deriv_within_at hd lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } lemma deriv_within_of_open (hs : is_open s) (hx : x ∈ s) : deriv_within f s x = deriv f x := by { unfold deriv_within, rw fderiv_within_of_open hs hx, refl } lemma deriv_mem_iff {f : 𝕜 → F} {s : set F} {x : 𝕜} : deriv f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ deriv f x ∈ s) ∨ (¬differentiable_at 𝕜 f x ∧ (0 : F) ∈ s) := by by_cases hx : differentiable_at 𝕜 f x; simp [deriv_zero_of_not_differentiable_at, *] lemma deriv_within_mem_iff {f : 𝕜 → F} {t : set 𝕜} {s : set F} {x : 𝕜} : deriv_within f t x ∈ s ↔ (differentiable_within_at 𝕜 f t x ∧ deriv_within f t x ∈ s) ∨ (¬differentiable_within_at 𝕜 f t x ∧ (0 : F) ∈ s) := by by_cases hx : differentiable_within_at 𝕜 f t x; simp [deriv_within_zero_of_not_differentiable_within_at, *] lemma differentiable_within_at_Ioi_iff_Ici [partial_order 𝕜] : differentiable_within_at 𝕜 f (Ioi x) x ↔ differentiable_within_at 𝕜 f (Ici x) x := ⟨λ h, h.has_deriv_within_at.Ici_of_Ioi.differentiable_within_at, λ h, h.has_deriv_within_at.Ioi_of_Ici.differentiable_within_at⟩ lemma deriv_within_Ioi_eq_Ici {E : Type*} [normed_group E] [normed_space ℝ E] (f : ℝ → E) (x : ℝ) : deriv_within f (Ioi x) x = deriv_within f (Ici x) x := begin by_cases H : differentiable_within_at ℝ f (Ioi x) x, { have A := H.has_deriv_within_at.Ici_of_Ioi, have B := (differentiable_within_at_Ioi_iff_Ici.1 H).has_deriv_within_at, simpa using (unique_diff_on_Ici x).eq le_rfl A B }, { rw [deriv_within_zero_of_not_differentiable_within_at H, deriv_within_zero_of_not_differentiable_within_at], rwa differentiable_within_at_Ioi_iff_Ici at H } end section congr /-! ### Congruence properties of derivatives -/ theorem filter.eventually_eq.has_deriv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := h₀.has_fderiv_at_filter_iff hx (by simp [h₁]) lemma has_deriv_at_filter.congr_of_eventually_eq (h : has_deriv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa hL.has_deriv_at_filter_iff hx rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_mem (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : x ∈ s) : has_deriv_within_at f₁ f' s x := h.congr hs (hs _ hx) lemma has_deriv_within_at.congr_of_eventually_eq (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_deriv_within_at.congr_of_eventually_eq_of_mem (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : has_deriv_within_at f₁ f' s x := h.congr_of_eventually_eq h₁ (h₁.eq_of_nhds_within hx) lemma has_deriv_at.congr_of_eventually_eq (h : has_deriv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_eventually_eq h h₁ (mem_of_mem_nhds h₁ : _) lemma filter.eventually_eq.deriv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw hL.fderiv_within_eq hs hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma filter.eventually_eq.deriv_eq (hL : f₁ =ᶠ[𝓝 x] f) : deriv f₁ x = deriv f x := by { unfold deriv, rwa filter.eventually_eq.fderiv_eq } protected lemma filter.eventually_eq.deriv (h : f₁ =ᶠ[𝓝 x] f) : deriv f₁ =ᶠ[𝓝 x] deriv f := h.eventually_eq_nhds.mono $ λ x h, h.deriv_eq end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (has_fderiv_at_filter_id x L).has_deriv_at_filter theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x := has_deriv_at_filter_id _ _ theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x := (has_strict_fderiv_at_id x).has_strict_deriv_at lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id @[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) = λ _, 1 := deriv_id' lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := (has_deriv_within_at_id x s).deriv_within hxs end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (has_fderiv_at_filter_const c x L).has_deriv_at_filter theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x := (has_strict_fderiv_at_const c x).has_strict_deriv_at theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := (has_deriv_within_at_const _ _ _).deriv_within hxs end const section continuous_linear_map /-! ### Derivative of continuous linear maps -/ variables (e : 𝕜 →L[𝕜] F) protected lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.has_fderiv_at_filter.has_deriv_at_filter protected lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.has_strict_fderiv_at.has_strict_deriv_at protected lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter protected lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] protected lemma continuous_linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv protected lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end continuous_linear_map section linear_map /-! ### Derivative of bundled linear maps -/ variables (e : 𝕜 →ₗ[𝕜] F) protected lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.to_continuous_linear_map₁.has_deriv_at_filter protected lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.to_continuous_linear_map₁.has_strict_deriv_at protected lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter protected lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] protected lemma linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv protected lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end linear_map section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := by simpa using (hf.add hg).has_deriv_at_filter theorem has_strict_deriv_at.add (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ y, f y + g y) (f' + g') x := by simpa using (hf.add hg).has_strict_deriv_at theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_add_const hxs] lemma deriv_add_const (c : F) : deriv (λy, f y + c) x = deriv f x := by simp only [deriv, fderiv_add_const] @[simp] lemma deriv_add_const' (c : F) : deriv (λ y, f y + c) = deriv f := funext $ λ x, deriv_add_const c theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c + f y) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_const_add hxs] lemma deriv_const_add (c : F) : deriv (λy, c + f y) x = deriv f x := by simp only [deriv, fderiv_const_add] @[simp] lemma deriv_const_add' (c : F) : deriv (λ y, c + f y) = deriv f := funext $ λ x, deriv_const_add c end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F} theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) : has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) : has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) : has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_deriv_at_filter.sum h theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) : has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_deriv_at_filter.sum h lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x := (has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs @[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x := (has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv end sum section pi /-! ### Derivatives of functions `f : 𝕜 → Π i, E i` -/ variables {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_group (E' i)] [Π i, normed_space 𝕜 (E' i)] {φ : 𝕜 → Π i, E' i} {φ' : Π i, E' i} @[simp] lemma has_strict_deriv_at_pi : has_strict_deriv_at φ φ' x ↔ ∀ i, has_strict_deriv_at (λ x, φ x i) (φ' i) x := has_strict_fderiv_at_pi' @[simp] lemma has_deriv_at_filter_pi : has_deriv_at_filter φ φ' x L ↔ ∀ i, has_deriv_at_filter (λ x, φ x i) (φ' i) x L := has_fderiv_at_filter_pi' lemma has_deriv_at_pi : has_deriv_at φ φ' x ↔ ∀ i, has_deriv_at (λ x, φ x i) (φ' i) x:= has_deriv_at_filter_pi lemma has_deriv_within_at_pi : has_deriv_within_at φ φ' s x ↔ ∀ i, has_deriv_within_at (λ x, φ x i) (φ' i) s x:= has_deriv_at_filter_pi lemma deriv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (λ x, φ x i) s x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within φ s x = λ i, deriv_within (λ x, φ x i) s x := (has_deriv_within_at_pi.2 (λ i, (h i).has_deriv_within_at)).deriv_within hs lemma deriv_pi (h : ∀ i, differentiable_at 𝕜 (λ x, φ x i) x) : deriv φ x = λ i, deriv (λ x, φ x i) x := (has_deriv_at_pi.2 (λ i, (h i).has_deriv_at)).deriv end pi section smul /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] {c : 𝕜 → 𝕜'} {c' : 𝕜'} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end theorem has_strict_deriv_at.smul (hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := by simpa using (hc.smul hf).has_strict_deriv_at lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_strict_deriv_at.smul_const (hc : has_strict_deriv_at c c' x) (f : F) : has_strict_deriv_at (λ y, c y • f) (c' • f) x := begin have := hc.smul (has_strict_deriv_at_const x f), rwa [smul_zero, zero_add] at this, end theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv end smul section const_smul variables {R : Type*} [semiring R] [module R F] [smul_comm_class 𝕜 R F] [has_continuous_const_smul R F] theorem has_strict_deriv_at.const_smul (c : R) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ y, c • f y) (c • f') x := by simpa using (hf.const_smul c).has_strict_deriv_at theorem has_deriv_at_filter.const_smul (c : R) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c • f y) (c • f') x L := by simpa using (hf.const_smul c).has_deriv_at_filter theorem has_deriv_within_at.const_smul (c : R) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := hf.const_smul c theorem has_deriv_at.const_smul (c : R) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := hf.const_smul c lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : R) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : R) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end const_smul section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := by simpa using h.neg.has_deriv_at_filter theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, -f x) (-f') x := by simpa using h.neg.has_strict_deriv_at lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := by simp only [deriv_within, fderiv_within_neg hxs, continuous_linear_map.neg_apply] lemma deriv.neg : deriv (λy, -f y) x = - deriv f x := by simp only [deriv, fderiv_neg, continuous_linear_map.neg_apply] @[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv.neg end neg section neg2 /-! ### Derivative of the negation function (i.e `has_neg.neg`) -/ variables (s x L) theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L := has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _ theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x := has_deriv_at_filter_neg _ _ theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x := has_strict_deriv_at.neg $ has_strict_deriv_at_id _ lemma deriv_neg : deriv has_neg.neg x = -1 := has_deriv_at.deriv (has_deriv_at_neg x) @[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 := funext deriv_neg @[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 := deriv_neg x lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 := (has_deriv_within_at_neg x s).deriv_within hxs lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) := differentiable.neg differentiable_id lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s := differentiable_on.neg differentiable_on_id end neg2 section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg theorem has_strict_deriv_at.sub (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : (λ x', f x' - f x) =O[L] (λ x', x' - x) := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.is_O_sub_rev (hf : has_deriv_at_filter f f' x L) (hf' : f' ≠ 0) : (λ x', x' - x) =O[L] (λ x', f x' - f x) := suffices antilipschitz_with ∥f'∥₊⁻¹ (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f'), from hf.is_O_sub_rev this, add_monoid_hom_class.antilipschitz_of_bound (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') $ λ x, by simp [norm_smul, ← div_eq_inv_mul, mul_div_cancel _ (mt norm_eq_zero.1 hf')] theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_sub_const hxs] lemma deriv_sub_const (c : F) : deriv (λ y, f y - c) x = deriv f x := by simp only [deriv, fderiv_sub_const] theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_strict_deriv_at.const_sub (c : F) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, c - f x) (-f') x := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c - f y) s x = -deriv_within f s x := by simp [deriv_within, fderiv_within_const_sub hxs] lemma deriv_const_sub (c : F) : deriv (λ y, c - f y) x = -deriv f x := by simp only [← deriv_within_univ, deriv_within_const_sub (unique_diff_within_at_univ : unique_diff_within_at 𝕜 _ _)] end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := h.tendsto_nhds hL theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds le_rfl h protected theorem has_deriv_at.continuous_on {f f' : 𝕜 → F} (hderiv : ∀ x ∈ s, has_deriv_at f (f' x) x) : continuous_on f s := λ x hx, (hderiv x hx).continuous_at.continuous_within_at end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := hf₁.prod hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ lemma has_strict_deriv_at.prod (hf₁ : has_strict_deriv_at f₁ f₁' x) (hf₂ : has_strict_deriv_at f₂ f₂' x) : has_strict_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector function and a scalar function We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp` in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also because the `comp` version with the shorter name will show up much more often in applications). The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to usual multiplication in `comp` lemmas. -/ /- 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 -/ variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] {s' t' : set 𝕜'} {h : 𝕜 → 𝕜'} {h₁ : 𝕜 → 𝕜} {h₂ : 𝕜' → 𝕜'} {h' h₂' : 𝕜'} {h₁' : 𝕜} {g₁ : 𝕜' → F} {g₁' : F} {L' : filter 𝕜'} (x) theorem has_deriv_at_filter.scomp (hg : has_deriv_at_filter g₁ g₁' (h x) L') (hh : has_deriv_at_filter h h' x L) (hL : tendsto h L L'): has_deriv_at_filter (g₁ ∘ h) (h' • g₁') x L := by simpa using ((hg.restrict_scalars 𝕜).comp x hh hL).has_deriv_at_filter theorem has_deriv_within_at.scomp_has_deriv_at (hg : has_deriv_within_at g₁ g₁' s' (h x)) (hh : has_deriv_at h h' x) (hs : ∀ x, h x ∈ s') : has_deriv_at (g₁ ∘ h) (h' • g₁') x := hg.scomp x hh $ tendsto_inf.2 ⟨hh.continuous_at, tendsto_principal.2 $ eventually_of_forall hs⟩ theorem has_deriv_within_at.scomp (hg : has_deriv_within_at g₁ g₁' t' (h x)) (hh : has_deriv_within_at h h' s x) (hst : maps_to h s t') : has_deriv_within_at (g₁ ∘ h) (h' • g₁') s x := hg.scomp x hh $ hh.continuous_within_at.tendsto_nhds_within hst /-- The chain rule. -/ theorem has_deriv_at.scomp (hg : has_deriv_at g₁ g₁' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g₁ ∘ h) (h' • g₁') x := hg.scomp x hh hh.continuous_at theorem has_strict_deriv_at.scomp (hg : has_strict_deriv_at g₁ g₁' (h x)) (hh : has_strict_deriv_at h h' x) : has_strict_deriv_at (g₁ ∘ h) (h' • g₁') x := by simpa using ((hg.restrict_scalars 𝕜).comp x hh).has_strict_deriv_at theorem has_deriv_at.scomp_has_deriv_within_at (hg : has_deriv_at g₁ g₁' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g₁ ∘ h) (h' • g₁') s x := has_deriv_within_at.scomp x hg.has_deriv_within_at hh (maps_to_univ _ _) lemma deriv_within.scomp (hg : differentiable_within_at 𝕜' g₁ t' (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : maps_to h s t') (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g₁ ∘ h) s x = deriv_within h s x • deriv_within g₁ t' (h x) := (has_deriv_within_at.scomp x hg.has_deriv_within_at hh.has_deriv_within_at hs).deriv_within hxs lemma deriv.scomp (hg : differentiable_at 𝕜' g₁ (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g₁ ∘ h) x = deriv h x • deriv g₁ (h x) := (has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at).deriv /-! ### Derivative of the composition of a scalar and vector functions -/ theorem has_deriv_at_filter.comp_has_fderiv_at_filter {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x) {L'' : filter E} (hh₂ : has_deriv_at_filter h₂ h₂' (f x) L') (hf : has_fderiv_at_filter f f' x L'') (hL : tendsto f L'' L') : has_fderiv_at_filter (h₂ ∘ f) (h₂' • f') x L'' := by { convert (hh₂.restrict_scalars 𝕜).comp x hf hL, ext x, simp [mul_comm] } theorem has_strict_deriv_at.comp_has_strict_fderiv_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x) (hh : has_strict_deriv_at h₂ h₂' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (h₂ ∘ f) (h₂' • f') x := begin rw has_strict_deriv_at at hh, convert (hh.restrict_scalars 𝕜).comp x hf, ext x, simp [mul_comm] end theorem has_deriv_at.comp_has_fderiv_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x) (hh : has_deriv_at h₂ h₂' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (h₂ ∘ f) (h₂' • f') x := hh.comp_has_fderiv_at_filter x hf hf.continuous_at theorem has_deriv_at.comp_has_fderiv_within_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} {s} (x) (hh : has_deriv_at h₂ h₂' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (h₂ ∘ f) (h₂' • f') s x := hh.comp_has_fderiv_at_filter x hf hf.continuous_within_at theorem has_deriv_within_at.comp_has_fderiv_within_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} {s t} (x) (hh : has_deriv_within_at h₂ h₂' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : maps_to f s t) : has_fderiv_within_at (h₂ ∘ f) (h₂' • f') s x := hh.comp_has_fderiv_at_filter x hf $ hf.continuous_within_at.tendsto_nhds_within hst /-! ### Derivative of the composition of two scalar functions -/ theorem has_deriv_at_filter.comp (hh₂ : has_deriv_at_filter h₂ h₂' (h x) L') (hh : has_deriv_at_filter h h' x L) (hL : tendsto h L L') : has_deriv_at_filter (h₂ ∘ h) (h₂' * h') x L := by { rw mul_comm, exact hh₂.scomp x hh hL } theorem has_deriv_within_at.comp (hh₂ : has_deriv_within_at h₂ h₂' s' (h x)) (hh : has_deriv_within_at h h' s x) (hst : maps_to h s s') : has_deriv_within_at (h₂ ∘ h) (h₂' * h') s x := by { rw mul_comm, exact hh₂.scomp x hh hst, } /-- The chain rule. -/ theorem has_deriv_at.comp (hh₂ : has_deriv_at h₂ h₂' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (h₂ ∘ h) (h₂' * h') x := hh₂.comp x hh hh.continuous_at theorem has_strict_deriv_at.comp (hh₂ : has_strict_deriv_at h₂ h₂' (h x)) (hh : has_strict_deriv_at h h' x) : has_strict_deriv_at (h₂ ∘ h) (h₂' * h') x := by { rw mul_comm, exact hh₂.scomp x hh } theorem has_deriv_at.comp_has_deriv_within_at (hh₂ : has_deriv_at h₂ h₂' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (h₂ ∘ h) (h₂' * h') s x := hh₂.has_deriv_within_at.comp x hh (maps_to_univ _ _) lemma deriv_within.comp (hh₂ : differentiable_within_at 𝕜' h₂ s' (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : maps_to h s s') (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (h₂ ∘ h) s x = deriv_within h₂ s' (h x) * deriv_within h s x := (hh₂.has_deriv_within_at.comp x hh.has_deriv_within_at hs).deriv_within hxs lemma deriv.comp (hh₂ : differentiable_at 𝕜' h₂ (h x)) (hh : differentiable_at 𝕜 h x) : deriv (h₂ ∘ h) x = deriv h₂ (h x) * deriv h x := (hh₂.has_deriv_at.comp x hh.has_deriv_at).deriv protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_deriv_at_filter (f^[n]) (f'^n) x L := begin have := hf.iterate hL hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_deriv_at (f^[n]) (f'^n) x := begin have := has_fderiv_at.iterate hf hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_deriv_within_at (f^[n]) (f'^n) s x := begin have := has_fderiv_within_at.iterate hf hx hs n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_deriv_at (f^[n]) (f'^n) x := begin have := hf.iterate hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and a function on `𝕜` -/ open continuous_linear_map variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : maps_to f s t) : has_deriv_within_at (l ∘ f) (l' f') s x := by simpa only [one_apply, one_smul, smul_right_apply, coe_comp', (∘)] using (hl.comp x hf.has_fderiv_within_at hst).has_deriv_within_at theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' f') s x := hl.has_fderiv_within_at.comp_has_deriv_within_at x hf (maps_to_univ _ _) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' f') x := has_deriv_within_at_univ.mp $ hl.comp_has_deriv_within_at x hf.has_deriv_within_at theorem has_strict_fderiv_at.comp_has_strict_deriv_at (hl : has_strict_fderiv_at l l' (f x)) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (l ∘ f) (l' f') x := by simpa only [one_apply, one_smul, smul_right_apply, coe_comp', (∘)] using (hl.comp x hf.has_strict_fderiv_at).has_strict_deriv_at lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := (hl.has_fderiv_within_at.comp_has_deriv_within_at x hf.has_deriv_within_at hs).deriv_within hxs lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := (hl.has_fderiv_at.comp_has_deriv_at x hf.has_deriv_at).deriv end composition_vector section mul /-! ### Derivative of the multiplication of two functions -/ variables {𝕜' 𝔸 : Type*} [normed_field 𝕜'] [normed_ring 𝔸] [normed_algebra 𝕜 𝕜'] [normed_algebra 𝕜 𝔸] {c d : 𝕜 → 𝔸} {c' d' : 𝔸} {u v : 𝕜 → 𝕜'} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin have := (has_fderiv_within_at.mul' hc hd).has_deriv_within_at, rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply, one_smul, one_smul, add_comm] at this, end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end theorem has_strict_deriv_at.mul (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin have := (has_strict_fderiv_at.mul' hc hd).has_strict_deriv_at, rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply, one_smul, one_smul, add_comm] at this, end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝔸) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝔸) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end theorem has_deriv_at_mul_const (c : 𝕜) : has_deriv_at (λ x, x * c) c x := by simpa only [one_mul] using (has_deriv_at_id' x).mul_const c theorem has_strict_deriv_at.mul_const (hc : has_strict_deriv_at c c' x) (d : 𝔸) : has_strict_deriv_at (λ y, c y * d) (c' * d) x := begin convert hc.mul (has_strict_deriv_at_const x d), rw [mul_zero, add_zero] end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝔸) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝔸) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv lemma deriv_mul_const_field (v : 𝕜') : deriv (λ y, u y * v) x = deriv u x * v := begin by_cases hu : differentiable_at 𝕜 u x, { exact deriv_mul_const hu v }, { rw [deriv_zero_of_not_differentiable_at hu, zero_mul], rcases eq_or_ne v 0 with rfl|hd, { simp only [mul_zero, deriv_const] }, { refine deriv_zero_of_not_differentiable_at (mt (λ H, _) hu), simpa only [mul_inv_cancel_right₀ hd] using H.mul_const v⁻¹ } } end @[simp] lemma deriv_mul_const_field' (v : 𝕜') : deriv (λ x, u x * v) = λ x, deriv u x * v := funext $ λ _, deriv_mul_const_field v theorem has_deriv_within_at.const_mul (c : 𝔸) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝔸) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end theorem has_strict_deriv_at.const_mul (c : 𝔸) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c * d y) (c * d') x := begin convert (has_strict_deriv_at_const _ _).mul hd, rw [zero_mul, zero_add] end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝔸) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝔸) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv lemma deriv_const_mul_field (u : 𝕜') : deriv (λ y, u * v y) x = u * deriv v x := by simp only [mul_comm u, deriv_mul_const_field] @[simp] lemma deriv_const_mul_field' (u : 𝕜') : deriv (λ x, u * v x) = λ x, u * deriv v x := funext (λ x, deriv_const_mul_field u) end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x := begin suffices : (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) =o[𝓝 (x, x)] (λ p, (p.1 - p.2) * 1), { refine this.congr' _ (eventually_of_forall $ λ _, mul_one _), refine eventually.mono (is_open.mem_nhds (is_open_ne.prod is_open_ne) ⟨hx, hx⟩) _, rintro ⟨y, z⟩ ⟨hy, hz⟩, simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0 field_simp [hx, hy, hz], ring, }, refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _), rw [← sub_self (x * x)⁻¹], exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv₀ $ mul_ne_zero hx hx) end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := (has_strict_deriv_at_inv x_ne_zero).has_deriv_at theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv : differentiable_at 𝕜 (λx, x⁻¹) x ↔ x ≠ 0:= ⟨λ H, normed_field.continuous_at_inv.1 H.continuous_at, λ H, (has_deriv_at_inv H).differentiable_at⟩ lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv.2 x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := begin rcases eq_or_ne x 0 with rfl|hne, { simp [deriv_zero_of_not_differentiable_at (mt differentiable_at_inv.1 (not_not.2 rfl))] }, { exact (has_deriv_at_inv hne).deriv } end @[simp] lemma deriv_inv' : deriv (λ x : 𝕜, x⁻¹) = λ x, -(x ^ 2)⁻¹ := funext (λ x, deriv_inv) lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv.2 x_ne_zero) hxs, exact deriv_inv end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv : fderiv 𝕜 (λx, x⁻¹) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) := by rw [← deriv_fderiv, deriv_inv] lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv.2 x_ne_zero) hxs, exact fderiv_inv end variables {c : 𝕜 → 𝕜} {c' : 𝕜} lemma has_deriv_within_at.inv (hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) : has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x := begin convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc, field_simp end lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) : has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.inv hx end lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) : differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x := (hc.has_deriv_within_at.inv hx).differentiable_within_at @[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : differentiable_at 𝕜 (λx, (c x)⁻¹) x := (hc.has_deriv_at.inv hx).differentiable_at lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) : differentiable_on 𝕜 (λx, (c x)⁻¹) s := λx h, (hc x h).inv (hx x h) @[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) : differentiable 𝕜 (λx, (c x)⁻¹) := λx, (hc x).inv (hx x) lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 := (hc.has_deriv_within_at.inv hx).deriv_within hxs @[simp] lemma deriv_inv'' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 := (hc.has_deriv_at.inv hx).deriv end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {c d : 𝕜 → 𝕜'} {c' d' : 𝕜'} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), { simp only [div_eq_mul_inv] }, { field_simp, ring } end lemma has_strict_deriv_at.div (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) (hx : d x ≠ 0) : has_strict_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin convert hc.mul ((has_strict_deriv_at_inv hx).comp x hd), { simp only [div_eq_mul_inv] }, { field_simp, ring } end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at @[simp] lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) @[simp] lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs @[simp] lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv lemma has_deriv_at.div_const (hc : has_deriv_at c c' x) (d : 𝕜') : has_deriv_at (λ x, c x / d) (c' / d) x := by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹ lemma has_deriv_within_at.div_const (hc : has_deriv_within_at c c' s x) (d : 𝕜') : has_deriv_within_at (λ x, c x / d) (c' / d) s x := by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹ lemma has_strict_deriv_at.div_const (hc : has_strict_deriv_at c c' x) (d : 𝕜') : has_strict_deriv_at (λ x, c x / d) (c' / d) x := by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹ lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜'} : differentiable_within_at 𝕜 (λx, c x / d) s x := (hc.has_deriv_within_at.div_const _).differentiable_within_at @[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜'} : differentiable_at 𝕜 (λ x, c x / d) x := (hc.has_deriv_at.div_const _).differentiable_at lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) {d : 𝕜'} : differentiable_on 𝕜 (λx, c x / d) s := λ x hx, (hc x hx).div_const @[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) {d : 𝕜'} : differentiable 𝕜 (λx, c x / d) := λ x, (hc x).div_const lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜'} (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d) s x = (deriv_within c s x) / d := by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs] @[simp] lemma deriv_div_const (d : 𝕜') : deriv (λx, c x / d) x = (deriv c x) / d := by simp only [div_eq_mul_inv, deriv_mul_const_field] end division section clm_comp_apply /-! ### Derivative of the pointwise composition/application of continuous linear maps -/ open continuous_linear_map variables {G : Type*} [normed_group G] [normed_space 𝕜 G] {c : 𝕜 → F →L[𝕜] G} {c' : F →L[𝕜] G} {d : 𝕜 → E →L[𝕜] F} {d' : E →L[𝕜] F} {u : 𝕜 → F} {u' : F} lemma has_strict_deriv_at.clm_comp (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') x := begin have := (hc.has_strict_fderiv_at.clm_comp hd.has_strict_fderiv_at).has_strict_deriv_at, rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_within_at.clm_comp (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') s x := begin have := (hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).has_deriv_within_at, rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_at.clm_comp (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.clm_comp hd end lemma deriv_within_clm_comp (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hxs : unique_diff_within_at 𝕜 s x): deriv_within (λ y, (c y).comp (d y)) s x = ((deriv_within c s x).comp (d x) + (c x).comp (deriv_within d s x)) := (hc.has_deriv_within_at.clm_comp hd.has_deriv_within_at).deriv_within hxs lemma deriv_clm_comp (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, (c y).comp (d y)) x = ((deriv c x).comp (d x) + (c x).comp (deriv d x)) := (hc.has_deriv_at.clm_comp hd.has_deriv_at).deriv lemma has_strict_deriv_at.clm_apply (hc : has_strict_deriv_at c c' x) (hu : has_strict_deriv_at u u' x) : has_strict_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x := begin have := (hc.has_strict_fderiv_at.clm_apply hu.has_strict_fderiv_at).has_strict_deriv_at, rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_within_at.clm_apply (hc : has_deriv_within_at c c' s x) (hu : has_deriv_within_at u u' s x) : has_deriv_within_at (λ y, (c y) (u y)) (c' (u x) + c x u') s x := begin have := (hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).has_deriv_within_at, rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_at.clm_apply (hc : has_deriv_at c c' x) (hu : has_deriv_at u u' x) : has_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x := begin have := (hc.has_fderiv_at.clm_apply hu.has_fderiv_at).has_deriv_at, rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma deriv_within_clm_apply (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) : deriv_within (λ y, (c y) (u y)) s x = (deriv_within c s x (u x) + c x (deriv_within u s x)) := (hc.has_deriv_within_at.clm_apply hu.has_deriv_within_at).deriv_within hxs lemma deriv_clm_apply (hc : differentiable_at 𝕜 c x) (hu : differentiable_at 𝕜 u x) : deriv (λ y, (c y) (u y)) x = (deriv c x (u x) + c x (deriv u x)) := (hc.has_deriv_at.clm_apply hu.has_deriv_at).deriv end clm_comp_apply theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) : has_strict_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_deriv_at f f' x) (hf' : f' ≠ 0) : has_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_deriv_at g f'⁻¹ a := (hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has a nonzero derivative `f'` at `f.symm a` in the strict sense, then `f.symm` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_strict_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜} (ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_strict_deriv_at f f' (f.symm a)) : has_strict_deriv_at f.symm f'⁻¹ a := htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha) /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_deriv_at g f'⁻¹ a := (hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an nonzero derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜} (ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_deriv_at f f' (f.symm a)) : has_deriv_at f.symm f'⁻¹ a := htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha) lemma has_deriv_at.eventually_ne (h : has_deriv_at f f' x) (hf' : f' ≠ 0) : ∀ᶠ z in 𝓝[≠] x, f z ≠ f x := (has_deriv_at_iff_has_fderiv_at.1 h).eventually_ne ⟨∥f'∥⁻¹, λ z, by field_simp [norm_smul, mt norm_eq_zero.1 hf']⟩ lemma has_deriv_at.tendsto_punctured_nhds (h : has_deriv_at f f' x) (hf' : f' ≠ 0) : tendsto f (𝓝[≠] x) (𝓝[≠] (f x)) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ h.continuous_at.continuous_within_at (h.eventually_ne hf') theorem not_differentiable_within_at_of_local_left_inverse_has_deriv_within_at_zero {f g : 𝕜 → 𝕜} {a : 𝕜} {s t : set 𝕜} (ha : a ∈ s) (hsu : unique_diff_within_at 𝕜 s a) (hf : has_deriv_within_at f 0 t (g a)) (hst : maps_to g s t) (hfg : f ∘ g =ᶠ[𝓝[s] a] id) : ¬differentiable_within_at 𝕜 g s a := begin intro hg, have := (hf.comp a hg.has_deriv_within_at hst).congr_of_eventually_eq_of_mem hfg.symm ha, simpa using hsu.eq_deriv _ this (has_deriv_within_at_id _ _) end theorem not_differentiable_at_of_local_left_inverse_has_deriv_at_zero {f g : 𝕜 → 𝕜} {a : 𝕜} (hf : has_deriv_at f 0 (g a)) (hfg : f ∘ g =ᶠ[𝓝 a] id) : ¬differentiable_at 𝕜 g a := begin intro hg, have := (hf.comp a hg.has_deriv_at).congr_of_eventually_eq hfg.symm, simpa using this.unique (has_deriv_at_id a) end end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : 𝕜[X]) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_strict_deriv_at (x : 𝕜) : has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_strict_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_strict_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := (p.has_strict_deriv_at x).has_deriv_at protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) x := p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) := (p.has_fderiv_within_at x).fderiv_within hxs end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜} variable (n : ℕ) lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) : has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x, { simp }, { rw [polynomial.derivative_C_mul_X_pow], simp } end lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := (has_strict_deriv_at_pow n x).has_deriv_at theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := (differentiable_at_pow n).differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λ x, differentiable_at_pow n lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := (differentiable_pow n).differentiable_on lemma deriv_pow : deriv (λ x, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λ x, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow n lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) : has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x := (has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc lemma has_deriv_at.pow (hc : has_deriv_at c c' x) : has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x := by { rw ← has_deriv_within_at_univ at *, exact hc.pow n } lemma differentiable_within_at.pow (hc : differentiable_within_at 𝕜 c s x) : differentiable_within_at 𝕜 (λx, (c x)^n) s x := (hc.has_deriv_within_at.pow n).differentiable_within_at @[simp] lemma differentiable_at.pow (hc : differentiable_at 𝕜 c x) : differentiable_at 𝕜 (λx, (c x)^n) x := (hc.has_deriv_at.pow n).differentiable_at lemma differentiable_on.pow (hc : differentiable_on 𝕜 c s) : differentiable_on 𝕜 (λx, (c x)^n) s := λx h, (hc x h).pow n @[simp] lemma differentiable.pow (hc : differentiable 𝕜 c) : differentiable 𝕜 (λx, (c x)^n) := λx, (hc x).pow n lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) := (hc.has_deriv_within_at.pow n).deriv_within hxs @[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) : deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) := (hc.has_deriv_at.pow n).deriv end pow section zpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} {m : ℤ} lemma has_strict_deriv_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) : has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [zpow_coe_nat, int.cast_coe_nat], convert has_strict_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, zpow_coe_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have hx : x ≠ 0, from h.resolve_right hm.not_le, have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm)); [skip, exact zpow_ne_zero_of_ne_zero hx _], simp only [(∘), zpow_neg, one_div, inv_inv, smul_eq_mul] at this, convert this using 1, rw [sq, mul_inv, inv_inv, int.cast_neg, neg_mul, neg_mul_neg, ← zpow_add₀ hx, mul_assoc, ← zpow_add₀ hx], congr, abel }, { simp only [hm, zpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] }, { exact this m hm } end lemma has_deriv_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := (has_strict_deriv_at_zpow m x h).has_deriv_at theorem has_deriv_within_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_zpow m x h).has_deriv_within_at lemma differentiable_at_zpow : differentiable_at 𝕜 (λx, x^m) x ↔ x ≠ 0 ∨ 0 ≤ m := ⟨λ H, normed_field.continuous_at_zpow.1 H.continuous_at, λ H, (has_deriv_at_zpow m x H).differentiable_at⟩ lemma differentiable_within_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_zpow.mpr h).differentiable_within_at lemma differentiable_on_zpow (m : ℤ) (s : set 𝕜) (h : (0 : 𝕜) ∉ s ∨ 0 ≤ m) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_zpow m x $ h.imp_left $ ne_of_mem_of_not_mem hxs lemma deriv_zpow (m : ℤ) (x : 𝕜) : deriv (λ x, x ^ m) x = m * x ^ (m - 1) := begin by_cases H : x ≠ 0 ∨ 0 ≤ m, { exact (has_deriv_at_zpow m x H).deriv }, { rw deriv_zero_of_not_differentiable_at (mt differentiable_at_zpow.1 H), push_neg at H, rcases H with ⟨rfl, hm⟩, rw [zero_zpow _ ((sub_one_lt _).trans hm).ne, mul_zero] } end @[simp] lemma deriv_zpow' (m : ℤ) : deriv (λ x : 𝕜, x ^ m) = λ x, m * x ^ (m - 1) := funext $ deriv_zpow m lemma deriv_within_zpow (hxs : unique_diff_within_at 𝕜 s x) (h : x ≠ 0 ∨ 0 ≤ m) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_zpow m x h s).deriv_within hxs @[simp] lemma iter_deriv_zpow' (m : ℤ) (k : ℕ) : deriv^[k] (λ x : 𝕜, x ^ m) = λ x, (∏ i in finset.range k, (m - i)) * x ^ (m - k) := begin induction k with k ihk, { simp only [one_mul, int.coe_nat_zero, id, sub_zero, finset.prod_range_zero, function.iterate_zero] }, { simp only [function.iterate_succ_apply', ihk, deriv_const_mul_field', deriv_zpow', finset.prod_range_succ, int.coe_nat_succ, ← sub_sub, int.cast_sub, int.cast_coe_nat, mul_assoc], } end lemma iter_deriv_zpow (m : ℤ) (x : 𝕜) (k : ℕ) : deriv^[k] (λ y, y ^ m) x = (∏ i in finset.range k, (m - i)) * x ^ (m - k) := congr_fun (iter_deriv_zpow' m k) x lemma iter_deriv_pow (n : ℕ) (x : 𝕜) (k : ℕ) : deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i)) * x^(n-k) := begin simp only [← zpow_coe_nat, iter_deriv_zpow, int.cast_coe_nat], cases le_or_lt k n with hkn hnk, { rw int.coe_nat_sub hkn }, { have : ∏ i in finset.range k, (n - i : 𝕜) = 0, from finset.prod_eq_zero (finset.mem_range.2 hnk) (sub_self _), simp only [this, zero_mul] } end @[simp] lemma iter_deriv_pow' (n k : ℕ) : deriv^[k] (λ x : 𝕜, x ^ n) = λ x, (∏ i in finset.range k, (n - i)) * x ^ (n - k) := funext $ λ x, iter_deriv_pow n x k lemma iter_deriv_inv (k : ℕ) (x : 𝕜) : deriv^[k] has_inv.inv x = (∏ i in finset.range k, (-1 - i)) * x ^ (-1 - k : ℤ) := by simpa only [zpow_neg_one, int.cast_neg, int.cast_one] using iter_deriv_zpow (-1) x k @[simp] lemma iter_deriv_inv' (k : ℕ) : deriv^[k] has_inv.inv = λ x : 𝕜, (∏ i in finset.range k, (-1 - i)) * x ^ (-1 - k : ℤ) := funext (iter_deriv_inv k) end zpow /-! ### Support of derivatives -/ section support open function variables {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : 𝕜 → F} lemma support_deriv_subset : support (deriv f) ⊆ tsupport f := begin intros x, rw [← not_imp_not], intro h2x, rw [not_mem_closure_support_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 /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in 𝓝[s \ {x}] x, slope f x z < r := has_deriv_within_at_iff_tendsto_slope.1 hf (is_open.mem_nhds is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in 𝓝[s] x, slope f x z < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (is_open.mem_nhds is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : f' < r) : ∃ᶠ z in 𝓝[>] x, slope f x z < r := (hf.Ioi_of_Ici.limsup_slope_le' (lt_irrefl x) hr).frequently end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in 𝓝[s \ {x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (is_open.mem_nhds is_open_Iio hr), have B : ∀ᶠ z in 𝓝[{x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup] at C, filter_upwards [C.1], simp only [norm_smul, mem_Iio, norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[>] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.Ioi_of_Ici.limsup_norm_slope_le hr).frequently /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[>] x, (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.Ioi_of_Ici.limsup_slope_norm_le hr).frequently, refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
382de026b55f2e97ff19e895cf92bdbdd2e9203f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/preserves/shapes/pullbacks.lean
0c24c8404924c0f3263417e4ed9b9ebb0b7e60b5
[ "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
11,093
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Andrew Yang -/ import category_theory.limits.shapes.pullbacks import category_theory.limits.preserves.basic /-! # Preserving pullbacks > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Constructions to relate the notions of preserving pullbacks and reflecting pullbacks to concrete pullback cones. In particular, we show that `pullback_comparison G f g` is an isomorphism iff `G` preserves the pullback of `f` and `g`. The dual is also given. ## TODO * Generalise to wide pullbacks -/ noncomputable theory universes v₁ v₂ u₁ u₂ open category_theory category_theory.category category_theory.limits namespace category_theory.limits section pullback variables {C : Type u₁} [category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] variables (G : C ⥤ D) variables {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} {h : W ⟶ X} {k : W ⟶ Y} (comm : h ≫ f = k ≫ g) /-- The map of a pullback cone is a limit iff the fork consisting of the mapped morphisms is a limit. This essentially lets us commute `pullback_cone.mk` with `functor.map_cone`. -/ def is_limit_map_cone_pullback_cone_equiv : is_limit (G.map_cone (pullback_cone.mk h k comm)) ≃ is_limit (pullback_cone.mk (G.map h) (G.map k) (by simp only [← G.map_comp, comm]) : pullback_cone (G.map f) (G.map g)) := (is_limit.postcompose_hom_equiv (diagram_iso_cospan.{v₂} _) _).symm.trans $ is_limit.equiv_iso_limit $ cones.ext (iso.refl _) $ (by rintro (_|_|_); dsimp; simp only [comp_id, id_comp, G.map_comp]) /-- The property of preserving pullbacks expressed in terms of binary fans. -/ def is_limit_pullback_cone_map_of_is_limit [preserves_limit (cospan f g) G] (l : is_limit (pullback_cone.mk h k comm)) : is_limit (pullback_cone.mk (G.map h) (G.map k) _) := is_limit_map_cone_pullback_cone_equiv G comm (preserves_limit.preserves l) /-- The property of reflecting pullbacks expressed in terms of binary fans. -/ def is_limit_of_is_limit_pullback_cone_map [reflects_limit (cospan f g) G] (l : is_limit (pullback_cone.mk (G.map h) (G.map k) _)) : is_limit (pullback_cone.mk h k comm) := reflects_limit.reflects ((is_limit_map_cone_pullback_cone_equiv G comm).symm l) variables (f g) [preserves_limit (cospan f g) G] /-- If `G` preserves pullbacks and `C` has them, then the pullback cone constructed of the mapped morphisms of the pullback cone is a limit. -/ def is_limit_of_has_pullback_of_preserves_limit [has_pullback f g] : is_limit (pullback_cone.mk (G.map pullback.fst) (G.map pullback.snd) _) := is_limit_pullback_cone_map_of_is_limit G _ (pullback_is_pullback f g) /-- If `F` preserves the pullback of `f, g`, it also preserves the pullback of `g, f`. -/ def preserves_pullback_symmetry : preserves_limit (cospan g f) G := { preserves := λ c hc, begin apply (is_limit.postcompose_hom_equiv (diagram_iso_cospan.{v₂} _) _).to_fun, apply is_limit.of_iso_limit _ (pullback_cone.iso_mk _).symm, apply pullback_cone.flip_is_limit, apply (is_limit_map_cone_pullback_cone_equiv _ _).to_fun, { apply_with preserves_limit.preserves { instances := ff }, { dsimp, apply_instance }, apply pullback_cone.flip_is_limit, apply is_limit.of_iso_limit _ (pullback_cone.iso_mk _), exact (is_limit.postcompose_hom_equiv (diagram_iso_cospan.{v₁} _) _).inv_fun hc }, { exact (c.π.naturality walking_cospan.hom.inr).symm.trans (c.π.naturality walking_cospan.hom.inl : _) } end } lemma has_pullback_of_preserves_pullback [has_pullback f g] : has_pullback (G.map f) (G.map g) := ⟨⟨⟨_, is_limit_pullback_cone_map_of_is_limit G _ (pullback_is_pullback _ _)⟩⟩⟩ variables [has_pullback f g] [has_pullback (G.map f) (G.map g)] /-- If `G` preserves the pullback of `(f,g)`, then the pullback comparison map for `G` at `(f,g)` is an isomorphism. -/ def preserves_pullback.iso : G.obj (pullback f g) ≅ pullback (G.map f) (G.map g) := is_limit.cone_point_unique_up_to_iso (is_limit_of_has_pullback_of_preserves_limit G f g) (limit.is_limit _) @[reassoc] lemma preserves_pullback.iso_hom_fst : (preserves_pullback.iso G f g).hom ≫ pullback.fst = G.map pullback.fst := by simp [preserves_pullback.iso] @[reassoc] lemma preserves_pullback.iso_hom_snd : (preserves_pullback.iso G f g).hom ≫ pullback.snd = G.map pullback.snd := by simp [preserves_pullback.iso] @[simp, reassoc] lemma preserves_pullback.iso_inv_fst : (preserves_pullback.iso G f g).inv ≫ G.map pullback.fst = pullback.fst := by simp [preserves_pullback.iso, iso.inv_comp_eq] @[simp, reassoc] lemma preserves_pullback.iso_inv_snd : (preserves_pullback.iso G f g).inv ≫ G.map pullback.snd = pullback.snd := by simp [preserves_pullback.iso, iso.inv_comp_eq] end pullback section pushout variables {C : Type u₁} [category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] variables (G : C ⥤ D) variables {W X Y Z : C} {h : X ⟶ Z} {k : Y ⟶ Z} {f : W ⟶ X} {g : W ⟶ Y} (comm : f ≫ h = g ≫ k) /-- The map of a pushout cocone is a colimit iff the cofork consisting of the mapped morphisms is a colimit. This essentially lets us commute `pushout_cocone.mk` with `functor.map_cocone`. -/ def is_colimit_map_cocone_pushout_cocone_equiv : is_colimit (G.map_cocone (pushout_cocone.mk h k comm)) ≃ is_colimit (pushout_cocone.mk (G.map h) (G.map k) (by simp only [← G.map_comp, comm]) : pushout_cocone (G.map f) (G.map g)) := (is_colimit.precompose_hom_equiv (diagram_iso_span.{v₂} _).symm _).symm.trans $ is_colimit.equiv_iso_colimit $ cocones.ext (iso.refl _) $ (by rintro (_|_|_); dsimp; simp only [category.comp_id, category.id_comp, ← G.map_comp]) /-- The property of preserving pushouts expressed in terms of binary cofans. -/ def is_colimit_pushout_cocone_map_of_is_colimit [preserves_colimit (span f g) G] (l : is_colimit (pushout_cocone.mk h k comm)) : is_colimit (pushout_cocone.mk (G.map h) (G.map k) _) := is_colimit_map_cocone_pushout_cocone_equiv G comm (preserves_colimit.preserves l) /-- The property of reflecting pushouts expressed in terms of binary cofans. -/ def is_colimit_of_is_colimit_pushout_cocone_map [reflects_colimit (span f g) G] (l : is_colimit (pushout_cocone.mk (G.map h) (G.map k) _)) : is_colimit (pushout_cocone.mk h k comm) := reflects_colimit.reflects ((is_colimit_map_cocone_pushout_cocone_equiv G comm).symm l) variables (f g) [preserves_colimit (span f g) G] /-- If `G` preserves pushouts and `C` has them, then the pushout cocone constructed of the mapped morphisms of the pushout cocone is a colimit. -/ def is_colimit_of_has_pushout_of_preserves_colimit [has_pushout f g] : is_colimit (pushout_cocone.mk (G.map pushout.inl) (G.map pushout.inr) _) := is_colimit_pushout_cocone_map_of_is_colimit G _ (pushout_is_pushout f g) /-- If `F` preserves the pushout of `f, g`, it also preserves the pushout of `g, f`. -/ def preserves_pushout_symmetry : preserves_colimit (span g f) G := { preserves := λ c hc, begin apply (is_colimit.precompose_hom_equiv (diagram_iso_span.{v₂} _).symm _).to_fun, apply is_colimit.of_iso_colimit _ (pushout_cocone.iso_mk _).symm, apply pushout_cocone.flip_is_colimit, apply (is_colimit_map_cocone_pushout_cocone_equiv _ _).to_fun, { apply_with preserves_colimit.preserves { instances := ff }, { dsimp, apply_instance }, apply pushout_cocone.flip_is_colimit, apply is_colimit.of_iso_colimit _ (pushout_cocone.iso_mk _), exact (is_colimit.precompose_hom_equiv (diagram_iso_span.{v₁} _) _).inv_fun hc }, { exact (c.ι.naturality walking_span.hom.snd).trans (c.ι.naturality walking_span.hom.fst).symm } end } lemma has_pushout_of_preserves_pushout [has_pushout f g] : has_pushout (G.map f) (G.map g) := ⟨⟨⟨_, is_colimit_pushout_cocone_map_of_is_colimit G _ (pushout_is_pushout _ _)⟩⟩⟩ variables [has_pushout f g] [has_pushout (G.map f) (G.map g)] /-- If `G` preserves the pushout of `(f,g)`, then the pushout comparison map for `G` at `(f,g)` is an isomorphism. -/ def preserves_pushout.iso : pushout (G.map f) (G.map g) ≅ G.obj (pushout f g) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (is_colimit_of_has_pushout_of_preserves_colimit G f g) @[reassoc] lemma preserves_pushout.inl_iso_hom : pushout.inl ≫ (preserves_pushout.iso G f g).hom = G.map pushout.inl := by { delta preserves_pushout.iso, simp } @[reassoc] lemma preserves_pushout.inr_iso_hom : pushout.inr ≫ (preserves_pushout.iso G f g).hom = G.map pushout.inr := by { delta preserves_pushout.iso, simp } @[simp, reassoc] lemma preserves_pushout.inl_iso_inv : G.map pushout.inl ≫ (preserves_pushout.iso G f g).inv = pushout.inl := by simp [preserves_pushout.iso, iso.comp_inv_eq] @[simp, reassoc] lemma preserves_pushout.inr_iso_inv : G.map pushout.inr ≫ (preserves_pushout.iso G f g).inv = pushout.inr := by simp [preserves_pushout.iso, iso.comp_inv_eq] end pushout section variables {C : Type u₁} [category.{v₁} C] variables {D : Type u₂} [category.{v₁} D] variables (G : C ⥤ D) section pullback variables {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} variables [has_pullback f g] [has_pullback (G.map f) (G.map g)] /-- If the pullback comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the pullback of `(f,g)`. -/ def preserves_pullback.of_iso_comparison [i : is_iso (pullback_comparison G f g)] : preserves_limit (cospan f g) G := begin apply preserves_limit_of_preserves_limit_cone (pullback_is_pullback f g), apply (is_limit_map_cone_pullback_cone_equiv _ _).symm _, apply is_limit.of_point_iso (limit.is_limit (cospan (G.map f) (G.map g))), apply i, end variable [preserves_limit (cospan f g) G] @[simp] lemma preserves_pullback.iso_hom : (preserves_pullback.iso G f g).hom = pullback_comparison G f g := rfl instance : is_iso (pullback_comparison G f g) := begin rw ← preserves_pullback.iso_hom, apply_instance end end pullback section pushout variables {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} variables [has_pushout f g] [has_pushout (G.map f) (G.map g)] /-- If the pushout comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the pushout of `(f,g)`. -/ def preserves_pushout.of_iso_comparison [i : is_iso (pushout_comparison G f g)] : preserves_colimit (span f g) G := begin apply preserves_colimit_of_preserves_colimit_cocone (pushout_is_pushout f g), apply (is_colimit_map_cocone_pushout_cocone_equiv _ _).symm _, apply is_colimit.of_point_iso (colimit.is_colimit (span (G.map f) (G.map g))), apply i, end variable [preserves_colimit (span f g) G] @[simp] lemma preserves_pushout.iso_hom : (preserves_pushout.iso G f g).hom = pushout_comparison G f g := rfl instance : is_iso (pushout_comparison G f g) := begin rw ← preserves_pushout.iso_hom, apply_instance end end pushout end end category_theory.limits
bc9b725b424308c60af97190501d359e01691a35
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/match_tactic.lean
cf6761c1d256a8a39b4395c7997f0960f27f587b
[ "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
5,679
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.interactive_base init.function namespace tactic /-- A pattern is an expression `target` containing temporary metavariables. A pattern also contains a list of `outputs` which also depend on these temporary metavariables. When we run `match p e`, the system will match `p.target` with `e` and assign the temporary metavariables. It then returns the outputs with the assigned variables. ## Fields - `target` Term to match. Contains temporary metavariables. - `uoutput` List of universes that are returned on a successful match. - `moutput` List of expressions that are returned on a successful match. - `nuvars` Number of (temporary) universe metavariables in this pattern. - `nmvars` Number of (temporary) metavariables in this pattern. ## Example The pattern for `list.cons h t` returning `h` and `t` would be ``` { target := `(@list.cons ?x_0 ?x_1 ?x_2), uoutput := [], moutput := [?x_1,?x_2], nuvars := 0, nmvars := 3 } ``` -/ meta structure pattern := (target : expr) (uoutput : list level) (moutput : list expr) (nuvars : nat) (nmvars : nat) /-- `mk_pattern umetas emetas target uoutput eoutput` creates a new pattern. The arguments are - `umetas` a list of level params to be replaced with temporary universe metavariables. - `emetas` a list of local constants to be replaced with temporary metavariables. - `target` the expression to be matched. - `uoutput` a list of levels to return upon matching. Fails if this depends on metavariables. - `eoutput` a list of expressions to return upon matching. Fails if this depends on metavariables. The procedure is as follows: 1. Convert all metavariables in `target` to temporary metavariables. 2. For each item in `umetas` amd `emetas`, create a temporary metavariable and replace each instance of the item in `target` with a temporary metavariable 3. Replace these instances in `uoutput` and `eoutput` too. 4. Return these replaced versions as a `pattern`. ## Example Let `h`,`t` be exprs with types `α` and `list α` respectively. Then `mk_pattern [] [α,h,t] `(@list.cons α h t) [] [h,t]` would `match_pattern` against any expr which is a list.cons constructor and return the head and tail arguments. -/ meta constant mk_pattern (umetas : list level) (emetas : list expr) (target : expr) (uoutput :list level) (eoutput : list expr) : tactic pattern /-- `mk_pattern p e m` matches (pattern.target p) and e using transparency m. If the matching is successful, then return the instantiation of `pattern.output p`. The tactic fails if not all (temporary) meta-variables are assigned. -/ meta constant match_pattern (p : pattern) (e : expr) (m : transparency := reducible) : tactic (list level × list expr) open expr private meta def to_pattern_core : expr → tactic (expr × list expr) | (lam n bi d b) := do id ← mk_fresh_name, let x := local_const id n bi d, let new_b := instantiate_var b x, (p, xs) ← to_pattern_core new_b, return (p, x::xs) | e := return (e, []) /-- Given a pre-term of the form `λ x₁ ... xₙ, t[x₁, ..., xₙ]`, converts it into the pattern `t[?x₁, ..., ?xₙ]` with outputs `[?x₁, ..., ?xₙ]` -/ meta def pexpr_to_pattern (p : pexpr) : tactic pattern := do /- Remark: in the following to_expr, we allow metavars but we do *not* create new goals for them. mk_pattern will convert them into temporary metavars. -/ e ← to_expr p tt ff, (new_p, xs) ← to_pattern_core e, mk_pattern [] xs new_p [] xs /-- Convert pre-term into a pattern and try to match e. Given p of the form `λ x₁ ... xₙ, t[x₁, ..., xₙ]`, a successful match will produce a list of length n. -/ meta def match_expr (p : pexpr) (e : expr) (m := reducible) : tactic (list expr) := do new_p ← pexpr_to_pattern p, prod.snd <$> match_pattern new_p e m private meta def match_subexpr_core (m : transparency) : pattern → list expr → tactic (list expr) | p [] := failed | p (e::es) := (prod.snd <$> match_pattern p e m) <|> match_subexpr_core p es <|> if is_app e then match_subexpr_core p (get_app_args e) else failed /-- Similar to match_expr, but it tries to match a subexpression of e. Remark: the procedure does not go inside binders. -/ meta def match_subexpr (p : pexpr) (e : expr) (m := reducible) : tactic (list expr) := do new_p ← pexpr_to_pattern p, match_subexpr_core m new_p [e] /-- Match the main goal target. -/ meta def match_target (p : pexpr) (m := reducible) : tactic (list expr) := do t ← target, match_expr p t m /-- Match a subterm in the main goal target. -/ meta def match_target_subexpr (p : pexpr) (m := reducible) : tactic (list expr) := do t ← target, match_subexpr p t m private meta def match_hypothesis_core (m : transparency) : pattern → list expr → tactic (expr × list expr) | p [] := failed | p (h::hs) := do h_type ← infer_type h, (do r ← match_pattern p h_type m, return (h, r.snd)) <|> match_hypothesis_core p hs /-- Match hypothesis in the main goal target. The result is pair (hypothesis, substitution). -/ meta def match_hypothesis (p : pexpr) (m := reducible) : tactic (expr × list expr) := do ctx ← local_context, new_p ← pexpr_to_pattern p, match_hypothesis_core m new_p ctx meta instance : has_to_tactic_format pattern := ⟨λp, do t ← pp p.target, mo ← pp p.moutput, uo ← pp p.uoutput, u ← pp p.nuvars, m ← pp p.nmvars, return format!"pattern.mk ({t}) {uo} {mo} {u} {m}" ⟩ end tactic
5889eaf75ed1e1171e8d0a462ccd2af87855bcbd
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/override/hertzOverride.lean
04b43ffb339d3057c4f1973f6d6b8b8406c35bf6
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
726
lean
import ..imperative_DSL.environment import ..eval.hertzEval open lang.classicalHertz def assignHertzSpace : environment.env → lang.classicalHertz.spaceVar → lang.classicalHertz.spaceExpr → environment.env | i v e := { h:={sp := (λ r, if (spaceVarEq v r) then (classicalHertzEval e i) else (i.h.sp r)), ..i.h}, ..i } def assignHertzQuantity : environment.env → lang.classicalHertz.QuantityVar → lang.classicalHertz.QuantityExpr → environment.env | i v e := { h:={s := (λ r, if (QuantityVarEq v r) then (classicalHertzQuantityEval e i) else (i.h.s r)), ..i.h}, ..i }
9f54757e5c6d594ee1d113e890a227f115c8e821
ce89339993655da64b6ccb555c837ce6c10f9ef4
/na4zagin3/top-13.lean
7fd304f822632f260aa4232be7f8f45551156dc7
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
451
lean
def injective1 (f : nat -> nat) : Prop := forall m n, f m = f n -> m = n. def injective2 (f : nat -> nat) : Prop := forall m n, m ≠ n -> f m ≠ f n. example : ∀ f, injective1 f ↔ injective2 f := begin intro f, unfold injective1, unfold injective2, split; intros HI m n H, intros Hinv, apply H, apply HI, assumption, cases nat.decidable_eq m n, have Hcontra := HI m n h, contradiction, assumption, end.
094cdd4d387cc84f6cbea05483bea8f62512c2f5
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/transport.lean
fae9706f826d40d5af9d31f1b28ce1c592af997c
[ "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
5,572
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Simon Hudon, Scott Morrison -/ import tactic.equiv_rw /-! ## The `transport` tactic `transport` attempts to move an `s : S α` expression across an equivalence `e : α ≃ β` to solve a goal of the form `S β`, by building the new object field by field, taking each field of `s` and rewriting it along `e` using the `equiv_rw` tactic. We try to ensure good definitional properties, so that, for example, when we transport a `monoid α` to a `monoid β`, the new multiplication is definitionally `λ x y, e (e.symm a * e.symm b)`. -/ namespace tactic open tactic.interactive mk_simp_attribute transport_simps "The simpset `transport_simps` is used by the tactic `transport` to simplify certain expressions involving application of equivalences, and trivial `eq.rec` or `ep.mpr` conversions. It's probably best not to adjust it without understanding the algorithm used by `transport`." attribute [transport_simps] eq_rec_constant eq_mpr_rfl equiv.to_fun_as_coe equiv.arrow_congr'_apply equiv.symm_apply_apply -- we use `apply_eq_iff_eq_symm_apply` rather than `apply_eq_iff_eq`, -- as many axioms have a constant on the right-hand-side equiv.apply_eq_iff_eq_symm_apply /-- Given `s : S α` for some structure `S` depending on a type `α`, and an equivalence `e : α ≃ β`, try to produce an `S β`, by transporting data and axioms across `e` using `equiv_rw`. -/ @[nolint unused_arguments] -- At present we don't actually use `s`; it's inferred in the `mk_app` call. meta def transport (s e : expr) : tactic unit := do (_, α, β) ← infer_type e >>= relation_lhs_rhs <|> fail format!"second argument to `transport` was not an equivalence-type relation", -- We explode the goal into individual fields using `refine_struct`. -- Later we'll want to also consider falling back to `fconstructor`, -- but for now this suffices. seq' `[refine_struct { .. }] -- We now deal with each field sequentially. -- Since we may pass goals through to the user if the heuristics here fail, -- we wrap everything in `propagate_tags`. (propagate_tags (try (do -- Look up the name of the current field being processed f ← get_current_field, -- Note the value in the original structure. -- (This `mk_mapp` call with second argument inferred only works for typeclasses!) mk_mapp f [α, none] >>= note f none, -- We now run different algorithms, -- depending on whether we're transporting data or a proposition. b ← target >>= is_prop, -- In order to achieve good definitional properties, -- we use `simp_result` to intercept the synthesized term and simplify it, -- in particular simplifying along `eq_rec_constant`. if ¬ b then simp_result (do -- For data fields, simply rewrite them using `equiv_rw`. equiv_rw_hyp f e, get_local f >>= exact) else try (do -- The goal probably has messy expressions produced by `equiv_rw` acting on early data fields, -- so we clean up a little. try unfold_projs_target, `[simp only with transport_simps], -- If the field is an equation in `β`, try to use injectivity of the equivalence -- to turn it into an equation in `α`. -- (If the left hand side of the equation involved an operation we've already transported, -- this step has already been achieved by the `transport_simps`, so we `try` this step.) try $ under_binders $ to_expr ``((%%e).symm.injective) >>= apply, -- Finally, rewrite the original field value using the equivalence `e`, and try to close -- the goal using equiv_rw_hyp f e, get_local f >>= exact)))) namespace interactive setup_tactic_parser /-- Given a goal `⊢ S β` for some type class `S`, and an equivalence `e : α ≃ β`. `transport using e` will look for a hypothesis `s : S α`, and attempt to close the goal by transporting `s` across the equivalence `e`. ```lean example {α : Type} [ring α] {β : Type} (e : α ≃ β) : ring β := by transport using e. ``` You can specify the object to transport using `transport s using e`. `transport` works by attempting to copy each of the operations and axiom fields of `s`, rewriting them using `equiv_rw e` and defining a new structure using these rewritten fields. If it fails to fill in all the new fields, `transport` will produce new subgoals. It's probably best to think about which missing `simp` lemmas would have allowed `transport` to finish, rather than solving these goals by hand. (This may require looking at the implementation of `tranport` to understand its algorithm; there are several examples of "transport-by-hand" at the end of `test/equiv_rw.lean`, which `transport` is an abstraction of.) -/ meta def transport (s : parse texpr?) (e : parse $ (tk "using" *> texpr)) : itactic := do s ← match s with | some s := to_expr s | none := (do t ← target, let n := t.get_app_fn.const_name, ctx ← local_context, ctx.any_of (λ e, (do t ← infer_type e, guard (t.get_app_fn.const_name = n), return e))) <|> fail "`transport` could not find an appropriate source object. Try `transport s using e`." end, e ← to_expr e, tactic.transport s e add_tactic_doc { name := "transport", category := doc_category.tactic, decl_names := [`tactic.interactive.transport], tags := ["rewriting", "equiv", "transport"] } end interactive end tactic
bbcc6ac37c63c6a5023fe645a7b30f20cf3e1f72
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/affine_space/combination.lean
119e009c1ea41ebdee83a63d759b689589df5c48
[ "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
55,646
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 algebra.invertible import algebra.indicator_function import algebra.module.big_operators import data.fintype.big_operators import linear_algebra.affine_space.affine_map import linear_algebra.affine_space.affine_subspace import linear_algebra.finsupp import tactic.fin_cases /-! # Affine combinations of points > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines affine combinations of points. ## Main definitions * `weighted_vsub_of_point` is a general weighted combination of subtractions with an explicit base point, yielding a vector. * `weighted_vsub` uses an arbitrary choice of base point and is intended to be used when the sum of weights is 0, in which case the result is independent of the choice of base point. * `affine_combination` adds the weighted combination to the arbitrary base point, yielding a point rather than a vector, and is intended to be used when the sum of weights is 1, in which case the result is independent of the choice of base point. These definitions are for sums over a `finset`; versions for a `fintype` may be obtained using `finset.univ`, while versions for a `finsupp` may be obtained using `finsupp.support`. ## References * https://en.wikipedia.org/wiki/Affine_space -/ noncomputable theory open_locale big_operators affine namespace finset lemma univ_fin2 : (univ : finset (fin 2)) = {0, 1} := by { ext x, fin_cases x; simp } variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [S : affine_space V P] include S variables {ι : Type*} (s : finset ι) variables {ι₂ : Type*} (s₂ : finset ι₂) /-- A weighted sum of the results of subtracting a base point from the given points, as a linear map on the weights. The main cases of interest are where the sum of the weights is 0, in which case the sum is independent of the choice of base point, and where the sum of the weights is 1, in which case the sum added to the base point is independent of the choice of base point. -/ def weighted_vsub_of_point (p : ι → P) (b : P) : (ι → k) →ₗ[k] V := ∑ i in s, (linear_map.proj i : (ι → k) →ₗ[k] k).smul_right (p i -ᵥ b) @[simp] lemma weighted_vsub_of_point_apply (w : ι → k) (p : ι → P) (b : P) : s.weighted_vsub_of_point p b w = ∑ i in s, w i • (p i -ᵥ b) := by simp [weighted_vsub_of_point, linear_map.sum_apply] /-- The value of `weighted_vsub_of_point`, where the given points are equal. -/ @[simp] lemma weighted_vsub_of_point_apply_const (w : ι → k) (p : P) (b : P) : s.weighted_vsub_of_point (λ _, p) b w = (∑ i in s, w i) • (p -ᵥ b) := by rw [weighted_vsub_of_point_apply, sum_smul] /-- `weighted_vsub_of_point` gives equal results for two families of weights and two families of points that are equal on `s`. -/ lemma weighted_vsub_of_point_congr {w₁ w₂ : ι → k} (hw : ∀ i ∈ s, w₁ i = w₂ i) {p₁ p₂ : ι → P} (hp : ∀ i ∈ s, p₁ i = p₂ i) (b : P) : s.weighted_vsub_of_point p₁ b w₁ = s.weighted_vsub_of_point p₂ b w₂ := begin simp_rw weighted_vsub_of_point_apply, convert sum_congr rfl (λ i hi, _), rw [hw i hi, hp i hi] end /-- Given a family of points, if we use a member of the family as a base point, the `weighted_vsub_of_point` does not depend on the value of the weights at this point. -/ lemma weighted_vsub_of_point_eq_of_weights_eq (p : ι → P) (j : ι) (w₁ w₂ : ι → k) (hw : ∀ i, i ≠ j → w₁ i = w₂ i) : s.weighted_vsub_of_point p (p j) w₁ = s.weighted_vsub_of_point p (p j) w₂ := begin simp only [finset.weighted_vsub_of_point_apply], congr, ext i, cases eq_or_ne i j with h h, { simp [h], }, { simp [hw i h], }, end /-- The weighted sum is independent of the base point when the sum of the weights is 0. -/ lemma weighted_vsub_of_point_eq_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 0) (b₁ b₂ : P) : s.weighted_vsub_of_point p b₁ w = s.weighted_vsub_of_point p b₂ w := begin apply eq_of_sub_eq_zero, rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←sum_sub_distrib], conv_lhs { congr, skip, funext, rw [←smul_sub, vsub_sub_vsub_cancel_left] }, rw [←sum_smul, h, zero_smul] end /-- The weighted sum, added to the base point, is independent of the base point when the sum of the weights is 1. -/ lemma weighted_vsub_of_point_vadd_eq_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 1) (b₁ b₂ : P) : s.weighted_vsub_of_point p b₁ w +ᵥ b₁ = s.weighted_vsub_of_point p b₂ w +ᵥ b₂ := begin erw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub, ←add_sub_assoc, add_comm, add_sub_assoc, ←sum_sub_distrib], conv_lhs { congr, skip, congr, skip, funext, rw [←smul_sub, vsub_sub_vsub_cancel_left] }, rw [←sum_smul, h, one_smul, vsub_add_vsub_cancel, vsub_self] end /-- The weighted sum is unaffected by removing the base point, if present, from the set of points. -/ @[simp] lemma weighted_vsub_of_point_erase [decidable_eq ι] (w : ι → k) (p : ι → P) (i : ι) : (s.erase i).weighted_vsub_of_point p (p i) w = s.weighted_vsub_of_point p (p i) w := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], apply sum_erase, rw [vsub_self, smul_zero] end /-- The weighted sum is unaffected by adding the base point, whether or not present, to the set of points. -/ @[simp] lemma weighted_vsub_of_point_insert [decidable_eq ι] (w : ι → k) (p : ι → P) (i : ι) : (insert i s).weighted_vsub_of_point p (p i) w = s.weighted_vsub_of_point p (p i) w := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], apply sum_insert_zero, rw [vsub_self, smul_zero] end /-- The weighted sum is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma weighted_vsub_of_point_indicator_subset (w : ι → k) (p : ι → P) (b : P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.weighted_vsub_of_point p b w = s₂.weighted_vsub_of_point p b (set.indicator ↑s₁ w) := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], exact set.sum_indicator_subset_of_eq_zero w (λ i wi, wi • (p i -ᵥ b : V)) h (λ i, zero_smul k _) end /-- A weighted sum, over the image of an embedding, equals a weighted sum with the same points and weights over the original `finset`. -/ lemma weighted_vsub_of_point_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) (b : P) : (s₂.map e).weighted_vsub_of_point p b w = s₂.weighted_vsub_of_point (p ∘ e) b (w ∘ e) := begin simp_rw [weighted_vsub_of_point_apply], exact finset.sum_map _ _ _ end /-- A weighted sum of pairwise subtractions, expressed as a subtraction of two `weighted_vsub_of_point` expressions. -/ lemma sum_smul_vsub_eq_weighted_vsub_of_point_sub (w : ι → k) (p₁ p₂ : ι → P) (b : P) : ∑ i in s, w i • (p₁ i -ᵥ p₂ i) = s.weighted_vsub_of_point p₁ b w - s.weighted_vsub_of_point p₂ b w := by simp_rw [weighted_vsub_of_point_apply, ←sum_sub_distrib, ←smul_sub, vsub_sub_vsub_cancel_right] /-- A weighted sum of pairwise subtractions, where the point on the right is constant, expressed as a subtraction involving a `weighted_vsub_of_point` expression. -/ lemma sum_smul_vsub_const_eq_weighted_vsub_of_point_sub (w : ι → k) (p₁ : ι → P) (p₂ b : P) : ∑ i in s, w i • (p₁ i -ᵥ p₂) = s.weighted_vsub_of_point p₁ b w - (∑ i in s, w i) • (p₂ -ᵥ b) := by rw [sum_smul_vsub_eq_weighted_vsub_of_point_sub, weighted_vsub_of_point_apply_const] /-- A weighted sum of pairwise subtractions, where the point on the left is constant, expressed as a subtraction involving a `weighted_vsub_of_point` expression. -/ lemma sum_smul_const_vsub_eq_sub_weighted_vsub_of_point (w : ι → k) (p₂ : ι → P) (p₁ b : P) : ∑ i in s, w i • (p₁ -ᵥ p₂ i) = (∑ i in s, w i) • (p₁ -ᵥ b) - s.weighted_vsub_of_point p₂ b w := by rw [sum_smul_vsub_eq_weighted_vsub_of_point_sub, weighted_vsub_of_point_apply_const] /-- A weighted sum may be split into such sums over two subsets. -/ lemma weighted_vsub_of_point_sdiff [decidable_eq ι] {s₂ : finset ι} (h : s₂ ⊆ s) (w : ι → k) (p : ι → P) (b : P) : (s \ s₂).weighted_vsub_of_point p b w + s₂.weighted_vsub_of_point p b w = s.weighted_vsub_of_point p b w := by simp_rw [weighted_vsub_of_point_apply, sum_sdiff h] /-- A weighted sum may be split into a subtraction of such sums over two subsets. -/ lemma weighted_vsub_of_point_sdiff_sub [decidable_eq ι] {s₂ : finset ι} (h : s₂ ⊆ s) (w : ι → k) (p : ι → P) (b : P) : (s \ s₂).weighted_vsub_of_point p b w - s₂.weighted_vsub_of_point p b (-w) = s.weighted_vsub_of_point p b w := by rw [map_neg, sub_neg_eq_add, s.weighted_vsub_of_point_sdiff h] /-- A weighted sum over `s.subtype pred` equals one over `s.filter pred`. -/ lemma weighted_vsub_of_point_subtype_eq_filter (w : ι → k) (p : ι → P) (b : P) (pred : ι → Prop) [decidable_pred pred] : (s.subtype pred).weighted_vsub_of_point (λ i, p i) b (λ i, w i) = (s.filter pred).weighted_vsub_of_point p b w := by rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←sum_subtype_eq_sum_filter] /-- A weighted sum over `s.filter pred` equals one over `s` if all the weights at indices in `s` not satisfying `pred` are zero. -/ lemma weighted_vsub_of_point_filter_of_ne (w : ι → k) (p : ι → P) (b : P) {pred : ι → Prop} [decidable_pred pred] (h : ∀ i ∈ s, w i ≠ 0 → pred i) : (s.filter pred).weighted_vsub_of_point p b w = s.weighted_vsub_of_point p b w := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, sum_filter_of_ne], intros i hi hne, refine h i hi _, intro hw, simpa [hw] using hne, end /-- A constant multiplier of the weights in `weighted_vsub_of_point` may be moved outside the sum. -/ lemma weighted_vsub_of_point_const_smul (w : ι → k) (p : ι → P) (b : P) (c : k) : s.weighted_vsub_of_point p b (c • w) = c • s.weighted_vsub_of_point p b w := by simp_rw [weighted_vsub_of_point_apply, smul_sum, pi.smul_apply, smul_smul, smul_eq_mul] /-- A weighted sum of the results of subtracting a default base point from the given points, as a linear map on the weights. This is intended to be used when the sum of the weights is 0; that condition is specified as a hypothesis on those lemmas that require it. -/ def weighted_vsub (p : ι → P) : (ι → k) →ₗ[k] V := s.weighted_vsub_of_point p (classical.choice S.nonempty) /-- Applying `weighted_vsub` with given weights. This is for the case where a result involving a default base point is OK (for example, when that base point will cancel out later); a more typical use case for `weighted_vsub` would involve selecting a preferred base point with `weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero` and then using `weighted_vsub_of_point_apply`. -/ lemma weighted_vsub_apply (w : ι → k) (p : ι → P) : s.weighted_vsub p w = ∑ i in s, w i • (p i -ᵥ (classical.choice S.nonempty)) := by simp [weighted_vsub, linear_map.sum_apply] /-- `weighted_vsub` gives the sum of the results of subtracting any base point, when the sum of the weights is 0. -/ lemma weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 0) (b : P) : s.weighted_vsub p w = s.weighted_vsub_of_point p b w := s.weighted_vsub_of_point_eq_of_sum_eq_zero w p h _ _ /-- The value of `weighted_vsub`, where the given points are equal and the sum of the weights is 0. -/ @[simp] lemma weighted_vsub_apply_const (w : ι → k) (p : P) (h : ∑ i in s, w i = 0) : s.weighted_vsub (λ _, p) w = 0 := by rw [weighted_vsub, weighted_vsub_of_point_apply_const, h, zero_smul] /-- The `weighted_vsub` for an empty set is 0. -/ @[simp] lemma weighted_vsub_empty (w : ι → k) (p : ι → P) : (∅ : finset ι).weighted_vsub p w = (0:V) := by simp [weighted_vsub_apply] /-- `weighted_vsub` gives equal results for two families of weights and two families of points that are equal on `s`. -/ lemma weighted_vsub_congr {w₁ w₂ : ι → k} (hw : ∀ i ∈ s, w₁ i = w₂ i) {p₁ p₂ : ι → P} (hp : ∀ i ∈ s, p₁ i = p₂ i) : s.weighted_vsub p₁ w₁ = s.weighted_vsub p₂ w₂ := s.weighted_vsub_of_point_congr hw hp _ /-- The weighted sum is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma weighted_vsub_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.weighted_vsub p w = s₂.weighted_vsub p (set.indicator ↑s₁ w) := weighted_vsub_of_point_indicator_subset _ _ _ h /-- A weighted subtraction, over the image of an embedding, equals a weighted subtraction with the same points and weights over the original `finset`. -/ lemma weighted_vsub_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) : (s₂.map e).weighted_vsub p w = s₂.weighted_vsub (p ∘ e) (w ∘ e) := s₂.weighted_vsub_of_point_map _ _ _ _ /-- A weighted sum of pairwise subtractions, expressed as a subtraction of two `weighted_vsub` expressions. -/ lemma sum_smul_vsub_eq_weighted_vsub_sub (w : ι → k) (p₁ p₂ : ι → P) : ∑ i in s, w i • (p₁ i -ᵥ p₂ i) = s.weighted_vsub p₁ w - s.weighted_vsub p₂ w := s.sum_smul_vsub_eq_weighted_vsub_of_point_sub _ _ _ _ /-- A weighted sum of pairwise subtractions, where the point on the right is constant and the sum of the weights is 0. -/ lemma sum_smul_vsub_const_eq_weighted_vsub (w : ι → k) (p₁ : ι → P) (p₂ : P) (h : ∑ i in s, w i = 0) : ∑ i in s, w i • (p₁ i -ᵥ p₂) = s.weighted_vsub p₁ w := by rw [sum_smul_vsub_eq_weighted_vsub_sub, s.weighted_vsub_apply_const _ _ h, sub_zero] /-- A weighted sum of pairwise subtractions, where the point on the left is constant and the sum of the weights is 0. -/ lemma sum_smul_const_vsub_eq_neg_weighted_vsub (w : ι → k) (p₂ : ι → P) (p₁ : P) (h : ∑ i in s, w i = 0) : ∑ i in s, w i • (p₁ -ᵥ p₂ i) = -s.weighted_vsub p₂ w := by rw [sum_smul_vsub_eq_weighted_vsub_sub, s.weighted_vsub_apply_const _ _ h, zero_sub] /-- A weighted sum may be split into such sums over two subsets. -/ lemma weighted_vsub_sdiff [decidable_eq ι] {s₂ : finset ι} (h : s₂ ⊆ s) (w : ι → k) (p : ι → P) : (s \ s₂).weighted_vsub p w + s₂.weighted_vsub p w = s.weighted_vsub p w := s.weighted_vsub_of_point_sdiff h _ _ _ /-- A weighted sum may be split into a subtraction of such sums over two subsets. -/ lemma weighted_vsub_sdiff_sub [decidable_eq ι] {s₂ : finset ι} (h : s₂ ⊆ s) (w : ι → k) (p : ι → P) : (s \ s₂).weighted_vsub p w - s₂.weighted_vsub p (-w) = s.weighted_vsub p w := s.weighted_vsub_of_point_sdiff_sub h _ _ _ /-- A weighted sum over `s.subtype pred` equals one over `s.filter pred`. -/ lemma weighted_vsub_subtype_eq_filter (w : ι → k) (p : ι → P) (pred : ι → Prop) [decidable_pred pred] : (s.subtype pred).weighted_vsub (λ i, p i) (λ i, w i) = (s.filter pred).weighted_vsub p w := s.weighted_vsub_of_point_subtype_eq_filter _ _ _ _ /-- A weighted sum over `s.filter pred` equals one over `s` if all the weights at indices in `s` not satisfying `pred` are zero. -/ lemma weighted_vsub_filter_of_ne (w : ι → k) (p : ι → P) {pred : ι → Prop} [decidable_pred pred] (h : ∀ i ∈ s, w i ≠ 0 → pred i) : (s.filter pred).weighted_vsub p w = s.weighted_vsub p w := s.weighted_vsub_of_point_filter_of_ne _ _ _ h /-- A constant multiplier of the weights in `weighted_vsub_of` may be moved outside the sum. -/ lemma weighted_vsub_const_smul (w : ι → k) (p : ι → P) (c : k) : s.weighted_vsub p (c • w) = c • s.weighted_vsub p w := s.weighted_vsub_of_point_const_smul _ _ _ _ variables (k) /-- A weighted sum of the results of subtracting a default base point from the given points, added to that base point, as an affine map on the weights. This is intended to be used when the sum of the weights is 1, in which case it is an affine combination (barycenter) of the points with the given weights; that condition is specified as a hypothesis on those lemmas that require it. -/ def affine_combination (p : ι → P) : (ι → k) →ᵃ[k] P := { to_fun := λ w, s.weighted_vsub_of_point p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty), linear := s.weighted_vsub p, map_vadd' := λ w₁ w₂, by simp_rw [vadd_vadd, weighted_vsub, vadd_eq_add, linear_map.map_add] } /-- The linear map corresponding to `affine_combination` is `weighted_vsub`. -/ @[simp] lemma affine_combination_linear (p : ι → P) : (s.affine_combination k p).linear = s.weighted_vsub p := rfl variables {k} /-- Applying `affine_combination` with given weights. This is for the case where a result involving a default base point is OK (for example, when that base point will cancel out later); a more typical use case for `affine_combination` would involve selecting a preferred base point with `affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one` and then using `weighted_vsub_of_point_apply`. -/ lemma affine_combination_apply (w : ι → k) (p : ι → P) : s.affine_combination k p w = s.weighted_vsub_of_point p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty) := rfl /-- The value of `affine_combination`, where the given points are equal. -/ @[simp] lemma affine_combination_apply_const (w : ι → k) (p : P) (h : ∑ i in s, w i = 1) : s.affine_combination k (λ _, p) w = p := by rw [affine_combination_apply, s.weighted_vsub_of_point_apply_const, h, one_smul, vsub_vadd] /-- `affine_combination` gives equal results for two families of weights and two families of points that are equal on `s`. -/ lemma affine_combination_congr {w₁ w₂ : ι → k} (hw : ∀ i ∈ s, w₁ i = w₂ i) {p₁ p₂ : ι → P} (hp : ∀ i ∈ s, p₁ i = p₂ i) : s.affine_combination k p₁ w₁ = s.affine_combination k p₂ w₂ := by simp_rw [affine_combination_apply, s.weighted_vsub_of_point_congr hw hp] /-- `affine_combination` gives the sum with any base point, when the sum of the weights is 1. -/ lemma affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 1) (b : P) : s.affine_combination k p w = s.weighted_vsub_of_point p b w +ᵥ b := s.weighted_vsub_of_point_vadd_eq_of_sum_eq_one w p h _ _ /-- Adding a `weighted_vsub` to an `affine_combination`. -/ lemma weighted_vsub_vadd_affine_combination (w₁ w₂ : ι → k) (p : ι → P) : s.weighted_vsub p w₁ +ᵥ s.affine_combination k p w₂ = s.affine_combination k p (w₁ + w₂) := by rw [←vadd_eq_add, affine_map.map_vadd, affine_combination_linear] /-- Subtracting two `affine_combination`s. -/ lemma affine_combination_vsub (w₁ w₂ : ι → k) (p : ι → P) : s.affine_combination k p w₁ -ᵥ s.affine_combination k p w₂ = s.weighted_vsub p (w₁ - w₂) := by rw [←affine_map.linear_map_vsub, affine_combination_linear, vsub_eq_sub] lemma attach_affine_combination_of_injective [decidable_eq P] (s : finset P) (w : P → k) (f : s → P) (hf : function.injective f) : s.attach.affine_combination k f (w ∘ f) = (image f univ).affine_combination k id w := begin simp only [affine_combination, weighted_vsub_of_point_apply, id.def, vadd_right_cancel_iff, function.comp_app, affine_map.coe_mk], let g₁ : s → V := λ i, w (f i) • (f i -ᵥ classical.choice S.nonempty), let g₂ : P → V := λ i, w i • (i -ᵥ classical.choice S.nonempty), change univ.sum g₁ = (image f univ).sum g₂, have hgf : g₁ = g₂ ∘ f, { ext, simp, }, rw [hgf, sum_image], exact λ _ _ _ _ hxy, hf hxy, end lemma attach_affine_combination_coe (s : finset P) (w : P → k) : s.attach.affine_combination k (coe : s → P) (w ∘ coe) = s.affine_combination k id w := by classical; rw [attach_affine_combination_of_injective s w (coe : s → P) subtype.coe_injective, univ_eq_attach, attach_image_coe] omit S /-- Viewing a module as an affine space modelled on itself, a `weighted_vsub` is just a linear combination. -/ @[simp] lemma weighted_vsub_eq_linear_combination {ι} (s : finset ι) {w : ι → k} {p : ι → V} (hw : s.sum w = 0) : s.weighted_vsub p w = ∑ i in s, w i • p i := by simp [s.weighted_vsub_apply, vsub_eq_sub, smul_sub, ← finset.sum_smul, hw] /-- Viewing a module as an affine space modelled on itself, affine combinations are just linear combinations. -/ @[simp] lemma affine_combination_eq_linear_combination (s : finset ι) (p : ι → V) (w : ι → k) (hw : ∑ i in s, w i = 1) : s.affine_combination k p w = ∑ i in s, w i • p i := by simp [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw 0] include S /-- An `affine_combination` equals a point if that point is in the set and has weight 1 and the other points in the set have weight 0. -/ @[simp] lemma affine_combination_of_eq_one_of_eq_zero (w : ι → k) (p : ι → P) {i : ι} (his : i ∈ s) (hwi : w i = 1) (hw0 : ∀ i2 ∈ s, i2 ≠ i → w i2 = 0) : s.affine_combination k p w = p i := begin have h1 : ∑ i in s, w i = 1 := hwi ▸ sum_eq_single i hw0 (λ h, false.elim (h his)), rw [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p h1 (p i), weighted_vsub_of_point_apply], convert zero_vadd V (p i), convert sum_eq_zero _, intros i2 hi2, by_cases h : i2 = i, { simp [h] }, { simp [hw0 i2 hi2 h] } end /-- An affine combination is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma affine_combination_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.affine_combination k p w = s₂.affine_combination k p (set.indicator ↑s₁ w) := by rw [affine_combination_apply, affine_combination_apply, weighted_vsub_of_point_indicator_subset _ _ _ h] /-- An affine combination, over the image of an embedding, equals an affine combination with the same points and weights over the original `finset`. -/ lemma affine_combination_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) : (s₂.map e).affine_combination k p w = s₂.affine_combination k (p ∘ e) (w ∘ e) := by simp_rw [affine_combination_apply, weighted_vsub_of_point_map] /-- A weighted sum of pairwise subtractions, expressed as a subtraction of two `affine_combination` expressions. -/ lemma sum_smul_vsub_eq_affine_combination_vsub (w : ι → k) (p₁ p₂ : ι → P) : ∑ i in s, w i • (p₁ i -ᵥ p₂ i) = s.affine_combination k p₁ w -ᵥ s.affine_combination k p₂ w := begin simp_rw [affine_combination_apply, vadd_vsub_vadd_cancel_right], exact s.sum_smul_vsub_eq_weighted_vsub_of_point_sub _ _ _ _ end /-- A weighted sum of pairwise subtractions, where the point on the right is constant and the sum of the weights is 1. -/ lemma sum_smul_vsub_const_eq_affine_combination_vsub (w : ι → k) (p₁ : ι → P) (p₂ : P) (h : ∑ i in s, w i = 1) : ∑ i in s, w i • (p₁ i -ᵥ p₂) = s.affine_combination k p₁ w -ᵥ p₂ := by rw [sum_smul_vsub_eq_affine_combination_vsub, affine_combination_apply_const _ _ _ h] /-- A weighted sum of pairwise subtractions, where the point on the left is constant and the sum of the weights is 1. -/ lemma sum_smul_const_vsub_eq_vsub_affine_combination (w : ι → k) (p₂ : ι → P) (p₁ : P) (h : ∑ i in s, w i = 1) : ∑ i in s, w i • (p₁ -ᵥ p₂ i) = p₁ -ᵥ s.affine_combination k p₂ w := by rw [sum_smul_vsub_eq_affine_combination_vsub, affine_combination_apply_const _ _ _ h] /-- A weighted sum may be split into a subtraction of affine combinations over two subsets. -/ lemma affine_combination_sdiff_sub [decidable_eq ι] {s₂ : finset ι} (h : s₂ ⊆ s) (w : ι → k) (p : ι → P) : (s \ s₂).affine_combination k p w -ᵥ s₂.affine_combination k p (-w) = s.weighted_vsub p w := begin simp_rw [affine_combination_apply, vadd_vsub_vadd_cancel_right], exact s.weighted_vsub_sdiff_sub h _ _ end /-- If a weighted sum is zero and one of the weights is `-1`, the corresponding point is the affine combination of the other points with the given weights. -/ lemma affine_combination_eq_of_weighted_vsub_eq_zero_of_eq_neg_one {w : ι → k} {p : ι → P} (hw : s.weighted_vsub p w = (0 : V)) {i : ι} [decidable_pred (≠ i)] (his : i ∈ s) (hwi : w i = -1) : (s.filter (≠ i)).affine_combination k p w = p i := begin classical, rw [←@vsub_eq_zero_iff_eq V, ←hw, ←s.affine_combination_sdiff_sub (singleton_subset_iff.2 his), sdiff_singleton_eq_erase, ←filter_ne'], congr, refine (affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_singleton_self _) _ _).symm, { simp [hwi] }, { simp } end /-- An affine combination over `s.subtype pred` equals one over `s.filter pred`. -/ lemma affine_combination_subtype_eq_filter (w : ι → k) (p : ι → P) (pred : ι → Prop) [decidable_pred pred] : (s.subtype pred).affine_combination k (λ i, p i) (λ i, w i) = (s.filter pred).affine_combination k p w := by rw [affine_combination_apply, affine_combination_apply, weighted_vsub_of_point_subtype_eq_filter] /-- An affine combination over `s.filter pred` equals one over `s` if all the weights at indices in `s` not satisfying `pred` are zero. -/ lemma affine_combination_filter_of_ne (w : ι → k) (p : ι → P) {pred : ι → Prop} [decidable_pred pred] (h : ∀ i ∈ s, w i ≠ 0 → pred i) : (s.filter pred).affine_combination k p w = s.affine_combination k p w := by rw [affine_combination_apply, affine_combination_apply, s.weighted_vsub_of_point_filter_of_ne _ _ _ h] variables {V} /-- Suppose an indexed family of points is given, along with a subset of the index type. A vector can be expressed as `weighted_vsub_of_point` using a `finset` lying within that subset and with a given sum of weights if and only if it can be expressed as `weighted_vsub_of_point` with that sum of weights for the corresponding indexed family whose index type is the subtype corresponding to that subset. -/ lemma eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype {v : V} {x : k} {s : set ι} {p : ι → P} {b : P} : (∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = x), v = fs.weighted_vsub_of_point p b w) ↔ ∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = x), v = fs.weighted_vsub_of_point (λ (i : s), p i) b w := begin classical, simp_rw weighted_vsub_of_point_apply, split, { rintros ⟨fs, hfs, w, rfl, rfl⟩, use [fs.subtype s, λ i, w i, sum_subtype_of_mem _ hfs, (sum_subtype_of_mem _ hfs).symm] }, { rintros ⟨fs, w, rfl, rfl⟩, refine ⟨fs.map (function.embedding.subtype _), map_subtype_subset _, λ i, if h : i ∈ s then w ⟨i, h⟩ else 0, _, _⟩; simp } end variables (k) /-- Suppose an indexed family of points is given, along with a subset of the index type. A vector can be expressed as `weighted_vsub` using a `finset` lying within that subset and with sum of weights 0 if and only if it can be expressed as `weighted_vsub` with sum of weights 0 for the corresponding indexed family whose index type is the subtype corresponding to that subset. -/ lemma eq_weighted_vsub_subset_iff_eq_weighted_vsub_subtype {v : V} {s : set ι} {p : ι → P} : (∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = 0), v = fs.weighted_vsub p w) ↔ ∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = 0), v = fs.weighted_vsub (λ (i : s), p i) w := eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype variables (V) /-- Suppose an indexed family of points is given, along with a subset of the index type. A point can be expressed as an `affine_combination` using a `finset` lying within that subset and with sum of weights 1 if and only if it can be expressed an `affine_combination` with sum of weights 1 for the corresponding indexed family whose index type is the subtype corresponding to that subset. -/ lemma eq_affine_combination_subset_iff_eq_affine_combination_subtype {p0 : P} {s : set ι} {p : ι → P} : (∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = 1), p0 = fs.affine_combination k p w) ↔ ∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = 1), p0 = fs.affine_combination k (λ (i : s), p i) w := begin simp_rw [affine_combination_apply, eq_vadd_iff_vsub_eq], exact eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype end variables {k V} /-- Affine maps commute with affine combinations. -/ lemma map_affine_combination {V₂ P₂ : Type*} [add_comm_group V₂] [module k V₂] [affine_space V₂ P₂] (p : ι → P) (w : ι → k) (hw : s.sum w = 1) (f : P →ᵃ[k] P₂) : f (s.affine_combination k p w) = s.affine_combination k (f ∘ p) w := begin have b := classical.choice (infer_instance : affine_space V P).nonempty, have b₂ := classical.choice (infer_instance : affine_space V₂ P₂).nonempty, rw [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw b, s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w (f ∘ p) hw b₂, ← s.weighted_vsub_of_point_vadd_eq_of_sum_eq_one w (f ∘ p) hw (f b) b₂], simp only [weighted_vsub_of_point_apply, ring_hom.id_apply, affine_map.map_vadd, linear_map.map_smulₛₗ, affine_map.linear_map_vsub, linear_map.map_sum], end variables (k) omit S /-- Weights for expressing a single point as an affine combination. -/ def affine_combination_single_weights [decidable_eq ι] (i : ι) : ι → k := function.update (function.const ι 0) i 1 @[simp] lemma affine_combination_single_weights_apply_self [decidable_eq ι] (i : ι) : affine_combination_single_weights k i i = 1 := by simp [affine_combination_single_weights] @[simp] lemma affine_combination_single_weights_apply_of_ne [decidable_eq ι] {i j : ι} (h : j ≠ i) : affine_combination_single_weights k i j = 0 := by simp [affine_combination_single_weights, h] @[simp] lemma sum_affine_combination_single_weights [decidable_eq ι] {i : ι} (h : i ∈ s) : ∑ j in s, affine_combination_single_weights k i j = 1 := begin rw ←affine_combination_single_weights_apply_self k i, exact sum_eq_single_of_mem i h (λ j _ hj, affine_combination_single_weights_apply_of_ne k hj) end /-- Weights for expressing the subtraction of two points as a `weighted_vsub`. -/ def weighted_vsub_vsub_weights [decidable_eq ι] (i j : ι) : ι → k := affine_combination_single_weights k i - affine_combination_single_weights k j @[simp] lemma weighted_vsub_vsub_weights_self [decidable_eq ι] (i : ι) : weighted_vsub_vsub_weights k i i = 0 := by simp [weighted_vsub_vsub_weights] @[simp] lemma weighted_vsub_vsub_weights_apply_left [decidable_eq ι] {i j : ι} (h : i ≠ j) : weighted_vsub_vsub_weights k i j i = 1 := by simp [weighted_vsub_vsub_weights, h] @[simp] lemma weighted_vsub_vsub_weights_apply_right [decidable_eq ι] {i j : ι} (h : i ≠ j) : weighted_vsub_vsub_weights k i j j = -1 := by simp [weighted_vsub_vsub_weights, h.symm] @[simp] lemma weighted_vsub_vsub_weights_apply_of_ne [decidable_eq ι] {i j t : ι} (hi : t ≠ i) (hj : t ≠ j) : weighted_vsub_vsub_weights k i j t = 0 := by simp [weighted_vsub_vsub_weights, hi, hj] @[simp] lemma sum_weighted_vsub_vsub_weights [decidable_eq ι] {i j : ι} (hi : i ∈ s) (hj : j ∈ s) : ∑ t in s, weighted_vsub_vsub_weights k i j t = 0 := begin simp_rw [weighted_vsub_vsub_weights, pi.sub_apply, sum_sub_distrib], simp [hi, hj] end variables {k} /-- Weights for expressing `line_map` as an affine combination. -/ def affine_combination_line_map_weights [decidable_eq ι] (i j : ι) (c : k) : ι → k := c • weighted_vsub_vsub_weights k j i + affine_combination_single_weights k i @[simp] lemma affine_combination_line_map_weights_self [decidable_eq ι] (i : ι) (c : k) : affine_combination_line_map_weights i i c = affine_combination_single_weights k i := by simp [affine_combination_line_map_weights] @[simp] lemma affine_combination_line_map_weights_apply_left [decidable_eq ι] {i j : ι} (h : i ≠ j) (c : k) : affine_combination_line_map_weights i j c i = 1 - c := by simp [affine_combination_line_map_weights, h.symm, sub_eq_neg_add] @[simp] lemma affine_combination_line_map_weights_apply_right [decidable_eq ι] {i j : ι} (h : i ≠ j) (c : k) : affine_combination_line_map_weights i j c j = c := by simp [affine_combination_line_map_weights, h.symm] @[simp] lemma affine_combination_line_map_weights_apply_of_ne [decidable_eq ι] {i j t : ι} (hi : t ≠ i) (hj : t ≠ j) (c : k) : affine_combination_line_map_weights i j c t = 0 := by simp [affine_combination_line_map_weights, hi, hj] @[simp] lemma sum_affine_combination_line_map_weights [decidable_eq ι] {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (c : k) : ∑ t in s, affine_combination_line_map_weights i j c t = 1 := begin simp_rw [affine_combination_line_map_weights, pi.add_apply, sum_add_distrib], simp [hi, hj, ←mul_sum] end include S variables (k) /-- An affine combination with `affine_combination_single_weights` gives the specified point. -/ @[simp] lemma affine_combination_affine_combination_single_weights [decidable_eq ι] (p : ι → P) {i : ι} (hi : i ∈ s) : s.affine_combination k p (affine_combination_single_weights k i) = p i := begin refine s.affine_combination_of_eq_one_of_eq_zero _ _ hi (by simp) _, rintro j - hj, simp [hj] end /-- A weighted subtraction with `weighted_vsub_vsub_weights` gives the result of subtracting the specified points. -/ @[simp] lemma weighted_vsub_weighted_vsub_vsub_weights [decidable_eq ι] (p : ι → P) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) : s.weighted_vsub p (weighted_vsub_vsub_weights k i j) = p i -ᵥ p j := begin rw [weighted_vsub_vsub_weights, ←affine_combination_vsub, s.affine_combination_affine_combination_single_weights k p hi, s.affine_combination_affine_combination_single_weights k p hj] end variables {k} /-- An affine combination with `affine_combination_line_map_weights` gives the result of `line_map`. -/ @[simp] lemma affine_combination_affine_combination_line_map_weights [decidable_eq ι] (p : ι → P) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (c : k) : s.affine_combination k p (affine_combination_line_map_weights i j c) = affine_map.line_map (p i) (p j) c := by rw [affine_combination_line_map_weights, ←weighted_vsub_vadd_affine_combination, weighted_vsub_const_smul, s.affine_combination_affine_combination_single_weights k p hi, s.weighted_vsub_weighted_vsub_vsub_weights k p hj hi, affine_map.line_map_apply] end finset namespace finset variables (k : Type*) {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} (s : finset ι) {ι₂ : Type*} (s₂ : finset ι₂) /-- The weights for the centroid of some points. -/ def centroid_weights : ι → k := function.const ι (card s : k) ⁻¹ /-- `centroid_weights` at any point. -/ @[simp] lemma centroid_weights_apply (i : ι) : s.centroid_weights k i = (card s : k) ⁻¹ := rfl /-- `centroid_weights` equals a constant function. -/ lemma centroid_weights_eq_const : s.centroid_weights k = function.const ι ((card s : k) ⁻¹) := rfl variables {k} /-- The weights in the centroid sum to 1, if the number of points, converted to `k`, is not zero. -/ lemma sum_centroid_weights_eq_one_of_cast_card_ne_zero (h : (card s : k) ≠ 0) : ∑ i in s, s.centroid_weights k i = 1 := by simp [h] variables (k) /-- In the characteristic zero case, the weights in the centroid sum to 1 if the number of points is not zero. -/ lemma sum_centroid_weights_eq_one_of_card_ne_zero [char_zero k] (h : card s ≠ 0) : ∑ i in s, s.centroid_weights k i = 1 := by simp [h] /-- In the characteristic zero case, the weights in the centroid sum to 1 if the set is nonempty. -/ lemma sum_centroid_weights_eq_one_of_nonempty [char_zero k] (h : s.nonempty) : ∑ i in s, s.centroid_weights k i = 1 := s.sum_centroid_weights_eq_one_of_card_ne_zero k (ne_of_gt (card_pos.2 h)) /-- In the characteristic zero case, the weights in the centroid sum to 1 if the number of points is `n + 1`. -/ lemma sum_centroid_weights_eq_one_of_card_eq_add_one [char_zero k] {n : ℕ} (h : card s = n + 1) : ∑ i in s, s.centroid_weights k i = 1 := s.sum_centroid_weights_eq_one_of_card_ne_zero k (h.symm ▸ nat.succ_ne_zero n) include V /-- The centroid of some points. Although defined for any `s`, this is intended to be used in the case where the number of points, converted to `k`, is not zero. -/ def centroid (p : ι → P) : P := s.affine_combination k p (s.centroid_weights k) /-- The definition of the centroid. -/ lemma centroid_def (p : ι → P) : s.centroid k p = s.affine_combination k p (s.centroid_weights k) := rfl lemma centroid_univ (s : finset P) : univ.centroid k (coe : s → P) = s.centroid k id := by { rw [centroid, centroid, ← s.attach_affine_combination_coe], congr, ext, simp, } /-- The centroid of a single point. -/ @[simp] lemma centroid_singleton (p : ι → P) (i : ι) : ({i} : finset ι).centroid k p = p i := by simp [centroid_def, affine_combination_apply] /-- The centroid of two points, expressed directly as adding a vector to a point. -/ lemma centroid_pair [decidable_eq ι] [invertible (2 : k)] (p : ι → P) (i₁ i₂ : ι) : ({i₁, i₂} : finset ι).centroid k p = (2 ⁻¹ : k) • (p i₂ -ᵥ p i₁) +ᵥ p i₁ := begin by_cases h : i₁ = i₂, { simp [h] }, { have hc : (card ({i₁, i₂} : finset ι) : k) ≠ 0, { rw [card_insert_of_not_mem (not_mem_singleton.2 h), card_singleton], norm_num, exact nonzero_of_invertible _ }, rw [centroid_def, affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one _ _ _ (sum_centroid_weights_eq_one_of_cast_card_ne_zero _ hc) (p i₁)], simp [h] } end /-- The centroid of two points indexed by `fin 2`, expressed directly as adding a vector to the first point. -/ lemma centroid_pair_fin [invertible (2 : k)] (p : fin 2 → P) : univ.centroid k p = (2 ⁻¹ : k) • (p 1 -ᵥ p 0) +ᵥ p 0 := begin rw univ_fin2, convert centroid_pair k p 0 1 end /-- A centroid, over the image of an embedding, equals a centroid with the same points and weights over the original `finset`. -/ lemma centroid_map (e : ι₂ ↪ ι) (p : ι → P) : (s₂.map e).centroid k p = s₂.centroid k (p ∘ e) := by simp [centroid_def, affine_combination_map, centroid_weights] omit V /-- `centroid_weights` gives the weights for the centroid as a constant function, which is suitable when summing over the points whose centroid is being taken. This function gives the weights in a form suitable for summing over a larger set of points, as an indicator function that is zero outside the set whose centroid is being taken. In the case of a `fintype`, the sum may be over `univ`. -/ def centroid_weights_indicator : ι → k := set.indicator ↑s (s.centroid_weights k) /-- The definition of `centroid_weights_indicator`. -/ lemma centroid_weights_indicator_def : s.centroid_weights_indicator k = set.indicator ↑s (s.centroid_weights k) := rfl /-- The sum of the weights for the centroid indexed by a `fintype`. -/ lemma sum_centroid_weights_indicator [fintype ι] : ∑ i, s.centroid_weights_indicator k i = ∑ i in s, s.centroid_weights k i := (set.sum_indicator_subset _ (subset_univ _)).symm /-- In the characteristic zero case, the weights in the centroid indexed by a `fintype` sum to 1 if the number of points is not zero. -/ lemma sum_centroid_weights_indicator_eq_one_of_card_ne_zero [char_zero k] [fintype ι] (h : card s ≠ 0) : ∑ i, s.centroid_weights_indicator k i = 1 := begin rw sum_centroid_weights_indicator, exact s.sum_centroid_weights_eq_one_of_card_ne_zero k h end /-- In the characteristic zero case, the weights in the centroid indexed by a `fintype` sum to 1 if the set is nonempty. -/ lemma sum_centroid_weights_indicator_eq_one_of_nonempty [char_zero k] [fintype ι] (h : s.nonempty) : ∑ i, s.centroid_weights_indicator k i = 1 := begin rw sum_centroid_weights_indicator, exact s.sum_centroid_weights_eq_one_of_nonempty k h end /-- In the characteristic zero case, the weights in the centroid indexed by a `fintype` sum to 1 if the number of points is `n + 1`. -/ lemma sum_centroid_weights_indicator_eq_one_of_card_eq_add_one [char_zero k] [fintype ι] {n : ℕ} (h : card s = n + 1) : ∑ i, s.centroid_weights_indicator k i = 1 := begin rw sum_centroid_weights_indicator, exact s.sum_centroid_weights_eq_one_of_card_eq_add_one k h end include V /-- The centroid as an affine combination over a `fintype`. -/ lemma centroid_eq_affine_combination_fintype [fintype ι] (p : ι → P) : s.centroid k p = univ.affine_combination k p (s.centroid_weights_indicator k) := affine_combination_indicator_subset _ _ (subset_univ _) /-- An indexed family of points that is injective on the given `finset` has the same centroid as the image of that `finset`. This is stated in terms of a set equal to the image to provide control of definitional equality for the index type used for the centroid of the image. -/ lemma centroid_eq_centroid_image_of_inj_on {p : ι → P} (hi : ∀ i j ∈ s, p i = p j → i = j) {ps : set P} [fintype ps] (hps : ps = p '' ↑s) : s.centroid k p = (univ : finset ps).centroid k (λ x, x) := begin let f : p '' ↑s → ι := λ x, x.property.some, have hf : ∀ x, f x ∈ s ∧ p (f x) = x := λ x, x.property.some_spec, let f' : ps → ι := λ x, f ⟨x, hps ▸ x.property⟩, have hf' : ∀ x, f' x ∈ s ∧ p (f' x) = x := λ x, hf ⟨x, hps ▸ x.property⟩, have hf'i : function.injective f', { intros x y h, rw [subtype.ext_iff, ←(hf' x).2, ←(hf' y).2, h] }, let f'e : ps ↪ ι := ⟨f', hf'i⟩, have hu : finset.univ.map f'e = s, { ext x, rw mem_map, split, { rintros ⟨i, _, rfl⟩, exact (hf' i).1 }, { intro hx, use [⟨p x, hps.symm ▸ set.mem_image_of_mem _ hx⟩, mem_univ _], refine hi _ (hf' _).1 _ hx _, rw (hf' _).2, refl } }, rw [←hu, centroid_map], congr' with x, change p (f' x) = ↑x, rw (hf' x).2 end /-- Two indexed families of points that are injective on the given `finset`s and with the same points in the image of those `finset`s have the same centroid. -/ lemma centroid_eq_of_inj_on_of_image_eq {p : ι → P} (hi : ∀ i j ∈ s, p i = p j → i = j) {p₂ : ι₂ → P} (hi₂ : ∀ i j ∈ s₂, p₂ i = p₂ j → i = j) (he : p '' ↑s = p₂ '' ↑s₂) : s.centroid k p = s₂.centroid k p₂ := by classical; rw [s.centroid_eq_centroid_image_of_inj_on k hi rfl, s₂.centroid_eq_centroid_image_of_inj_on k hi₂ he] end finset section affine_space' variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V /-- A `weighted_vsub` with sum of weights 0 is in the `vector_span` of an indexed family. -/ lemma weighted_vsub_mem_vector_span {s : finset ι} {w : ι → k} (h : ∑ i in s, w i = 0) (p : ι → P) : s.weighted_vsub p w ∈ vector_span k (set.range p) := begin classical, rcases is_empty_or_nonempty ι with hι|⟨⟨i0⟩⟩, { resetI, simp [finset.eq_empty_of_is_empty s] }, { rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ, finsupp.mem_span_image_iff_total, finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero s w p h (p i0), finset.weighted_vsub_of_point_apply], let w' := set.indicator ↑s w, have hwx : ∀ i, w' i ≠ 0 → i ∈ s := λ i, set.mem_of_indicator_ne_zero, use [finsupp.on_finset s w' hwx, set.subset_univ _], rw [finsupp.total_apply, finsupp.on_finset_sum hwx], { apply finset.sum_congr rfl, intros i hi, simp [w', set.indicator_apply, if_pos hi] }, { exact λ _, zero_smul k _ } }, end /-- An `affine_combination` with sum of weights 1 is in the `affine_span` of an indexed family, if the underlying ring is nontrivial. -/ lemma affine_combination_mem_affine_span [nontrivial k] {s : finset ι} {w : ι → k} (h : ∑ i in s, w i = 1) (p : ι → P) : s.affine_combination k p w ∈ affine_span k (set.range p) := begin classical, have hnz : ∑ i in s, w i ≠ 0 := h.symm ▸ one_ne_zero, have hn : s.nonempty := finset.nonempty_of_sum_ne_zero hnz, cases hn with i1 hi1, let w1 : ι → k := function.update (function.const ι 0) i1 1, have hw1 : ∑ i in s, w1 i = 1, { rw [finset.sum_update_of_mem hi1, finset.sum_const_zero, add_zero] }, have hw1s : s.affine_combination k p w1 = p i1 := s.affine_combination_of_eq_one_of_eq_zero w1 p hi1 (function.update_same _ _ _) (λ _ _ hne, function.update_noteq hne _ _), have hv : s.affine_combination k p w -ᵥ p i1 ∈ (affine_span k (set.range p)).direction, { rw [direction_affine_span, ←hw1s, finset.affine_combination_vsub], apply weighted_vsub_mem_vector_span, simp [pi.sub_apply, h, hw1] }, rw ←vsub_vadd (s.affine_combination k p w) (p i1), exact affine_subspace.vadd_mem_of_mem_direction hv (mem_affine_span k (set.mem_range_self _)) end variables (k) {V} /-- A vector is in the `vector_span` of an indexed family if and only if it is a `weighted_vsub` with sum of weights 0. -/ lemma mem_vector_span_iff_eq_weighted_vsub {v : V} {p : ι → P} : v ∈ vector_span k (set.range p) ↔ ∃ (s : finset ι) (w : ι → k) (h : ∑ i in s, w i = 0), v = s.weighted_vsub p w := begin classical, split, { rcases is_empty_or_nonempty ι with hι|⟨⟨i0⟩⟩, swap, { rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ, finsupp.mem_span_image_iff_total], rintros ⟨l, hl, hv⟩, use insert i0 l.support, set w := (l : ι → k) - function.update (function.const ι 0 : ι → k) i0 (∑ i in l.support, l i) with hwdef, use w, have hw : ∑ i in insert i0 l.support, w i = 0, { rw hwdef, simp_rw [pi.sub_apply, finset.sum_sub_distrib, finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero, finset.sum_insert_of_eq_zero_if_not_mem finsupp.not_mem_support_iff.1, add_zero, sub_self] }, use hw, have hz : w i0 • (p i0 -ᵥ p i0 : V) = 0 := (vsub_self (p i0)).symm ▸ smul_zero _, change (λ i, w i • (p i -ᵥ p i0 : V)) i0 = 0 at hz, rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero _ w p hw (p i0), finset.weighted_vsub_of_point_apply, ←hv, finsupp.total_apply, finset.sum_insert_zero hz], change ∑ i in l.support, l i • _ = _, congr' with i, by_cases h : i = i0, { simp [h] }, { simp [hwdef, h] } }, { resetI, rw [set.range_eq_empty, vector_span_empty, submodule.mem_bot], rintro rfl, use [∅], simp } }, { rintros ⟨s, w, hw, rfl⟩, exact weighted_vsub_mem_vector_span hw p } end variables {k} /-- A point in the `affine_span` of an indexed family is an `affine_combination` with sum of weights 1. See also `eq_affine_combination_of_mem_affine_span_of_fintype`. -/ lemma eq_affine_combination_of_mem_affine_span {p1 : P} {p : ι → P} (h : p1 ∈ affine_span k (set.range p)) : ∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination k p w := begin classical, have hn : ((affine_span k (set.range p)) : set P).nonempty := ⟨p1, h⟩, rw [affine_span_nonempty, set.range_nonempty_iff_nonempty] at hn, cases hn with i0, have h0 : p i0 ∈ affine_span k (set.range p) := mem_affine_span k (set.mem_range_self i0), have hd : p1 -ᵥ p i0 ∈ (affine_span k (set.range p)).direction := affine_subspace.vsub_mem_direction h h0, rw [direction_affine_span, mem_vector_span_iff_eq_weighted_vsub] at hd, rcases hd with ⟨s, w, h, hs⟩, let s' := insert i0 s, let w' := set.indicator ↑s w, have h' : ∑ i in s', w' i = 0, { rw [←h, set.sum_indicator_subset _ (finset.subset_insert i0 s)] }, have hs' : s'.weighted_vsub p w' = p1 -ᵥ p i0, { rw hs, exact (finset.weighted_vsub_indicator_subset _ _ (finset.subset_insert i0 s)).symm }, let w0 : ι → k := function.update (function.const ι 0) i0 1, have hw0 : ∑ i in s', w0 i = 1, { rw [finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero, add_zero] }, have hw0s : s'.affine_combination k p w0 = p i0 := s'.affine_combination_of_eq_one_of_eq_zero w0 p (finset.mem_insert_self _ _) (function.update_same _ _ _) (λ _ _ hne, function.update_noteq hne _ _), use [s', w0 + w'], split, { simp [pi.add_apply, finset.sum_add_distrib, hw0, h'] }, { rw [add_comm, ←finset.weighted_vsub_vadd_affine_combination, hw0s, hs', vsub_vadd] } end lemma eq_affine_combination_of_mem_affine_span_of_fintype [fintype ι] {p1 : P} {p : ι → P} (h : p1 ∈ affine_span k (set.range p)) : ∃ (w : ι → k) (hw : ∑ i, w i = 1), p1 = finset.univ.affine_combination k p w := begin classical, obtain ⟨s, w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span h, refine ⟨(s : set ι).indicator w, _, finset.affine_combination_indicator_subset w p s.subset_univ⟩, simp only [finset.mem_coe, set.indicator_apply, ← hw], rw fintype.sum_extend_by_zero s w, end variables (k V) /-- A point is in the `affine_span` of an indexed family if and only if it is an `affine_combination` with sum of weights 1, provided the underlying ring is nontrivial. -/ lemma mem_affine_span_iff_eq_affine_combination [nontrivial k] {p1 : P} {p : ι → P} : p1 ∈ affine_span k (set.range p) ↔ ∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination k p w := begin split, { exact eq_affine_combination_of_mem_affine_span }, { rintros ⟨s, w, hw, rfl⟩, exact affine_combination_mem_affine_span hw p } end /-- Given a family of points together with a chosen base point in that family, membership of the affine span of this family corresponds to an identity in terms of `weighted_vsub_of_point`, with weights that are not required to sum to 1. -/ lemma mem_affine_span_iff_eq_weighted_vsub_of_point_vadd [nontrivial k] (p : ι → P) (j : ι) (q : P) : q ∈ affine_span k (set.range p) ↔ ∃ (s : finset ι) (w : ι → k), q = s.weighted_vsub_of_point p (p j) w +ᵥ (p j) := begin split, { intros hq, obtain ⟨s, w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span hq, exact ⟨s, w, s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw (p j)⟩, }, { rintros ⟨s, w, rfl⟩, classical, let w' : ι → k := function.update w j (1 - (s \ {j}).sum w), have h₁ : (insert j s).sum w' = 1, { by_cases hj : j ∈ s, { simp [finset.sum_update_of_mem hj, finset.insert_eq_of_mem hj], }, { simp [w', finset.sum_insert hj, finset.sum_update_of_not_mem hj, hj], }, }, have hww : ∀ i, i ≠ j → w i = w' i, { intros i hij, simp [w', hij], }, rw [s.weighted_vsub_of_point_eq_of_weights_eq p j w w' hww, ← s.weighted_vsub_of_point_insert w' p j, ← (insert j s).affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w' p h₁ (p j)], exact affine_combination_mem_affine_span h₁ p, }, end variables {k V} /-- Given a set of points, together with a chosen base point in this set, if we affinely transport all other members of the set along the line joining them to this base point, the affine span is unchanged. -/ lemma affine_span_eq_affine_span_line_map_units [nontrivial k] {s : set P} {p : P} (hp : p ∈ s) (w : s → units k) : affine_span k (set.range (λ (q : s), affine_map.line_map p ↑q (w q : k))) = affine_span k s := begin have : s = set.range (coe : s → P), { simp, }, conv_rhs { rw this, }, apply le_antisymm; intros q hq; erw mem_affine_span_iff_eq_weighted_vsub_of_point_vadd k V _ (⟨p, hp⟩ : s) q at hq ⊢; obtain ⟨t, μ, rfl⟩ := hq; use t; [use λ x, (μ x) * ↑(w x), use λ x, (μ x) * ↑(w x)⁻¹]; simp [smul_smul], end end affine_space' section division_ring variables {k : Type*} {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} include V open set finset /-- The centroid lies in the affine span if the number of points, converted to `k`, is not zero. -/ lemma centroid_mem_affine_span_of_cast_card_ne_zero {s : finset ι} (p : ι → P) (h : (card s : k) ≠ 0) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_cast_card_ne_zero h) p variables (k) /-- In the characteristic zero case, the centroid lies in the affine span if the number of points is not zero. -/ lemma centroid_mem_affine_span_of_card_ne_zero [char_zero k] {s : finset ι} (p : ι → P) (h : card s ≠ 0) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_card_ne_zero k h) p /-- In the characteristic zero case, the centroid lies in the affine span if the set is nonempty. -/ lemma centroid_mem_affine_span_of_nonempty [char_zero k] {s : finset ι} (p : ι → P) (h : s.nonempty) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_nonempty k h) p /-- In the characteristic zero case, the centroid lies in the affine span if the number of points is `n + 1`. -/ lemma centroid_mem_affine_span_of_card_eq_add_one [char_zero k] {s : finset ι} (p : ι → P) {n : ℕ} (h : card s = n + 1) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_card_eq_add_one k h) p end division_ring namespace affine_map variables {k : Type*} {V : Type*} (P : Type*) [comm_ring k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} (s : finset ι) include V -- TODO: define `affine_map.proj`, `affine_map.fst`, `affine_map.snd` /-- A weighted sum, as an affine map on the points involved. -/ def weighted_vsub_of_point (w : ι → k) : ((ι → P) × P) →ᵃ[k] V := { to_fun := λ p, s.weighted_vsub_of_point p.fst p.snd w, linear := ∑ i in s, w i • ((linear_map.proj i).comp (linear_map.fst _ _ _) - linear_map.snd _ _ _), map_vadd' := begin rintros ⟨p, b⟩ ⟨v, b'⟩, simp [linear_map.sum_apply, finset.weighted_vsub_of_point, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, ← sub_add_eq_add_sub, smul_add, finset.sum_add_distrib] end } end affine_map
c4e2c9b95df2d5d3a9a24c9017ae80271b6ab989
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/algebra/category/constructions/sum.hlean
20601b8157371412f299ff7fe079b0ad490a6e38
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,870
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, Jakob von Raumer Functor product precategory and (TODO) category -/ import ..category ..functor types.sum open eq sum is_trunc functor lift namespace category --set_option pp.universes true definition sum_hom.{u v w x} [unfold 5 6] {obC : Type.{u}} {obD : Type.{v}} (C : precategory.{u w} obC) (D : precategory.{v x} obD) : obC + obD → obC + obD → Type.{max w x} := sum.rec (λc, sum.rec (λc', lift (c ⟶ c')) (λd, lift empty)) (λd, sum.rec (λc, lift empty) (λd', lift (d ⟶ d'))) theorem is_hset_sum_hom {obC : Type} {obD : Type} (C : precategory obC) (D : precategory obD) (x y : obC + obD) : is_hset (sum_hom C D x y) := by induction x: induction y: esimp at *: exact _ local attribute is_hset_sum_hom [instance] definition precategory_sum [constructor] {obC obD : Type} (C : precategory obC) (D : precategory obD) : precategory (obC + obD) := precategory.mk (sum_hom C D) (λ a b c g f, begin induction a: induction b: induction c: esimp at *; induction f with f; induction g with g; (contradiction | exact up (g ∘ f)) end) (λ a, by induction a: exact up id) (λ a b c d h g f, abstract begin induction a: induction b: induction c: induction d: esimp at *; induction f with f; induction g with g; induction h with h; esimp at *; try contradiction: apply ap up !assoc end end) (λ a b f, abstract begin induction a: induction b: esimp at *; induction f with f; esimp; try contradiction: exact ap up !id_left end end) (λ a b f, abstract begin induction a: induction b: esimp at *; induction f with f; esimp; try contradiction: exact ap up !id_right end end) definition Precategory_sum [constructor] (C D : Precategory) : Precategory := precategory.Mk (precategory_sum C D) infixr `+c`:27 := Precategory_sum definition sum_functor [constructor] {C C' D D' : Precategory} (F : C ⇒ D) (G : C' ⇒ D') : C +c C' ⇒ D +c D' := functor.mk (λ a, by induction a: (exact inl (F a)|exact inr (G a))) (λ a b f, begin induction a: induction b: esimp at *; induction f with f; esimp; try contradiction: (exact up (F f)|exact up (G f)) end) (λ a, abstract by induction a: esimp; exact ap up !respect_id end) (λ a b c g f, abstract begin induction a: induction b: induction c: esimp at *; induction f with f; induction g with g; try contradiction: esimp; exact ap up !respect_comp end end) infixr `+f`:27 := sum_functor end category
045c32ca3d5d821e330ce7806060f8f8b939284c
4efff1f47634ff19e2f786deadd394270a59ecd2
/archive/imo1988_q6.lean
f0a41e3f5b38c979f77d2444234b1a56dc8d47e9
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
13,794
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.rat.basic import tactic /-! # IMO1988 Q6 and constant descent Vieta jumping Question 6 of IMO1988 is somewhat (in)famous. Several expert problem solvers could not tackle the question within the given time limit. The problem lead to the introduction of a new proof technique, so called “Vieta jumping”. In this file we formalise constant descent Vieta jumping, and apply this to prove Q6 of IMO1988. To illustrate the technique, we also prove a similar result. -/ -- open_locale classical local attribute [instance] classical.prop_decidable local attribute [simp] nat.pow_two /-- Constant descent Vieta jumping. This proof technique allows one to prove an arbitrary proposition `claim`, by running a descent argument on a hyperbola `H` in the first quadrant of the plane, under the following conditions: * `h₀` : There exists an integral point `(x,y)` on the hyperbola `H`. * `H_symm` : The hyperbola has a symmetry along the diagonal in the plane. * `H_zero` : If an integral point `(x,0)` lies on the hyperbola `H`, then `claim` is true. * `H_diag` : If an integral point `(x,x)` lies on the hyperbola `H`, then `claim` is true. * `H_desc` : If `(x,y)` is an integral point on the hyperbola `H`, with `x < y` then there exists a “smaller” point on `H`: a point `(x',y')` with `x' < y' ≤ x`. For reasons of usability, the hyperbola `H` is implemented as an arbitrary predicate. (In question 6 of IMO1988, where this proof technique was first developped, the predicate `claim` would be `∃ (d : ℕ), d ^ 2 = k` for some natural number `k`, and the predicate `H` would be `λ a b, a * a + b * b = (a * b + 1) * k`.) To ensure that the predicate `H` actually describes a hyperbola, the user must provide arguments `B` and `C` that are used as coefficients for a quadratic equation. Finally, `H_quad` is the proof obligation that the quadratic equation `(y:ℤ) * y - B x * y + C x = 0` describes the same hyperbola as the predicate `H`. For extra flexibility, one must provide a predicate `base` on the integral points in the plane. In the descent step `H_desc` this will give the user the additional assumption that the point `(x,y)` does not lie in this base locus. The user must provide a proof that the proposition `claim` is true if there exists an integral point `(x,y)` on the hyperbola `H` that lies in the base locus. If such a base locus is not necessary, once can simply let it be `λ x y, false`. -/ lemma constant_descent_vieta_jumping (x y : ℕ) {claim : Prop} {H : ℕ → ℕ → Prop} (h₀ : H x y) (B : ℕ → ℤ) (C : ℕ → ℤ) (base : ℕ → ℕ → Prop) (H_quad : ∀ {x y}, H x y ↔ (y:ℤ) * y - B x * y + C x = 0) (H_symm : ∀ {x y}, H x y ↔ H y x) (H_zero : ∀ {x}, H x 0 → claim) (H_diag : ∀ {x}, H x x → claim) (H_desc : ∀ {x y}, 0 < x → x < y → ¬base x y → H x y → ∀ y', y' * y' - B x * y' + C x = 0 → y' = B x - y → y' * y = C x → 0 ≤ y' ∧ y' ≤ x) (H_base : ∀ {x y}, H x y → base x y → claim) : claim := begin -- First of all, we may assume that x ≤ y. -- We justify this using H_symm. wlog hxy : x ≤ y, swap, { rw H_symm at h₀, solve_by_elim }, -- In fact, we can easily deal with the case x = y. by_cases x_eq_y : x = y, {subst x_eq_y, exact H_diag h₀}, -- Hence we may assume that x < y. replace hxy : x < y := lt_of_le_of_ne hxy x_eq_y, clear x_eq_y, -- Consider the upper branch of the hyperbola defined by H. let upper_branch : set (ℕ × ℕ) := {p | H p.1 p.2 ∧ p.1 < p.2}, -- Note that the point p = (x,y) lies on the upper branch. let p : ℕ × ℕ := ⟨x,y⟩, have hp : p ∈ upper_branch := ⟨h₀, hxy⟩, -- We also consider the exceptional set of solutions (a,b) that satisfy -- a = 0 or a = b or B a = b or B a = b + a or that lie in the base locus. let exceptional : set (ℕ × ℕ) := {p | H p.1 p.2 ∧ (base p.1 p.2 ∨ p.1 = 0 ∨ p.1 = p.2 ∨ B p.1 = p.2 ∨ B p.1 = p.2 + p.1) }, -- Let S be the projection of the upper branch on to the y-axis -- after removing the exceptional locus. let S : set ℕ := prod.snd '' (upper_branch \ exceptional), -- The strategy is to show that the exceptional locus in nonempty -- by running a descent argument that starts with the given point p = (x,y). -- Our assumptions ensure that we can then prove the claim. suffices exc : exceptional.nonempty, { -- Suppose that there exists an element in the exceptional locus. simp [exceptional, -add_comm, set.nonempty] at exc, -- Let (a,b) be such an element, and consider all the possible cases. rcases exc with ⟨a, b, hH, hb⟩, rcases hb with _|rfl|rfl|hB|hB, -- The first three cases are rather easy to solve. { solve_by_elim }, { rw H_symm at hH, solve_by_elim }, { solve_by_elim }, -- The final two cases are very similar. all_goals { -- Consider the quadratic equation that (a,b) satisfies. rw H_quad at hH, -- We find the other root of the equation, and Vieta's formulas. rcases Vieta_formula_quadratic hH with ⟨c, h_root, hV₁, hV₂⟩, -- By substitutions we find that b = 0 or b = a. simp [hB] at hV₁, subst hV₁, rw [← int.coe_nat_zero] at *, rw ← H_quad at h_root, -- And hence we are done by H_zero and H_diag. solve_by_elim } }, -- To finish the main proof, we need to show that the exceptional locus is nonempty. -- So we assume that the exceptional locus is empty, and work towards dering a contradiction. rw ← set.ne_empty_iff_nonempty, assume exceptional_empty, -- Observe that S is nonempty. have S_nonempty : S.nonempty, { -- It contains the image of p. use p.2, apply set.mem_image_of_mem, -- After all, we assumed that the exceptional locus is empty. rwa [exceptional_empty, set.diff_empty], }, -- We are now set for an infinite descent argument. -- Let m be the smallest element of the nonempty set S. let m : ℕ := well_founded.min nat.lt_wf S S_nonempty, have m_mem : m ∈ S := well_founded.min_mem nat.lt_wf S S_nonempty, have m_min : ∀ k ∈ S, ¬ k < m := λ k hk, well_founded.not_lt_min nat.lt_wf S S_nonempty hk, -- It suffices to show that there is point (a,b) with b ∈ S and b < m. suffices hp' : ∃ p' : ℕ × ℕ, p'.2 ∈ S ∧ p'.2 < m, { rcases hp' with ⟨p', p'_mem, p'_small⟩, solve_by_elim }, -- Let (m_x, m_y) be a point on the upper branch that projects to m ∈ S -- and that does not lie in the exceptional locus. rcases m_mem with ⟨⟨mx, my⟩, ⟨⟨hHm, mx_lt_my⟩, h_base⟩, m_eq⟩, -- This means that m_y = m, -- and the conditions H(m_x, m_y) and m_x < m_y are satisfied. simp [exceptional, hHm] at mx_lt_my h_base m_eq, push_neg at h_base, -- Finally, it also means that (m_x, m_y) does not lie in the base locus, -- that m_x ≠ 0, m_x ≠ m_y, B(m_x) ≠ m_y, and B(m_x) ≠ m_x + m_y. rcases h_base with ⟨h_base, hmx, hm_diag, hm_B₁, hm_B₂⟩, replace hmx : 0 < mx := nat.pos_iff_ne_zero.mpr hmx, -- Consider the quadratic equation that (m_x, m_y) satisfies. have h_quad := hHm, rw H_quad at h_quad, -- We find the other root of the equation, and Vieta's formulas. rcases Vieta_formula_quadratic h_quad with ⟨c, h_root, hV₁, hV₂⟩, -- No we rewrite Vietas formulas a bit, and apply the descent step. replace hV₁ : c = B mx - my := eq_sub_of_add_eq' hV₁, rw mul_comm at hV₂, have Hc := H_desc hmx mx_lt_my h_base hHm c h_root hV₁ hV₂, -- This means that we may assume that c ≥ 0 and c ≤ m_x. cases Hc with c_nonneg c_lt, -- In other words, c is a natural number. lift c to ℕ using c_nonneg, -- Recall that we are trying find a point (a,b) such that b ∈ S and b < m. -- We claim that p' = (c, m_x) does the job. let p' : ℕ × ℕ := ⟨c, mx⟩, use p', -- The second condition is rather easy to check, so we do that first. split, swap, { rwa m_eq at mx_lt_my }, -- Now we need to show that p' projects onto S. In other words, that c ∈ S. -- We do that, by showing that it lies in the upper branch -- (which is sufficient, because we assumed that the exceptional locus is empty). apply set.mem_image_of_mem, rw [exceptional_empty, set.diff_empty], -- Now we are ready to prove that p' = (c, m_x) lies on the upper branch. -- We need to check two conditions: H(c, m_x) and c < m_x. split; dsimp only, { -- The first condition is not so hard. After all, c is the other root of the quadratic equation. rw [H_symm, H_quad], simpa using h_root, }, { -- For the second condition, we note that it suffices to check that c ≠ m_x. suffices hc : c ≠ mx, { refine lt_of_le_of_ne _ hc, exact_mod_cast c_lt, }, -- However, recall that B(m_x) ≠ m_x + m_y. -- If c = m_x, we can prove B(m_x) = m_x + m_y. contrapose! hm_B₂, subst c, simp [hV₁], } -- Hence p' = (c, m_x) lies on the upper branch, and we are done. end /--Question 6 of IMO1988. If a and b are two natural numbers such that a*b+1 divides a^2 + b^2, show that their quotient is a perfect square.-/ lemma imo1988_q6 {a b : ℕ} (h : (a*b+1) ∣ a^2 + b^2) : ∃ d, d^2 = (a^2 + b^2)/(a*b + 1) := begin rcases h with ⟨k, hk⟩, rw [hk, nat.mul_div_cancel_left _ (nat.succ_pos (a*b))], simp only [nat.pow_two] at hk, apply constant_descent_vieta_jumping a b hk (λ x, k * x) (λ x, x*x - k) (λ x y, false); clear hk a b, { -- We will now show that the fibers of the solution set are described by a quadratic equation. intros x y, dsimp only, rw [← int.coe_nat_inj', ← sub_eq_zero], apply eq_iff_eq_cancel_right.2, norm_cast, simp, ring, }, { -- Show that the solution set is symmetric in a and b. intros x y, simp [add_comm (x*x), mul_comm x], }, { -- Show that the claim is true if b = 0. suffices : ∀ a, a * a = k → ∃ d, d * d = k, by simpa, rintros x rfl, use x }, { -- Show that the claim is true if a = b. intros x hx, suffices : k ≤ 1, { rw [nat.le_add_one_iff, nat.le_zero_iff] at this, rcases this with rfl|rfl, { use 0, simp }, { use 1, simp } }, contrapose! hx with k_lt_one, apply ne_of_lt, calc x*x + x*x = x*x * 2 : by rw mul_two ... ≤ x*x * k : nat.mul_le_mul_left (x*x) k_lt_one ... < (x*x + 1) * k : by linarith }, { -- Show the descent step. intros x y hx x_lt_y hxky h z h_root hV₁ hV₀, split, { dsimp [-sub_eq_add_neg] at *, have hpos : z*z + x*x > 0, { apply add_pos_of_nonneg_of_pos, { apply mul_self_nonneg }, { apply mul_pos; exact_mod_cast hx }, }, have hzx : z*z + x*x = (z * x + 1) * k, { rw [← sub_eq_zero, ← h_root], ring, }, rw hzx at hpos, replace hpos : z * x + 1 > 0 := pos_of_mul_pos_right hpos (int.coe_zero_le k), replace hpos : z * x ≥ 0 := int.le_of_lt_add_one hpos, apply nonneg_of_mul_nonneg_right hpos (by exact_mod_cast hx), }, { contrapose! hV₀ with x_lt_z, apply ne_of_gt, calc z * y > x*x : by apply mul_lt_mul'; linarith ... ≥ x*x - k : sub_le_self _ (int.coe_zero_le k) }, }, { -- There is no base case in this application of Vieta jumping. simp }, end /- The following example illustrates the use of constant descent Vieta jumping in the presence of a non-trivial base case. -/ example {a b : ℕ} (h : a*b ∣ a^2 + b^2 + 1) : 3*a*b = a^2 + b^2 + 1 := begin rcases h with ⟨k, hk⟩, suffices : k = 3, { simp * at *, ring, }, simp only [nat.pow_two] at hk, apply constant_descent_vieta_jumping a b hk (λ x, k * x) (λ x, x*x + 1) (λ x y, x ≤ 1); clear hk a b, { -- We will now show that the fibers of the solution set are described by a quadratic equation. intros x y, dsimp only, rw [← int.coe_nat_inj', ← sub_eq_zero], apply eq_iff_eq_cancel_right.2, simp, ring, }, { -- Show that the solution set is symmetric in a and b. cc }, { -- Show that the claim is true if b = 0. simp }, { -- Show that the claim is true if a = b. intros x hx, have x_sq_dvd : x*x ∣ x*x*k := dvd_mul_right (x*x) k, rw ← hx at x_sq_dvd, obtain ⟨y, hy⟩ : x * x ∣ 1 := by simpa only [nat.dvd_add_self_left, add_assoc] using x_sq_dvd, obtain ⟨rfl,rfl⟩ : x = 1 ∧ y = 1 := by simpa [nat.mul_eq_one_iff] using hy.symm, simpa using hx.symm, }, { -- Show the descent step. intros x y x_lt_y hx h_base h z h_root hV₁ hV₀, split, { have zy_pos : z * y ≥ 0, { rw hV₀, exact_mod_cast (nat.zero_le _) }, apply nonneg_of_mul_nonneg_right zy_pos, linarith }, { contrapose! hV₀ with x_lt_z, apply ne_of_gt, push_neg at h_base, calc z * y > x * y : by apply mul_lt_mul_of_pos_right; linarith ... ≥ x * (x + 1) : by apply mul_le_mul; linarith ... > x * x + 1 : begin rw [mul_add, mul_one], apply add_lt_add_left, assumption_mod_cast end, } }, { -- Show the base case. intros x y h h_base, obtain rfl|rfl : x = 0 ∨ x = 1 := by rwa [nat.le_add_one_iff, nat.le_zero_iff] at h_base, { simpa using h, }, { simp only [mul_one, one_mul, add_comm, zero_add] at h, have y_dvd : y ∣ y * k := dvd_mul_right y k, rw [← h, ← add_assoc, nat.dvd_add_left (dvd_mul_left y y)] at y_dvd, obtain rfl|rfl : y = 1 ∨ y = 2 := nat.prime_two.2 y y_dvd, all_goals { ring at h, omega } } } end
85644240377d3bbd7e23573f6166a96c4e516d8d
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/10_Structures_and_Records.org.5.lean
e032a013326e2b0e79089c87ff8ec882ef74a0e0
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
131
lean
import standard namespace hide -- BEGIN structure prod (A : Type) (B : Type) := (pr1 : A) (pr2 : B) check prod.mk -- END end hide
322d87a15a2baefa89c3eb942fd80cb67e6fc9df
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/sites/compatible_sheafification.lean
d9b682b87047a2d40080653b47b128f1c6f8c426
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,833
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.sites.compatible_plus import category_theory.sites.sheafification /-! In this file, we prove that sheafification is compatible with functors which preserve the correct limits and colimits. -/ namespace category_theory.grothendieck_topology open category_theory open category_theory.limits open opposite universes w₁ w₂ v u variables {C : Type u} [category.{v} C] (J : grothendieck_topology C) variables {D : Type w₁} [category.{max v u} D] variables {E : Type w₂} [category.{max v u} E] variables (F : D ⥤ E) noncomputable theory variables [∀ (α β : Type (max v u)) (fst snd : β → α), has_limits_of_shape (walking_multicospan fst snd) D] variables [∀ (α β : Type (max v u)) (fst snd : β → α), has_limits_of_shape (walking_multicospan fst snd) E] variables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D] variables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ E] variables [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ F] variables [∀ (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan F] variables (P : Cᵒᵖ ⥤ D) /-- The isomorphism between the sheafification of `P` composed with `F` and the sheafification of `P ⋙ F`. Use the lemmas `whisker_right_to_sheafify_sheafify_comp_iso_hom`, `to_sheafify_comp_sheafify_comp_iso_inv` and `sheafify_comp_iso_inv_eq_sheafify_lift` to reduce the components of this isomorphisms to a state that can be handled using the universal property of sheafification. -/ def sheafify_comp_iso : J.sheafify P ⋙ F ≅ J.sheafify (P ⋙ F) := J.plus_comp_iso _ _ ≪≫ (J.plus_functor _).map_iso (J.plus_comp_iso _ _) /-- The isomorphism between the sheafification of `P` composed with `F` and the sheafification of `P ⋙ F`, functorially in `F`. -/ def sheafification_whisker_left_iso (P : Cᵒᵖ ⥤ D) [∀ (F : D ⥤ E) (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ F] [∀ (F : D ⥤ E) (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan F] : (whiskering_left _ _ E).obj (J.sheafify P) ≅ (whiskering_left _ _ _).obj P ⋙ J.sheafification E := begin refine J.plus_functor_whisker_left_iso _ ≪≫ _ ≪≫ functor.associator _ _ _, refine iso_whisker_right _ _, refine J.plus_functor_whisker_left_iso _, end @[simp] lemma sheafification_whisker_left_iso_hom_app (P : Cᵒᵖ ⥤ D) (F : D ⥤ E) [∀ (F : D ⥤ E) (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ F] [∀ (F : D ⥤ E) (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan F] : (sheafification_whisker_left_iso J P).hom.app F = (J.sheafify_comp_iso F P).hom := begin dsimp [sheafification_whisker_left_iso, sheafify_comp_iso], rw category.comp_id, end @[simp] lemma sheafification_whisker_left_iso_inv_app (P : Cᵒᵖ ⥤ D) (F : D ⥤ E) [∀ (F : D ⥤ E) (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ F] [∀ (F : D ⥤ E) (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan F] : (sheafification_whisker_left_iso J P).inv.app F = (J.sheafify_comp_iso F P).inv := begin dsimp [sheafification_whisker_left_iso, sheafify_comp_iso], erw category.id_comp, end /-- The isomorphism between the sheafification of `P` composed with `F` and the sheafification of `P ⋙ F`, functorially in `P`. -/ def sheafification_whisker_right_iso : J.sheafification D ⋙ (whiskering_right _ _ _).obj F ≅ (whiskering_right _ _ _).obj F ⋙ J.sheafification E := begin refine functor.associator _ _ _ ≪≫ _, refine iso_whisker_left (J.plus_functor D) (J.plus_functor_whisker_right_iso _) ≪≫ _, refine _ ≪≫ functor.associator _ _ _, refine (functor.associator _ _ _).symm ≪≫ _, exact iso_whisker_right (J.plus_functor_whisker_right_iso _) (J.plus_functor E), end @[simp] lemma sheafification_whisker_right_iso_hom_app : (J.sheafification_whisker_right_iso F).hom.app P = (J.sheafify_comp_iso F P).hom := begin dsimp [sheafification_whisker_right_iso, sheafify_comp_iso], simp only [category.id_comp, category.comp_id], erw category.id_comp, end @[simp] lemma sheafification_whisker_right_iso_inv_app : (J.sheafification_whisker_right_iso F).inv.app P = (J.sheafify_comp_iso F P).inv := begin dsimp [sheafification_whisker_right_iso, sheafify_comp_iso], simp only [category.id_comp, category.comp_id], erw category.id_comp, end @[simp, reassoc] lemma whisker_right_to_sheafify_sheafify_comp_iso_hom : whisker_right (J.to_sheafify _) _ ≫ (J.sheafify_comp_iso F P).hom = J.to_sheafify _ := begin dsimp [sheafify_comp_iso], erw [whisker_right_comp, category.assoc], slice_lhs 2 3 { rw plus_comp_iso_whisker_right }, rw [category.assoc, ← J.plus_map_comp, whisker_right_to_plus_comp_plus_comp_iso_hom, ← category.assoc, whisker_right_to_plus_comp_plus_comp_iso_hom], refl, end @[simp, reassoc] lemma to_sheafify_comp_sheafify_comp_iso_inv : J.to_sheafify _ ≫ (J.sheafify_comp_iso F P).inv = whisker_right (J.to_sheafify _) _ := by { rw iso.comp_inv_eq, simp } section -- We will sheafify `D`-valued presheaves in this section. variables [concrete_category.{max v u} D] [preserves_limits (forget D)] [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)] [reflects_isomorphisms (forget D)] @[simp] lemma sheafify_comp_iso_inv_eq_sheafify_lift : (J.sheafify_comp_iso F P).inv = J.sheafify_lift (whisker_right (J.to_sheafify _) _) ((J.sheafify_is_sheaf _).comp _) := begin apply J.sheafify_lift_unique, rw iso.comp_inv_eq, simp, end end end category_theory.grothendieck_topology
f894a4152e6748231718cf43e198d9a4a858372a
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/examples/types/monoidal_category_of_types.lean
65a5d935029fb5a36e63529217f98bab773728d1
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
2,231
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 ...monoidal_categories.monoidal_category import ...monoidal_categories.braided_monoidal_category import .types namespace tqft.categories.examples.types open tqft.categories open tqft.categories.monoidal_category open tqft.categories.braided_monoidal_category -- PROJECT really this should be a special case of the (uniquely braided, symmetric) monoidal structure coming from a product. definition TensorProductOfTypes : TensorProduct CategoryOfTypes := { onObjects := λ p, p.1 × p.2, onMorphisms := λ _ _ p q, (p.1 q.1, p.2 q.2), identities := ♯, functoriality := ♮ } -- PROJECT it would be great to generate all these _is_isomorphism fields via refine definition MonoidalCategoryOfTypes : MonoidalStructure CategoryOfTypes := { tensor := TensorProductOfTypes, tensor_unit := punit, associator_transformation := { morphism := { components := λ p t, (t.1.1, (t.1.2, t.2)), naturality := ♮ }, inverse := { components := λ p t, ((t.1, t.2.1), t.2.2), naturality := ♮ }, witness_1 := ♯, witness_2 := ♯ }, left_unitor := { morphism := { components := λ p t, t.2, naturality := ♮ }, inverse := { components := λ p t, (punit.star, t), naturality := ♮ }, witness_1 := ♯, witness_2 := ♮ }, right_unitor := { morphism := { components := λ p t, t.1, naturality := ♮ }, inverse := { components := λ p t, (t, punit.star), naturality := ♮ }, witness_1 := ♯, witness_2 := ♮ }, pentagon := ♯, triangle := ♯ } definition SymmetricMonoidalCategoryOfTypes : Symmetry MonoidalCategoryOfTypes := { braiding := { morphism := { components := λ p t, (t.snd, t.fst), naturality := ♮ }, inverse := { components := λ p t, (t.snd, t.fst), naturality := ♮ }, witness_1 := ♯, witness_2 := ♯ }, hexagon_1 := ♯, hexagon_2 := ♯, symmetry := ♯ } end tqft.categories.examples.types
7d45a465ca2c8732f41646f9b494412c7e70cb1c
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/abbrev2.lean
3b996a1fb358e03fca885359b302e825efa225e0
[ "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
431
lean
open nat namespace bla local abbreviation foo : nat := 10 + 1 definition tst : nat := foo print definition tst end bla -- abbreviation is gone print definition bla.tst check bla.foo open bla check foo print definition tst namespace bla2 abbreviation foo2 : nat := 1 definition tst2 : nat := foo2 print definition tst2 end bla2 print definition bla2.tst2 open bla2 print definition bla2.tst2 print definition tst2